eBPF-based security platform
bpm: publish fixes on tree operations and carry them forward
John Fastabend67f4181781d4
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex 2bd90951..5c2c6bc7 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -489,6 +489,11 @@ signed config image.* - ``t7006-policy-labels``- Beefile policy declarations are serialized into the signedupatch section+ * - ``t7007-bpm-tree-fixes``+ - ``bpm tree append`` writes ``fixes`` on an ``add`` in byte order,+ after ``artifact`` and outside ``operation_digest``, none on a+ ``delete``, carries every earlier operation's list into the next+ generation, and refuses to carry a list it would not write* - ``t7101-bpm-tree``- Tree sync with a selector* - ``t7102-bpm-tree-sequential``@@ -508,6 +513,11 @@ signed config image.accepted publication on record after a sync that failed at afetch; the record agrees with the tree eventlog and theoperations' digests throughout+ * - ``t7107-bpm-tree-fixes-ignored``+ - A publication whose operations carry ``fixes``, well-formed and+ malformed, on an ``add``, a ``delete`` and an operation without a+ match, syncs with the outcomes, state and tree eventlog of the+ same operations without it``otel`` (8)~~~~~~~~~~~~@@ -722,8 +732,9 @@ Coverage by area``oci-http``, ``oci-manifest``, ``oci-ref``, ``registry-auth``. Unit:``bpm_oci``, ``bpm_package``* - upatch tree- - ``t3011``, ``t5004``, ``t7005``, ``t7101``, ``t7102``,- ``t7103``, ``t7104``, ``t7105``, ``t7106``, ``t9105``. Fuzz: ``tree``,+ - ``t3011``, ``t5004``, ``t7005``, ``t7007``, ``t7101``,+ ``t7102``, ``t7103``, ``t7104``, ``t7105``, ``t7106``,+ ``t7107``, ``t9105``. Fuzz: ``tree``,``tree-state``, ``kconfig``. Unit: ``bpm_tree``,``bpm_tree_overlap``, ``bpm_tree_state``, ``kernel_build_id``,``kernel_release``@@ -786,7 +797,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``, ``t8005``, ``t9105``+ ``t7103``, ``t7104``, ``t7105``, ``t7106``, ``t7107``, ``t8005``,+ ``t9105``* - T8 Quantum-capable adversaries- ``t2001``, ``t2002``, ``t5001``, ``t8005``* - T9 A target lying about its statediff --git a/Documentation/internals/design-decisions.rst b/Documentation/internals/design-decisions.rstindex 93a55590..38063769 100644--- a/Documentation/internals/design-decisions.rst+++ b/Documentation/internals/design-decisions.rst@@ -220,6 +220,29 @@ what is required. The cost is a narrow set of kernels: bpf-next or arelease that contains its signed-loader work, with the patches in:doc:`kernel-patches`.+A tree key the node never parses+--------------------------------++``bpm tree append`` carries each earlier operation's ``fixes`` into the+next generation from a second read of its own over the previous+publication's bytes, with the JSON reader of :src:`util/json.c`, in the+operator's helper. ``tree_parse()``, which reads the publication on the+node as well, is unchanged and still skips the key; the shared emitter,+``tree_emit_publication()``, takes only an optional callback that adds+keys after an operation's ``artifact``, which the publisher passes and+nothing else does.++``tree_parse()`` is the node's parser of registry input. A key it reads+is a key a malformed document can make the node refuse, and ``fixes`` is+a convention of the keepalive backend that must never stop a node's+sync (:doc:`/reference/formats/bpm-formats`). The cost is that the+operator parses each previous publication twice. A single pass, in+which ``tree_parse()`` takes an optional field and sink for extra+operation keys that the publisher passes and the node leaves ``NULL``,+would read it once, at the price of a change to the node's parser and+to the ``bpm-tree-reader`` and ``bpm-tree-sync-model`` proofs that+include it; it is left for later.+Related-------diff --git a/Documentation/reference/cli/bpm.rst b/Documentation/reference/cli/bpm.rstindex 77dd2a25..40a141f1 100644--- a/Documentation/reference/cli/bpm.rst+++ b/Documentation/reference/cli/bpm.rst@@ -261,6 +261,14 @@ shared classes, and nothing is published.the registry, so the append fails when one of them cannot be fetched.Two upatches of the package being appended are compared as well.+An ``add`` carries the entry's ``fixes``, a ``delete`` none, and every+earlier operation keeps its own. The append is refused, and nothing is+published, when the existing publication holds a ``fixes`` list+``bpm tree append`` would not write; the message is ``bpm tree append:+the publication at <repository>:<reference> has a fixes list bpm tree+append would not write, so it cannot carry it into the next+generation``.+key---diff --git a/Documentation/reference/formats/bpm-formats.rst b/Documentation/reference/formats/bpm-formats.rstindex 0cac29be..5d1adda6 100644--- a/Documentation/reference/formats/bpm-formats.rst+++ b/Documentation/reference/formats/bpm-formats.rst@@ -404,6 +404,7 @@ Operation"manifest_digest": "sha256:<hex>","layer_digest": "sha256:<hex>","payload_sha256": "sha256:<hex>"},+ "fixes": ["<advisory-id>", ...],"operation_digest": "sha256:<hex>"}.. list-table::@@ -429,6 +430,19 @@ Operation- Digest of the ``.upatch`` layer.* - ``artifact.payload_sha256``- ``sha256:`` and the artifact's header ``payload_sha256``.+ * - ``fixes``+ - Optional, on an ``add`` only: the IDs of the advisories the upatch+ fixes, 1 to 16 strings of 1 to 255 bytes of letters, digits,+ ``.``, ``_``, ``:`` and ``-``, each once, in byte order. A+ convention of the keepalive backend, not of shirudo: the CMS+ signature covers it, the operation digest does not, and the target+ never reads, checks or measures it, so a malformed one never makes+ a node refuse the publication. ``bpm tree append`` writes it after+ ``artifact`` from the Beefile's ``fixes``+ (:doc:`/upatches/publish/beefile`), leaves it out when the list is+ empty, carries every earlier operation's list into the next+ generation unchanged, and refuses to append to a publication whose+ list breaks these rules.* - ``operation_digest``- ``sha256:`` and the SHA-256 of the canonical operation, see`Operation digest`_.@@ -479,7 +493,7 @@ Operation digest~~~~~~~~~~~~~~~~``operation_digest`` is the SHA-256 of the compact JSON of the operation-without ``operation_digest``, in this form:+without ``operation_digest`` and ``fixes``, in this form:- Keys in the order ``seq``, ``op``, ``id``, ``selector``, ``artifact``.- ``selector`` keys in byte order: ``architecture``, ``kconfig``,diff --git a/Documentation/security/threat-model.rst b/Documentation/security/threat-model.rstindex 91daa9b5..2761e74a 100644--- a/Documentation/security/threat-model.rst+++ b/Documentation/security/threat-model.rst@@ -1032,7 +1032,10 @@ compares 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 anolder one. A delete applies-the signed unload directive whose name equals the operation's id.+the signed unload directive whose name equals the operation's id. An+operation's ``fixes``, which the backend reads and the operation digest+does not cover, the target's parser skips: a malformed one cannot make+it refuse a publication.The transport is TLS 1.3 only, with the hybrid groups``X25519MLKEM768`` and ``SecP256r1MLKEM768`` and certificate@@ -1053,7 +1056,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``, ``t8005``+ ``t7105``, ``t7106``, ``t7107``, ``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``,diff --git a/Documentation/upatches/publish/beefile.rst b/Documentation/upatches/publish/beefile.rstindex 6e0b1b26..024d939c 100644--- a/Documentation/upatches/publish/beefile.rst+++ b/Documentation/upatches/publish/beefile.rst@@ -294,8 +294,9 @@ checks the form of each ID, not that the advisory exists, and refuses alist that breaks the rules above, an empty list and a value that is notan array of strings. It keeps the Beefile as written; the order of theIDs does not matter, because the list is published in byte order.-Publishing it comes with ``bpm tree append``, which does not write it-yet.+``bpm tree append`` writes it on the operation it publishes as an+``add``, outside the operation digest, and never on a ``delete``+(:doc:`publishing`).``[upatches.tree.selector]``~~~~~~~~~~~~~~~~~~~~~~~~~~~~diff --git a/Documentation/upatches/publish/publishing.rst b/Documentation/upatches/publish/publishing.rstindex 26beabde..cd2e63d5 100644--- a/Documentation/upatches/publish/publishing.rst+++ b/Documentation/upatches/publish/publishing.rst@@ -117,9 +117,11 @@ Append it to the treeyour certificate. For every entry it checks that the artifact is aload directive whose upatch name equals the entry's ``id``, pushes theartifact as an artifact of its own, and appends an operation with the- entry's selector. It then signs the next generation, which names the- previous publication's digest as its parent, and prints the tree's- reference and new digest.+ entry's selector and, when the entry has one, its ``fixes`` list. It+ then signs the next generation, which names the previous+ publication's digest as its parent, and prints the tree's reference+ and new digest. Every earlier operation goes into the new generation+ as it was, its ``fixes`` included.A repository without a publication starts a new tree at generation 1,with the package name as tree id or the id ``--tree-id`` gives. For an@@ -135,10 +137,11 @@ Append it to the treeoci://<registry>/<namespace>/<tree> --keys-dir <keys-dir> --op deleteNothing is ever removed from the tree: a ``delete`` is a new operation- after the ``add``. To replace a loaded upatch with a new build of the- same name, append the ``delete`` of the old package first and the- ``add`` of the new one after it, since a target cannot load a second- upatch under a name that is already loaded.+ after the ``add``, and carries no ``fixes``. To replace a loaded+ upatch with a new build of the same name, append the ``delete`` of the+ old package first and the ``add`` of the new one after it, since a+ target cannot load a second upatch under a name that is already+ loaded.``tree append`` refuses an ``add`` whose XDP programs select a deviceclass that another upatch of the tree selects on the same nodes, since adiff --git a/testing/functional/bpm/t7007-bpm-tree-fixes.sh b/testing/functional/bpm/t7007-bpm-tree-fixes.shnew file mode 100644index 00000000..f1bffe81--- /dev/null+++ b/testing/functional/bpm/t7007-bpm-tree-fixes.sh@@ -0,0 +1,255 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# t7007 -- bpm tree append publishes the fixes of a Beefile's+# [upatches.tree] on an add, in byte order, after artifact and outside+# operation_digest; carries every earlier operation's fixes into the next+# generation unchanged; writes none on a delete; and refuses to carry a+# previous publication's fixes in a form bpm build would not write.+# Needs clang, shirudo-build, python3 and an OpenSSL >= 3.5 (ML-DSA).++cd "$(dirname "$0")/../.."+. ./test-lib.sh++S=../shirudo+SHB=../tools/shirudo-build/shirudo-build++command -v clang >/dev/null 2>&1 || test_skip_all "no clang"+command -v openssl >/dev/null 2>&1 || test_skip_all "no openssl"+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"+[ -x "$S" ] || test_skip_all "shirudo not built"+[ -x "$SHB" ] || test_skip_all "shirudo-build not built (make shirudo-build)"+[ -e ../vendor/linux/vmlinux.h ] || test_skip_all "no vendor/linux/vmlinux.h (build the tree)"+openssl list -public-key-algorithms 2>/dev/null | grep -qi 'ML-DSA' ||+ test_skip_all "openssl without ML-DSA (needs OpenSSL >= 3.5)"++REPO=$(cd .. && pwd)+case "$SHB" in+/*) B="$SHB" ;;+*) B="$REPO/${SHB#../}" ;;+esac+S="$REPO/shirudo"++WORK=$(mktemp -d)+SERVER_PID=+cleanup() {+ [ -z "$SERVER_PID" ] || kill "$SERVER_PID" 2>/dev/null || :+ rm -rf "$WORK"+}+trap cleanup EXIT HUP INT TERM++"$S" genkey --keys-dir "$WORK/keys" >/dev/null 2>&1 ||+ test_skip_all "genkey failed"++export SHIRUDO_BUILD="$B" BPM_OCI_SCHEME=http+export REGISTRY_AUTH_FILE="$WORK/absent-auth.json" NO_PROXY=127.0.0.1 no_proxy=127.0.0.1+unset BPM_OCI_CA_FILE BPM_OCI_USERNAME BPM_OCI_PASSWORD++# A package of one upatch named $1 with $2 as the rest of its tree entry.+# The package directory doubles as shirudo-build's working directory, so+# the vendored headers and vmlinux.h are reached through symlinks.+package() {+ mkdir -p "$WORK/$1" &&+ ln -s "$REPO/vendor" "$WORK/$1/vendor" &&+ ln -s "$REPO/bpf" "$WORK/$1/bpf" &&+ printf '// SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause\n#include "vmlinux.h"\n#include <bpf/bpf_helpers.h>\n#include <bpf/bpf_tracing.h>\n\nchar _license[] SEC("license") = "Dual BSD/GPL";\n\nSEC("fentry/do_nanosleep")\nint BPF_PROG(%s_fn)\n{\n\treturn 0;\n}\n' \+ "$1" >"$WORK/$1/$1.bpf.c" &&+ printf '[package]\nname = "%s"\n\n[[upatches]]\nsource = "%s.bpf.c"\n\n[upatches.tree]\nid = "%s"\n%s' \+ "$1" "$1" "$1" "$2" >"$WORK/$1/Beefile" &&+ ( cd "$WORK" && "$S" bpm build "$1" --version 1.0.0 \+ --keys-dir "$WORK/keys" ) >&2+}++test_expect_success 'bpm build packages an upatch with fixes and one without' '+ package t7007a "fixes = [\"B\", \"A\"]+" &&+ package t7007b "" &&+ test -s "$WORK/t7007a-1.0.0.bee" && test -s "$WORK/t7007b-1.0.0.bee"+'+[ -s "$WORK/t7007a-1.0.0.bee" ] && [ -s "$WORK/t7007b-1.0.0.bee" ] || test_done++PORT=$(python3 -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')+REG="$WORK/registry"+python3 ./helper/test-oci-registry.py --root "$REG" --port "$PORT" --writable \+ --log "$WORK/requests.log" --ready-file "$WORK/ready" &+SERVER_PID=$!+i=0+while [ ! -e "$WORK/ready" ]; do+ i=$((i + 1))+ [ "$i" -lt 100 ] || test_skip_all "registry fixture did not start"+ sleep .05+done+TREE="oci://127.0.0.1:$PORT/ns/tree"++# Append the package of $1 with the rest of the arguments, and keep the+# publication it leaves as $WORK/gen<generation>.json.+append() {+ pkg=$1+ shift+ "$S" bpm tree append "$WORK/$pkg-1.0.0.bee" "$TREE" \+ --keys-dir "$WORK/keys" "$@" >/dev/null 2>"$WORK/append.err" &&+ python3 - "$REG/ns/tree" "$WORK" <<'PY'+import json, pathlib, sys+repo, work = map(pathlib.Path, sys.argv[1:3])+manifest = json.loads((repo / "manifests" / "stable").read_bytes())+layer = [l for l in manifest["layers"] if l["mediaType"].endswith("+json")][0]+body = (repo / "blobs" / layer["digest"]).read_bytes()+pub = json.loads(body)+(work / f"gen{pub['generation']}.json").write_bytes(body)+PY+}++# Check generation $1 with a Python body on pub, its parsed document, and+# digest(op), the operation digest recomputed from the five canonical keys.+check() {+ python3 -c '+import hashlib, json, sys+body = open(sys.argv[1], "rb").read()+pub = json.loads(body)+def digest(op):+ canonical = {k: op[k] for k in ("seq", "op", "id", "selector", "artifact")}+ text = json.dumps(canonical, separators=(",", ":")).encode()+ return "sha256:" + hashlib.sha256(text).hexdigest()+for op in pub["operations"]:+ assert op["operation_digest"] == digest(op), op+exec(sys.argv[2])+' "$WORK/gen$1.json" "$2"+}++test_expect_success 'an add carries its fixes in byte order after artifact' '+ append t7007a &&+ check 1 "+op = pub[\"operations\"][0]+assert op[\"op\"] == \"add\" and op[\"id\"] == \"t7007a\", op+assert op[\"fixes\"] == [\"A\", \"B\"], op+assert list(op) == [\"seq\", \"op\", \"id\", \"selector\", \"artifact\",+ \"fixes\", \"operation_digest\"], list(op)+assert b\"\\\"artifact\\\":{\" in body and b\"},\\\"fixes\\\":[\\\"A\\\",\\\"B\\\"],\\\"operation_digest\\\":\" in body+"+'++test_expect_success 'operation_digest covers the five canonical keys, not fixes' '+ check 1 "+op = pub[\"operations\"][0]+six = {k: op[k] for k in (\"seq\", \"op\", \"id\", \"selector\", \"artifact\", \"fixes\")}+text = json.dumps(six, separators=(\",\", \":\")).encode()+assert op[\"operation_digest\"] == digest(op), op+assert op[\"operation_digest\"] != \"sha256:\" + hashlib.sha256(text).hexdigest(), op+"+'++test_expect_success 'an add without fixes writes no key, and earlier fixes carry over' '+ append t7007b &&+ check 2 "+first = json.load(open(sys.argv[1].replace(\"gen2\", \"gen1\")))[\"operations\"][0]+assert pub[\"operations\"][0] == first, pub+assert list(pub[\"operations\"][0]) == list(first), pub+op = pub[\"operations\"][1]+assert op[\"id\"] == \"t7007b\" and \"fixes\" not in op, op+"+'++test_expect_success 'a delete writes no fixes, though its Beefile names some' '+ append t7007a --op delete &&+ check 3 "+before = json.load(open(sys.argv[1].replace(\"gen3\", \"gen2\")))[\"operations\"]+assert pub[\"operations\"][:2] == before, pub+op = pub[\"operations\"][2]+assert op[\"op\"] == \"delete\" and op[\"id\"] == \"t7007a\", op+assert \"fixes\" not in op, op+" &&+ append t7007a &&+ check 4 "+assert pub[\"operations\"][0][\"fixes\"] == [\"A\", \"B\"], pub+assert \"fixes\" not in pub[\"operations\"][1], pub+assert \"fixes\" not in pub[\"operations\"][2], pub+assert pub[\"operations\"][3][\"fixes\"] == [\"A\", \"B\"], pub+"+'++# Sign $1, a document, with the operator key and make it the tree's+# stable publication.+publish_signed() {+ openssl cms -sign -binary -md sha512 -in "$1" \+ -signer "$WORK/keys/cert.der" -inkey "$WORK/keys/signing_key.pem" \+ -outform DER -out "$1.sig" -nosmimecap -nocerts -keyid &&+ python3 - "$REG/ns/tree" "$1" <<'PY'+import hashlib, json, pathlib, sys+repo, doc = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2])+layers = []+for path, media in ((doc, "application/vnd.shirudo.upatch.tree.v1+json"),+ (doc.with_name(doc.name + ".sig"),+ "application/vnd.shirudo.upatch.tree.signature.v1")):+ body = path.read_bytes()+ digest = "sha256:" + hashlib.sha256(body).hexdigest()+ (repo / "blobs" / digest).write_bytes(body)+ layers.append({"mediaType": media, "digest": digest, "size": len(body)})+manifest = {"schemaVersion": 2,+ "mediaType": "application/vnd.oci.image.manifest.v1+json",+ "artifactType": "application/vnd.shirudo.upatch.tree.v1",+ "config": {"mediaType": "application/vnd.oci.empty.v1+json",+ "digest": "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",+ "size": 2},+ "layers": layers}+(repo / "manifests" / "stable").write_bytes(+ json.dumps(manifest, separators=(",", ":")).encode())+PY+}++# Generation 4 with fixes $2 on its operation $1 (from 0), re-signed.+malformed() {+ python3 - "$WORK/gen4.json" "$1" "$2" "$WORK/bad.json" <<'PY'+import json, sys+pub = json.load(open(sys.argv[1]))+op = pub["operations"][int(sys.argv[2])]+fixes = json.loads(sys.argv[3])+if fixes is None:+ op.pop("fixes")+else:+ out = {}+ for key, value in op.items():+ if key == "operation_digest":+ out["fixes"] = fixes+ out[key] = value+ op.clear()+ op.update(out)+open(sys.argv[4], "wb").write(json.dumps(pub, separators=(",", ":")).encode())+PY+ publish_signed "$WORK/bad.json"+}++# $1 the operation, $2 the fixes, which tree append must refuse to carry.+refused() {+ malformed "$1" "$2" &&+ cp "$REG/ns/tree/manifests/stable" "$WORK/bad.manifest" &&+ ! "$S" bpm tree append "$WORK/t7007b-1.0.0.bee" "$TREE" \+ --keys-dir "$WORK/keys" >/dev/null 2>"$WORK/bad.err" &&+ grep -q "has a fixes list bpm tree append would not write" \+ "$WORK/bad.err" &&+ cmp -s "$WORK/bad.manifest" "$REG/ns/tree/manifests/stable"+}++test_expect_success 'tree append refuses to carry fixes it would not write' '+ refused 2 "[\"A\"]" &&+ refused 0 "[\"B\",\"A\"]" &&+ refused 0 "[\"A\",\"A\"]" &&+ refused 0 "[]" &&+ refused 0 "[\"\"]" &&+ refused 0 "[\"A/B\"]" &&+ refused 0 "[1]" &&+ refused 0 "\"A\"" &&+ refused 0 "[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\"]"+'++test_expect_success 'a re-signed publication of 16 IDs in byte order carries over' '+ malformed 1 "[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\"]" &&+ append t7007b &&+ check 5 "+assert pub[\"operations\"][1][\"fixes\"] == list(\"123456789ABCDEFG\"), pub+assert pub[\"operations\"][0][\"fixes\"] == [\"A\", \"B\"], pub+assert \"fixes\" not in pub[\"operations\"][4], pub+"+'++test_donediff --git a/testing/functional/bpm/t7107-bpm-tree-fixes-ignored.sh b/testing/functional/bpm/t7107-bpm-tree-fixes-ignored.shnew file mode 100644index 00000000..720c44ee--- /dev/null+++ b/testing/functional/bpm/t7107-bpm-tree-fixes-ignored.sh@@ -0,0 +1,127 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# t7107 -- a node reads past the fixes of a tree operation: a publication+# whose operations carry fixes as a publisher writes it, and in forms no+# publisher writes, on a delete and on an operation without a match,+# syncs with the outcomes, state, tree eventlog and upatches the same+# operations give without the key.++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}+REGISTRY="$FIXTURES/tree-oci"+TREE_REPO="$REGISTRY/shirudo/upatch-tree"+TREE_DIR=/var/lib/shirudo/bpm/upatch-tree+OUTCOMES=$TREE_DIR/outcomes+TREE_EVENTLOG=$TREE_DIR/tree-eventlog+MATCH_PIN=/run/shirudo/bpffs/upatches/shirudo-test-tree-match/link+SKIP_PIN=/run/shirudo/bpffs/upatches/shirudo-test-tree-skip/link+WORK=$(mktemp -d)++for fixture in \+ "$TREE_REPO/manifests/fixes" \+ "$FIXTURES/shirudo-test-tree-skip.unload.upatch" \+ "./helper/test-oci-registry.py"+do+ [ -s "$fixture" ] || test_skip_all "missing tree fixture: $fixture"+done++[ "$(tree_state_field tree_id)" = shirudo-test-tree ] &&+ [ "$(tree_state_field last_seq)" = 13 ] &&+ [ ! -e "$MATCH_PIN" ] && [ ! -e "$SKIP_PIN" ] ||+ test_skip_all "tree state is not where t7106 leaves it"++cleanup()+{+ tree_registry_stop+ if [ -e "$SKIP_PIN" ]; then+ "$SHIRUDO_BIN" upatch unload \+ "$FIXTURES/shirudo-test-tree-skip.unload.upatch" \+ --no-precheck >/dev/null 2>&1 || true+ fi+ tree_cleanup_config+ rm -rf "$WORK"+}+trap cleanup EXIT++# The publication at the reference fixes, as the registry serves it.+DOCUMENT="$WORK/fixes.json"+python3 - "$TREE_REPO" "$DOCUMENT" <<'PY'+import json+import pathlib+import sys++repo, out = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2])+manifest = json.loads((repo / "manifests" / "fixes").read_bytes())+out.write_bytes((repo / "blobs" / manifest["layers"][0]["digest"])+ .read_bytes())+PY++tree_configure fixes+tree_registry_start "$REGISTRY" "$WORK"++test_expect_success 'the publication carries fixes outside every operation digest' '+ python3 - "$DOCUMENT" <<'"'"'PY'"'"'+import hashlib, json, sys+pub = json.load(open(sys.argv[1]))+ops = {op["seq"]: op for op in pub["operations"]}+assert ops[14]["fixes"] == ["EXAMPLE-0101"], ops[14]+assert ops[15]["op"] == "delete" and isinstance(ops[15]["fixes"], dict), ops[15]+assert len(ops[16]["fixes"]) > 16 and "" in ops[16]["fixes"], ops[16]+for op in pub["operations"]:+ canonical = {k: op[k] for k in ("seq", "op", "id", "selector", "artifact")}+ text = json.dumps(canonical, separators=(",", ":")).encode()+ assert op["operation_digest"] == "sha256:" + hashlib.sha256(text).hexdigest(), op+PY+'++test_expect_success 'the node syncs the operations as it would without fixes' '+ tree_sync "$WORK/fixes-report.json" &&+ [ "$(report_field selected <"$WORK/fixes-report.json")" = 2 ] &&+ [ "$(report_field skipped <"$WORK/fixes-report.json")" = 1 ] &&+ [ "$(report_field applied <"$WORK/fixes-report.json")" = 2 ] &&+ [ "$(report_field last_seq <"$WORK/fixes-report.json")" = 16 ] &&+ [ "$(tree_state_field generation)" = 10 ] &&+ [ "$(tree_state_field head_seq)" = 16 ] &&+ [ "$(tree_state_field last_seq)" = 16 ] &&+ [ ! -e "$MATCH_PIN" ] && [ ! -e "$SKIP_PIN" ]+'++# Lines 14 to 16 of the outcomes record are those of the operations+# without fixes: 1 for the add and the delete, 2 for the operation+# without a match, each with the history root its digest folds to and the+# projection root the tree eventlog has.+test_expect_success 'the outcomes and the tree eventlog are those of the same tree without fixes' '+ python3 - "$OUTCOMES" "$TREE_EVENTLOG" "$DOCUMENT" <<'"'"'PY'"'"'+import hashlib, json, sys+outcomes, eventlog, document = sys.argv[1:4]+pub = json.load(open(document))+digests = {op["seq"]: bytes.fromhex(op["operation_digest"][len("sha256:"):])+ for op in pub["operations"]}+applied = {}+for text in open(eventlog, encoding="utf-8").read().splitlines():+ event = json.loads(text)+ applied[event["seq"]] = event["projection_root"]+lines = [json.loads(text)+ for text in open(outcomes, encoding="utf-8").read().splitlines()]+assert [line["seq"] for line in lines] == list(range(1, 17)), lines+assert sorted(s for s in applied if s > 13) == [14, 15], applied+history = bytes(32)+projection = "00" * 32+for line in lines:+ seq = line["seq"]+ history = hashlib.sha256(b"shirudo-tree-history\0" + history ++ digests[seq]).digest()+ projection = applied.get(seq, projection)+ assert line["history_root"] == history.hex(), line+ assert line["projection_root"] == projection, line+assert [line["outcome"] for line in lines[13:]] == [1, 1, 2], lines[13:]+PY+'++test_donediff --git a/testing/fuzz/corpus/tree/fixes b/testing/fuzz/corpus/tree/fixesnew file mode 100644index 00000000..0e8e84b0--- /dev/null+++ b/testing/fuzz/corpus/tree/fixes@@ -0,0 +1 @@+{"schema":1,"tree_id":"t","generation":3,"parent_manifest_digest":"sha256:d1a131e345e29aa6c2e01cb7edb6e8797804d87a0140f7372e9a0ca93fa62320","base":{"seq":0},"operations":[{"seq":1,"op":"add","id":"t","selector":{"architecture":["s390x"]},"artifact":{"repository":"oci://127.0.0.1:5532/ns/tree","manifest_digest":"sha256:cac08beec0a2d3554112aae593c63dfadda4e9192793351cf07f39c7f6706df4","layer_digest":"sha256:f8712d5eab7c627741d2b229c520156859e764641205d07a78a598a72a147c13","payload_sha256":"sha256:c5073b25dfb8f6b4136f62b9aa8e874bd9a38cbf8ce964a0a55cc86eee11a41f"},"fixes":["EXAMPLE-0101"],"operation_digest":"sha256:a33ee3eae67efc9098443c491a70df4711e70f4cc8a7da5691a99be39d1faf76"},{"seq":2,"op":"delete","id":"t","selector":{"architecture":["s390x"]},"artifact":{"repository":"oci://127.0.0.1:5532/ns/tree","manifest_digest":"sha256:b2b47fc759de49231fc9d9778cc42be4d6fbf5a12393bbb2fd62f75dcdd07066","layer_digest":"sha256:68d80fc35958ebbff8b82bbbbbf58dff8bc416b2a3e194ac0191499cf90bb14c","payload_sha256":"sha256:6d30cc3bd7b43b3ea26375e14353601f6d679c3b73d8434e76c83e5e8ac7ee99"},"operation_digest":"sha256:d9e8cb4347a5e43ace9b901a6ba8f068d8a306b31224a9a889e5c34e939101be"},{"seq":3,"op":"add","id":"t","selector":{"architecture":["s390x"]},"artifact":{"repository":"oci://127.0.0.1:5532/ns/tree","manifest_digest":"sha256:cac08beec0a2d3554112aae593c63dfadda4e9192793351cf07f39c7f6706df4","layer_digest":"sha256:f8712d5eab7c627741d2b229c520156859e764641205d07a78a598a72a147c13","payload_sha256":"sha256:c5073b25dfb8f6b4136f62b9aa8e874bd9a38cbf8ce964a0a55cc86eee11a41f"},"fixes":["CVE-2026-0001","EXAMPLE-0101"],"operation_digest":"sha256:a87247aa5b91f0df7c23d09c17b85e65d0de675323f02fa2a2edf7c7f4751164"}],"head":{"seq":3}}\ No newline at end of filediff --git a/testing/fuzz/corpus/tree/fixes-malformed b/testing/fuzz/corpus/tree/fixes-malformednew file mode 100644index 00000000..b7f5c0d6--- /dev/null+++ b/testing/fuzz/corpus/tree/fixes-malformed@@ -0,0 +1 @@+{"schema":1,"tree_id":"t","generation":3,"parent_manifest_digest":"sha256:d1a131e345e29aa6c2e01cb7edb6e8797804d87a0140f7372e9a0ca93fa62320","base":{"seq":0},"operations":[{"seq":1,"op":"add","id":"t","selector":{"architecture":["s390x"]},"artifact":{"repository":"oci://127.0.0.1:5532/ns/tree","manifest_digest":"sha256:cac08beec0a2d3554112aae593c63dfadda4e9192793351cf07f39c7f6706df4","layer_digest":"sha256:f8712d5eab7c627741d2b229c520156859e764641205d07a78a598a72a147c13","payload_sha256":"sha256:c5073b25dfb8f6b4136f62b9aa8e874bd9a38cbf8ce964a0a55cc86eee11a41f"},"fixes":{"not":[1,null,"\u0007"]},"operation_digest":"sha256:a33ee3eae67efc9098443c491a70df4711e70f4cc8a7da5691a99be39d1faf76"},{"seq":2,"op":"delete","id":"t","selector":{"architecture":["s390x"]},"artifact":{"repository":"oci://127.0.0.1:5532/ns/tree","manifest_digest":"sha256:b2b47fc759de49231fc9d9778cc42be4d6fbf5a12393bbb2fd62f75dcdd07066","layer_digest":"sha256:68d80fc35958ebbff8b82bbbbbf58dff8bc416b2a3e194ac0191499cf90bb14c","payload_sha256":"sha256:6d30cc3bd7b43b3ea26375e14353601f6d679c3b73d8434e76c83e5e8ac7ee99"},"fixes":["","B","A","A"],"operation_digest":"sha256:d9e8cb4347a5e43ace9b901a6ba8f068d8a306b31224a9a889e5c34e939101be"},{"seq":3,"op":"add","id":"t","selector":{"architecture":["s390x"]},"artifact":{"repository":"oci://127.0.0.1:5532/ns/tree","manifest_digest":"sha256:cac08beec0a2d3554112aae593c63dfadda4e9192793351cf07f39c7f6706df4","layer_digest":"sha256:f8712d5eab7c627741d2b229c520156859e764641205d07a78a598a72a147c13","payload_sha256":"sha256:c5073b25dfb8f6b4136f62b9aa8e874bd9a38cbf8ce964a0a55cc86eee11a41f"},"fixes":17,"operation_digest":"sha256:a87247aa5b91f0df7c23d09c17b85e65d0de675323f02fa2a2edf7c7f4751164"}],"head":{"seq":3}}\ No newline at end of filediff --git a/testing/fuzz/fuzz-tree.c b/testing/fuzz/fuzz-tree.cindex 7e6319f2..fa86dbb2 100644--- a/testing/fuzz/fuzz-tree.c+++ b/testing/fuzz/fuzz-tree.c@@ -4,7 +4,8 @@** tree_parse() on an upatch tree publication, the canonical* digest of every operation it accepts and the publication emitted again,- * which must read back with the same operations and digests.+ * bare and with the publisher's fixes, which must read back with the same+ * operations and digests.*/#include <stdlib.h>@@ -14,34 +15,56 @@#include <shirudo/string.h>#include "bpm_tree.h"+#include "json.h"#include "malloc.h"-int LLVMFuzzerTestOneInput(const __u8 *data, size_t size)+static int emit_fixes(struct json_emit *e, int index, void *ctx)+{+ if (index % 2)+ return 0;+ json_arr_open(e, "fixes");+ json_str(e, "EXAMPLE-0101");+ json_str(e, ((const struct tree_publication *)ctx)->tree_id);+ json_arr_close(e);+ return 0;+}++static void read_back(const struct tree_publication *pub,+ const struct tree_emit_extra *extra){- struct tree_publication pub, again;char digest[72], back[72], *out;+ struct tree_publication again;size_t len;- if (tree_parse((const char *)data, size, &pub))- return 0;- if (tree_emit_publication(&pub, &out, &len)) {- tree_publication_free(&pub);- return 0;- }+ if (tree_emit_publication(pub, extra, &out, &len))+ return;if (tree_parse(out, len, &again) ||- again.n_operations != pub.n_operations ||- strcmp(again.tree_id, pub.tree_id) ||- again.generation != pub.generation ||- again.head_seq != pub.head_seq)+ again.n_operations != pub->n_operations ||+ strcmp(again.tree_id, pub->tree_id) ||+ again.generation != pub->generation ||+ again.head_seq != pub->head_seq)abort();- for (int i = 0; i < pub.n_operations; i++) {- if (tree_operation_digest(&pub.operations[i], digest) !=+ for (int i = 0; i < pub->n_operations; i++) {+ if (tree_operation_digest(&pub->operations[i], digest) !=tree_operation_digest(&again.operations[i], back) ||- strcmp(digest, back))+ strcmp(digest, back) ||+ strcmp(again.operations[i].operation_digest,+ pub->operations[i].operation_digest))abort();}tree_publication_free(&again);xfree(out, len);+}++int LLVMFuzzerTestOneInput(const __u8 *data, size_t size)+{+ struct tree_publication pub;+ struct tree_emit_extra extra = { emit_fixes, &pub };++ if (tree_parse((const char *)data, size, &pub))+ return 0;+ read_back(&pub, NULL);+ read_back(&pub, &extra);tree_publication_free(&pub);return 0;}diff --git a/testing/proofs/cbmc/bpm-tree-writer.c b/testing/proofs/cbmc/bpm-tree-writer.cindex 51061f7f..ca68300d 100644--- a/testing/proofs/cbmc/bpm-tree-writer.c+++ b/testing/proofs/cbmc/bpm-tree-writer.c@@ -78,7 +78,7 @@ void harness(void)char *body;int ret;- __CPROVER_assert(!tree_emit_publication(pub, &body, &len),+ __CPROVER_assert(!tree_emit_publication(pub, NULL, &body, &len),"a publication written");ret = tree_parse(body, len, &back);/* bpm tree append refuses to write the last three. */diff --git a/testing/unit/bpm_tree.c b/testing/unit/bpm_tree.cindex b4360dfc..3e1e61bc 100644--- a/testing/unit/bpm_tree.c+++ b/testing/unit/bpm_tree.c@@ -7,6 +7,7 @@#include <shirudo/string.h>#include "bpm_tree.h"+#include "json.h"#include "malloc.h"#include "unit.h"@@ -79,7 +80,7 @@ static void publication_reads_back(void)ASSERT_EQ(tree_operation_digest(op, op->operation_digest), 0);ASSERT_EQ(tree_publication_append(&pub, op), 0);pub.head_seq = 1;- ASSERT_EQ(tree_emit_publication(&pub, &doc, &len), 0);+ ASSERT_EQ(tree_emit_publication(&pub, NULL, &doc, &len), 0);ASSERT_EQ(tree_parse(doc, len, &back), 0);EXPECT_EQ(back.schema, 1);ASSERT_EQ(back.n_operations, 1);@@ -93,6 +94,97 @@ static void publication_reads_back(void)xfree(op, sizeof(*op));}+/* Keys past the emitter's bound, as a publisher's fixes can be. */+static int emit_fixes(struct json_emit *e, int index, void *ctx)+{+ char id[201];++ if (ctx)+ return -EIO;+ memset(id, 'A' + index, sizeof(id) - 1);+ id[sizeof(id) - 1] = '\0';+ json_arr_open(e, "fixes");+ for (int i = 0; i < 64; i++)+ json_str(e, id);+ json_arr_close(e);+ return 0;+}++static void publication_carries_keys_outside_the_digest(void)+{+ struct tree_publication pub = { .schema = 1, .generation = 1 };+ struct tree_emit_extra extra = { emit_fixes, NULL };+ struct tree_publication back = {};+ struct tree_operation *op = operation();+ char *doc = NULL, again[72];+ const char *fixes, *digest;+ size_t len = 0;++ set(pub.tree_id, sizeof(pub.tree_id), "t");+ ASSERT_EQ(tree_operation_digest(op, op->operation_digest), 0);+ ASSERT_EQ(tree_publication_append(&pub, op), 0);+ pub.head_seq = 1;+ ASSERT_EQ(tree_emit_publication(&pub, &extra, &doc, &len), 0);+ EXPECT_GT(len, 64 * 200);+ fixes = strstr(doc, "},\"fixes\":[\"AAAA");+ digest = strstr(doc, "\"],\"operation_digest\":");+ EXPECT_TRUE(fixes && digest && fixes < digest);+ ASSERT_EQ(tree_parse(doc, len, &back), 0);+ ASSERT_EQ(back.n_operations, 1);+ ASSERT_EQ(tree_operation_digest(&back.operations[0], again), 0);+ EXPECT_STREQ(again, op->operation_digest);+ EXPECT_STREQ(back.operations[0].operation_digest, op->operation_digest);+ xfree(doc, len);+ doc = NULL;+ extra.ctx = &extra;+ EXPECT_EQ(tree_emit_publication(&pub, &extra, &doc, &len), -EIO);+ EXPECT_FALSE(doc);+ tree_publication_free(&pub);+ tree_publication_free(&back);+ tree_selector_free(&op->selector);+ xfree(op, sizeof(*op));+}++static int emit_malformed_fixes(struct json_emit *e, int index, void *ctx)+{+ json_obj_open_key(e, "fixes");+ json_arr_open(e, "n");+ json_raw_value(e, "null", 4);+ json_str(e, "\a");+ json_arr_close(e);+ json_obj_close(e);+ json_arr_open(e, "fixes");+ json_str(e, "");+ json_arr_close(e);+ return 0;+}++static void publication_reads_past_malformed_fixes(void)+{+ struct tree_emit_extra extra = { emit_malformed_fixes, NULL };+ struct tree_publication pub = { .schema = 1, .generation = 1 };+ struct tree_publication back = {};+ struct tree_operation *op = operation();+ char *doc = NULL;+ size_t len = 0;++ set(pub.tree_id, sizeof(pub.tree_id), "t");+ ASSERT_EQ(tree_operation_digest(op, op->operation_digest), 0);+ ASSERT_EQ(tree_publication_append(&pub, op), 0);+ pub.head_seq = 1;+ ASSERT_EQ(tree_emit_publication(&pub, &extra, &doc, &len), 0);+ EXPECT_TRUE(strstr(doc, "\"fixes\":{\"n\":[null,\"\\u0007\"]}"));+ ASSERT_EQ(tree_parse(doc, len, &back), 0);+ EXPECT_EQ(tree_publication_check(&back), 0);+ ASSERT_EQ(back.n_operations, 1);+ EXPECT_EQ(tree_operation_validate(&back.operations[0]), 0);+ xfree(doc, len);+ tree_publication_free(&pub);+ tree_publication_free(&back);+ tree_selector_free(&op->selector);+ xfree(op, sizeof(*op));+}+/* What sync checks of an operation before it applies one. */static void operation_validates_against_its_digest(void){@@ -182,6 +274,8 @@ static void publication_follows_the_recorded_state(void)static const struct unit_case cases[] = {UNIT_CASE(operation_takes_no_control_character),UNIT_CASE(publication_reads_back),+ UNIT_CASE(publication_carries_keys_outside_the_digest),+ UNIT_CASE(publication_reads_past_malformed_fixes),UNIT_CASE(operation_validates_against_its_digest),UNIT_CASE(publication_runs_from_base_to_head),UNIT_CASE(publication_follows_the_recorded_state),diff --git a/testing/vm/build-bundle.sh b/testing/vm/build-bundle.shindex 53647b45..e951a013 100755--- a/testing/vm/build-bundle.sh+++ b/testing/vm/build-bundle.sh@@ -448,7 +448,7 @@ build_tree_test_registry()local payloads="$FIXTURE_WORK/tree-payload"local reference- # One append-only tree that t7101 to t7106 walk in order:+ # One append-only tree that t7101 to t7107 walk in order:# the tree state a target writes is sealed, so no test can start# over, and each generation extends the one before it.python3 - "$registry_dir" \@@ -511,7 +511,9 @@ def artifact(repository, path, title, payload_sha256):}-def operation(seq, name, selector, artifact_info, op="add"):+# fixes, when given, goes where a publisher writes it: after the artifact,+# outside the digest.+def operation(seq, name, selector, artifact_info, op="add", fixes=None):unsigned = {"seq": seq,"op": op,@@ -521,7 +523,10 @@ def operation(seq, name, selector, artifact_info, op="add"):}operation_digest = digest(json.dumps(unsigned, separators=(",", ":")).encode())- return dict(unsigned, operation_digest=operation_digest)+ published = dict(unsigned)+ if fixes is not None:+ published["fixes"] = fixes+ return dict(published, operation_digest=operation_digest)match_artifact = artifact("shirudo/tree-match", match_path,@@ -564,10 +569,20 @@ operations = [operation(12, "shirudo-test-tree-skip", this_node, skip_artifact),operation(13, "shirudo-test-tree-skip", this_node, skip_unload_artifact,op="delete"),+ # t7107: fixes as a publisher writes it, then fixes no publisher+ # writes, on a delete and on an operation without a match.+ operation(14, "shirudo-test-tree-skip", this_node, skip_artifact,+ fixes=["EXAMPLE-0101"]),+ operation(15, "shirudo-test-tree-skip", this_node, skip_unload_artifact,+ op="delete",+ fixes={"not": ["an", "array"], "n": [1, None, "\u0007"]}),+ operation(16, "shirudo-test-tree-match", other_node, match_artifact,+ fixes=["", "B", "A", "A", "x y\n"] ++ ["ID-%d" % i for i in range(17)]),]heads = {"stable": 2, "updated": 3, "deleted": 4, "restored": 5,"kconfig": 6, "reloaded": 7, "outcomes": 10, "stopped": 12,- "fetched": 13}+ "fetched": 13, "fixes": 16}for generation, (reference, head) in enumerate(heads.items(), start=1):publication = {"schema": 1,@@ -583,7 +598,7 @@ for generation, (reference, head) in enumerate(heads.items(), start=1):PYfor reference in stable updated deleted restored kconfig reloaded \- outcomes stopped fetched; do+ outcomes stopped fetched fixes; doopenssl cms -sign -binary -md sha512 \-in "$payloads-$reference.json" \-signer "$FIXTURE_WORK/trusted/cert.der" \@@ -612,7 +627,7 @@ def write(path, body):for reference in ("stable", "updated", "deleted", "restored", "kconfig",- "reloaded", "outcomes", "stopped", "fetched"):+ "reloaded", "outcomes", "stopped", "fetched", "fixes"):stem = payloads.name + "-" + referencepayload = payloads.with_name(stem + ".json").read_bytes()signature = payloads.with_name(stem + ".sig").read_bytes()diff --git a/testing/vm/image-fixtures.sh b/testing/vm/image-fixtures.shindex 2175719c..d3dd94b9 100755--- a/testing/vm/image-fixtures.sh+++ b/testing/vm/image-fixtures.sh@@ -73,7 +73,7 @@ donefor name in config-boot-keys config-live-new-key config-live-revoke-a config-a config-b config-bad config-revoke \config-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-stopped config-tree-fetched config-tree-fixes \config-otel config-jsonl config-jsonl-bad config-interrupted config-end2end \config-local-stack config-builtin config-untrusted; do[ "$name" != config-builtin ] || [ -n "$builtin_key" ] || continuediff --git a/tools/shirudo-build/bpm-build.c b/tools/shirudo-build/bpm-build.cindex 297b76c1..7dd5c26a 100644--- a/tools/shirudo-build/bpm-build.c+++ b/tools/shirudo-build/bpm-build.c@@ -302,7 +302,7 @@ static int build_parse_selector_kv(const char *key, const char *value,return 0;}-static bool build_fix_id_ok(const char *id)+bool bpm_fix_id_ok(const char *id){return id[0] && !id[strspn(id, BPM_FIX_ID_CHARS)];}@@ -342,7 +342,7 @@ static int build_parse_fixes(const char *value, struct bpm_fixes *fixes)pr_err("Beefile: fixes holds an empty ID");return -EINVAL;}- if (!build_fix_id_ok(fixes->ids[i])) {+ if (!bpm_fix_id_ok(fixes->ids[i])) {pr_err("Beefile: ID %d of fixes has a character outside [A-Za-z0-9._:-]",i + 1);return -EINVAL;diff --git a/tools/shirudo-build/bpm-publish.c b/tools/shirudo-build/bpm-publish.cindex 0db7c7eb..10c77c6f 100644--- a/tools/shirudo-build/bpm-publish.c+++ b/tools/shirudo-build/bpm-publish.c@@ -562,6 +562,116 @@ static int tree_describe_blob(const void *body, size_t len, const char *media,return 0;}+static bool tree_fixes_valid(const struct bpm_fixes *fixes)+{+ if (!fixes->n)+ return false;+ for (int i = 0; i < fixes->n; i++) {+ if (!bpm_fix_id_ok(fixes->ids[i]) ||+ (i && strcmp(fixes->ids[i - 1], fixes->ids[i]) >= 0))+ return false;+ }+ return true;+}++struct tree_fixes_reader {+ const struct tree_publication *pub;+ struct bpm_fixes *fixes;+ int n;+ struct json_field *fixes_key;+ __s64 seq;+ struct bpm_fixes op;+ char id[TREE_STRING_MAX];+};++static int tree_fixes_take_id(void *ctx)+{+ struct tree_fixes_reader *r = ctx;++ if (r->op.n >= BPM_BUILD_MAX_FIXES)+ return -E2BIG;+ memcpy(r->op.ids[r->op.n++], r->id, sizeof(r->id));+ return 0;+}++static int tree_fixes_take_operation(void *ctx)+{+ struct tree_fixes_reader *r = ctx;+ const struct tree_operation *op;++ if (r->n >= r->pub->n_operations)+ return -EINVAL;+ op = &r->pub->operations[r->n];+ if (r->seq != op->seq)+ return -EINVAL;+ if (r->fixes_key->seen &&+ (strcmp(op->op, "add") || !tree_fixes_valid(&r->op)))+ return -EINVAL;+ r->fixes[r->n++] = r->op;+ r->seq = 0;+ r->op.n = 0;+ return 0;+}++static int tree_fixes_parse(struct tree_fixes_reader *r,+ const struct bpm_buffer *document)+{+ struct json_array id_sink = { tree_fixes_take_id, r };+ struct json_array operation_sink = { tree_fixes_take_operation, r };+ struct json_field id[] = {+ { "", JSON_T_STRING, r->id, sizeof(r->id), 0, NULL, 0 },+ };+ struct json_field operation[] = {+ { "seq", JSON_T_INT, &r->seq, 0, 0, NULL, 0 },+ { "fixes", JSON_T_ARRAY, &id_sink, 0, 0, id, ARRAY_SIZE(id) },+ };+ struct json_field root[] = {+ { "operations", JSON_T_ARRAY, &operation_sink, 0, 0,+ operation, ARRAY_SIZE(operation) },+ };++ r->fixes_key = &operation[1];+ return json_parse((const char *)document->data, document->len, root,+ ARRAY_SIZE(root));+}++/*+ * tree_parse() is the node's parser and keeps no key a node does not+ * use, so the fixes of the previous publication come from a second read+ * of its bytes. fixes has room for every operation of pub.+ */+static int tree_read_fixes(const struct bpm_buffer *document,+ const struct tree_publication *pub,+ struct bpm_fixes *fixes)+{+ struct tree_fixes_reader *r;+ int ret;++ r = xcalloc(1, sizeof(*r));+ if (!r)+ return -ENOMEM;+ r->pub = pub;+ r->fixes = fixes;+ ret = tree_fixes_parse(r, document);+ if (!ret && r->n != pub->n_operations)+ ret = -EINVAL;+ xfree(r, sizeof(*r));+ return ret;+}++static int tree_emit_fixes(struct json_emit *e, int index, void *ctx)+{+ const struct bpm_fixes *fixes = (const struct bpm_fixes *)ctx + index;++ if (!fixes->n)+ return 0;+ json_arr_open(e, "fixes");+ for (int i = 0; i < fixes->n; i++)+ json_str(e, fixes->ids[i]);+ json_arr_close(e);+ return 0;+}+/** Describe one immutable upatch artifact for the tree, with the manifest* its upload will put. The bytes are checked to be the directive the@@ -786,6 +896,10 @@ static int cmd_bpm_tree_append(int argc, char **argv)char parent[BPM_MAX_DIGEST] = {}, digest[72];struct tree_xdp_classes *seen = NULL;struct tree_upload *uploads = NULL;+ struct bpm_buffer previous = {};+ struct bpm_fixes *fixes = NULL;+ struct tree_emit_extra extra;+ size_t n_fixes = 0;struct tree_publication pub = {};struct tree_operation *op = NULL;size_t len, payload_len = 0, sig_len = 0;@@ -904,8 +1018,11 @@ static int cmd_bpm_tree_append(int argc, char **argv)pr_err("bpm tree append: the repository must be oci://registry/repository");goto out;}- ret = bpm_tree_fetch_publication(&c, repository, reference, previous_cert,- NULL, &pub, parent, sizeof(parent));+ ret = bpm_tree_fetch_document(&c, repository, reference, previous_cert,+ NULL, &previous, parent, sizeof(parent));+ if (!ret)+ ret = tree_parse((const char *)previous.data, previous.len,+ &pub);if (ret == -ENOENT) {pub = (struct tree_publication){ .schema = 1,.generation = 1 };@@ -936,6 +1053,21 @@ static int cmd_bpm_tree_append(int argc, char **argv)bpm_copy_string(pub.parent_manifest_digest,sizeof(pub.parent_manifest_digest), parent);+ n_fixes = min_t(size_t, pub.n_operations + spec->n_upatches,+ TREE_MAX_OPS);+ n_fixes = max(n_fixes, 1U);+ fixes = xcalloc(n_fixes, sizeof(*fixes));+ if (!fixes) {+ ret = -ENOMEM;+ goto out;+ }+ if (previous.data && tree_read_fixes(&previous, &pub, fixes)) {+ pr_err("bpm tree append: the publication at %s:%s has a fixes list bpm tree append would not write, so it cannot carry it into the next generation",+ repo_ref, reference);+ ret = -EINVAL;+ goto out;+ }+op = xmalloc(sizeof(*op));seen = xcalloc(1, sizeof(*seen));uploads = xcalloc(BPM_BUILD_MAX_ENTRIES, sizeof(*uploads));@@ -1013,6 +1145,8 @@ static int cmd_bpm_tree_append(int argc, char **argv)goto out;seen->classes[pub.n_operations - 1] = classes;seen->known[pub.n_operations - 1] = true;+ if (!unload)+ fixes[pub.n_operations - 1] = u->tree.fixes;pub.head_seq = op->seq;appended++;}@@ -1021,7 +1155,8 @@ static int cmd_bpm_tree_append(int argc, char **argv)ret = -ENOENT;goto out;}- ret = tree_emit_publication(&pub, &payload, &payload_len);+ extra = (struct tree_emit_extra){ tree_emit_fixes, fixes };+ ret = tree_emit_publication(&pub, &extra, &payload, &payload_len);if (ret)goto out;ret = sign_detached(payload, payload_len, key, cert, &sig, &sig_len);@@ -1083,6 +1218,8 @@ out:xfree(uploads[i].body, uploads[i].body_len + 1);}xfree(uploads, BPM_BUILD_MAX_ENTRIES * sizeof(*uploads));+ xfree(fixes, n_fixes * sizeof(*fixes));+ bpm_buffer_free(&previous);tree_publication_free(&pub);bpm_build_spec_free(spec);xfree(beefile, len + 1);diff --git a/tools/shirudo-build/bpm.h b/tools/shirudo-build/bpm.hindex f0efc315..25f53817 100644--- a/tools/shirudo-build/bpm.h+++ b/tools/shirudo-build/bpm.h@@ -109,6 +109,7 @@ int bpm_build_parse_beefile(const __u8 *body, size_t len,struct bpm_build_spec *spec);void bpm_build_spec_free(struct bpm_build_spec *spec);void bpm_strings_sort(char strings[][TREE_STRING_MAX], int n);+bool bpm_fix_id_ok(const char *id);int build_bpm(int argc, char **argv);int build_bpm_push(int argc, char **argv);diff --git a/util/bpm_package.c b/util/bpm_package.cindex 55edf310..c1915898 100644--- a/util/bpm_package.c+++ b/util/bpm_package.c@@ -892,15 +892,14 @@ out:return ret;}-int bpm_tree_fetch_publication(struct bpm_oci_client *c,- const char *repository,- const char *reference,- const char *cert_path,- const struct trusted_set *trusted,- struct tree_publication *pub,- char *manifest_digest, size_t digest_sz)+int bpm_tree_fetch_document(struct bpm_oci_client *c,+ const char *repository, const char *reference,+ const char *cert_path,+ const struct trusted_set *trusted,+ struct bpm_buffer *payload,+ char *manifest_digest, size_t digest_sz){- struct bpm_buffer manifest = {}, payload = {}, sig = {};+ struct bpm_buffer manifest = {}, sig = {};struct bpm_descriptor *layers = NULL;char url[PATH_MAX], hex[65];int nl = 0, ret;@@ -933,19 +932,40 @@ int bpm_tree_fetch_publication(struct bpm_oci_client *c,if (ret)goto out;ret = bpm_oci_get_signed(c, repository, layers, nl, BPM_TREE_MEDIA,- BPM_TREE_SIG_MEDIA, &payload, &sig);+ BPM_TREE_SIG_MEDIA, payload, &sig);if (ret)goto out;- ret = trusted ? keys_verify_signature(trusted, payload.data, payload.len,- sig.data, sig.len, NULL) :- bpm_verify_cms(payload.data, payload.len, sig.data, sig.len, cert_path);- if (ret)- goto out;- ret = tree_parse((const char *)payload.data, payload.len, pub);+ ret = trusted ? keys_verify_signature(trusted, payload->data,+ payload->len, sig.data, sig.len,+ NULL) :+ bpm_verify_cms(payload->data, payload->len, sig.data, sig.len,+ cert_path);out:+ if (ret)+ bpm_buffer_free(payload);xfree(layers, BPM_MAX_ENTRIES * sizeof(*layers));bpm_buffer_free(&manifest);- bpm_buffer_free(&payload);bpm_buffer_free(&sig);return ret;}++int bpm_tree_fetch_publication(struct bpm_oci_client *c,+ const char *repository,+ const char *reference,+ const char *cert_path,+ const struct trusted_set *trusted,+ struct tree_publication *pub,+ char *manifest_digest, size_t digest_sz)+{+ struct bpm_buffer payload = {};+ int ret;++ ret = bpm_tree_fetch_document(c, repository, reference, cert_path,+ trusted, &payload, manifest_digest,+ digest_sz);+ if (ret)+ return ret;+ ret = tree_parse((const char *)payload.data, payload.len, pub);+ bpm_buffer_free(&payload);+ return ret;+}diff --git a/util/bpm_package.h b/util/bpm_package.hindex 7f0dc39d..7b22d0c1 100644--- a/util/bpm_package.h+++ b/util/bpm_package.h@@ -100,7 +100,15 @@ int bpm_pkg_load_info(const char *archive, struct bpm_package_info *info);* layer against its descriptor and the payload against trusted, or* cert_path when trusted is NULL, and* parse it. -ENOENT when the reference does not exist yet.+ * bpm_tree_fetch_document() stops before the parse and hands over the+ * checked bytes, which the caller frees with bpm_buffer_free().*/+int bpm_tree_fetch_document(struct bpm_oci_client *c,+ const char *repository, const char *reference,+ const char *cert_path,+ const struct trusted_set *trusted,+ struct bpm_buffer *payload,+ char *manifest_digest, size_t digest_sz);int bpm_tree_fetch_publication(struct bpm_oci_client *c,const char *repository, const char *reference,const char *cert_path,diff --git a/util/bpm_tree.c b/util/bpm_tree.cindex dde37892..50a19ace 100644--- a/util/bpm_tree.c+++ b/util/bpm_tree.c@@ -486,15 +486,14 @@ static void tree_emit_artifact(struct json_emit *e,json_obj_close(e);}-static int tree_emit_operation(struct json_emit *e,- const struct tree_operation *op,- bool with_digest)+/* The five keys the operation digest covers, into an open object. */+static int tree_emit_operation_keys(struct json_emit *e,+ const struct tree_operation *op){int ret;if (!tree_operation_text(op))return -EINVAL;- json_obj_open(e);json_kv_int(e, "seq", op->seq);json_kv_string(e, "op", op->op);json_kv_string(e, "id", op->id);@@ -502,8 +501,23 @@ static int tree_emit_operation(struct json_emit *e,if (ret)return ret;tree_emit_artifact(e, &op->artifact);- if (with_digest)- json_kv_string(e, "operation_digest", op->operation_digest);+ return 0;+}++static int tree_emit_operation(struct json_emit *e,+ const struct tree_publication *pub, int index,+ const struct tree_emit_extra *extra)+{+ const struct tree_operation *op = &pub->operations[index];+ int ret;++ json_obj_open(e);+ ret = tree_emit_operation_keys(e, op);+ if (!ret && extra)+ ret = extra->operation(e, index, extra->ctx);+ if (ret)+ return ret;+ json_kv_string(e, "operation_digest", op->operation_digest);json_obj_close(e);return e->err;}@@ -525,7 +539,11 @@ int tree_operation_digest(const struct tree_operation *op,if (!body)return -ENOMEM;e = (struct json_emit){ .buf = body, .cap = body_cap };- ret = tree_emit_operation(&e, op, false);+ json_obj_open(&e);+ ret = tree_emit_operation_keys(&e, op);+ json_obj_close(&e);+ if (!ret)+ ret = e.err;if (!ret && sha256_buffer(body, e.len, digest))ret = -EIO;if (!ret) {@@ -578,9 +596,11 @@ static size_t tree_operation_bound(const struct tree_operation *op)/** Serialise a publication in the field order every publisher has used:* schema, tree_id, generation, parent_manifest_digest (when any), base,- * operations, head.+ * operations, head. The bound covers the published form; the emitter+ * grows past it only for keys extra adds.*/int tree_emit_publication(const struct tree_publication *pub,+ const struct tree_emit_extra *extra,char **out, size_t *out_len){struct json_emit e;@@ -593,7 +613,9 @@ int tree_emit_publication(const struct tree_publication *pub,body = xmalloc(cap);if (!body)return -ENOMEM;- e = (struct json_emit){ .buf = body, .cap = cap };+ e = (struct json_emit){+ .buf = body, .cap = cap, .max = JSON_MAX_BYTES + 1,+ };json_obj_open(&e);json_kv_int(&e, "schema", pub->schema);json_kv_string(&e, "tree_id", pub->tree_id);@@ -606,7 +628,7 @@ int tree_emit_publication(const struct tree_publication *pub,json_obj_close(&e);json_arr_open(&e, "operations");for (int i = 0; !ret && i < pub->n_operations; i++)- ret = tree_emit_operation(&e, &pub->operations[i], true);+ ret = tree_emit_operation(&e, pub, i, extra);json_arr_close(&e);json_obj_open_key(&e, "head");json_kv_int(&e, "seq", pub->head_seq);@@ -618,10 +640,10 @@ int tree_emit_publication(const struct tree_publication *pub,if (!ret && e.len > JSON_MAX_BYTES)ret = -E2BIG;if (ret) {- xfree(body, cap);+ xfree(e.buf, e.cap);return ret;}- *out = body;+ *out = e.buf;*out_len = e.len;return 0;}diff --git a/util/bpm_tree.h b/util/bpm_tree.hindex a9e00691..c0f1133f 100644--- a/util/bpm_tree.h+++ b/util/bpm_tree.h@@ -111,10 +111,20 @@ void tree_publication_free(struct tree_publication *pub);* ("sha256:" + 64 hex) over an operation without its digest field, and* the publication document. The emitted document is xmalloc'd; release* it with xfree(out, out_len).+ *+ * extra, NULL for none, adds keys to the operation at index of+ * pub->operations after its artifact, outside the operation digest: the+ * publisher's fixes, which no node reads.*/+struct tree_emit_extra {+ int (*operation)(struct json_emit *e, int index, void *ctx);+ void *ctx;+};+int tree_operation_digest(const struct tree_operation *op,char out[72]);int tree_emit_publication(const struct tree_publication *pub,+ const struct tree_emit_extra *extra,char **out, size_t *out_len);/*