eBPF-based security platform
bpm: walk back through sealed tree segments in bpm tree sync
John Fastabend081bc158caed
diff --git a/.agents/skills/upatch/SKILL.md b/.agents/skills/upatch/SKILL.mdindex bd253688..e3155a34 100644--- a/.agents/skills/upatch/SKILL.md+++ b/.agents/skills/upatch/SKILL.md@@ -147,7 +147,13 @@ class to one upatch, or the two entries selectors that exclude eachother. A segment that holds `--segment-ops` operations (64 by default,1 to 512) is sealed and tagged `segment-<k>`, and the append starts thenext one; keep the `segment-*` tags in the registry, since targets walk-back through the sealed segments by digest. `tree+back through the sealed segments by digest: up to 65,536 operations from+where they are, or 1,048,576 for one that has applied none, past which+`bpm tree sync` refuses with the `segment_walk` phase. A target refuses+a segment that does not start from its own `history_root`, or whose+operations up to its cursor differ from the ones it processed+(`history_base`, `history_prefix`), so never republish a sealed segment+or rewrite an operation a target may have taken. `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 79f66896..0143f808 100644--- a/Documentation/contribute/testing/proof-coverage.rst+++ b/Documentation/contribute/testing/proof-coverage.rst@@ -234,7 +234,8 @@ or shorter, and "lengths 0 to 6" every input of each of those lengths.exactly without the segment keys, a later one exactly with anoperation, a ``sha256:`` digest and a root of 64 hex digits* - ``bpm-tree-follows``- - ``tree_publication_follows()``, ``tree_segment_precedes()``+ - ``tree_publication_follows()``, ``tree_segment_precedes()``,+ ``tree_walk_within()``- Every sequence number and generation; strings up to 2 bytes- Refuses exactly a publication of another tree, of an earliergeneration unless the same manifest, naming another parent when@@ -242,9 +243,13 @@ or shorter, and "lengths 0 to 6" every input of each of those lengths.asks for a walk exactly when one it accepts starts past thecursor, or past 0 without a state. A step of the walk acceptsexactly the segment the successor names, of its tree, ending at- its base and of a lower generation+ its base and of a lower generation. The walk is allowed exactly+ ``TREE_MAX_JOIN_OPS`` operations back from 0 and+ ``TREE_MAX_WALK_OPS`` from any other cursor, and a negative number+ is ``-EINVAL``* - ``bpm-tree-signers``- - ``tree_fetch_publication()``+ - ``tree_source_open()``, ``tree_fetch_checked()``,+ ``tree_source_clear()``- Active or inactive image config; every signing-set count throughcapacity, every unvouched count through the set size, and parse,allocation, load, check and fetch failures@@ -253,17 +258,22 @@ or shorter, and "lengths 0 to 6" every input of each of those lengths.failures refuse the fetch and every allocated set is released* - ``bpm-tree-sync-model``- ``cmd_bpm_tree_sync()``, ``tree_recover_pending()``,- ``tree_publication_check()``, ``tree_publication_follows()``- - The full command with 0 or 1 operation, every pending state,- selector answer, install answer and first failing I/O call, or no- failure. Names have one byte, and the previous root and the- history root the outcomes record holds at the cursor have 32- symbolic bytes each.+ ``tree_publication_check()``, ``tree_publication_follows()``,+ the walk back and forwards, the base and prefix checks,+ ``tree_history_at()``+ - The full command with 0 or 1 operation at any base, every pending+ state, selector answer, install answer and first failing I/O+ call, or no failure; a publication past the cursor asks for a walk+ the registry cannot serve. Names have one byte, and the previous+ root and the history roots the outcomes record holds at the cursor+ and at any other seq have 32 symbolic bytes each.- Writes match the Lean model ``Shirudo.TreeSync`` in order, thecut of the outcomes record, each outcome line with its code andboth roots, and the state written at acceptance with the- publication's head and base included; nothing is written after a- failure and every expected write happens when nothing fails+ publication's head and base included; a publication whose base+ or prefix is not the node's history writes nothing past the cut;+ nothing is written after a failure and every expected write+ happens when nothing fails* - ``bpm-tree-sync-application``- ``cmd_bpm_tree_sync()``- Two operations with no pending record; every selector answer@@ -277,6 +287,19 @@ or shorter, and "lengths 0 to 6" every input of each of those lengths.replay equals the previous root, the next root, or neither;the previous root has 32 symbolic bytes.- The same ordered-write properties as ``bpm-tree-sync-model``+ * - ``bpm-tree-sync-walk``+ - ``cmd_bpm_tree_sync()``, ``tree_walk_back()``,+ ``tree_walk_forward()``, ``tree_recover_pending()``+ - The publication the tag names and a sealed segment the registry+ serves by its digest, one operation each, at any bases and+ generations; every pending state, selector answer, walk limit,+ link between the two and first failing I/O call, or no failure+ - The same ordered-write properties as ``bpm-tree-sync-model``,+ through a walk: the sealed segment is applied first, with+ recovery, then the tag's, each recorded before its operations;+ a walk past its limit, a segment the registry does not serve or+ one that is not the predecessor its successor names writes+ nothing past the cut* - ``bpm-tree-recovery-model``- ``tree_recover_pending()``- Publications with 0 to 2 operations, a matching or unrelated@@ -1160,8 +1183,14 @@ the model follows the C.``outcomes_fixed``, ``lastSeq_le_head``: the outcomes record has aline for every operation from 1 to the cursor, in order, no lineat or below the cursor ever changes, and the cursor never passes- the head of the recorded publication- - A manifest digest names one publication; the hash is injective on+ the head of the recorded publication. All of these hold across+ segment boundaries, as a publication of any base is a sync+ - A sync that walks is one sync per segment: it leaves out only the+ state each segment but the last writes at its end, which the next+ segment's record overwrites with the same cursor and root, and+ its cut keeps every line; the base and prefix checks are left out+ of the model, as they only refuse more. A manifest digest names+ one publication; the hash is injective on(root, digest) and never 64 zeros; only sync writes the tree files,each write whole, one sync at a time; the unlink of ``pending.json``succeeds; an extend and its eventlog record are one write. An@@ -1170,9 +1199,10 @@ the model follows the C.cursor is a theorem, not a branch of the model- CBMC: ``bpm-tree-follows`` for ``tree_publication_follows()``,``bpm-tree-sync-model`` and its two-operation variants for- sync writes, ``bpm-tree-recovery-model`` for pending recovery,+ sync writes, ``bpm-tree-sync-walk`` for a walk,+ ``bpm-tree-recovery-model`` for pending recovery,``bpm-tree-state-replay`` for ``tree_event_replay()``;- ``tree_parse()`` by review+ ``tree_parse()`` and the walk as one sync per segment by review* - ``Shirudo.TreeOverlap``, :src:`util/bpm_tree_overlap.c` against``tree_selector_matches()`` of :src:`util/bpm_tree_state.c`- ``disjoint_sound``: no node matches two selectors thatdiff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex 354433c8..987742d3 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -551,6 +551,24 @@ signed config image.malformed, on an ``add``, a ``delete`` and an operation without amatch, syncs with the outcomes, state and tree eventlog of thesame operations without it+ * - ``t7108-bpm-tree-segments``+ - In ``functional/bpm-segments/``, a VM of its own, so that the node+ starts without a tree, on a tree ``bpm tree append --segment-ops+ 2`` published and a bundle that lowers the walk limits to 4 and 6+ operations. A new node refuses a walk past its limit before it+ fetches a sealed segment, then walks back through four segments,+ past the running limit, and applies them with the tree eventlog,+ ``tree_op`` records, projection root and outcomes of the+ operations taken as one publication; a node inside the current+ segment fetches only it; a walk stopped between two segments, at+ a registry request held, or with an operation pending, resumes+ with a shorter walk and applies no operation twice; a forked+ predecessor fails the base check and a forked current segment the+ prefix check; a sealed segment the registry lost, a predecessor+ ending before its successor's base and a running node's walk past+ its limit are refused with nothing applied; a dry run walks and+ records nothing; ``init`` walks nothing and takes the projection+ root one publication gives* - ``t7109-bpm-tree-keepalive``- ``status --keepalive``: the keys of the body in order, its treekeys and mask as ``state.json`` and the outcomes record have them,@@ -806,7 +824,7 @@ Coverage by area* - upatch tree- ``t3011``, ``t5004``, ``t7005``, ``t7007``, ``t7008``, ``t7009``,``t7101``, ``t7102``, ``t7103``, ``t7104``, ``t7105``, ``t7106``,- ``t7107``, ``t7109``, ``t9105``, ``t9109``. Fuzz: ``tree``,+ ``t7107``, ``t7108``, ``t7109``, ``t9105``, ``t9109``. Fuzz: ``tree``,``tree-state``, ``kconfig``. Unit: ``bpm_tree``,``bpm_tree_overlap``, ``bpm_tree_state``, ``chain_history``,``kernel_build_id``, ``kernel_release``@@ -871,8 +889,8 @@ The threats are those of :doc:`/security/threat-model`.- ``t1006``, ``t4101``, ``t6115``, ``t6126``* - T7 The delivery path- ``t7002``, ``t7003``, ``t7005``, ``t7101``, ``t7102``,- ``t7103``, ``t7104``, ``t7105``, ``t7106``, ``t7107``, ``t8005``,- ``t9105``+ ``t7103``, ``t7104``, ``t7105``, ``t7106``, ``t7107``, ``t7108``,+ ``t8005``, ``t9105``* - T8 Quantum-capable adversaries- ``t2001``, ``t2002``, ``t5001``, ``t8005``* - T9 A target lying about its statediff --git a/Documentation/contribute/testing/testing.rst b/Documentation/contribute/testing/testing.rstindex 45ab511c..da99cbbe 100644--- a/Documentation/contribute/testing/testing.rst+++ b/Documentation/contribute/testing/testing.rst@@ -149,9 +149,10 @@ A shell test is named ``t<F><K><NN>-<what>.sh``:seal, task authority, task and socket policy inheritance, thekeyrings and the TPM path* - 7- - ``functional/bpm/``+ - ``functional/bpm/``, ``functional/bpm-segments/``- Package commands, Beefile policy labels, publishing and the- upatch tree+ upatch tree; ``bpm-segments`` boots a VM of its own, whose node+ starts without a tree, for the walk through a tree's segments* - 8- ``functional/otel/``- Map export, the status keepalive, OTLP transport and TLS policydiff --git a/Documentation/reference/cli/bpm.rst b/Documentation/reference/cli/bpm.rstindex f4658af3..d056b2df 100644--- a/Documentation/reference/cli/bpm.rst+++ b/Documentation/reference/cli/bpm.rst@@ -181,9 +181,18 @@ reading its options.and sequence numbers against the state in``/var/lib/shirudo/bpm/upatch-tree/state.json``.#. It drops from ``upatch-tree/outcomes`` what a sync that stopped left- past the recorded ``last_seq``, refuses a record that does not cover- it, completes an operation that sync left in progress, and records- the publication in ``state.json``.+ past the recorded ``last_seq`` and refuses a record that does not+ cover it.+#. When the publication is a segment that starts past the recorded+ ``last_seq``, it walks back through the sealed segments by their+ digests to the one ``last_seq`` lies in, and refuses a walk of more+ than 65,536 operations, or 1,048,576 when the node has processed+ none. It then takes the segments oldest first, the publication+ last.+#. It refuses a segment that does not start from the node's+ ``history_root`` at its base, or whose operations up to ``last_seq``+ are not the ones the node processed. It completes an operation a+ sync left in progress and records the segment in ``state.json``.#. For each new operation whose selector matches the node labels(``etc/shirudo/node.labels`` of the config image, or``/etc/shirudo/node.labels``), it fetches and verifies the artifact,@@ -192,10 +201,17 @@ reading its options.operation, matched or not, gets its line in ``outcomes``.#. It prints a JSON report to standard output, or to ``--report``.+A failure names its phase as :doc:`/reference/failure-categories`+lists them, and the sync applies nothing past it. The walk, its limits+and the time a joining node takes, which grows linearly with the tree,+are in :doc:`/reference/formats/bpm-formats`; both limits are to be+revisited on live clusters.+With ``--dry-run``, it reports which operations would apply and applies-none: it neither records the publication nor writes a line for a new-operation, but it still drops the leftovers in ``outcomes`` and-completes an operation left in progress. An ``add`` whose kprobe target+none: it fetches and checks every segment of a walk, but neither+records a segment nor writes a line for a new operation, and reports+the recorded ``last_seq``. It still drops the leftovers in ``outcomes``+and completes an operation left in progress. An ``add`` whose kprobe targetmodule is not loaded is skipped and recorded as ``skipped: module notloaded``.diff --git a/Documentation/reference/failure-categories.rst b/Documentation/reference/failure-categories.rstindex 9629f6bf..6db302be 100644--- a/Documentation/reference/failure-categories.rst+++ b/Documentation/reference/failure-categories.rst@@ -612,17 +612,35 @@ rc=<rc> (<strerror>)`` and exits 1:* - ``operation_validate``- An operation of the publication is malformed or its digest doesnot match.- * - ``segment``- - The publication is a segment after the first (``base.seq`` above- 0), which this release does not apply (``ENOTSUP``): it neither- walks back through the sealed segments nor checks a segment's base- against the node's history. A line before it names the segment's- base and the node's last applied ``seq``. Nothing is applied.* - ``outcomes_check``- The ``outcomes`` record does not cover the recorded ``last_seq``:it is missing (``ENOENT``), has a gap or a malformed line, or endsearly (``EBADMSG``), or it cannot be read or cut. Nothing isapplied.+ * - ``segment_walk``+ - The segment the tag names starts further past the node's last+ applied ``seq`` than the walk limit allows (``E2BIG``): 65,536+ operations, or 1,048,576 for a node that has processed none. A+ line before it names the segment's base, the limit and the node's+ ``seq``. Nothing is fetched further and nothing is applied.+ * - ``segment_fetch``+ - A sealed segment of the walk cannot be fetched, ``ENOENT`` when+ the registry does not serve its digest, or does not verify, or+ has changed when it is fetched again. A line before it names its+ digest. Nothing past it is applied.+ * - ``segment_chain``+ - A sealed segment is not the one its successor names: another+ digest, tree, head or a generation that is not lower, or it does+ not follow the node's state (``ERANGE``).+ * - ``history_base``+ - The segment's ``base.history_root`` is not the ``history_root``+ the node's ``outcomes`` holds at ``base.seq`` (``EKEYREJECTED``),+ or that line cannot be read. Nothing of the segment is applied.+ * - ``history_prefix``+ - The publication's operations up to the node's last applied+ ``seq`` are not the ones the node processed: their+ ``history_root`` differs from the node's (``EKEYREJECTED``).+ Nothing of the publication is applied.* - ``pending_recovery``- An interrupted operation cannot be reconciled with the treeeventlog, or its ``outcomes`` lines or state cannot be written.diff --git a/Documentation/reference/formats/bpm-formats.rst b/Documentation/reference/formats/bpm-formats.rstindex 9afae48a..36c7e22b 100644--- a/Documentation/reference/formats/bpm-formats.rst+++ b/Documentation/reference/formats/bpm-formats.rst@@ -543,11 +543,20 @@ Target acceptance``generation``. A direct successor that names a``parent_manifest_digest`` names the recorded manifest.#. ``head.seq`` is not below the node's last applied ``seq``.-#. ``base.seq`` is 0. The target does not yet walk back through the- sealed segments to a node's last applied ``seq``, nor check a later- segment's base against the node's history, and refuses a later- segment with the ``segment`` phase of- :doc:`/reference/failure-categories`.+#. When ``base.seq`` lies past the node's last applied ``seq``, 0 for a+ node without a state, the node walks back to it through the sealed+ segments, see `Walk`_.+#. Base check: the ``history_root`` of the node's ``outcomes`` at+ ``base.seq``, 32 zero bytes at 0, equals ``base.history_root``.+#. Prefix check: the publication's operation digests, folded from+ ``base.history_root`` up to the node's last applied ``seq``, give the+ node's ``history_root`` there. This applies to every publication, so+ a registry that serves operations other than the ones a node already+ processed, inside a segment or at its base, is refused with+ ``EKEYREJECTED``.++The node then records the publication, see `Node records`_, and processes+the operations after its last applied ``seq``.For each new operation whose selector matches, the target then fetches theartifact manifest by ``manifest_digest``, takes the layer with@@ -556,6 +565,34 @@ checks its digest and size, and refuses the ``.upatch`` unless its header``payload_sha256`` equals ``artifact.payload_sha256``, its ``name`` equals``id`` and it is an unload directive exactly when ``op`` is ``delete``.+Walk+~~~~++A node behind the segment that ``<reference>`` names fetches back to the+segment its last applied ``seq`` lies in, then applies the segments+forwards. It keeps the manifest digest, ``base.seq``, ``head.seq`` and+``generation`` of each segment, not the documents.++#. While the oldest segment so far starts past the node's last applied+ ``seq``, the node refuses the sync when the distance between the two+ exceeds the walk limit (``E2BIG``), see `Limits`_, then fetches+ ``manifests/<base.segment_manifest_digest>``. The sealed segment must+ pass checks 1 to 3 above, hash to that digest, have the same+ ``tree_id``, end at its successor's ``base.seq`` and have a lower+ ``generation`` (``ERANGE``). A segment the registry does not serve+ refuses the sync; the node never skips ahead.+#. Oldest first, the node fetches each sealed segment again by its+ digest and checks it as before, then runs checks 4 to 9 and applies+ it as above. The segment ``<reference>`` names, which the walk holds,+ comes last.++An operation left in progress is completed against the oldest segment of+the walk alone: the node records a segment before it processes it, so the+operation lies in the segment its state names. ``state.json`` moves at+each applied operation and at each segment recorded, so a walk that stops+resumes with a shorter one. A reboot never walks: ``init`` reads+``state.json`` alone.+Node records~~~~~~~~~~~~@@ -574,10 +611,12 @@ not published.publication the node last accepted, ``last_seq``,``projection_root`` and ``projection_root_tpm``. ``head_seq`` and``segment_base_seq`` are the publication's ``head.seq`` and- ``base.seq``. A sync records a publication once it passes the- checks above and an interrupted operation is completed, before it- processes the first new operation, so a sync that stops among them- leaves ``last_seq`` at or below ``head_seq`` and the node refuses+ ``base.seq``. A sync records a publication, each segment of a walk+ in turn, once it passes the checks above and an interrupted+ operation is completed, before it processes the first new+ operation of it, so a sync that stops among them leaves+ ``last_seq`` from ``segment_base_seq`` to ``head_seq`` and the+ node refusesan older generation from then on. ``last_seq`` also moves pastoperations whose selector does not match. A state without one of``tree_id``, ``last_seq``, the two roots, ``head_seq`` and@@ -652,11 +691,32 @@ Limits- 512* - Tree operations per publication- 512+ * - Tree walk of a node that has processed an operation,+ ``TREE_MAX_WALK_OPS``+ - 65,536 operations from its last applied ``seq``+ * - Tree walk of a node that has processed none, ``TREE_MAX_JOIN_OPS``+ - 1,048,576 operations from ``seq`` 0* - JSON document- 8 MiB* - Detached signature- 64 KiB (writer)+A walk past its limit refuses the sync with ``E2BIG`` before it fetches a+sealed segment, see `Walk`_. The bound is on the distance from the node's+last applied ``seq``, not on the size of the tree. A node that has+applied nothing holds no upatch of the tree yet and is joining, so it+gets the higher limit; a running node walks holding the bpm lock, which+stops its keepalive, and gets the lower one. A higher limit only allows+more verified fetches and never makes a node accept what it would+otherwise refuse. Join time grows linearly with the tree: each segment+of a walk costs two fetches of its manifest, document and signature and+two signature checks, so a node that joins at the limit with the default+64 operations per segment walks 16,384 segments, about 100,000 registry+requests, besides fetching, loading and measuring each operation its+selectors match. Both limits are compile-time defines, settled for now+and to be revisited by experiment on live clusters; a node further+behind than its limit is refused every sync of the tree.+Related-------diff --git a/Documentation/security/threat-model.rst b/Documentation/security/threat-model.rstindex 9a5f9f06..170d2253 100644--- a/Documentation/security/threat-model.rst+++ b/Documentation/security/threat-model.rst@@ -1050,7 +1050,14 @@ has a higher generation, and names its parent, which the targetcompares when the generation is exactly one higher. The target recordsa publication when it accepts it, before it applies the first newoperation, so one it stopped in the middle of is not followed by an-older one. A delete applies+older one. It refuses a publication whose operations up to its last+applied one are not the ones it processed, by the history root its+``outcomes`` record holds, and a segment that does not start from that+root at its base. A node behind the segment the tag names walks back+through the sealed segments by digest, each signed and naming the one+before it, up to a limit of 65,536 operations, or 1,048,576 for a node+that has processed none, so a registry can neither splice another+history in nor keep a node walking without end. A delete appliesthe signed unload directive whose name equals the operation's id. Anoperation's ``fixes``, which the backend reads and the operation digestdoes not cover, the target's parser skips: a malformed one cannot make@@ -1075,7 +1082,7 @@ and tree signatures accept algorithms other than ML-DSA (U4).:Refusal: the ``bpm`` command fails and installs nothing:Counters: none:Tests: ``t7005``, ``t7101``, ``t7102``, ``t7103``, ``t7104``,- ``t7105``, ``t7106``, ``t7107``, ``t8005``+ ``t7105``, ``t7106``, ``t7107``, ``t7108``, ``t8005``:Proofs: ``bpm-tar-header``, ``bpm-tar-octal``, ``bpm-archive-path``,``bpm-oci-challenge``, ``bpm-oci-token``, ``bpm-oci-header``,``bpm-oci-descriptor``, ``bpm-semver-model``, ``Shirudo.SemVer``,@@ -1459,11 +1466,16 @@ R8 Registry withholding and replayunless ``--new-index`` is given. ``bpm tree append`` builds the nextpublication on the one the registry serves the same way, so an olderone makes the operator sign a second branch of the tree. A target- compares the parent of a direct successor only, and takes a- publication of that branch two or more generations on, applying its- operations after those of the first. Detection: compare the upatch payloads- and tree operations that ``attest verify`` certifies with what you- published, and the pushed index with the versions you released.+ that processed an operation the second branch does not have refuses+ it, as its operations up to the target's cursor do not fold to the+ ``history_root`` the target holds, in a segment and at a segment's+ base alike; a target behind the point where the branches part takes+ either. A registry can still withhold the latest publication or a+ sealed segment, which stops a walk, and keep serving a stale tag,+ which a target takes for current until a later one reaches it.+ Detection: compare the upatch payloads and tree operations that+ ``attest verify`` certifies with what you published, and the pushed+ index with the versions you released.R9 Classical piecesThe WebPKI certificates of registries and collectors authenticatediff --git a/Makefile.shirudo b/Makefile.shirudoindex e0ab6b31..6fbe0432 100644--- a/Makefile.shirudo+++ b/Makefile.shirudo@@ -429,6 +429,31 @@ build/target/%.o: %.c Makefile.shirudo $(CONFIG_MK_DEP)-include $(DEPS)+# The tree walk limits of util/bpm_tree.h. The test VM bundle builds its+# target with them low, TREE_LIMIT_CFLAGS='-DTREE_MAX_WALK_OPS=<n>+# -DTREE_MAX_JOIN_OPS=<n>', so that a target test reaches them; the operator+# profile ignores it. The objects that read them rebuild whenever the value+# differs from the one they were built with, so a build without it never+# keeps the lowered limits.+ifeq ($(PROFILE),target)+TREE_LIMIT_CFLAGS ?=+else+override TREE_LIMIT_CFLAGS :=+endif+TREE_LIMIT_STAMP := build/tree-limits-$(PROFILE)+TREE_LIMIT_OBJS := $(call obj,builtin-bpm.o) $(call obj,util/bpm_tree.o)++.PHONY: FORCE_TREE_LIMITS+FORCE_TREE_LIMITS:++$(TREE_LIMIT_STAMP): FORCE_TREE_LIMITS+ $(Q)mkdir -p $(dir $@)+ $(Q)printf '%s\n' '$(TREE_LIMIT_CFLAGS)' | cmp -s - $@ 2>/dev/null || \+ printf '%s\n' '$(TREE_LIMIT_CFLAGS)' > $@++$(TREE_LIMIT_OBJS): $(TREE_LIMIT_STAMP)+$(TREE_LIMIT_OBJS): CFLAGS += $(TREE_LIMIT_CFLAGS)+# BPF objects pull vmlinux.h from vendor/linux, <bpf/...> helper headers# and UAPI kernel headers from vendor/libbpf, and shirudo's own BPF# library headers from bpf/lib.@@ -1105,8 +1130,8 @@ FUZZ_CONFIG := util/config.c util/image_config.cFUZZ_SEAL := util/seal.c $(FUZZ_CONFIG)FUZZ_OCI := util/bpm_oci.c util/curl.c util/io.c $(FUZZ_SEAL) \util/crypto_openssl.c util/tls_openssl.c-FUZZ_PACKAGE := util/bpm_package.c util/bpm_tree.c util/upatch.c \- util/keys.c $(FUZZ_OCI)+FUZZ_PACKAGE := util/bpm_package.c util/bpm_tree.c util/chain_history.c \+ util/upatch.c util/keys.c $(FUZZ_OCI)FUZZ_TARGETS := $(patsubst %.c,%,$(wildcard testing/fuzz/fuzz-*.c))@@ -1116,8 +1141,9 @@ testing/fuzz/fuzz-oci-manifest: testing/fuzz/fuzz-oci-manifest.c \testing/fuzz/fuzz-bpm-index: testing/fuzz/fuzz-bpm-index.c \$(FUZZ_BASE) $(FUZZ_PACKAGE)testing/fuzz/fuzz-tree: testing/fuzz/fuzz-tree.c $(FUZZ_BASE) \- util/bpm_tree.c util/crypto_openssl.c util/io.c \- util/upatch.c $(FUZZ_SEAL)+ util/bpm_tree.c util/chain_history.c \+ util/crypto_openssl.c util/io.c util/upatch.c \+ $(FUZZ_SEAL)testing/fuzz/fuzz-upatch: testing/fuzz/fuzz-upatch.c $(FUZZ_BASE) \util/upatch.ctesting/fuzz/fuzz-prog-metadata: testing/fuzz/fuzz-prog-metadata.c \@@ -1195,7 +1221,8 @@ testing/fuzz/fuzz-config-update: testing/fuzz/fuzz-config-update.c \$(FUZZ_BASE) util/config_update.c \util/config_measure.c testing/fuzz/chain.c \util/crypto_openssl.c util/io.c $(FUZZ_SEAL)-FUZZ_TREE_STATE := util/bpm_tree_state.c util/bpm_tree.c util/upatch.c \+FUZZ_TREE_STATE := util/bpm_tree_state.c util/bpm_tree.c \+ util/chain_history.c util/upatch.c \util/io.c $(FUZZ_SEAL) \util/kernel_build_id.c util/kernel_release.c \util/crypto_openssl.c testing/fuzz/chain.cdiff --git a/builtin-bpm.c b/builtin-bpm.cindex 6203abf6..620633a9 100644--- a/builtin-bpm.c+++ b/builtin-bpm.c@@ -1612,37 +1612,38 @@ static bool tree_digest_valid(const char *digest)return !sha256_digest_decode(digest, raw);}-static int tree_fetch_publication(const struct bpm_tree_config *cfg,- struct tree_publication *pub,- char *manifest_digest, size_t digest_sz)-{- struct bpm_oci_client c __cleanup(bpm_oci_client_clear) = {};- struct trusted_set *trusted = NULL;+struct tree_source {+ struct bpm_oci_client c;char repository[BPM_MAX_ENDPOINT];+ struct trusted_set *trusted;+};++static void tree_source_clear(struct tree_source *src)+{+ bpm_oci_client_clear(&src->c);+ xfree(src->trusted, sizeof(*src->trusted));+ src->trusted = NULL;+}++/* The signing set is loaded once, for every segment a walk fetches. */+static int tree_source_open(const struct bpm_tree_config *cfg,+ struct tree_source *src)+{int ret;- ret = bpm_oci_parse_tree_repo(cfg->endpoint, &c,- repository, sizeof(repository));- if (ret)+ ret = bpm_oci_parse_tree_repo(cfg->endpoint, &src->c,+ src->repository, sizeof(src->repository));+ if (ret || !image_config_active())return ret;- if (image_config_active()) {- trusted = xcalloc(1, sizeof(*trusted));- if (!trusted)- return -ENOMEM;- ret = keys_load_image_root(get_cert_path(), image_config_root_fd(),- true, trusted);- if (!ret && (!trusted->n || trusted->n_unvouched))- ret = -EKEYREJECTED;- if (!ret)- ret = keys_check_image_set(trusted);- if (ret)- goto out;- }- ret = bpm_tree_fetch_publication(&c, repository, cfg->reference,- get_cert_path(), trusted, pub,- manifest_digest, digest_sz);-out:- xfree(trusted, sizeof(*trusted));+ src->trusted = xcalloc(1, sizeof(*src->trusted));+ if (!src->trusted)+ return -ENOMEM;+ ret = keys_load_image_root(get_cert_path(), image_config_root_fd(),+ true, src->trusted);+ if (!ret && (!src->trusted->n || src->trusted->n_unvouched))+ ret = -EKEYREJECTED;+ if (!ret)+ ret = keys_check_image_set(src->trusted);return ret;}@@ -2045,257 +2046,535 @@ static void tree_sync_report_error(const char *phase,err ? strerror(err) : "success");}-static int cmd_bpm_tree_sync(int argc, const char **argv)+/*+ * The publication reference names, a tag or a manifest digest, signed and+ * with what tree sync checks before it applies anything.+ */+static int tree_fetch_checked(struct tree_source *src, const char *reference,+ struct tree_publication *pub,+ char *manifest_digest, size_t digest_sz){- struct bpm_tree_config cfg;- struct tree_publication pub = {};- struct tree_state state = {};- char manifest_digest[BPM_MAX_DIGEST];- char report[PATH_MAX] = {};- __u8 root[32], history_root[32];- bool dry_run = false, have_state = false;- int selected = 0, skipped = 0, applied = 0, module_skipped = 0;- int tpm_available = 0;int ret;- if (argc < 2 || strcmp(argv[1], "sync")) {- ret = -EINVAL;- goto out;- }- for (int i = 2; i < argc; i++) {- if (!strcmp(argv[i], "--dry-run")) {- dry_run = true;- } else if (!strncmp(argv[i], "--report=", 9) ||- (!strcmp(argv[i], "--report") && i + 1 < argc)) {- const char *path = argv[i][8] == '=' ? argv[i] + 9 :- argv[++i];-- if (strscpy(report, path, sizeof(report)) < 0) {- pr_err("bpm tree sync: report path too long");- return 2;- }- } else if (is_help(argv[i])) {- fprintf(stderr, "usage: shirudo bpm tree sync [--dry-run] [--report=<path>]\n");- ret = 0;- goto out;- } else {- ret = -EINVAL;- goto out;- }- }- ret = load_tree_config(&cfg);- /* Optional integration: manual `shirudo upatch` remains valid. */- if (ret == -ENOENT) {- ret = 0;- goto out;- }- if (ret)- goto out;- ret = tree_state_read(&state);- if (!ret)- have_state = true;- else if (ret != -ENOENT)- goto out;- ret = tree_fetch_publication(&cfg, &pub, manifest_digest,- sizeof(manifest_digest));+ ret = bpm_tree_fetch_publication(&src->c, src->repository, reference,+ get_cert_path(), src->trusted, pub,+ manifest_digest, digest_sz);if (ret)- goto out;+ return ret;/** The node records the tree ID in its state, which takes names* alone: one that is not would be applied, measured and logged* and then never recorded, failing every later sync.*/- if (!bpm_package_name_ok(pub.tree_id)) {- ret = -EINVAL;- goto out;- }- ret = tree_publication_check(&pub);+ if (!bpm_package_name_ok(pub->tree_id))+ return -EINVAL;+ ret = tree_publication_check(pub);if (ret)- goto out;- for (int i = 0; i < pub.n_operations; i++) {- ret = tree_operation_validate(&pub.operations[i]);+ return ret;+ for (int i = 0; i < pub->n_operations; i++) {+ ret = tree_operation_validate(&pub->operations[i]);if (ret) {- tree_sync_report_error("operation_validate", &pub.operations[i], ret);- goto out;+ tree_sync_report_error("operation_validate",+ &pub->operations[i], ret);+ return ret;}}- ret = tree_publication_follows(&pub, have_state ? &state : NULL,- manifest_digest);- if (ret < 0)- goto out;- /*- * A later segment is applied only after its base is checked- * against the node's history root, and reached only by a walk- * back through the sealed segments when the node is behind it.- */- if (ret == TREE_FOLLOWS_WALK || pub.base_seq) {- pr_err("bpm tree sync: the publication is a segment that starts "- "after seq %lld and this node is at seq %lld; walking "- "back through sealed segments and checking a segment's "- "base are not supported", pub.base_seq, state.last_seq);- ret = -ENOTSUP;- tree_sync_report_error("segment", NULL, ret);- goto out;+ return 0;+}++/*+ * A segment the walk back passed: the forward pass fetches it again by+ * its manifest digest, which names the same bytes, so only this is kept+ * and not the document.+ */+struct tree_segment {+ __u8 manifest_digest[32];+ __s64 base_seq;+ __s64 head_seq;+ __s64 generation;+};++/* The segments of a walk, newest first. */+struct tree_walk {+ struct tree_segment *segments;+ size_t n;+ size_t cap;+};++static void tree_walk_free(struct tree_walk *w)+{+ xfree(w->segments, w->cap * sizeof(*w->segments));+ *w = (struct tree_walk){};+}++static int tree_walk_add(struct tree_walk *w, const struct tree_publication *pub,+ const char *manifest_digest)+{+ struct tree_segment *seg;++ if (w->n == w->cap) {+ size_t cap = w->cap ? 2 * w->cap : 8;++ seg = xreallocarray(w->segments, w->cap, cap, sizeof(*seg));+ if (!seg)+ return -ENOMEM;+ w->segments = seg;+ w->cap = cap;}- if (!have_state) {- state.schema = 1;- bpm_copy_string(state.tree_id, sizeof(state.tree_id), pub.tree_id);- memset(state.projection_root, '0', 64);- state.projection_root[64] = '\0';- memset(state.projection_root_tpm, '0', 64);- state.projection_root_tpm[64] = '\0';+ seg = &w->segments[w->n];+ if (sha256_digest_decode(manifest_digest, seg->manifest_digest))+ return -EINVAL;+ seg->base_seq = pub->base_seq;+ seg->head_seq = pub->head_seq;+ seg->generation = pub->generation;+ w->n++;+ return 0;+}++/*+ * Back from the publication the tag names to the segment the cursor+ * last_seq lies in, each sealed segment fetched by the digest its+ * successor names and checked as the one it names. Nothing is applied+ * before the whole chain is known, and a gap, a fork or a walk past its+ * limit refuses the sync.+ */+static int tree_walk_back(struct tree_source *src,+ const struct tree_publication *tag,+ const char *tag_digest, __s64 last_seq,+ struct tree_walk *w)+{+ const struct tree_publication *succ = tag;+ struct tree_publication fetched[2] = {};+ char digest[BPM_MAX_DIGEST];+ int next = 0, ret;++ ret = tree_walk_add(w, tag, tag_digest);+ while (!ret && succ->base_seq > last_seq) {+ ret = tree_walk_within(succ->base_seq, last_seq);+ if (ret) {+ pr_err("bpm tree sync: the segment that starts after seq %lld is more than %d operations past seq %lld, where this node is",+ succ->base_seq,+ last_seq ? TREE_MAX_WALK_OPS : TREE_MAX_JOIN_OPS,+ last_seq);+ tree_sync_report_error("segment_walk", NULL, ret);+ break;+ }+ tree_publication_free(&fetched[next]);+ ret = tree_fetch_checked(src, succ->segment_manifest_digest,+ &fetched[next], digest, sizeof(digest));+ if (ret) {+ pr_err("bpm tree sync: the sealed segment %s, which ends at seq %lld, cannot be fetched or does not verify",+ succ->segment_manifest_digest, succ->base_seq);+ tree_sync_report_error("segment_fetch", NULL, ret);+ break;+ }+ ret = tree_segment_precedes(&fetched[next], digest, succ);+ if (ret) {+ pr_err("bpm tree sync: the sealed segment %s is not the one before the segment that starts after seq %lld",+ succ->segment_manifest_digest, succ->base_seq);+ tree_sync_report_error("segment_chain", NULL, ret);+ break;+ }+ ret = tree_walk_add(w, &fetched[next], digest);+ succ = &fetched[next];+ next ^= 1;}- ret = tree_outcomes_resume(state.last_seq, history_root);+ tree_publication_free(&fetched[0]);+ tree_publication_free(&fetched[1]);+ return ret;+}++struct tree_sync {+ struct tree_state state;+ bool have_state;+ /* The history root at state.last_seq. */+ __u8 history_root[32];+ bool dry_run;+ /* The cursor a dry run reports, which it moves in memory alone. */+ __s64 dry_seq;+ int selected, skipped, applied, module_skipped;+};++/*+ * Acceptance steps 4 and 5: the segment starts where this node's history+ * was at its base, and its operations up to the cursor are the ones the+ * node processed, so a registry that serves another history than the one+ * the node went through is refused, inside a segment as at its base.+ */+static int tree_history_check(const struct tree_publication *pub,+ const struct tree_sync *sync)+{+ __u8 projection_root[32], node[32], doc[32];+ __s64 last_seq = sync->state.last_seq;+ int ret = 0;++ if (pub->base_seq == last_seq)+ memcpy(node, sync->history_root, sizeof(node));+ else+ ret = tree_outcomes_read(pub->base_seq, pub->base_seq, NULL,+ projection_root, node);+ if (!ret)+ ret = tree_history_at(pub, pub->base_seq, doc);+ if (!ret && memcmp(node, doc, sizeof(doc)))+ ret = -EKEYREJECTED;if (ret) {- tree_sync_report_error("outcomes_check", NULL, ret);- goto out;+ pr_err("bpm tree sync: the segment that starts after seq %lld does not start from this node's history there",+ pub->base_seq);+ tree_sync_report_error("history_base", NULL, ret);+ return ret;}- ret = tree_recover_pending(&pub, &state, history_root);+ ret = tree_history_at(pub, last_seq, doc);+ if (!ret && memcmp(sync->history_root, doc, sizeof(doc)))+ ret = -EKEYREJECTED;if (ret) {- tree_sync_report_error("pending_recovery", NULL, ret);- goto out;+ pr_err("bpm tree sync: the operations of the publication up to seq %lld are not the ones this node processed",+ last_seq);+ tree_sync_report_error("history_prefix", NULL, ret);}- /*- * Recorded before its first operation is processed, so that a- * sync that stops among them leaves the cursor within the- * publication the state names.- */- if (!dry_run) {- state.generation = pub.generation;- bpm_copy_string(state.manifest_digest, sizeof(state.manifest_digest),- manifest_digest);- state.head_seq = pub.head_seq;- state.segment_base_seq = pub.base_seq;- ret = tree_state_write(&state);- if (ret) {- tree_sync_report_error("tree_state_commit_accept", NULL, ret);- goto out;- }- }- if (hex_decode(state.projection_root, root, sizeof(root))) {+ return ret;+}++/*+ * Recorded before its first operation is processed, so that a sync that+ * stops among them leaves the cursor within the publication the state+ * names.+ */+static int tree_record(struct tree_sync *sync,+ const struct tree_publication *pub,+ const char *manifest_digest)+{+ struct tree_state *st = &sync->state;+ int ret;++ st->generation = pub->generation;+ bpm_copy_string(st->manifest_digest, sizeof(st->manifest_digest),+ manifest_digest);+ st->head_seq = pub->head_seq;+ st->segment_base_seq = pub->base_seq;+ sync->have_state = true;+ if (sync->dry_run)+ return 0;+ ret = tree_state_write(st);+ if (ret)+ tree_sync_report_error("tree_state_commit_accept", NULL, ret);+ return ret;+}++/* A dry run moves its cursor in memory alone, for a walk to go on. */+static int tree_dry_pass(struct tree_sync *sync,+ const struct tree_operation *op)+{+ __u8 digest[32];++ if (sha256_digest_decode(op->operation_digest, digest))+ return -EINVAL;+ sync->state.last_seq = op->seq;+ return chain_history_step(sync->history_root, digest,+ sync->history_root);+}++static int tree_apply_operations(struct tree_sync *sync,+ struct tree_publication *pub)+{+ struct tree_state *st = &sync->state;+ __u8 root[32];+ int ret;++ if (hex_decode(st->projection_root, root, sizeof(root))) {tree_sync_report_error("projection_root_decode", NULL, -EINVAL);- ret = -EINVAL;- goto out;+ return -EINVAL;}- tpm_available = chain_bound();- for (int i = 0; i < pub.n_operations; i++) {- struct tree_operation *op = &pub.operations[i];+ for (int i = 0; i < pub->n_operations; i++) {+ struct tree_operation *op = &pub->operations[i];__u8 digest[32], next[32];char artifact[PATH_MAX];bool skipped_module = false;- if (op->seq <= state.last_seq)+ if (op->seq <= st->last_seq)continue;ret = tree_selector_matches(&op->selector);if (ret < 0) {tree_sync_report_error("selector_evaluate", op, ret);- goto out;+ return ret;+ }+ if (ret)+ sync->selected++;+ else+ sync->skipped++;+ if (sync->dry_run) {+ ret = tree_dry_pass(sync, op);+ if (ret)+ return ret;+ continue;}if (!ret) {- skipped++;- if (dry_run)- continue;- ret = tree_outcome_unmatched(op, root, history_root);+ ret = tree_outcome_unmatched(op, root,+ sync->history_root);if (ret) {tree_sync_report_error("tree_outcome_append", op, ret);- goto out;+ return ret;}- state.last_seq = op->seq;+ st->last_seq = op->seq;continue;}- selected++;- if (dry_run)- continue;ret = sha256_digest_decode(op->operation_digest, digest);if (ret) {tree_sync_report_error("operation_digest_parse", op, ret);- ret = -EINVAL;- goto out;+ return -EINVAL;}ret = tree_pending_write(op);if (ret) {tree_sync_report_error("pending_write", op, ret);- goto out;+ return ret;}ret = tree_pull_artifact(op, artifact, sizeof(artifact));if (ret) {tree_sync_report_error("artifact_fetch_or_verify", op, ret);- goto out;+ return ret;}- if (!strcmp(op->op, "add")) {+ if (!strcmp(op->op, "add"))ret = upatch_install(artifact);- } else if (!strcmp(op->op, "delete")) {+ else if (!strcmp(op->op, "delete"))ret = upatch_remove(artifact);- } else {- ret = -EINVAL;- goto out;- }+ else+ return -EINVAL;if (ret == UPATCH_INSTALL_TARGET_MISSING &&!strcmp(op->op, "add")) {skipped_module = true;ret = 0;- module_skipped++;+ sync->module_skipped++;pr_warn("bpm tree: skipped %s: module not loaded", op->id);}if (ret) {tree_sync_report_error("upatch_install", op, ret);- goto out;+ return ret;}ret = sha256_2(root, 32, digest, 32, next);if (ret) {tree_sync_report_error("projection_root_hash", op, ret);- goto out;+ return ret;}ret = tree_measure_operation(op, digest);if (ret) {tree_sync_report_error("register_extend", op, ret);- goto out;+ return ret;}memcpy(root, next, sizeof(root));- hex_encode(next, 32, state.projection_root);- hex_encode(next, 32, state.projection_root_tpm);+ hex_encode(next, 32, st->projection_root);+ hex_encode(next, 32, st->projection_root_tpm);ret = tree_event_append(op->seq, op->operation_digest, next);if (ret) {tree_sync_report_error("tree_event_append", op, ret);- goto out;+ return ret;}ret = tree_outcome_record(op->seq, digest,skipped_module ?TREE_OUTCOME_MODULE_ABSENT :TREE_OUTCOME_APPLIED,- next, history_root);+ next, sync->history_root);if (ret) {tree_sync_report_error("tree_outcome_append", op, ret);- goto out;+ return ret;}- state.last_seq = op->seq;- applied++;- ret = tree_state_write(&state);+ st->last_seq = op->seq;+ sync->applied++;+ ret = tree_state_write(st);if (ret) {tree_sync_report_error("tree_state_commit", op, ret);- goto out;+ return ret;}ret = tree_status_update(op->id, skipped_module);if (ret) {tree_sync_report_error("tree_status_write", op, ret);- goto out;+ return ret;}unlink(BPM_TREE_PENDING_PATH);}+ return 0;+}++/*+ * Acceptance steps 4 to 6 and the operations of one segment, the oldest+ * of a walk first, or of the one publication without a walk. Only the+ * oldest has an operation left pending: the node records a segment+ * before it processes any, so the state names the segment that operation+ * is in, and the walk starts from that one.+ */+static int tree_apply_segment(struct tree_sync *sync,+ struct tree_publication *pub,+ const char *manifest_digest, bool oldest)+{+ int ret;++ ret = tree_publication_follows(pub, sync->have_state ?+ &sync->state : NULL,+ manifest_digest);+ if (ret) {+ ret = ret < 0 ? ret : -ERANGE;+ pr_err("bpm tree sync: the segment %s does not follow seq %lld, where this node is",+ manifest_digest, sync->state.last_seq);+ tree_sync_report_error("segment_chain", NULL, ret);+ return ret;+ }+ ret = tree_history_check(pub, sync);+ if (ret)+ return ret;+ if (oldest) {+ ret = tree_recover_pending(pub, &sync->state,+ sync->history_root);+ if (ret) {+ tree_sync_report_error("pending_recovery", NULL, ret);+ return ret;+ }+ sync->dry_seq = sync->state.last_seq;+ }+ ret = tree_record(sync, pub, manifest_digest);+ if (ret)+ return ret;+ return tree_apply_operations(sync, pub);+}++/*+ * The walk forwards, oldest segment first: each sealed one fetched again+ * by its digest and checked as before, and the tag's document, which the+ * walk holds, last.+ */+static int tree_walk_forward(struct tree_source *src, struct tree_sync *sync,+ const struct tree_walk *w,+ struct tree_publication *tag,+ const char *tag_digest)+{+ char want[BPM_MAX_DIGEST], digest[BPM_MAX_DIGEST];+ __u8 got[32];+ int ret;++ for (size_t i = w->n; i-- > 1;) {+ struct tree_publication seg = {};++ memcpy(want, "sha256:", 7);+ hex_encode(w->segments[i].manifest_digest, 32, want + 7);+ ret = tree_fetch_checked(src, want, &seg, digest,+ sizeof(digest));+ if (!ret && (sha256_digest_decode(digest, got) ||+ memcmp(got, w->segments[i].manifest_digest,+ sizeof(got))))+ ret = -ERANGE;+ if (ret) {+ pr_err("bpm tree sync: the sealed segment %s, which ends at seq %lld, cannot be fetched again or has changed",+ want, w->segments[i].head_seq);+ tree_sync_report_error("segment_fetch", NULL, ret);+ } else {+ ret = tree_apply_segment(sync, &seg, digest,+ i == w->n - 1);+ }+ tree_publication_free(&seg);+ if (ret)+ return ret;+ }+ return tree_apply_segment(sync, tag, tag_digest, w->n == 1);+}++static int cmd_bpm_tree_sync(int argc, const char **argv)+{+ struct tree_source src = {};+ struct tree_walk walk = {};+ struct tree_sync sync = {};+ struct bpm_tree_config cfg;+ struct tree_publication pub = {};+ char manifest_digest[BPM_MAX_DIGEST];+ char report[PATH_MAX] = {};+ int ret;++ if (argc < 2 || strcmp(argv[1], "sync")) {+ ret = -EINVAL;+ goto out;+ }+ for (int i = 2; i < argc; i++) {+ if (!strcmp(argv[i], "--dry-run")) {+ sync.dry_run = true;+ } else if (!strncmp(argv[i], "--report=", 9) ||+ (!strcmp(argv[i], "--report") && i + 1 < argc)) {+ const char *path = argv[i][8] == '=' ? argv[i] + 9 :+ argv[++i];++ if (strscpy(report, path, sizeof(report)) < 0) {+ pr_err("bpm tree sync: report path too long");+ return 2;+ }+ } else if (is_help(argv[i])) {+ fprintf(stderr, "usage: shirudo bpm tree sync [--dry-run] [--report=<path>]\n");+ ret = 0;+ goto out;+ } else {+ ret = -EINVAL;+ goto out;+ }+ }+ ret = load_tree_config(&cfg);+ /* Optional integration: manual `shirudo upatch` remains valid. */+ if (ret == -ENOENT) {+ ret = 0;+ goto out;+ }+ if (ret)+ goto out;+ ret = tree_state_read(&sync.state);+ if (!ret)+ sync.have_state = true;+ else if (ret != -ENOENT)+ goto out;+ ret = tree_source_open(&cfg, &src);+ if (ret)+ goto out;+ ret = tree_fetch_checked(&src, cfg.reference, &pub, manifest_digest,+ sizeof(manifest_digest));+ if (ret)+ goto out;+ ret = tree_publication_follows(&pub, sync.have_state ?+ &sync.state : NULL,+ manifest_digest);+ if (ret < 0)+ goto out;+ if (!sync.have_state) {+ sync.state.schema = 1;+ bpm_copy_string(sync.state.tree_id, sizeof(sync.state.tree_id),+ pub.tree_id);+ memset(sync.state.projection_root, '0', 64);+ sync.state.projection_root[64] = '\0';+ memset(sync.state.projection_root_tpm, '0', 64);+ sync.state.projection_root_tpm[64] = '\0';+ }+ ret = tree_outcomes_resume(sync.state.last_seq, sync.history_root);+ if (ret) {+ tree_sync_report_error("outcomes_check", NULL, ret);+ goto out;+ }+ ret = tree_walk_back(&src, &pub, manifest_digest, sync.state.last_seq,+ &walk);+ if (ret)+ goto out;+ ret = tree_walk_forward(&src, &sync, &walk, &pub, manifest_digest);+ if (ret)+ goto out;/* A run of operations without a match at the end moved the cursor. */- if (!dry_run) {- ret = tree_state_write(&state);+ if (!sync.dry_run) {+ ret = tree_state_write(&sync.state);if (ret) {tree_sync_report_error("tree_state_commit_final", NULL, ret);goto out;}+ } else {+ sync.state.last_seq = sync.dry_seq;}/* "-" is standard output, where the report goes without --report. */ret = tree_write_report(report[0] && strcmp(report, "-") ? report : NULL,- &state, selected, skipped, applied,- module_skipped, dry_run, tpm_available);+ &sync.state, sync.selected, sync.skipped,+ sync.applied, sync.module_skipped,+ sync.dry_run, chain_bound());out:+ tree_walk_free(&walk);tree_publication_free(&pub);+ tree_source_clear(&src);return ret;}diff --git a/testing/Makefile b/testing/Makefileindex 81a0d70c..3a725856 100644--- a/testing/Makefile+++ b/testing/Makefile@@ -141,6 +141,7 @@ TEST_VM_BUNDLE_SOURCES := $(sort $(wildcard \$(ROOT)/testing/fixtures/*.h \$(ROOT)/testing/fixtures/policy-labels/* \$(ROOT)/testing/fixtures/policy-exec-graph/* \+ $(ROOT)/testing/fixtures/segments/*/* \$(ROOT)/testing/fixtures/decoders/* \$(ROOT)/upatches/kernel-obs/*.c $(ROOT)/upatches/kernel-obs/*.h $(ROOT)/upatches/kernel-obs/*.list \$(ROOT)/upatches/kernel-obs/*.py $(ROOT)/upatches/kernel-obs/Beefile \diff --git a/testing/fixtures/segments/seg-match/Beefile b/testing/fixtures/segments/seg-match/Beefilenew file mode 100644index 00000000..eaf369df--- /dev/null+++ b/testing/fixtures/segments/seg-match/Beefile@@ -0,0 +1,14 @@+[package]+name = "seg-match"+description = "An upatch every node of the test VM selects, for the tree that t7108 walks"+license = "GPL-2.0 OR BSD-2-Clause"+authors = ["Authors of shirudo"]++[[upatches]]+source = "shirudo-test-seg-match.bpf.c"++[upatches.tree]+id = "shirudo-test-seg-match"++[upatches.tree.selector.labels]+env = ["tree-test"]diff --git a/testing/fixtures/segments/seg-match/shirudo-test-seg-match.bpf.c b/testing/fixtures/segments/seg-match/shirudo-test-seg-match.bpf.cnew file mode 100644index 00000000..5719d7d7--- /dev/null+++ b/testing/fixtures/segments/seg-match/shirudo-test-seg-match.bpf.c@@ -0,0 +1,18 @@+// SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause+/*+ * Copyright (c) 2026 Authors of shirudo+ *+ * An operation of the segmented tree t7108 walks. It attaches to a function+ * every test kernel has, so that it always loads.+ */+#include "vmlinux.h"+#include <bpf/bpf_helpers.h>+#include <bpf/bpf_tracing.h>++char _license[] SEC("license") = "Dual BSD/GPL";++SEC("fentry/do_nanosleep")+int BPF_PROG(shirudo_test_seg_match)+{+ return 0;+}diff --git a/testing/fixtures/segments/seg-other/Beefile b/testing/fixtures/segments/seg-other/Beefilenew file mode 100644index 00000000..021c1441--- /dev/null+++ b/testing/fixtures/segments/seg-other/Beefile@@ -0,0 +1,14 @@+[package]+name = "seg-other"+description = "An upatch no node of the test VM selects, for the tree that t7108 walks"+license = "GPL-2.0 OR BSD-2-Clause"+authors = ["Authors of shirudo"]++[[upatches]]+source = "shirudo-test-seg-other.bpf.c"++[upatches.tree]+id = "shirudo-test-seg-other"++[upatches.tree.selector.labels]+env = ["not-this-node"]diff --git a/testing/fixtures/segments/seg-other/shirudo-test-seg-other.bpf.c b/testing/fixtures/segments/seg-other/shirudo-test-seg-other.bpf.cnew file mode 100644index 00000000..f39686f0--- /dev/null+++ b/testing/fixtures/segments/seg-other/shirudo-test-seg-other.bpf.c@@ -0,0 +1,18 @@+// SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause+/*+ * Copyright (c) 2026 Authors of shirudo+ *+ * An operation of the segmented tree t7108 walks. It attaches to a function+ * every test kernel has, so that it always loads.+ */+#include "vmlinux.h"+#include <bpf/bpf_helpers.h>+#include <bpf/bpf_tracing.h>++char _license[] SEC("license") = "Dual BSD/GPL";++SEC("fentry/do_nanosleep")+int BPF_PROG(shirudo_test_seg_other)+{+ return 0;+}diff --git a/testing/functional/bpm-segments/t7108-bpm-tree-segments.sh b/testing/functional/bpm-segments/t7108-bpm-tree-segments.shnew file mode 100644index 00000000..5e5b659d--- /dev/null+++ b/testing/functional/bpm-segments/t7108-bpm-tree-segments.sh@@ -0,0 +1,430 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# t7108 -- a node walks back through the sealed segments of a tree that bpm+# tree append published with --segment-ops 2 and applies them oldest first,+# with the same tree eventlog, register events, projection root and outcomes+# as the operations taken from one publication. A node inside the current+# segment fetches only it; a walk stopped between segments or with an+# operation pending resumes with a shorter one and applies nothing twice; a+# forked base, a forked prefix, a missing sealed segment, a broken link and+# a walk past either limit are refused before anything applies; init reads+# the state and walks nothing. Its own VM: the node starts without a tree.+# The bundle lowers the limits to 4 operations from a cursor past 0 and 6+# from 0.++cd "$(dirname "$0")/../.."+. ./integration-lib.sh+target_guard+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"++FIXTURES=${SHIRUDO_TEST_FIXTURES_DIR:?target fixture directory is not set}+SOURCE="$FIXTURES/segments-oci"+TREE_DIR=/var/lib/shirudo/bpm/upatch-tree+TREE_EVENTLOG=$TREE_DIR/tree-eventlog+PENDING=$TREE_DIR/pending.json+EVENTLOG=/var/lib/shirudo/eventlog+WORK=$(mktemp -d)+SERVED="$WORK/registry"+REPO="$SERVED/shirudo/segments"+LOG="$WORK/requests.log"+SERVER_PID=+HOLDER_PID=++for fixture in "$SOURCE/port" "$SOURCE/shirudo/segments/manifests/g28" \+ "$SOURCE/shirudo/segments/manifests/fork-base" \+ "$SOURCE/shirudo/segments/manifests/fork-prefix" \+ "$SOURCE/shirudo/segments/manifests/head-gap" \+ "$SHIRUDO_TEST_KEY_FIXTURES/config-tree-segments.img" \+ ./helper/test-oci-registry.py+do+ [ -s "$fixture" ] || test_skip_all "missing segment fixture: $fixture"+done+[ ! -e "$TREE_STATE_FILE" ] || test_skip_all "the node already follows a tree"+PORT=$(cat "$SOURCE/port")++release_tree_eventlog()+{+ [ -n "$HOLDER_PID" ] || return 0+ kill "$HOLDER_PID" 2>/dev/null || true+ wait "$HOLDER_PID" 2>/dev/null || true+ HOLDER_PID=+}++cleanup()+{+ release_tree_eventlog+ rm -f "$REPO"/manifests/*.hold+ if [ -n "$SERVER_PID" ]; then+ kill "$SERVER_PID" 2>/dev/null || true+ wait "$SERVER_PID" 2>/dev/null || true+ fi+ rm -rf "$WORK"+}+trap cleanup EXIT++# What the node should hold after the first $2 operations of the tree, as+# one publication of them gives it, and the digest of a manifest.+cat >"$WORK/segments.py" <<\PY+import hashlib+import json+import pathlib+import sys++DOC = "application/vnd.shirudo.upatch.tree.v1+json"+TREE = pathlib.Path("/var/lib/shirudo/bpm/upatch-tree")+repo = pathlib.Path(sys.argv[1])+++def manifest(ref):+ return (repo / "manifests" / ref).read_bytes()+++def digest(body):+ return "sha256:" + hashlib.sha256(body).hexdigest()+++def document(ref):+ layers = json.loads(manifest(ref))["layers"]+ blob = [layer for layer in layers if layer["mediaType"] == DOC][0]+ return json.loads((repo / "blobs" / blob["digest"]).read_bytes())+++def operations(n):+ ops = []+ for k in range(2, 29, 2):+ ops += document("g%d" % k)["operations"]+ assert [op["seq"] for op in ops] == list(range(1, 29)), ops+ return ops[:n]+++def lines(path):+ return [json.loads(text)+ for text in path.read_text(encoding="utf-8").splitlines()]+++def agree(n):+ projection, history = bytes(32), bytes(32)+ log, outcomes, measured = [], [], []+ for op in operations(n):+ raw = bytes.fromhex(op["operation_digest"][len("sha256:"):])+ history = hashlib.sha256(b"shirudo-tree-history\0" + history ++ raw).digest()+ matched = op["selector"]["labels"]["env"] == ["tree-test"]+ if matched:+ projection = hashlib.sha256(projection + raw).digest()+ log.append((op["seq"], op["operation_digest"], projection.hex()))+ measured.append((op["seq"], op["operation_digest"]))+ outcomes.append((op["seq"], 1 if matched else 2, projection.hex(),+ history.hex()))+ got = [(l["seq"], l["digest"], l["projection_root"])+ for l in lines(TREE / "tree-eventlog")]+ assert got == log, ("tree-eventlog", got, log)+ got = [(l["seq"], l["outcome"], l["projection_root"], l["history_root"])+ for l in lines(TREE / "outcomes")]+ assert got == outcomes, ("outcomes", got, outcomes)+ got = [(r["tree"]["seq"], r["tree"]["operation_digest"])+ for r in lines(pathlib.Path("/var/lib/shirudo/eventlog"))+ if r.get("type") == "tree_op"]+ assert got == measured, ("tree_op records", got, measured)+ state = json.loads((TREE / "state.json").read_bytes())+ assert state["last_seq"] == n, state+ assert state["projection_root"] == projection.hex(), state+ assert state["projection_root_tpm"] == projection.hex(), state+++if sys.argv[2] == "digest":+ print(digest(manifest(sys.argv[3])))+elif sys.argv[2] == "agree":+ agree(int(sys.argv[3]))+else:+ sys.exit("unknown command " + sys.argv[2])+PY++segments()+{+ python3 "$WORK/segments.py" "$REPO" "$@"+}++# The digest of the manifest the reference $1 names.+digest_of()+{+ segments digest "$1"+}++# The target follows the reference segments, which names generation $1.+serve()+{+ cp "$REPO/manifests/$1" "$REPO/manifests/segments"+}++sync_tree()+{+ BPM_OCI_SCHEME=http "$SHIRUDO_BIN" bpm tree sync \+ --report "$WORK/$1.json" >/dev/null 2>"$WORK/$1.err"+}++# The requests the registry logged since it had $1 lines.+requests_since()+{+ sed -n "$(($1 + 1)),\$p" "$LOG"+}++# How many GETs of the manifest $2 the requests since line $1 hold.+manifest_gets()+{+ requests_since "$1" | grep -c "^GET /v2/shirudo/segments/manifests/$2 " || :+}++state_is()+{+ [ "$(tree_state_field last_seq)" = "$1" ] &&+ [ "$(tree_state_field generation)" = "$2" ] &&+ [ "$(tree_state_field segment_base_seq)" = "$3" ] &&+ [ "$(tree_state_field head_seq)" = "$4" ]+}++hold_tree_eventlog()+{+ python3 -c '+import fcntl, os, sys, time+fd = os.open(sys.argv[1], os.O_RDONLY)+fcntl.flock(fd, fcntl.LOCK_EX)+open(sys.argv[2], "w").close()+time.sleep(600)+' "$TREE_EVENTLOG" "$WORK/held" &+ HOLDER_PID=$!+ for _ in 1 2 3 4 5 6 7 8 9 10; do+ [ -e "$WORK/held" ] && return 0+ sleep 1+ done+ return 1+}++tree_op_measured()+{+ python3 - "$EVENTLOG" "$1" <<'PY'+import json+import sys+import time++seq = int(sys.argv[2])+for _ in range(600):+ with open(sys.argv[1], encoding="utf-8") as stream:+ for text in stream:+ try:+ record = json.loads(text)+ except ValueError:+ continue+ if record.get("type") == "tree_op" and \+ record.get("tree", {}).get("seq") == seq:+ sys.exit(0)+ time.sleep(0.1)+sys.exit(1)+PY+}++# Wait until the registry holds the request the file $1 marks.+request_held()+{+ for _ in $(seq 100); do+ [ -e "$1" ] && return 0+ sleep 0.1+ done+ return 1+}++cp -R "$SOURCE" "$SERVED"+python3 ./helper/test-oci-registry.py --root "$SERVED" --port "$PORT" \+ --log "$LOG" --ready-file "$WORK/ready" &+SERVER_PID=$!+for _ in 1 2 3 4 5; do+ [ -e "$WORK/ready" ] && break+ sleep 1+done+[ -e "$WORK/ready" ] || test_skip_all "the segment registry did not start"+"$SHIRUDO_BIN" image update "$SHIRUDO_TEST_KEY_FIXTURES/config-tree-segments" \+ >/dev/null || test_skip_all "cannot activate config-tree-segments"+G2=$(digest_of g2) && G4=$(digest_of g4) && G6=$(digest_of g6) &&+G12=$(digest_of g12) && G14=$(digest_of g14) && G18=$(digest_of g18) &&+G22=$(digest_of g22) || test_skip_all "cannot read the segment fixtures"++test_expect_success 'a joining node refuses a walk past its limit before it fetches a sealed segment' '+ serve g9 &&+ n=$(wc -l <"$LOG") &&+ ! sync_tree join-limit &&+ grep -q "phase=segment_walk rc=-7 " "$WORK/join-limit.err" &&+ ! requests_since "$n" | grep -q "/manifests/sha256:" &&+ [ ! -e "$TREE_STATE_FILE" ] &&+ [ ! -e "$TREE_EVENTLOG" ]+'++test_expect_success 'a new node walks back past the running limit through four segments and applies them in order' '+ serve g8 &&+ n=$(wc -l <"$LOG") &&+ sync_tree join &&+ [ "$(report_field selected <"$WORK/join.json")" = 5 ] &&+ [ "$(report_field skipped <"$WORK/join.json")" = 3 ] &&+ [ "$(report_field applied <"$WORK/join.json")" = 5 ] &&+ [ "$(report_field last_seq <"$WORK/join.json")" = 8 ] &&+ [ "$(manifest_gets "$n" "$G2")" = 2 ] &&+ [ "$(manifest_gets "$n" "$G4")" = 2 ] &&+ [ "$(manifest_gets "$n" "$G6")" = 2 ] &&+ state_is 8 8 6 8 &&+ segments agree 8 &&+ "$SHIRUDO_BIN" status --json | python3 -c "+import json, sys+assert json.load(sys.stdin)[\"tpm\"][\"chain_matches_eventlog\"] is True+"+'++test_expect_success 'a node inside the current segment fetches only it' '+ serve g9 &&+ sync_tree current-start &&+ state_is 9 9 8 9 &&+ serve g10 &&+ n=$(wc -l <"$LOG") &&+ sync_tree current &&+ [ "$(report_field applied <"$WORK/current.json")" = 1 ] &&+ [ "$(manifest_gets "$n" segments)" = 1 ] &&+ ! requests_since "$n" | grep -q "/manifests/sha256:" &&+ state_is 10 10 8 10 &&+ segments agree 10+'++# A test body runs in a subshell, which could not hand a holder process to+# the cleanup: stop each sync here and let the bodies look at what is left.+serve g16+printf '2\n' >"$REPO/manifests/$G14.hold"+BETWEEN=no+BPM_OCI_SCHEME=http "$SHIRUDO_BIN" bpm tree sync \+ --report "$WORK/between.json" >/dev/null 2>&1 &+SYNC_PID=$!+request_held "$REPO/manifests/$G14.held" && BETWEEN=yes+kill -9 "$SYNC_PID" 2>/dev/null || true+wait "$SYNC_PID" 2>/dev/null || true+rm -f "$REPO/manifests/$G14.hold"++test_expect_success 'a walk stopped between two segments leaves the first applied and recorded' '+ [ "$BETWEEN" = yes ] &&+ [ ! -e "$WORK/between.json" ] &&+ [ ! -e "$PENDING" ] &&+ state_is 12 12 10 12 &&+ segments agree 12+'++test_expect_success 'the next sync walks back only to the segment not applied' '+ n=$(wc -l <"$LOG") &&+ sync_tree resumed &&+ [ "$(manifest_gets "$n" "$G12")" = 0 ] &&+ [ "$(manifest_gets "$n" "$G14")" = 2 ] &&+ [ "$(report_field applied <"$WORK/resumed.json")" = 3 ] &&+ state_is 16 16 14 16 &&+ segments agree 16+'++serve g20+PENDED=no+if hold_tree_eventlog; then+ BPM_OCI_SCHEME=http "$SHIRUDO_BIN" bpm tree sync \+ --report "$WORK/pended.json" >/dev/null 2>&1 &+ SYNC_PID=$!+ tree_op_measured 18 && PENDED=yes+ kill -9 "$SYNC_PID" 2>/dev/null || true+ wait "$SYNC_PID" 2>/dev/null || true+fi+release_tree_eventlog++test_expect_success 'a walk stopped with an operation pending leaves its segment recorded' '+ [ "$PENDED" = yes ] &&+ [ ! -e "$WORK/pended.json" ] &&+ [ -e "$PENDING" ] &&+ state_is 16 18 16 18+'++test_expect_success 'the next sync completes it from the oldest segment of its walk, once' '+ n=$(wc -l <"$LOG") &&+ sync_tree completed &&+ [ "$(manifest_gets "$n" "$G18")" = 2 ] &&+ [ ! -e "$PENDING" ] &&+ [ "$(report_field last_seq <"$WORK/completed.json")" = 20 ] &&+ state_is 20 20 18 20 &&+ segments agree 20+'++test_expect_success 'a predecessor that does not start from the node history is refused on the base check' '+ serve fork-base &&+ ! sync_tree fork-base &&+ grep -q "phase=history_base rc=-129 " "$WORK/fork-base.err" &&+ state_is 20 20 18 20 &&+ segments agree 20+'++test_expect_success 'a segment whose operations before the cursor differ is refused on the prefix check' '+ serve fork-prefix &&+ ! sync_tree fork-prefix &&+ grep -q "phase=history_prefix rc=-129 " "$WORK/fork-prefix.err" &&+ state_is 20 20 18 20 &&+ segments agree 20+'++test_expect_success 'a sealed segment the registry lost refuses the sync with nothing applied' '+ serve g24 &&+ mv "$REPO/manifests/$G22" "$WORK/sealed" &&+ n=$(wc -l <"$LOG") &&+ ! sync_tree lost &&+ mv "$WORK/sealed" "$REPO/manifests/$G22" &&+ grep -q "phase=segment_fetch rc=-2 " "$WORK/lost.err" &&+ requests_since "$n" |+ grep -q "^GET /v2/shirudo/segments/manifests/$G22 404$" &&+ state_is 20 20 18 20 &&+ segments agree 20+'++test_expect_success 'a predecessor that ends before the base of its successor is refused' '+ serve head-gap &&+ ! sync_tree head-gap &&+ grep -q "phase=segment_chain rc=-34 " "$WORK/head-gap.err" &&+ state_is 20 20 18 20+'++test_expect_success 'a running node refuses a walk past its limit before anything applies' '+ serve g28 &&+ n=$(wc -l <"$LOG") &&+ ! sync_tree walk-limit &&+ grep -q "phase=segment_walk rc=-7 " "$WORK/walk-limit.err" &&+ ! requests_since "$n" | grep -q "/manifests/sha256:" &&+ state_is 20 20 18 20 &&+ segments agree 20+'++test_expect_success 'a dry run walks and checks every segment and records nothing' '+ serve g24 &&+ BPM_OCI_SCHEME=http "$SHIRUDO_BIN" bpm tree sync --dry-run \+ --report "$WORK/dry.json" >/dev/null &&+ [ "$(report_field selected <"$WORK/dry.json")" = 3 ] &&+ [ "$(report_field skipped <"$WORK/dry.json")" = 1 ] &&+ [ "$(report_field applied <"$WORK/dry.json")" = 0 ] &&+ [ "$(report_field last_seq <"$WORK/dry.json")" = 20 ] &&+ state_is 20 20 18 20 &&+ segments agree 20+'++test_expect_success 'the node catches up with the segments the registry serves again' '+ sync_tree caught-up &&+ [ "$(report_field applied <"$WORK/caught-up.json")" = 3 ] &&+ state_is 24 24 22 24 &&+ segments agree 24+'++test_expect_success 'init mid-tree walks nothing and takes the projection root one publication gives' '+ n=$(wc -l <"$LOG") &&+ lines=$(wc -l <"$EVENTLOG") &&+ "$SHIRUDO_BIN" init >/dev/null &&+ [ "$(wc -l <"$LOG")" = "$n" ] &&+ [ "$(wc -l <"$EVENTLOG")" = "$lines" ] &&+ segments agree 24+'++test_donediff --git a/testing/functional/build/t1007-test-vm-cli.sh b/testing/functional/build/t1007-test-vm-cli.shindex 72442133..87fbb913 100755--- a/testing/functional/build/t1007-test-vm-cli.sh+++ b/testing/functional/build/t1007-test-vm-cli.sh@@ -957,7 +957,7 @@ test_expect_success 'the runners split the tests by number' '! grep -q "/t[0-9]1[0-9][0-9]-" "$WORK/operator-tests" &&families=$(make -s -C .. -f testing/Makefile help |sed -n "s/.*families: //p") &&- [ "$families" = "build signing upatch tpm image labels tamperproof bpm otel" ] &&+ [ "$families" = "build signing upatch tpm image labels tamperproof bpm bpm-segments otel" ] &&for d in functional/*/; dof=${d#functional/}case " $families " in *" ${f%/} "*) ;; *) return 1 ;; esacdiff --git a/testing/helper/test-image-cli.c b/testing/helper/test-image-cli.cindex c22b876c..b4578655 100644--- a/testing/helper/test-image-cli.c+++ b/testing/helper/test-image-cli.c@@ -15,6 +15,7 @@ int __wrap_bpm_tree_fetch_publication(struct bpm_oci_client *client,char *digest, size_t capacity){puts(certificate);+ strscpy(pub->tree_id, "t", sizeof(pub->tree_id));return 0;}@@ -81,12 +82,17 @@ int main(int argc, const char **argv)} else if (!strcmp(argv[2], "tree")) {struct tree_publication publication = {};struct bpm_tree_config config = {};+ struct tree_source source = {};char digest[BPM_MAX_DIGEST];strscpy(config.endpoint, "oci://example.invalid/tree", sizeof(config.endpoint));strscpy(config.reference, "latest", sizeof(config.reference));- ret = tree_fetch_publication(&config, &publication, digest,- sizeof(digest));+ ret = tree_source_open(&config, &source);+ if (!ret)+ ret = tree_fetch_checked(&source, config.reference,+ &publication, digest,+ sizeof(digest));+ tree_source_clear(&source);} else {ret = 2;}diff --git a/testing/helper/test-oci-registry.py b/testing/helper/test-oci-registry.pyindex faeed77c..5db64975 100644--- a/testing/helper/test-oci-registry.py+++ b/testing/helper/test-oci-registry.py@@ -14,6 +14,11 @@ and manifest puts). Files are laid out as:Every request is recorded as ``METHOD<TAB>PATH<TAB>STATUS`` when --log isprovided, so tests can assert that selectors caused only the expectedartifact requests.++A file beside a manifest or blob, named after it with ``.hold`` and+holding a number n, stops the n-th GET of it that comes while the file is+there: the fixture creates ``<name>.held`` and answers only once the hold+file is gone, so a test can stop a client at that request."""import argparse@@ -23,6 +28,8 @@ import pathlibimport reimport secretsimport sys+import threading+import timeimport urllib.parseUPLOAD_RE = re.compile(r"/v2/(.+)/blobs/uploads/?")@@ -103,6 +110,7 @@ class RegistryHandler(http.server.BaseHTTPRequestHandler):self._reply(404)returncandidate, kind = result+ self._hold(candidate)if not candidate.is_file():self._reply(404)return@@ -113,6 +121,23 @@ class RegistryHandler(http.server.BaseHTTPRequestHandler):)self._reply(200, body, content_type)+ def _hold(self, candidate):+ if self.command != "GET":+ return+ hold = candidate.with_name(candidate.name + ".hold")+ try:+ wanted = int(hold.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return+ with self.server.lock:+ count = self.server.held.get(candidate, 0) + 1+ self.server.held[candidate] = count+ if count != wanted:+ return+ candidate.with_name(candidate.name + ".held").touch()+ while hold.exists():+ time.sleep(0.05)+def do_POST(self):self._body()if not self.server.writable:@@ -189,6 +214,8 @@ def main():server.request_log = args.logserver.writable = args.writableserver.uploads = {}+ server.held = {}+ server.lock = threading.Lock()if args.ready_file is not None:args.ready_file.touch()try:diff --git a/testing/proofs/cbmc/bpm-tree-follows.c b/testing/proofs/cbmc/bpm-tree-follows.cindex 9bcc545f..4c9fc39f 100644--- a/testing/proofs/cbmc/bpm-tree-follows.c+++ b/testing/proofs/cbmc/bpm-tree-follows.c@@ -11,8 +11,10 @@* asks for a walk back exactly when such a publication starts past the* cursor, or past 0 without a state. And tree_segment_precedes(), one* step of that walk, which accepts exactly the segment the successor- * names, of its tree, ending at its base and of a lower generation.- * Strings are of up to two bytes.+ * names, of its tree, ending at its base and of a lower generation. And+ * tree_walk_within(), the limit of that walk, which allows exactly+ * TREE_MAX_JOIN_OPS operations back from 0 and TREE_MAX_WALK_OPS from any+ * other cursor. Strings are of up to two bytes.*/#include <stdbool.h>@@ -88,8 +90,26 @@ static void precedes_the_successor(void)"successor names, ending at its base");}+static void walks_within_the_limit(void)+{+ __s64 base, last;+ int ret = tree_walk_within(base, last);++ __CPROVER_assert(ret == 0 || ret == -E2BIG || ret == -EINVAL,+ "0, -E2BIG or -EINVAL");+ __CPROVER_assert((ret == -EINVAL) == (base < 0 || last < 0),+ "-EINVAL exactly for a negative number");+ __CPROVER_assert(ret == -EINVAL || !ret ==+ (base <= last ||+ (last ? base - last <= TREE_MAX_WALK_OPS :+ base <= TREE_MAX_JOIN_OPS)),+ "within the walk limit of a running node, or of one "+ "at 0 that joins");+}+void harness(void){follows_the_state();precedes_the_successor();+ walks_within_the_limit();}diff --git a/testing/proofs/cbmc/bpm-tree-signers.c b/testing/proofs/cbmc/bpm-tree-signers.cindex eab58f3f..de05bebd 100644--- a/testing/proofs/cbmc/bpm-tree-signers.c+++ b/testing/proofs/cbmc/bpm-tree-signers.c@@ -2,8 +2,9 @@/** Copyright (c) 2026 Authors of shirudo*- * Prove that tree_fetch_publication() checks the active image's signing set- * before fetching a tree, and releases the set on every path that allocates it.+ * Prove that tree_source_open() checks the active image's signing set+ * before tree_fetch_checked() fetches a tree with it, and that+ * tree_source_clear() releases the set on every path that allocates it.*/#define __NO_CTYPE 1@@ -106,21 +107,41 @@ int bpm_tree_fetch_publication(struct bpm_oci_client *c,__CPROVER_assert(set == (active ? &signing_set : NULL),"fetch receives the checked signing set");fetched = true;+ pub->tree_id[0] = 't';return fetch_fail ? -EIO : 0;}+/* The checks of the publication, which other proofs cover. */+bool bpm_package_name_ok(const char *name)+{+ return true;+}++int tree_publication_check(const struct tree_publication *pub)+{+ return 0;+}++int tree_operation_validate(const struct tree_operation *op)+{+ return 0;+}++/* xfree(NULL) releases nothing. */void xfree(void *p, size_t size){- __CPROVER_assert(!freed && size == sizeof(signing_set) &&- p == (allocated ? &signing_set : NULL),+ __CPROVER_assert(size == sizeof(signing_set) &&+ p == (allocated && !freed ? &signing_set : NULL),"the owned signing set is released once");- freed = true;+ if (p)+ freed = true;}void harness(void){struct bpm_tree_config cfg = {};struct tree_publication pub = {};+ struct tree_source src = {};struct {__u32 signers, unvouched;bool active, parse_fail, alloc_fail;@@ -141,7 +162,11 @@ void harness(void)__CPROVER_assume(n_signers <= KEYS_MAX && n_unvouched <= n_signers);cfg.endpoint[0] = 'e';cfg.reference[0] = 'f';- ret = tree_fetch_publication(&cfg, &pub, manifest, sizeof(manifest));+ ret = tree_source_open(&cfg, &src);+ if (!ret)+ ret = tree_fetch_checked(&src, cfg.reference, &pub, manifest,+ sizeof(manifest));+ tree_source_clear(&src);should_check = !parse_fail && active && !alloc_fail &&!load_fail && n_signers && !n_unvouched;@@ -153,7 +178,7 @@ void harness(void)"a valid loaded set is always checked");__CPROVER_assert(fetched == should_fetch,"fetch occurs exactly after successful preflight");- should_free = !parse_fail && (!active || !alloc_fail);+ should_free = !parse_fail && active && !alloc_fail;__CPROVER_assert(freed == should_free,"every allocated set is released");if (!should_fetch)diff --git a/testing/proofs/cbmc/bpm-tree-sync-model.c b/testing/proofs/cbmc/bpm-tree-sync-model.cindex 3ced2c08..f95d51af 100644--- a/testing/proofs/cbmc/bpm-tree-sync-model.c+++ b/testing/proofs/cbmc/bpm-tree-sync-model.c@@ -2,22 +2,25 @@/** Copyright (c) 2026 Authors of shirudo*- * cmd_bpm_tree_sync() of builtin-bpm.c, tree_recover_pending() and the loop- * over the operations included, against the run of the model that+ * cmd_bpm_tree_sync() of builtin-bpm.c, tree_recover_pending(), the walk+ * back through sealed segments, the base and prefix checks and the loop over+ * the operations included, against the run of the model that* testing/proofs/lean4/Shirudo/TreeSync.lean proves never takes a node back.* Below sync, the files and the rest of the I/O are stubs that record the* write the model names, or fail. For every state, pending record, tree* eventlog replay and record of the pending operation this boot, every- * publication of LEN operations that tree_parse() lets through, every- * selector answer and every failure, sync makes the model's writes in the- * model's order, nothing after a failure and all of them when nothing fails.- * Strings are of one byte, as sync only compares them; hashes, hex and paths- * are stubs the model does not depend on. The functions after the stubs- * restate the Lean definitions: checked() is Checked, follows() Follows,- * recover() recover and run() run, with its loop. An outcome line carries- * more here than in the Lean model: its code, 1 or 3 by what the install or- * the pins say, and the history root, a fold the sync starts from the root- * its record holds at the cursor.+ * publication of LEN operations that tree_parse() lets through, at any base,+ * with NSEG 2 a sealed segment of LEN operations the registry serves by its+ * digest too, every selector answer and every failure, sync makes the+ * model's writes in the model's order, nothing after a failure and all of+ * them when nothing fails. Strings are of one byte, as sync only compares+ * them; hashes, hex and paths are stubs the model does not depend on. The+ * functions after the stubs restate the Lean definitions: checked() is+ * Checked, follows() Follows, recover() recover, history_ok() the base and+ * prefix checks and run() run, with its walk and loop. An outcome line+ * carries more here than in the Lean model: its code, 1 or 3 by what the+ * install or the pins say, and the history root, a fold the sync starts+ * from the root its record holds at the cursor.*//* As proof.h, before the system headers can include <ctype.h>. */@@ -64,8 +67,18 @@ struct write {__u8 h[32];};-/* The cut, recovery's append, lines, state and unlink, the record, the loop. */-#define MAX_WRITES (8 + 7 * LEN)+/*+ * NSEG publications: the one the tag names, and with 2 the sealed segment+ * before it. Their operations are ops[0] to ops[LEN - 1] and, for the+ * sealed one, ops[LEN] to ops[2 * LEN - 1].+ */+#ifndef NSEG+#define NSEG 1+#endif+#define NOPS (NSEG * (LEN ? LEN : 1))++/* The cut, recovery's append, lines, state and unlink, the records, the loops. */+#define MAX_WRITES (8 + 8 * NOPS)static struct write want[MAX_WRITES];static int n_got, n_want;@@ -78,12 +91,17 @@ static struct tree_state disk_state;static struct tree_pending disk_pending;static int replay_kind; /* 0 -ENOENT, 1 -EINVAL, 2 a root */static __u8 replay_root[32];-static struct tree_operation ops[LEN ? LEN : 1];-static struct tree_publication fetched;-static char fetched_manifest[2];-static bool sel_match[LEN ? LEN : 1], sel_fail[LEN ? LEN : 1];-static __u8 disk_history[32];-static bool op_add[LEN ? LEN : 1], module_absent[LEN ? LEN : 1];+static struct tree_operation ops[NOPS];+static struct tree_publication fetched, sealed;+static char fetched_manifest[2], sealed_manifest[2];+static int fetches;+static bool sel_match[NOPS], sel_fail[NOPS];+/*+ * The history roots the record holds at the cursor and at any other seq,+ * and what an install finds.+ */+static __u8 disk_history[32], disk_other_history[32];+static bool op_add[NOPS], module_absent[NOPS];static bool pins_loaded;static int installing = -1;static __s64 measure_seq;@@ -124,7 +142,7 @@ static void record(const struct write *w)/* Which operation a pointer is into, without a division by its size. */static int op_index(const char *digest){- for (int i = 0; i < LEN; i++)+ for (int i = 0; i < NOPS; i++)if (digest == ops[i].operation_digest)return i;return -1;@@ -132,7 +150,7 @@ static int op_index(const char *digest)static int op_of(const struct tree_operation *op){- for (int i = 0; i < LEN; i++)+ for (int i = 0; i < NOPS; i++)if (op == &ops[i])return i;return -1;@@ -277,6 +295,24 @@ const char *get_cert_path(void)return "c";}+/*+ * The publication a digest of one byte names, as a registry serves it: 0 the+ * tag's, 1 the sealed segment, -1 none.+ */+static int served(char digest)+{+ if (digest == fetched_manifest[0])+ return 0;+ if (NSEG == 2 && digest == sealed_manifest[0])+ return 1;+ return -1;+}++/*+ * The first fetch is of the tag; the others name a digest, which sync+ * passes as it is or as "sha256:" and the hex of the byte the decode stub+ * takes, the one byte of a NUL-terminated hex_encode() of it.+ */int bpm_tree_fetch_publication(struct bpm_oci_client *c,const char *repository, const char *reference,const char *cert_path,@@ -284,9 +320,29 @@ int bpm_tree_fetch_publication(struct bpm_oci_client *c,struct tree_publication *pub,char *manifest_digest, size_t digest_sz){- *pub = fetched;- copy_short(manifest_digest, fetched_manifest);- return fail_here() ? -EIO : 0;+ int s = 0;++ if (fail_here())+ return -EIO;+ if (fetches++)+ s = served(strncmp(reference, "sha256:", 7) ? reference[0] :+ reference[7]);+ if (s < 0)+ return -ENOENT;+ *pub = s ? sealed : fetched;+ copy_short(manifest_digest, s ? sealed_manifest : fetched_manifest);+ return 0;+}++static struct tree_segment walk_store[8];++void *xreallocarray(void *ptr, size_t old_nmemb, size_t new_nmemb,+ size_t size)+{+ __CPROVER_assert(size == sizeof(struct tree_segment) && new_nmemb <= 8 &&+ (!ptr || ptr == walk_store),+ "only the walk's descriptors are reallocated");+ return fail_here() ? NULL : walk_store;}bool bpm_package_name_ok(const char *s)@@ -398,10 +454,26 @@ int tree_outcomes_resume(__s64 last_seq, __u8 history_root[32])if (fail_here())return -EBADMSG;record(&w);- memcpy(history_root, disk_history, 32);+ if (last_seq)+ memcpy(history_root, disk_history, 32);return 0;}+int tree_outcomes_read(__s64 from, __s64 to, __u8 *codes,+ __u8 projection_root[32], __u8 history_root[32])+{+ __s64 cursor = have_state ? disk_state.last_seq : 0;++ __CPROVER_assert(from == to && !codes,+ "the roots at one seq are what sync reads");+ if (!from)+ memset(history_root, 0, 32);+ else+ memcpy(history_root, from == cursor ? disk_history :+ disk_other_history, 32);+ return fail_here() ? -EIO : 0;+}+int chain_history_step(const __u8 prev[32], const __u8 operation_digest[32],__u8 out[32]){@@ -453,7 +525,7 @@ int tree_selector_matches(const struct tree_selector *selector){int i = -1;- for (int k = 0; k < LEN; k++)+ for (int k = 0; k < NOPS; k++)if (selector == &ops[k].selector)i = k;__CPROVER_assert(i >= 0, "the selector of an operation");@@ -526,9 +598,9 @@ int upatch_install(const char *path){int ret;- __CPROVER_assert(installing >= 0 && installing < LEN,+ __CPROVER_assert(installing >= 0 && installing < NOPS,"an install follows its pending record");- if (installing >= 0 && installing < LEN && module_absent[installing])+ if (installing >= 0 && installing < NOPS && module_absent[installing])return UPATCH_INSTALL_TARGET_MISSING;__CPROVER_assume(ret == 0 || ret == 1 || ret == -EIO);if (ret)@@ -755,36 +827,108 @@ static bool same_write(const struct write *a, int index)}/*- * Checked, and the first segment naming no predecessor, which Checked- * leaves out as it does the digests: the sync refuses every later one.+ * Checked: the numbers of tree_publication_check() and the base keys,+ * present past base 0 and absent at it. Their form is the decode stubs',+ * which accept any; the generation tree_parse() keeps from 0.*/-static bool checked(void)+static bool checked_pub(const struct tree_publication *p){- if (fetched.generation < 0 || fetched.base_seq != 0 ||- fetched.segment_manifest_digest[0] || fetched.history_root[0] ||- fetched.head_seq != fetched.n_operations)+ int n = p->n_operations;++ if (p->generation < 0 || p->base_seq < 0)return false;- for (int i = 0; i < fetched.n_operations; i++)- if (ops[i].seq != 1 + i)- return false;- return true;+ if (!p->base_seq && (p->segment_manifest_digest[0] ||+ p->history_root[0]))+ return false;+ if (p->base_seq && !n)+ return false;+ if (n && (p->operations[0].seq != p->base_seq + 1 ||+ p->head_seq != p->operations[n - 1].seq))+ return false;+ return n || p->head_seq == p->base_seq;}-static bool follows(const struct mstate *s)+static bool checked(void)+{+ return checked_pub(&fetched);+}++/*+ * tree_publication_follows(): -1 for a refusal, 0 when the publication+ * follows the state, Follows, and 1 for a walk back to its base.+ */+static int follows_pub(const struct tree_publication *p, const char *m,+ const struct mstate *s){bool same;if (!s)- return fetched.base_seq == 0;- same = !strcmp(s->manifest, fetched_manifest);- return !strcmp(s->tree_id, fetched.tree_id) &&- (same || s->generation < fetched.generation) &&- (same || !(s->generation < fetched.generation &&- fetched.generation - 1 == s->generation) ||- !fetched.parent_manifest_digest[0] ||- !strcmp(fetched.parent_manifest_digest, s->manifest)) &&- fetched.base_seq <= s->last_seq &&- s->last_seq <= fetched.head_seq;+ return p->base_seq ? 1 : 0;+ same = !strcmp(s->manifest, m);+ if (strcmp(s->tree_id, p->tree_id) ||+ (!same && p->generation <= s->generation) ||+ (!same && p->generation - 1 == s->generation &&+ p->parent_manifest_digest[0] &&+ strcmp(p->parent_manifest_digest, s->manifest)) ||+ p->head_seq < s->last_seq)+ return -1;+ return p->base_seq > s->last_seq ? 1 : 0;+}++static bool follows(const struct mstate *s)+{+ return follows_pub(&fetched, fetched_manifest, s) == 0;+}++/* tree_walk_within() with the limits of util/bpm_tree.h. */+static bool within(__s64 base, __s64 last)+{+ return base >= 0 && last >= 0 &&+ base - last <= (last ? TREE_MAX_WALK_OPS : TREE_MAX_JOIN_OPS);+}++/* tree_segment_precedes() of the publication the walk fetched. */+static bool precedes(const struct tree_publication *pred, const char *m,+ const struct tree_publication *succ)+{+ return succ->base_seq > 0 &&+ !strcmp(succ->segment_manifest_digest, m) &&+ !strcmp(pred->tree_id, succ->tree_id) &&+ pred->head_seq == succ->base_seq &&+ pred->generation < succ->generation;+}++/*+ * The base check and the prefix check: the node's history root at the+ * segment's base, the one sync holds when the base is its cursor and the+ * record's otherwise, is the segment's, and the segment's operations up to+ * the cursor fold from it to the one sync holds.+ */+static bool history_ok(const struct tree_publication *p,+ const struct mstate *st)+{+ __u8 node[32], doc[32], d[32];++ if (p->base_seq == st->last_seq)+ memcpy(node, st->hist, 32);+ else if (!p->base_seq)+ memset(node, 0, 32);+ else+ memcpy(node, p->base_seq == (have_state ? disk_state.last_seq : 0) ?+ disk_history : disk_other_history, 32);+ memset(doc, 0, 32);+ if (p->base_seq)+ for (int i = 0; i < 32; i++)+ doc[i] = (__u8)p->history_root[i];+ if (memcmp(node, doc, 32))+ return false;+ for (int i = 0; i < p->n_operations; i++) {+ if (p->operations[i].seq > st->last_seq)+ break;+ digest_of(p->operations[i].operation_digest, d);+ model_history(doc, d, doc);+ }+ return !memcmp(doc, st->hist, 32);}/*@@ -792,20 +936,23 @@ static bool follows(const struct mstate *s)* is in the tree eventlog: a line for each operation the stopped sync passed* over, the operation's own, the state and the unlink.*/-static void want_recovered(struct mstate *st, const struct tree_operation *o,- const __u8 *d, const __u8 *next)+static void want_recovered(struct mstate *st, const struct tree_publication *p,+ const struct tree_operation *o, const __u8 *d,+ const __u8 *next){int index = op_of(o);__u8 passed[32];- for (int i = 0; i < fetched.n_operations; i++) {- if (ops[i].seq >= o->seq)+ for (int i = 0; i < p->n_operations; i++) {+ const struct tree_operation *q = &p->operations[i];++ if (q->seq >= o->seq)break;- if (ops[i].seq <= st->last_seq)+ if (q->seq <= st->last_seq)continue;- digest_of(ops[i].operation_digest, passed);+ digest_of(q->operation_digest, passed);model_history(st->hist, passed, st->hist);- want_outcome(ops[i].seq, TREE_OUTCOME_UNMATCHED, st->root,+ want_outcome(q->seq, TREE_OUTCOME_UNMATCHED, st->root,st->hist);}model_history(st->hist, d, st->hist);@@ -819,19 +966,21 @@ static void want_recovered(struct mstate *st, const struct tree_operation *o,}/* false for a refusal before it writes anything. */-static bool recover(struct mstate *st)+static bool recover_in(struct mstate *st, const struct tree_publication *p){const struct tree_operation *o = NULL;__u8 d[32], next[32];if (!have_pending)return true;- for (int i = 0; i < fetched.n_operations; i++) {- if (ops[i].seq == disk_pending.seq &&- !strcmp(ops[i].id, disk_pending.id) &&- !strcmp(ops[i].operation_digest,+ for (int i = 0; i < p->n_operations; i++) {+ const struct tree_operation *q = &p->operations[i];++ if (q->seq == disk_pending.seq &&+ !strcmp(q->id, disk_pending.id) &&+ !strcmp(q->operation_digest,disk_pending.operation_digest)) {- o = &ops[i];+ o = q;break;}}@@ -846,7 +995,7 @@ static bool recover(struct mstate *st)if (replay_kind == 1)return false;if (replay_kind == 2 && !memcmp(replay_root, next, 32)) {- want_recovered(st, o, d, next);+ want_recovered(st, p, o, d, next);return true;}if (replay_kind == 2 && memcmp(replay_root, st->root, 32))@@ -854,14 +1003,57 @@ static bool recover(struct mstate *st)if (!measured)return true;want_write(W_APPEND, op_of(o), o->seq, next, NULL);- want_recovered(st, o, d, next);+ want_recovered(st, p, o, d, next);return true;}+static bool recover(struct mstate *st)+{+ return recover_in(st, &fetched);+}++/* The loop over one publication's operations. */+static void loop(struct mstate *st, const struct tree_publication *p)+{+ __u8 d[32];++ for (int i = 0; i < p->n_operations; i++) {+ const struct tree_operation *o = &p->operations[i];+ int k = op_of(o);++ if (o->seq <= st->last_seq)+ continue;+ digest_of(o->operation_digest, d);+ if (!sel_match[k]) {+ model_history(st->hist, d, st->hist);+ want_outcome(o->seq, TREE_OUTCOME_UNMATCHED, st->root,+ st->hist);+ st->last_seq = o->seq;+ continue;+ }+ want_write(W_PENDING, k, 0, NULL, NULL);+ want_write(W_MEASURE, k, o->seq, d, NULL);+ model_hash(st->root, d, st->root);+ want_write(W_APPEND, k, o->seq, st->root, NULL);+ model_history(st->hist, d, st->hist);+ want_outcome(o->seq, op_add[k] && module_absent[k] ?+ TREE_OUTCOME_MODULE_ABSENT : TREE_OUTCOME_APPLIED,+ st->root, st->hist);+ st->last_seq = o->seq;+ want_write(W_STATE, 0, 0, NULL, st);+ want_write(W_UNLINK, 0, 0, NULL, NULL);+ }+}+static void run(void){+ const struct tree_publication *walk[NSEG + 1];+ const char *names[NSEG + 1];+ const struct tree_publication *succ = &fetched;+ bool have = have_state;struct mstate st;- __u8 d[32];+ __s64 cursor;+ int n = 0;/* The node's state, or the fresh one sync starts from without it. */st.tree_id[0] = have_state ? disk_state.tree_id[0] : fetched.tree_id[0];@@ -874,39 +1066,51 @@ static void run(void)st.manifest[1] = '\0';st.head_seq = have_state ? disk_state.head_seq : 0;st.base_seq = have_state ? disk_state.segment_base_seq : 0;- memcpy(st.hist, disk_history, 32);- if (!checked() || !follows(have_state ? &st : NULL))+ if (st.last_seq)+ memcpy(st.hist, disk_history, 32);+ else+ memset(st.hist, 0, 32);+ if (!checked() ||+ follows_pub(&fetched, fetched_manifest, have ? &st : NULL) < 0)return;want_write(W_TRUNCATE, 0, st.last_seq, NULL, NULL);- if (!recover(&st))- return;- st.generation = fetched.generation;- copy_short(st.manifest, fetched_manifest);- st.head_seq = fetched.head_seq;- st.base_seq = fetched.base_seq;- want_write(W_STATE, 0, 0, NULL, &st);- for (int i = 0; i < fetched.n_operations; i++) {- if (ops[i].seq <= st.last_seq)- continue;- digest_of(ops[i].operation_digest, d);- if (!sel_match[i]) {- model_history(st.hist, d, st.hist);- want_outcome(ops[i].seq, TREE_OUTCOME_UNMATCHED,- st.root, st.hist);- st.last_seq = ops[i].seq;- continue;- }- want_write(W_PENDING, i, 0, NULL, NULL);- want_write(W_MEASURE, i, ops[i].seq, d, NULL);- model_hash(st.root, d, st.root);- want_write(W_APPEND, i, ops[i].seq, st.root, NULL);- model_history(st.hist, d, st.hist);- want_outcome(ops[i].seq, op_add[i] && module_absent[i] ?- TREE_OUTCOME_MODULE_ABSENT : TREE_OUTCOME_APPLIED,- st.root, st.hist);- st.last_seq = ops[i].seq;+ /* Back to the segment the cursor lies in. */+ cursor = st.last_seq;+ walk[n] = &fetched;+ names[n++] = fetched_manifest;+ while (succ->base_seq > cursor) {+ int s;++ if (!within(succ->base_seq, cursor))+ return;+ s = served(succ->segment_manifest_digest[0]);+ if (s < 0)+ return;+ if (!checked_pub(s ? &sealed : &fetched) ||+ !precedes(s ? &sealed : &fetched,+ s ? sealed_manifest : fetched_manifest, succ))+ return;+ __CPROVER_assert(n <= NSEG, "a walk passes each segment once");+ walk[n] = s ? &sealed : &fetched;+ names[n++] = s ? sealed_manifest : fetched_manifest;+ succ = walk[n - 1];+ }+ /* Forwards, the oldest first. */+ for (int k = n - 1; k >= 0; k--) {+ const struct tree_publication *p = walk[k];++ if (follows_pub(p, names[k], have ? &st : NULL) ||+ !history_ok(p, &st))+ return;+ if (k == n - 1 && !recover_in(&st, p))+ return;+ st.generation = p->generation;+ copy_short(st.manifest, names[k]);+ st.head_seq = p->head_seq;+ st.base_seq = p->base_seq;+ have = true;want_write(W_STATE, 0, 0, NULL, &st);- want_write(W_UNLINK, 0, 0, NULL, NULL);+ loop(&st, p);}want_write(W_STATE, 0, 0, NULL, &st);}@@ -925,12 +1129,15 @@ static void any_name(char *s, bool may_be_empty)s[1] = '\0';}-/* What tree_parse() lets through, which the fetch stub stands for. */-static void any_publication(void)+/*+ * What tree_parse() lets through, which the fetch stub stands for: the+ * publication of the operations from first on, and its manifest digest.+ */+static void any_one(struct tree_publication *out, int first, char *manifest){struct tree_publication pub;- pub.operations = ops;+ pub.operations = &ops[first];pub.operations_capacity = 0;pub.n_operations = LEN;any_name(pub.tree_id, false);@@ -940,13 +1147,13 @@ static void any_publication(void)__CPROVER_assume(pub.generation >= 0 && pub.generation != INT64_MAX &&pub.base_seq >= 0 && pub.head_seq >= pub.base_seq &&pub.head_seq != INT64_MAX);- fetched = pub;- for (int i = 0; i < LEN; i++) {+ *out = pub;+ for (int i = first; i < first + LEN; i++) {struct tree_operation *o = &ops[i];bool add, match, fail, absent;__s64 seq;- __CPROVER_assume(seq > 0 && (!i || seq - 1 == ops[i - 1].seq));+ __CPROVER_assume(seq > 0 && (i == first || seq - 1 == ops[i - 1].seq));o->seq = seq;any_name(o->id, false);any_name(o->operation_digest, false);@@ -960,7 +1167,15 @@ static void any_publication(void)op_add[i] = add;module_absent[i] = absent;}- any_name(fetched_manifest, false);+ any_name(manifest, false);+}++static void any_publication(void)+{+ any_one(&fetched, 0, fetched_manifest);+#if NSEG == 2+ any_one(&sealed, LEN, sealed_manifest);+#endif}/*@@ -985,10 +1200,11 @@ static void any_node(void)disk_state.head_seq = state_there ? head_seq : 0;disk_state.segment_base_seq = state_there ? base_seq : 0;for (int i = 0; i < 32; i++) {- __u8 b, h;+ __u8 b, h, o;disk_state.projection_root[i] = state_there ? (char)b : '\0';disk_history[i] = h;+ disk_other_history[i] = o;}__CPROVER_assume(seq > 0 && id && digest);disk_pending.seq = pending_there ? seq : 0;diff --git a/testing/proofs/cbmc/bpm-tree-sync-walk.c b/testing/proofs/cbmc/bpm-tree-sync-walk.cnew file mode 100644index 00000000..83ee4361--- /dev/null+++ b/testing/proofs/cbmc/bpm-tree-sync-walk.c@@ -0,0 +1,6 @@+// SPDX-License-Identifier: BSD-2-Clause+/* Copyright (c) 2026 Authors of shirudo */++/* Check a walk back through a sealed segment and the two applied in order. */+#define NSEG 2+#include "bpm-tree-sync-model.c"diff --git a/testing/proofs/cbmc/proofs.list b/testing/proofs/cbmc/proofs.listindex 979e6734..6ce57fde 100644--- a/testing/proofs/cbmc/proofs.list+++ b/testing/proofs/cbmc/proofs.list@@ -26,10 +26,11 @@ upatch-rodata -I ../../../vendor/libbpf/include/uapi -I ../../../vendor/libbpfstring-number-model --unwind 6measured-fold-model --unwind 7bpm-tree-follows --unwind 4-bpm-tree-sync-model --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,model_history.0:33,want_outcome.0:33,want_outcome.1:33,same_history.0:33,any_node.0:33,run.0:33,same_digest.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66 --max-field-sensitivity-array-size 257 --slice-formula LEN=0-1-bpm-tree-sync-application --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,model_history.0:33,want_outcome.0:33,want_outcome.1:33,same_history.0:33,any_node.0:33,run.0:33,same_digest.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66 --max-field-sensitivity-array-size 257 --slice-formula LEN=2-bpm-tree-sync-pending --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,model_history.0:33,want_outcome.0:33,want_outcome.1:33,same_history.0:33,any_node.0:33,run.0:33,same_digest.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66 --max-field-sensitivity-array-size 257 --slice-formula LEN=2-bpm-tree-recovery-model --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,model_history.0:33,want_outcome.0:33,want_outcome.1:33,same_history.0:33,any_node.0:33,same_digest.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66,recovery_start.0:33,recovery_state_matches.0:33 --max-field-sensitivity-array-size 257 --slice-formula LEN=0-2+bpm-tree-sync-model --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,model_history.0:33,want_outcome.0:33,want_outcome.1:33,same_history.0:33,any_node.0:33,run.0:33,same_digest.0:33,history_ok.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66 --max-field-sensitivity-array-size 257 --slice-formula LEN=0-1+bpm-tree-sync-application --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,model_history.0:33,want_outcome.0:33,want_outcome.1:33,same_history.0:33,any_node.0:33,run.0:33,same_digest.0:33,history_ok.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66 --max-field-sensitivity-array-size 257 --slice-formula LEN=2+bpm-tree-sync-pending --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,model_history.0:33,want_outcome.0:33,want_outcome.1:33,same_history.0:33,any_node.0:33,run.0:33,same_digest.0:33,history_ok.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66 --max-field-sensitivity-array-size 257 --slice-formula LEN=2+bpm-tree-sync-walk --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,model_history.0:33,want_outcome.0:33,want_outcome.1:33,same_history.0:33,any_node.0:33,run.0:33,same_digest.0:33,history_ok.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66 --max-field-sensitivity-array-size 257 --slice-formula LEN=1+bpm-tree-recovery-model --object-bits 10 --unwind 8 --unwindset memcmp.0:33,memneq_explicit.0:33,hex_encode.0:33,hex_decode.0:33,model_hash.0:33,model_history.0:33,want_outcome.0:33,want_outcome.1:33,same_history.0:33,any_node.0:33,same_digest.0:33,history_ok.0:33,want_write.0:33,want_write.1:33,strcmp.0:66,strlen.0:66,recovery_start.0:33,recovery_state_matches.0:33 --max-field-sensitivity-array-size 257 --slice-formula LEN=0-2bpm-tree-signers --unwind 8bpm-upatch-member --unwind 30 LEN=0-18tpm-reader --unwind 1diff --git a/testing/proofs/lean4/Shirudo/TreeSync.lean b/testing/proofs/lean4/Shirudo/TreeSync.leanindex 253a3bb7..7e6100a5 100644--- a/testing/proofs/lean4/Shirudo/TreeSync.lean+++ b/testing/proofs/lean4/Shirudo/TreeSync.lean@@ -76,10 +76,27 @@ applies it again, and that goes on to measure it: `upatch_install()` takesthe payload already loaded under the name as installed, and`upatch_remove()` an upatch already gone as removed.testing/proofs/cbmc/bpm-tree-follows.c proves-`tree_publication_follows()` returns 0 exactly when `Follows` holds, the-sync refusing the walk it asks for otherwise, and bpm-tree-sync-model.c checks-the writes of `cmd_bpm_tree_sync()` against `run` for publications of up to-two operations.+`tree_publication_follows()` returns 0 exactly when `Follows` holds and asks+for a walk exactly when the publication starts past the cursor, and+bpm-tree-sync-model.c checks the writes of `cmd_bpm_tree_sync()` against+`run` for publications of up to two operations, and through a walk back+over one sealed segment.++A publication that starts past the cursor is a segment the node reaches by+walking back through the sealed segments before it. The sync then takes+the segments oldest first, each recorded at acceptance and its operations+applied, as `run` takes one publication: the oldest segment with the cut+of the outcomes record and recovery, and each later one, which starts at+the cursor the one before left, with neither, as the cut keeps every line+and nothing is pending between two segments. A sync that walks is+therefore a sync of each segment in turn, with one write fewer: the state+`run` writes at the end of a segment, which the next segment's record at+acceptance overwrites with the same cursor and root. Every node such a+sync leaves is one a `Steps` history of single syncs leaves, so every+theorem here holds across segment boundaries too. The base check and the+prefix check+of the walk only refuse more; the model leaves them out, as it does the+digest checks.-/namespace Shirudo.TreeSync@@ -110,7 +127,8 @@ structure Pub (T M I D : Type) where/-- `struct tree_state`: `root` is `projection_root`, which sync writes into`projection_root_tpm` too, `manifest` is `none` for an empty`manifest_digest`, and `headSeq` is `head_seq`, the head of the recorded-publication. `segment_base_seq` is 0 with `Checked` and is left out. -/+publication. `segment_base_seq` is left out: no write of the model depends+on it. -/structure State (T M D : Type) wheretreeId : Tgeneration : Int@@ -188,10 +206,12 @@ def cursor (n : Node T M I D) : Int :=/-! ### The checks before anything is applied -//-- What `tree_parse()` and `tree_publication_check()` require of a-publication's numbers: a generation of 0 or more, a base of 0, and-operations numbered from base + 1 to head without a gap. -/+publication's numbers: a generation of 0 or more, a base of 0 or more, and+operations numbered from base + 1 to head without a gap. A segment past+the first, base above 0, is one of these too; the keys that name its+sealed predecessor and its history root are left out with the digests. -/def Checked (pub : Pub T M I D) : Prop :=- 0 ≤ pub.generation ∧ pub.baseSeq = 0 ∧+ 0 ≤ pub.generation ∧ 0 ≤ pub.baseSeq ∧pub.headSeq = pub.baseSeq + pub.ops.length ∧pub.ops.map (·.seq) =(List.range pub.ops.length).map@@ -202,8 +222,9 @@ instance (pub : Pub T M I D) : Decidable (Checked pub) := by/-- What the sync takes of `tree_publication_follows()`, a return of 0,as `bpm-tree-follows.c` states it and proves the C meets for every-`__s64`; it refuses the walk the function asks for past the cursor.-Without a state, a base of 0; with+`__s64`. A publication that starts past the cursor, for which the function+asks for a walk, is applied as the segments of the walk, each of which+returns 0 in its turn; see `run`. Without a state, a base of 0; withone, the same tree, a later generation unless it is the same manifest, therecorded manifest as parent when it is the next generation and names one,and the cursor between base and head. -/@@ -2061,10 +2082,23 @@ theorem consec_of_range : ∀ (os : List (Op I D)) (a : Int),/-- What `Checked` says of a publication's numbers, as the loops readthem. -/theorem consec_of_checked {pub : Pub T M I D} (h : Checked pub) :- Consec 0 pub.ops ∧ (pub.ops.length : Int) = pub.headSeq := by- obtain ⟨-, hb, hh, hm⟩ := h- rw [hb] at hm hh- exact ⟨consec_of_range pub.ops 0 hm, by omega⟩+ Consec pub.baseSeq pub.ops ∧+ pub.baseSeq + (pub.ops.length : Int) = pub.headSeq := by+ obtain ⟨-, -, hh, hm⟩ := h+ exact ⟨consec_of_range pub.ops pub.baseSeq hm, by omega⟩++/-- A publication that follows the node starts at or before its cursor. -/+theorem base_le_cursor [DecidableEq T] [DecidableEq M] {pub : Pub T M I D}+ {n : Node T M I D} {m : M} (h : Follows pub n.state m) :+ pub.baseSeq ≤ cursor n := by+ cases hs : n.state with+ | none =>+ simp only [hs, Follows] at h+ simp [cursor, hs, h]+ | some s =>+ simp only [hs, Follows] at h+ simp only [cursor, hs]+ exact h.2.2.2.1theorem consec_mem {o : Op I D} : ∀ (os : List (Op I D)) (a : Int),Consec a os → o ∈ os → a < o.seq ∧ o.seq ≤ a + (os.length : Int)@@ -2435,7 +2469,9 @@ record and the head go, stopped after any of its writes: the lines continuethe record to the operation's number before the state that covers them. -/theorem ocomplete_inv {H : D → D → D} {pub : Pub T M I D} {n : Node T M I D}{st0 st : State T M D} {p : Op I D} (hx : Exact n (cursor n)) (ho : OInv n)- (hcs : Consec 0 pub.ops) (hlen : (pub.ops.length : Int) = pub.headSeq)+ (hcs : Consec pub.baseSeq pub.ops)+ (hlen : pub.baseSeq + (pub.ops.length : Int) = pub.headSeq)+ (hbc : pub.baseSeq ≤ cursor n)(hst0 : st0.lastSeq = cursor n) (hlt : cursor n < p.seq)(hph : p.seq ≤ pub.headSeq) (hl : st.lastSeq = p.seq)(hh : ∀ s, n.state = some s → st.headSeq = s.headSeq)@@ -2450,8 +2486,9 @@ theorem ocomplete_inv {H : D → D → D} {pub : Pub T M I D} {n : Node T M I D}obtain ⟨c, hc, he⟩ := hxobtain ⟨s1, hs1, hps⟩ := ho.pend p hpnhave hhs := hh s1 hs1- obtain ⟨c', hc', hext⟩ := passed_ext st0.lastSeq p.seq st0.root pub.ops 0 c- hcs (by omega) (by omega) (Or.inr (by omega)) (by omega) (by omega)+ obtain ⟨c', hc', hext⟩ := passed_ext st0.lastSeq p.seq st0.root pub.ops+ pub.baseSeq c hcs (by omega) (by omega) (Or.inr (by omega)) (by omega)+ (by omega)obtain ⟨hal, hoL, heq⟩ := along_olines(passed st0.lastSeq p.seq st0.root pub.ops ++[(⟨p.seq, true, H st0.root p.digest⟩ : OLine D)]) n ho hlenx@@ -2522,8 +2559,9 @@ loop goes on from a record that holds exactly the lines up to its cursor,and an operation still pending is one of the publication. -/theorem orecover_inv {H : D → D → D} {pub : Pub T M I D} {n : Node T M I D}{st0 st : State T M D} {ws : List (Write T M I D)}- (hx : Exact n (cursor n)) (ho : OInv n) (hcs : Consec 0 pub.ops)- (hlen : (pub.ops.length : Int) = pub.headSeq)+ (hx : Exact n (cursor n)) (ho : OInv n) (hcs : Consec pub.baseSeq pub.ops)+ (hlen : pub.baseSeq + (pub.ops.length : Int) = pub.headSeq)+ (hbc : pub.baseSeq ≤ cursor n)(hst0 : st0.lastSeq = cursor n) (hcur : cursor n ≤ pub.headSeq)(hfound : ∀ p, n.pending = some p → ∃ o ∈ pub.ops, o.seq = p.seq)(hspec : RecoverSpec n (recLines H pub st0) ws st) :@@ -2540,7 +2578,7 @@ theorem orecover_inv {H : D → D → D} {pub : Pub T M I D} {n : Node T M I D}| some p =>simp only [RecoverSpec, hp] at hspecobtain ⟨o, hom, hop⟩ := hfound p hp- have hoh := (consec_mem pub.ops 0 hcs hom).2+ have hoh := (consec_mem pub.ops pub.baseSeq hcs hom).2have hph : p.seq ≤ pub.headSeq := by omegarcases hspec with ⟨-, rfl, hl⟩ | ⟨-, -, -, rfl, hl⟩ |⟨hlt, -, -, ⟨r, rfl⟩, hl, hh⟩ | ⟨hlt, -, rfl, hl, hh⟩@@ -2562,11 +2600,11 @@ theorem orecover_inv {H : D → D → D} {pub : Pub T M I D} {n : Node T M I D}ho.inert rfl rfl ho.pendobtain ⟨ha, hxe, hcu, hoi, hpe⟩ := ocomplete_inv (H := H) (pub := pub)(n := (Write.append ⟨p.seq, p.digest, r⟩ : Write T M I D).apply n)- (st0 := st0) (st := st) hx h1 hcs hlen hst0 hlt hph hl hh hp+ (st0 := st0) (st := st) hx h1 hcs hlen hbc hst0 hlt hph hl hh hpexact ⟨along_cons ho (OMono.inert rfl rfl) ha, hxe, hcu, by omega, hoi,hpe⟩· obtain ⟨ha, hxe, hcu, hoi, hpe⟩ := ocomplete_inv (H := H) (pub := pub)- (st0 := st0) (st := st) hx ho hcs hlen hst0 hlt hph hl hh hp+ (st0 := st0) (st := st) hx ho hcs hlen hbc hst0 hlt hph hl hh hpexact ⟨ha, hxe, hcu, by omega, hoi, hpe⟩/-- A whole sync, as far as the outcomes record and the head go, stopped@@ -2582,6 +2620,8 @@ theorem orun_inv [DecidableEq T] [DecidableEq M] [DecidableEq I]· rename_i hcobtain ⟨hchk, hfol⟩ := hcobtain ⟨hcs, hlen⟩ := consec_of_checked hchk+ have hbc := base_le_cursor hfol+ have hb0 := hchk.2.1have hsm : Same n ((Write.truncate (cursor n).toNat).apply n) :=⟨rfl, rfl, rfl, rfl⟩have hinv0 := Inv.of_same hsm hinv@@ -2627,10 +2667,15 @@ theorem orun_inv [DecidableEq T] [DecidableEq M] [DecidableEq I]obtain ⟨-, -, hspec⟩ := recover_inv H init ha.binds ha.hash_injha.hash_init hinv0 hchk hfol hsig hrec0have hst0 := (start_facts H init ha.binds hinv0 hchk hfol hsig).2.1- obtain ⟨haw, hxw, hcw, hbw, how, hpw⟩ := orecover_inv hx0 ho0 hcs hlen hst0- hcur (fun p hp => recover_found hrec0 hp) hspec- have hnn : 0 ≤ st.lastSeq := by- obtain ⟨cw, hcw', -⟩ := hxw+ obtain ⟨haw, hxw, hcw, hbw, how, hpw⟩ := orecover_inv hx0 ho0 hcs hlen+ hbc hst0 hcur (fun p hp => recover_found hrec0 hp) hspec+ have hnn : pub.baseSeq ≤ st.lastSeq := by+ have hm := along_between OMono.refl (fun _ _ _ => OMono.trans) haw 0+ ws.length (Nat.zero_le _)+ simp only [List.take_zero, applyAll_nil, List.take_length] at hm+ have hm1 := hm.1+ have : cursor ((Write.truncate (cursor n).toNat).apply n) = cursor n :=+ rflomegahave hoA : OInv ((Write.state ⟨st.treeId, pub.generation, st.lastSeq,st.root, some m, pub.headSeq⟩).apply@@ -2660,7 +2705,7 @@ theorem orun_inv [DecidableEq T] [DecidableEq M] [DecidableEq I]pub.headSeq⟩, rfl, rfl⟩, hoA⟩obtain ⟨hl, hr'⟩ := oloop_inv (H := H) sel pub.ops _⟨st.treeId, pub.generation, st.lastSeq, st.root, some m, pub.headSeq⟩- 0 hcs hnn (by omega) hrA+ pub.baseSeq hcs hnn (by omega) hrArefine along_append (along_append(along_append haw (along_one how hmA hoA)) ?_) ?_· rw [applyAll_append]diff --git a/testing/unit/bpm_tree.c b/testing/unit/bpm_tree.cindex 89ecd6f2..fa7a88f7 100644--- a/testing/unit/bpm_tree.c+++ b/testing/unit/bpm_tree.c@@ -7,6 +7,9 @@#include <shirudo/string.h>#include "bpm_tree.h"+#include "chain.h"+#include "crypto.h"+#include "hex.h"#include "json.h"#include "malloc.h"#include "unit.h"@@ -464,6 +467,79 @@ static void segment_precedes_its_successor(void)EXPECT_EQ(tree_segment_precedes(&pred, "", &succ), -ERANGE);}+/*+ * A joining node may walk further back than one that holds upatches of the+ * tree, and neither past its limit.+ */+static void walk_stays_within_its_limit(void)+{+ EXPECT_EQ(tree_walk_within(0, 0), 0);+ EXPECT_EQ(tree_walk_within(TREE_MAX_JOIN_OPS, 0), 0);+ EXPECT_EQ(tree_walk_within((__s64)TREE_MAX_JOIN_OPS + 1, 0), -E2BIG);+ EXPECT_EQ(tree_walk_within(1 + TREE_MAX_WALK_OPS, 1), 0);+ EXPECT_EQ(tree_walk_within(2 + TREE_MAX_WALK_OPS, 1), -E2BIG);+ EXPECT_EQ(tree_walk_within(INT64_MAX, 1), -E2BIG);+ EXPECT_EQ(tree_walk_within(3, 7), 0);+ EXPECT_EQ(tree_walk_within(-1, 0), -EINVAL);+ EXPECT_EQ(tree_walk_within(INT64_MAX, -1), -EINVAL);+}++/* The history root at any seq of a segment, folded from its base. */+static void history_folds_from_the_base(void)+{+ struct tree_publication pub = { .base_seq = 4, .head_seq = 6 };+ struct tree_operation *ops = xcalloc(2, sizeof(*ops));+ __u8 base[32], one[32], two[32], digest[32], out[32];++ ASSERT_TRUE(ops);+ pub.operations = ops;+ pub.n_operations = 2;+ ops[0].seq = 5;+ ops[1].seq = 6;+ set(ops[0].operation_digest, sizeof(ops[0].operation_digest), DIGEST);+ set(ops[1].operation_digest, sizeof(ops[1].operation_digest), SEALED);+ set(pub.history_root, sizeof(pub.history_root), ROOT);+ ASSERT_EQ(hex_decode(ROOT, base, sizeof(base)), 0);+ ASSERT_EQ(sha256_digest_decode(DIGEST, digest), 0);+ ASSERT_EQ(chain_history_step(base, digest, one), 0);+ ASSERT_EQ(sha256_digest_decode(SEALED, digest), 0);+ ASSERT_EQ(chain_history_step(one, digest, two), 0);++ EXPECT_EQ(tree_history_at(&pub, 4, out), 0);+ EXPECT_EQ(memcmp(out, base, 32), 0);+ EXPECT_EQ(tree_history_at(&pub, 5, out), 0);+ EXPECT_EQ(memcmp(out, one, 32), 0);+ EXPECT_EQ(tree_history_at(&pub, 6, out), 0);+ EXPECT_EQ(memcmp(out, two, 32), 0);+ EXPECT_EQ(tree_history_at(&pub, 3, out), -EINVAL);+ EXPECT_EQ(tree_history_at(&pub, 7, out), -EINVAL);++ /* The first segment starts from 32 zero bytes, whatever it holds. */+ pub.base_seq = 0;+ ops[0].seq = 1;+ ops[1].seq = 2;+ pub.head_seq = 2;+ memset(base, 0, sizeof(base));+ EXPECT_EQ(tree_history_at(&pub, 0, out), 0);+ EXPECT_EQ(memcmp(out, base, 32), 0);+ ASSERT_EQ(sha256_digest_decode(DIGEST, digest), 0);+ ASSERT_EQ(chain_history_step(base, digest, one), 0);+ EXPECT_EQ(tree_history_at(&pub, 1, out), 0);+ EXPECT_EQ(memcmp(out, one, 32), 0);++ pub.base_seq = 4;+ set(pub.history_root, sizeof(pub.history_root), "00");+ EXPECT_EQ(tree_history_at(&pub, 4, out), -EINVAL);+ set(pub.history_root, sizeof(pub.history_root), ROOT);+ ops[0].seq = 5;+ ops[1].seq = 6;+ pub.head_seq = 6;+ ops[1].operation_digest[7] = 'x';+ EXPECT_EQ(tree_history_at(&pub, 5, out), 0);+ EXPECT_EQ(tree_history_at(&pub, 6, out), -EINVAL);+ xfree(ops, 2 * sizeof(*ops));+}+static const struct unit_case cases[] = {UNIT_CASE(operation_takes_no_control_character),UNIT_CASE(publication_reads_back),@@ -477,6 +553,8 @@ static const struct unit_case cases[] = {UNIT_CASE(publication_follows_the_recorded_state),UNIT_CASE(segment_asks_for_a_walk),UNIT_CASE(segment_precedes_its_successor),+ UNIT_CASE(walk_stays_within_its_limit),+ UNIT_CASE(history_folds_from_the_base),{}};diff --git a/testing/vm/build-bundle.sh b/testing/vm/build-bundle.shindex 9e1bf2ce..ef7d93fc 100755--- a/testing/vm/build-bundle.sh+++ b/testing/vm/build-bundle.sh@@ -338,7 +338,11 @@ cleanup()}trap cleanup EXIT-make -C "$REPO_ROOT" -j"$jobs" DESTDIR="$TMP_DIR/root" install-target+# t7108 reaches the tree walk limits: the guest runs a target that walks+# 4 operations back from a cursor past 0 and 6 from 0.+make -C "$REPO_ROOT" -j"$jobs" \+ TREE_LIMIT_CFLAGS="-DTREE_MAX_WALK_OPS=4 -DTREE_MAX_JOIN_OPS=6" \+ DESTDIR="$TMP_DIR/root" install-targetmake -C "$REPO_ROOT" -j"$jobs" -f Makefile.shirudo \PROFILE=target CONFIG_MK=config-target.mk verity-test-helpers@@ -670,6 +674,197 @@ for reference in ("stable", "updated", "deleted", "restored", "kconfig",PY}+# The tree t7108 walks: one operation per append with --segment-ops 2, so+# segments of two, published by bpm tree append to a registry on the+# loopback. Each generation's manifest stays as g<k>, and the test moves the+# reference the target follows from one to the next. Its artifacts name the+# registry's port, so the guest serves the copy on the same one.+build_tree_segments_registry()+{+ local work="$FIXTURE_WORK/segments"+ local registry="$TMP_DIR/fixtures/segments-oci"+ local repo="$registry/shirudo/segments"+ local builder="$REPO_ROOT/tools/shirudo-build/shirudo-build"+ local pid port pkg op k++ mkdir -p "$work"+ for pkg in match other; do+ mkdir "$work/seg-$pkg"+ cp "$REPO_ROOT/testing/fixtures/segments/seg-$pkg/"* "$work/seg-$pkg/"+ ln -s "$REPO_ROOT/vendor" "$work/seg-$pkg/vendor"+ ln -s "$REPO_ROOT/bpf" "$work/seg-$pkg/bpf"+ (+ cd "$work"+ SHIRUDO_BUILD="$builder" "$REPO_ROOT/shirudo" bpm build \+ "$work/seg-$pkg" --version 1.0.0 \+ --keys-dir "$FIXTURE_WORK/trusted" \+ --vmlinux "$REPO_ROOT/vendor/linux/vmlinux.h" >/dev/null+ )+ done+ port=$(python3 -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')+ python3 "$REPO_ROOT/testing/helper/test-oci-registry.py" \+ --root "$registry" --port "$port" --writable \+ --ready-file "$work/ready" &+ pid=$!+ for k in $(seq 50); do+ [ -e "$work/ready" ] && break+ sleep 0.1+ done+ [ -e "$work/ready" ] || die "the segment registry did not start"+ # k = 1, 2, 0 mod 3: add the upatch this node takes, add one it does+ # not, delete the first.+ for k in $(seq 28); do+ case $((k % 3)) in+ 1) pkg=match op=add ;;+ 2) pkg=other op=add ;;+ *) pkg=match op=delete ;;+ esac+ env -u BPM_OCI_CA_FILE -u BPM_OCI_USERNAME -u BPM_OCI_PASSWORD \+ BPM_OCI_SCHEME=http REGISTRY_AUTH_FILE="$work/absent-auth.json" \+ NO_PROXY=127.0.0.1 no_proxy=127.0.0.1 \+ SHIRUDO_BUILD="$builder" "$REPO_ROOT/shirudo" bpm tree append \+ "$work/seg-$pkg-1.0.0.bee" \+ "oci://127.0.0.1:$port/shirudo/segments" \+ --keys-dir "$FIXTURE_WORK/trusted" --tree-id shirudo-test-segments \+ --segment-ops 2 --op "$op" >/dev/null ||+ { kill "$pid"; die "bpm tree append $k of the segment tree failed"; }+ cp "$repo/manifests/stable" "$repo/manifests/g$k"+ done+ kill "$pid"+ wait "$pid" 2>/dev/null || :+ printf '%s\n' "$port" >"$registry/port"++ # What the publisher refuses to write, re-signed as a registry that+ # holds the operator's key could: t7108's forks and a broken link.+ python3 - "$repo" "$work" <<'PY'+import hashlib+import json+import pathlib+import sys++repo, work = map(pathlib.Path, sys.argv[1:3])+DOC = "application/vnd.shirudo.upatch.tree.v1+json"+++def digest(body):+ return "sha256:" + hashlib.sha256(body).hexdigest()+++def manifest(ref):+ return (repo / "manifests" / ref).read_bytes()+++def document(ref):+ layers = json.loads(manifest(ref))["layers"]+ blob = [layer for layer in layers if layer["mediaType"] == DOC][0]+ return json.loads((repo / "blobs" / blob["digest"]).read_bytes())+++def with_digest(op):+ canonical = {k: v for k, v in op.items()+ if k not in ("operation_digest", "fixes")}+ body = json.dumps(canonical, separators=(",", ":")).encode()+ return dict(canonical, operation_digest=digest(body))+++g20, g22, g24 = document("g20"), document("g22"), document("g24")+pred = {"schema": 1, "tree_id": g20["tree_id"], "generation": 21,+ "parent_manifest_digest": digest(manifest("g20")),+ "base": {"seq": 20,+ "segment_manifest_digest": digest(manifest("g18")),+ "history_root": "ab" * 32},+ "operations": g22["operations"], "head": {"seq": 22}}+forked = dict(g20["operations"][0], selector={"labels": {"env": ["forked"]}})+docs = {+ # A predecessor that starts from another history than the node's.+ "fork-pred": pred,+ # The current segment, its first operation not the one nodes took.+ "fork-prefix": {"schema": 1, "tree_id": g20["tree_id"], "generation": 21,+ "parent_manifest_digest": digest(manifest("g20")),+ "base": g20["base"],+ "operations": [with_digest(forked), g20["operations"][1],+ g22["operations"][0]],+ "head": {"seq": 21}},+ # A segment that names a sealed one ending a step before its base.+ "head-gap": {"schema": 1, "tree_id": g20["tree_id"], "generation": 23,+ "parent_manifest_digest": digest(manifest("g22")),+ "base": {"seq": 23,+ "segment_manifest_digest": digest(manifest("g22")),+ "history_root": "cd" * 32},+ "operations": [g24["operations"][1]], "head": {"seq": 24}},+}+for name, doc in docs.items():+ (work / (name + ".json")).write_bytes(+ json.dumps(doc, separators=(",", ":")).encode())+PY+ for name in fork-pred fork-prefix head-gap fork-base; do+ if [ "$name" = fork-base ]; then+ python3 - "$repo" "$work" <<'PY'+import hashlib+import json+import pathlib+import sys++repo, work = map(pathlib.Path, sys.argv[1:3])+pred_manifest = (repo / "manifests" / "fork-pred").read_bytes()+pred = json.loads((work / "fork-pred.json").read_bytes())+for layer in json.loads((repo / "manifests" / "g24").read_bytes())["layers"]:+ if layer["mediaType"] == "application/vnd.shirudo.upatch.tree.v1+json":+ g24 = json.loads((repo / "blobs" / layer["digest"]).read_bytes())+root = bytes.fromhex(pred["base"]["history_root"])+for op in pred["operations"]:+ root = hashlib.sha256(b"shirudo-tree-history\0" + root ++ bytes.fromhex(op["operation_digest"][7:])).digest()+pred_digest = "sha256:" + hashlib.sha256(pred_manifest).hexdigest()+# The segment after the forked predecessor, consistent with it.+doc = {"schema": 1, "tree_id": pred["tree_id"], "generation": 23,+ "parent_manifest_digest": pred_digest,+ "base": {"seq": 22, "segment_manifest_digest": pred_digest,+ "history_root": root.hex()},+ "operations": g24["operations"], "head": {"seq": 24}}+(work / "fork-base.json").write_bytes(+ json.dumps(doc, separators=(",", ":")).encode())+PY+ fi+ openssl cms -sign -binary -md sha512 -in "$work/$name.json" \+ -signer "$FIXTURE_WORK/trusted/cert.der" \+ -inkey "$FIXTURE_WORK/trusted/signing_key.pem" \+ -outform DER -out "$work/$name.sig" \+ -nosmimecap -nocerts -keyid+ python3 - "$repo" "$work" "$name" <<'PY'+import hashlib+import json+import pathlib+import sys++repo, work = map(pathlib.Path, sys.argv[1:3])+name = sys.argv[3]+++def digest(body):+ return "sha256:" + hashlib.sha256(body).hexdigest()+++payload = (work / (name + ".json")).read_bytes()+signature = (work / (name + ".sig")).read_bytes()+for body in (payload, signature):+ (repo / "blobs" / digest(body)).write_bytes(body)+manifest = json.dumps({+ "schemaVersion": 2,+ "mediaType": "application/vnd.oci.image.manifest.v1+json",+ "layers": [+ {"mediaType": "application/vnd.shirudo.upatch.tree.v1+json",+ "digest": digest(payload), "size": len(payload)},+ {"mediaType": "application/vnd.shirudo.upatch.tree.signature.v1",+ "digest": digest(signature), "size": len(signature)},+ ],+}, separators=(",", ":")).encode()+for ref in (name, digest(manifest)):+ (repo / "manifests" / ref).write_bytes(manifest)+PY+ done+}+build_obs_fixture(){local keys_dir="$1"@@ -927,6 +1122,7 @@ tree_skip_unload_payload="$($REPO_ROOT/shirudo upatch info \"$TMP_DIR/fixtures/shirudo-test-tree-skip.unload.upatch" --json |python3 -c 'import json,sys; print(json.load(sys.stdin)["payload_sha256"])')"build_tree_test_registry+build_tree_segments_registrymv /tmp/shirudo-test-uprobe-target \"$TMP_DIR/fixtures/shirudo-test-uprobe-target"diff --git a/testing/vm/bundle-images.sh b/testing/vm/bundle-images.shindex f40ca3ab..6052f64e 100755--- a/testing/vm/bundle-images.sh+++ b/testing/vm/bundle-images.sh@@ -11,7 +11,9 @@ work=$2keys=$3boot_keys=$4"$source_dir/testing/vm/image-fixtures.sh" --keys-dir "$keys" \- --boot-keys-dir "$boot_keys" --output "$work/verity"+ --boot-keys-dir "$boot_keys" \+ --segments-port "$(cat "$bundle/fixtures/segments-oci/port")" \+ --output "$work/verity"mkdir "$bundle/verity"cp -a "$work/verity/public/." "$bundle/verity/"sed 's/@config_image@/config-boot-keys/g' "$templates/runtime.conf.in" \diff --git a/testing/vm/image-fixtures.sh b/testing/vm/image-fixtures.shindex effe5c20..ebdded4b 100755--- a/testing/vm/image-fixtures.sh+++ b/testing/vm/image-fixtures.sh@@ -10,6 +10,7 @@ templates="$source_dir/testing/vm/files"keys_dir=boot_keys_dir=output=+segments_port=builtin_key=${TEST_VM_BUILTIN_SIGNING_KEY:-}builtin_cert=${TEST_VM_BUILTIN_SIGNING_CERT:-}while [ $# -gt 0 ]; do@@ -17,8 +18,9 @@ while [ $# -gt 0 ]; do--boot-keys-dir) boot_keys_dir=${2:?}; shift 2 ;;--keys-dir) keys_dir=${2:?}; shift 2 ;;--output) output=${2:?}; shift 2 ;;+ --segments-port) segments_port=${2:?}; shift 2 ;;*)- printf 'usage: %s --keys-dir <operator-keys> [--boot-keys-dir <operator-keys>] --output <new-directory>\n' \+ printf 'usage: %s --keys-dir <operator-keys> [--boot-keys-dir <operator-keys>] [--segments-port <port>] --output <new-directory>\n' \"$0" >&2exit 2;;@@ -74,10 +76,11 @@ for name in config-boot-keys config-live-new-key config-live-revoke-a config-a cconfig-tree-stable config-tree-updated config-tree-deleted config-tree-restored \config-tree-kconfig config-tree-reloaded config-tree-outcomes \config-tree-stopped config-tree-fetched config-tree-fixes \- config-tree-keepalive config-tree-unmatched \+ config-tree-keepalive config-tree-unmatched config-tree-segments \config-otel config-jsonl config-jsonl-bad config-interrupted config-end2end \config-edge config-core config-local-stack config-builtin config-untrusted; do[ "$name" != config-builtin ] || [ -n "$builtin_key" ] || continue+ [ "$name" != config-tree-segments ] || [ -n "$segments_port" ] || continueroot="$output/source/$name"mkdir -p "$root/etc/shirudo" "$root/keys/trusted" "$root/keys/revoked"sed "s/@tenant@/$name/g" "$templates/config.conf.in" \@@ -89,6 +92,10 @@ for name in config-boot-keys config-live-new-key config-live-revoke-a config-a csed "s/@reference@/${name#config-tree-}/g" \"$templates/upatch-tree.conf.in" \>"$root/etc/shirudo/bpm/upatch-tree.conf"+ # The segment tree's artifacts name the port it was published on.+ [ "$name" != config-tree-segments ] ||+ sed -i "s|127.0.0.1:5443/shirudo/upatch-tree|127.0.0.1:$segments_port/shirudo/segments|" \+ "$root/etc/shirudo/bpm/upatch-tree.conf";;config-otel)cp "$templates/otel.conf" "$root/etc/shirudo/shirudo.conf"diff --git a/tools/shirudo-build/bpm-publish.c b/tools/shirudo-build/bpm-publish.cindex dc5173fe..8890a78b 100644--- a/tools/shirudo-build/bpm-publish.c+++ b/tools/shirudo-build/bpm-publish.c@@ -1041,27 +1041,6 @@ static int tree_refuse_sealed_xdp_class(struct bpm_oci_client *c,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 ?@@ -1171,6 +1150,9 @@ static int tree_start_segment(const struct tree_publication *sealed,const char *sealed_digest,struct tree_publication *pub){+ __u8 root[32];+ int ret;+*pub = (struct tree_publication){.schema = 1,.generation = sealed->generation,@@ -1180,7 +1162,10 @@ static int tree_start_segment(const struct tree_publication *sealed,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);+ ret = tree_history_at(sealed, sealed->head_seq, root);+ if (!ret)+ hex_encode(root, sizeof(root), pub->history_root);+ return ret;}static int cmd_bpm_tree_append(int argc, char **argv)diff --git a/util/bpm_tree.c b/util/bpm_tree.cindex cf20ad02..c5ffdff1 100644--- a/util/bpm_tree.c+++ b/util/bpm_tree.c@@ -746,3 +746,36 @@ int tree_segment_precedes(const struct tree_publication *pred,return -ERANGE;return 0;}++int tree_walk_within(__s64 base_seq, __s64 last_seq)+{+ __s64 limit = last_seq ? TREE_MAX_WALK_OPS : TREE_MAX_JOIN_OPS;++ if (base_seq < 0 || last_seq < 0)+ return -EINVAL;+ return base_seq - last_seq > limit ? -E2BIG : 0;+}++int tree_history_at(const struct tree_publication *pub, __s64 seq,+ __u8 out[32])+{+ __u8 digest[32];+ int ret;++ memset(out, 0, 32);+ if (seq < pub->base_seq || seq > pub->head_seq)+ return -EINVAL;+ if (pub->base_seq && hex_decode(pub->history_root, out, 32))+ return -EINVAL;+ for (int i = 0; i < pub->n_operations; i++) {+ if (pub->operations[i].seq > seq)+ break;+ if (sha256_digest_decode(pub->operations[i].operation_digest,+ digest))+ return -EINVAL;+ ret = chain_history_step(out, digest, out);+ if (ret)+ return ret;+ }+ return 0;+}diff --git a/util/bpm_tree.h b/util/bpm_tree.hindex 091b067f..a97c4e66 100644--- a/util/bpm_tree.h+++ b/util/bpm_tree.h@@ -18,12 +18,17 @@/** 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.+ * seq 0, as a node that joins a tree does, and from the cursor of a node+ * that has processed one: one past it is -E2BIG. A running node walks+ * holding the bpm lock, with its keepalive stopped, so it gets the lower+ * one. A test build sets both low.*/#ifndef TREE_MAX_JOIN_OPS#define TREE_MAX_JOIN_OPS 1048576#endif+#ifndef TREE_MAX_WALK_OPS+#define TREE_MAX_WALK_OPS 65536+#endifstruct json_emit;@@ -174,6 +179,21 @@ int tree_segment_precedes(const struct tree_publication *pred,const char *pred_manifest_digest,const struct tree_publication *succ) __must_check;+/*+ * tree_walk_within() is the limit of that walk: 0 when a node whose cursor+ * is last_seq may walk back to a segment that starts at base_seq,+ * TREE_MAX_JOIN_OPS operations at most from 0 and TREE_MAX_WALK_OPS from+ * any other cursor, -E2BIG past it, -EINVAL for a negative number.+ *+ * tree_history_at() gives the history root at seq of a publication that+ * tree_publication_check() accepts: its base's, 32 zero bytes at 0, over+ * the digests of its operations up to seq. -EINVAL for a seq outside base+ * to head or a malformed root or digest.+ */+int tree_walk_within(__s64 base_seq, __s64 last_seq) __must_check;+int tree_history_at(const struct tree_publication *pub, __s64 seq,+ __u8 out[32]) __must_check;+/** Evaluate a publication selector against the running node. An empty* selector is an unconstrained wildcard and matches every node. 1 on a