Skip to content

eBPF-based security platform

testing: run the keepalive backend end to end

John Fastabend5bbefbc6213b
diff --git a/.agents/skills/testing/SKILL.md b/.agents/skills/testing/SKILL.md
index 141fd64c..d1f0fd54 100644
--- a/.agents/skills/testing/SKILL.md
+++ b/.agents/skills/testing/SKILL.md
@@ -24,6 +24,10 @@ make -C testing fuzz [FUZZ_SECONDS=60]
make -C testing help
```
+The end2end tier runs t9107 against the keepalive backend that
+`BACKEND_DIR` names, a checkout or a git URL, `../backend` by default;
+without one t9107 skips, so say so when reporting the tier.
+
Host tests run as they are. A target test, `t?1??`, runs in a fresh VM
per family, which needs KVM, an unlimited `ulimit -l`, the test kernel
and the bundle, but not root; see
diff --git a/Documentation/concepts/background/siem-export.rst b/Documentation/concepts/background/siem-export.rst
index c8d8bbdb..0b1b3bab 100644
--- a/Documentation/concepts/background/siem-export.rst
+++ b/Documentation/concepts/background/siem-export.rst
@@ -107,9 +107,10 @@ keepalive of every target it knows against the current time. It knows
the targets that reported within a longer window, such as a day, so a
target silent for longer drops out of the alert. A
keepalive runs a minute after the previous run ends and may wait up to
-30 seconds for the config operation lock, so five minutes without one
-spans several missed intervals. A tree sync holds that lock for as long
-as it runs, so a target whose syncs take minutes needs a longer
+30 seconds for the config operation lock. A tree sync holds that lock
+for as long as it runs, and a keepalive that cannot take it sends
+nothing, so ten minutes without one spans several missed intervals and
+a sync of a few minutes. A target whose syncs take longer needs a longer
window.
A verdict other than ``ok`` is the second. The keepalive's severity
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rst
index dae2c355..fb7b1b51 100644
--- a/Documentation/contribute/testing/test-coverage.rst
+++ b/Documentation/contribute/testing/test-coverage.rst
@@ -616,6 +616,14 @@ signed config image.
0x1 to exec 0x2, and denies 0x1 and socket policy B from execing
unlabeled files; socket-storage bits allow 127.0.0.1 for policy A
and deny it for B; final evidence includes the loaded policy upatch
+ * - ``t9107-keepalive-backend``
+ - The keepalive backend that ``BACKEND_DIR`` names: its tree ingest
+ job loads the example publication through ``bpm tree show``, the
+ example keepalives of node A and node B with their recorded quotes
+ pass its collector and ``shirudo-quote-check``, and
+ ``node_status`` gives the example's results; a body altered in
+ transit is ``body_mismatch``, a replayed record collapses and an
+ older one does not become the latest
Unit suites and fuzz targets
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -786,9 +794,9 @@ Coverage by area
inheritance: ``t6141``, ``t6142``
* - Telemetry
- ``t4006``, ``t4104``, ``t6139``, ``t7109``, ``t8001`` to
- ``t8007``, ``t8101`` to ``t8106``, ``t9101`` to ``t9105``. Fuzz:
- ``otel``, ``quote-check``, ``serializer``. Unit: ``keepalive``,
- ``keepalive_quote``, ``sysinfo``
+ ``t8007``, ``t8101`` to ``t8106``, ``t9101`` to ``t9105``,
+ ``t9107``. Fuzz: ``otel``, ``quote-check``, ``serializer``.
+ Unit: ``keepalive``, ``keepalive_quote``, ``sysinfo``
* - Decoders
- ``t3002``, ``t8102``, ``t9101``. Fuzz: ``decoder``
* - Tamper counters
diff --git a/Documentation/contribute/testing/testing.rst b/Documentation/contribute/testing/testing.rst
index 13bd832a..34a417d2 100644
--- a/Documentation/contribute/testing/testing.rst
+++ b/Documentation/contribute/testing/testing.rst
@@ -637,6 +637,25 @@ The host side writes to ``build/test-vm/end2end/``. The guest reaches
the registry and collector through QEMU's address for the host. ClickHouse
is available to the collector on the test's Docker network.
+``t9107`` runs the reference keepalive backend, which lives in a
+repository of its own, ``shirudo-dev/backend``. ``host.sh`` finds it
+through ``BACKEND_DIR``: a directory, relative to the checkout when the
+path is relative, ``../backend`` by default, or a git URL, which it
+clones into ``build/test-vm/end2end/backend``. It starts a ClickHouse of
+the backend's own on ``http://127.0.0.1:18125``, with the backend's schema
+and ``shirudo-quote-check`` as ``tpm_quote_check``, and a collector with
+the backend's configuration on ``https://127.0.0.1:14320``. It publishes
+the example tree of :src:`testing/fixtures/keepalive/` signed with the
+operator key and loads it with the backend's tree ingest job, which runs
+``bpm tree show``. In the guest, ``t9107`` sends the example keepalives
+with their recorded quotes through that collector and queries
+ClickHouse, both through QEMU's address for the host. Without
+``BACKEND_DIR`` and without ``../backend``, ``t9107`` skips:
+
+.. code-block:: console
+
+ # make -C testing end2end BACKEND_DIR=/path/to/backend
+
Select test scripts
~~~~~~~~~~~~~~~~~~~
diff --git a/Documentation/operate/integrations/clickhouse.rst b/Documentation/operate/integrations/clickhouse.rst
index 339cc536..63013b27 100644
--- a/Documentation/operate/integrations/clickhouse.rst
+++ b/Documentation/operate/integrations/clickhouse.rst
@@ -15,7 +15,9 @@ own.
This is a do-it-yourself example to get started from, not an
integration that shirudo ships or maintains. Adapt retention, access
-control and sizing to your deployment.
+control and sizing to your deployment. To check the keepalives' quotes
+and compare each target with its upatch tree as well, start from the
+:doc:`keepalive-backend` instead.
Before you begin
----------------
@@ -143,10 +145,10 @@ from Grafana with its ClickHouse data source or from any tool that can
run SQL. :doc:`/operate/run/telemetry` explains each signal under what
to alert on.
-#. Find targets that stopped sending keepalives. Five minutes covers
- several keepalive intervals and the 30 seconds a keepalive may wait
- for the config operation lock; a target whose tree syncs run for
- longer needs a longer threshold:
+#. Find targets that stopped sending keepalives. Ten minutes covers
+ several keepalive intervals and a tree sync of a few minutes, which
+ holds the config operation lock that a keepalive waits for; a target
+ whose tree syncs run for longer needs a longer threshold:
.. code-block:: sql
@@ -155,7 +157,7 @@ to alert on.
FROM shirudo.otel_logs
WHERE ServiceName = 'shirudo' AND EventName = 'shirudo.keepalive'
GROUP BY host
- HAVING last_seen < now() - INTERVAL 5 MINUTE;
+ HAVING last_seen < now() - INTERVAL 10 MINUTE;
#. Find targets that reported a verdict other than ``ok`` in the last
five minutes:
@@ -199,5 +201,7 @@ Next steps
- :doc:`/upatches/write/decoders` to turn a map into log records or
metrics
- :doc:`grafana` to chart the same data
+- :doc:`keepalive-backend` to check the quotes and the tree state the
+ keepalives report
- :doc:`/concepts/background/siem-export` for how the records reach a
backend and what to build on them
diff --git a/Documentation/operate/integrations/elasticsearch.rst b/Documentation/operate/integrations/elasticsearch.rst
index 97265e67..2b8f7bb7 100644
--- a/Documentation/operate/integrations/elasticsearch.rst
+++ b/Documentation/operate/integrations/elasticsearch.rst
@@ -150,17 +150,17 @@ rows. In Elastic Security, use the query in a detection rule of type
ES|QL instead. :doc:`/operate/run/telemetry` explains each signal under
what to alert on.
-#. Find targets that stopped sending keepalives. Five minutes covers
- several keepalive intervals and the 30 seconds a keepalive may wait
- for the config operation lock; a target whose tree syncs run for
- longer needs a longer threshold:
+#. Find targets that stopped sending keepalives. Ten minutes covers
+ several keepalive intervals and a tree sync of a few minutes, which
+ holds the config operation lock that a keepalive waits for; a target
+ whose tree syncs run for longer needs a longer threshold:
.. code-block:: text
FROM logs-generic.otel-default
| WHERE event_name == "shirudo.keepalive" AND @timestamp > NOW() - 1 day
| STATS last_seen = MAX(@timestamp) BY host.name
- | WHERE last_seen < NOW() - 5 minutes
+ | WHERE last_seen < NOW() - 10 minutes
A target silent for longer than a day drops out of the query.
diff --git a/Documentation/operate/integrations/grafana.rst b/Documentation/operate/integrations/grafana.rst
index ef88f144..e06d0beb 100644
--- a/Documentation/operate/integrations/grafana.rst
+++ b/Documentation/operate/integrations/grafana.rst
@@ -154,7 +154,7 @@ on.
expr: |
sum by (host_name) (count_over_time({service_name="shirudo"} |= `"schema":"shirudo.keepalive/1"` [1d]))
unless
- sum by (host_name) (count_over_time({service_name="shirudo"} |= `"schema":"shirudo.keepalive/1"` [5m]))
+ sum by (host_name) (count_over_time({service_name="shirudo"} |= `"schema":"shirudo.keepalive/1"` [10m]))
- alert: ShirudoTargetNotOk
expr: |
sum by (host_name) (count_over_time({service_name="shirudo"} |= `"schema":"shirudo.keepalive/1"` | json verdict="verdict" | verdict != "ok" [5m])) > 0
@@ -167,10 +167,10 @@ on.
) > 1
``ShirudoTargetSilent`` fires for a target that sent keepalives in
- the last day but none in the last five minutes, which covers several
- keepalive intervals and the 30 seconds a keepalive may wait for the
- config operation lock; a target whose tree syncs run for longer needs
- a longer window. A target silent for longer than a day drops out of
+ the last day but none in the last ten minutes, which covers several
+ keepalive intervals and a tree sync of a few minutes, which holds the
+ config operation lock that a keepalive waits for; a target whose tree
+ syncs run for longer needs a longer window. A target silent for longer than a day drops out of
the rule. ``ShirudoTargetNotOk`` fires for a verdict other than
``ok`` in the last five minutes. ``ShirudoTamperAttempts`` counts the
different lists of counters, ``tamper``, in the keepalives of one
diff --git a/Documentation/operate/integrations/index.rst b/Documentation/operate/integrations/index.rst
index 37ebfaf8..fd8cef40 100644
--- a/Documentation/operate/integrations/index.rst
+++ b/Documentation/operate/integrations/index.rst
@@ -13,7 +13,9 @@ target that goes silent, reports a verdict other than ``ok`` or counts
tamper attempts. Adapt them to your deployment.
Splunk and Elastic Security are SIEMs, ClickHouse keeps records for
-analysis in SQL, and Grafana charts them from Loki and Prometheus.
+analysis in SQL, and Grafana charts them from Loki and Prometheus. The
+keepalive backend builds on ClickHouse to check every keepalive's quote
+and each target's state against its upatch tree.
Targets speak OTLP over HTTP with JSON bodies and TLS 1.3 with a hybrid
post-quantum key exchange, and nothing else. Each page puts an
@@ -29,6 +31,7 @@ post-quantum support.
elasticsearch
grafana
splunk
+ keepalive-backend
:doc:`/concepts/background/siem-export` explains how the records reach a
backend and what to build on them.
diff --git a/Documentation/operate/integrations/keepalive-backend.rst b/Documentation/operate/integrations/keepalive-backend.rst
new file mode 100644
index 00000000..b5669033
--- /dev/null
+++ b/Documentation/operate/integrations/keepalive-backend.rst
@@ -0,0 +1,70 @@
+..
+ SPDX-License-Identifier: BSD-2-Clause
+ Copyright (c) 2026 Authors of shirudo
+
+:page-type: Explanation
+:audience: Operators, SecOps
+
+Keepalive backend
+=================
+
+The other pages of this section store what targets send and alert on
+it. The keepalive backend goes further: it checks every keepalive's TPM
+quote and compares what each target reports with the upatch tree it
+follows. It lives in a repository of its own,
+`shirudo-dev/backend <https://github.com/shirudo-dev/backend>`_, whose
+README is its documentation.
+
+This is a do-it-yourself example, not an integration shirudo
+maintains. shirudo holds no fleet state: a target only sends its
+keepalive to the collector it is configured with, and nothing on the
+target depends on the backend. Start from it and adapt retention,
+access control and sizing to your deployment.
+
+What it does
+------------
+
+- An OpenTelemetry Collector configuration that writes every keepalive
+ to ClickHouse, where a materialized view checks its quote with
+ ``shirudo-quote-check``, installed as the ClickHouse function
+ ``tpm_quote_check``, and keeps the record or the reason it was
+ refused. A node is known by the name of its attestation key, never by
+ the host name it claims, and its records are ordered by the quote's
+ clock.
+- A tree ingest job that loads every publication of an upatch tree
+ through ``shirudo bpm tree show``, which verifies it as a target does,
+ and the ``fixes`` its operations carry.
+- A table, ``node_status``, refreshed every minute, that says for every
+ node whether it is healthy, unhealthy or stale, with one line per
+ check: the record is fresh, the target reports no problem, its mask
+ and roots match the tree, it is at the head of the tree or still
+ within the time a rollout may take, the upatches it has loaded are
+ those the tree leaves, and its outcomes are the most common among
+ nodes in the same place in the tree.
+- A table, ``node_vulns``, refreshed every five minutes, that says
+ which advisories affect each node's image and kernel and whether a
+ published upatch shields it.
+
+``shirudo-quote-check`` and ``shirudo bpm tree show`` come with the
+operator package, :doc:`/reference/cli/quote-check` and
+:doc:`/reference/cli/bpm` describe them. A pass of the quote check says
+that the body is what one key signed, not that the key lives in a
+genuine TPM, so every node reads ``untrusted``, nor that the body is
+true: root on a target can have its TPM quote a body of its own, so
+``healthy`` is the target's own account until ``shirudo attest verify``
+confirms it (R17 of :doc:`/security/threat-model`).
+
+A silent node
+-------------
+
+A node turns stale when its newest keepalive is older than the
+backend's ``stale_seconds``, 10 minutes by default. A keepalive cannot
+run while a ``bpm tree sync`` holds the config operation lock, so a sync
+of several minutes leaves a gap of that length, as
+:doc:`/operate/run/telemetry` explains; the alerts for a silent target on
+the other pages of this section use the same 10 minutes. Tune the value
+to the longest sync your fleet runs.
+
+The end-to-end test ``t9107`` runs the backend against the example
+keepalives of :src:`testing/fixtures/keepalive/` and their recorded
+quotes, through its collector, its quote check and its tree ingest job.
diff --git a/Documentation/operate/integrations/splunk.rst b/Documentation/operate/integrations/splunk.rst
index 7105b276..96f99e02 100644
--- a/Documentation/operate/integrations/splunk.rst
+++ b/Documentation/operate/integrations/splunk.rst
@@ -109,16 +109,16 @@ the number of results is greater than zero.
:doc:`/operate/run/telemetry` explains each signal under what to alert
on.
-#. Find targets that stopped sending. Five minutes covers several
- keepalive intervals and the 30 seconds a keepalive may wait for the
- config operation lock; a target whose tree syncs run for longer needs
- a longer threshold:
+#. Find targets that stopped sending. Ten minutes covers several
+ keepalive intervals and a tree sync of a few minutes, which holds the
+ config operation lock that a keepalive waits for; a target whose tree
+ syncs run for longer needs a longer threshold:
.. code-block:: text
| tstats latest(_time) AS last_seen
WHERE index=shirudo sourcetype=shirudo earliest=-1d BY host
- | where last_seen < relative_time(now(), "-5m")
+ | where last_seen < relative_time(now(), "-10m")
A target silent for longer than a day drops out of the search.
diff --git a/testing/end2end/host.sh b/testing/end2end/host.sh
index 5ee3cfba..8d6e04a1 100755
--- a/testing/end2end/host.sh
+++ b/testing/end2end/host.sh
@@ -15,6 +15,8 @@ TLS_DIR=$HOST_PRIVATE_DIR/end2end-tls
REGISTRY=127.0.0.1:15443
COLLECTOR=127.0.0.1:14318
CLICKHOUSE=127.0.0.1:18123
+BACKEND_COLLECTOR=127.0.0.1:14320
+BACKEND_CLICKHOUSE=127.0.0.1:18125
. "$REPO/testing/vm/stack-lib.sh"
STACK_NAME=shirudo-end2end
STACK_PERSIST=0
@@ -25,6 +27,8 @@ VM_NAME=${VM_NAME:-end2end-$$}
export VM_NAME
RESULT=$REPO/build/test-vm/vms/$VM_NAME-end2end/result/end2end
POLICY_FIXTURE=$TEST_VM_HOST_BUNDLE/fixtures/shirudo-test-policy-exec-graph.upatch
+CHECKER=$REPO/tools/quote-check/shirudo-quote-check
+KEEPALIVE=$REPO/testing/fixtures/keepalive
say() { printf 'end2end: %s\n' "$*"; }
die() { printf 'end2end: %s\n' "$*" >&2; exit 1; }
@@ -34,6 +38,81 @@ down() {
rm -rf -- "$TLS_DIR"
}
+# The keepalive backend t9107 runs against, in $BACKEND: BACKEND_DIR, a
+# directory relative to the checkout or a git URL cloned into $W, by
+# default ../backend. Without the variable and without that directory
+# there is none, and t9107 skips.
+backend_find() {
+ case "${BACKEND_DIR-}" in
+ "")
+ [ -d ../backend ] || return 1
+ BACKEND=$(cd ../backend && pwd) ;;
+ *://* | *@*:*)
+ git clone --quiet --depth 1 "$BACKEND_DIR" "$W/backend" ||
+ die "cannot clone BACKEND_DIR $BACKEND_DIR"
+ BACKEND=$W/backend ;;
+ *)
+ [ -d "$BACKEND_DIR" ] || die "BACKEND_DIR is no directory: $BACKEND_DIR"
+ BACKEND=$(cd "$BACKEND_DIR" && pwd) ;;
+ esac
+ [ -f "$BACKEND/otelcol.yaml" ] && [ -x "$BACKEND/jobs/tree-ingest" ] ||
+ die "no keepalive backend in $BACKEND"
+}
+
+# Publish the example tree of the keepalive fixtures, signed with the
+# operator key, at oci://$REGISTRY/$1:stable. Its operations name
+# artifacts that do not exist, so bpm tree append cannot write it: the
+# document and its signature take the place of those of a publication
+# append made. Prints the manifest digest.
+publish_document() {
+ "$S" bpm tree append "$BEE" "oci://$REGISTRY/$1" --keys-dir "$KEYS" \
+ >/dev/null &&
+ openssl cms -sign -binary -md sha512 -in "$KEEPALIVE/tree-1.1.0.json" \
+ -signer "$KEYS/cert.der" -inkey "$KEYS/signing_key.pem" \
+ -outform DER -out "$W/tree-1.1.0.sig" -nosmimecap -nocerts -keyid &&
+ python3 - "$REGISTRY" "$W/ca.pem" "$1" "$KEEPALIVE/tree-1.1.0.json" \
+ "$W/tree-1.1.0.sig" <<'PY'
+import hashlib, json, ssl, sys, urllib.request
+
+registry, ca, repository, document, signature = sys.argv[1:6]
+ctx = ssl.create_default_context(cafile=ca)
+base = f"https://{registry}/v2/{repository}"
+MANIFEST = "application/vnd.oci.image.manifest.v1+json"
+LAYERS = {"application/vnd.shirudo.upatch.tree.v1+json": document,
+ "application/vnd.shirudo.upatch.tree.signature.v1": signature}
+
+
+def call(method, url, body=None, headers=None):
+ request = urllib.request.Request(url, data=body, method=method,
+ headers=headers or {})
+ return urllib.request.urlopen(request, context=ctx)
+
+
+def push(body):
+ digest = "sha256:" + hashlib.sha256(body).hexdigest()
+ with call("POST", f"{base}/blobs/uploads/") as response:
+ location = response.headers["Location"]
+ if location.startswith("/"):
+ location = f"https://{registry}{location}"
+ separator = "&" if "?" in location else "?"
+ call("PUT", f"{location}{separator}digest={digest}", body,
+ {"Content-Type": "application/octet-stream"}).close()
+ return digest
+
+
+with call("GET", f"{base}/manifests/stable", headers={"Accept": MANIFEST}) as r:
+ manifest = json.load(r)
+for layer in manifest["layers"]:
+ body = open(LAYERS[layer["mediaType"]], "rb").read()
+ layer["digest"] = push(body)
+ layer["size"] = len(body)
+raw = json.dumps(manifest, separators=(",", ":")).encode()
+call("PUT", f"{base}/manifests/stable", raw,
+ {"Content-Type": manifest.get("mediaType", MANIFEST)}).close()
+print("sha256:" + hashlib.sha256(raw).hexdigest())
+PY
+}
+
command -v docker >/dev/null 2>&1 || die "docker is required"
private_dir="$(realpath -m "$HOST_PRIVATE_DIR")"
repo_dir="$(realpath -m "$REPO")"
@@ -82,6 +161,24 @@ tar -xzf "$BEE" -C "$W/pkg"
python3 -c 'import json, sys; print(json.load(sys.stdin)["payload_sha256"])' \
>"$W/policy-payload"
+if backend_find; then
+ say "the keepalive backend of $BACKEND loads the example tree"
+ [ -x "$CHECKER" ] || die "no quote checker: $CHECKER"
+ stack_backend "$BACKEND" "$CHECKER" ||
+ die "the keepalive backend did not come up"
+ publish_document shirudo/fleet-base >"$W/backend-tree.digest" ||
+ die "cannot publish the example tree"
+ CLICKHOUSE_CLIENT="docker exec -i $STACK_NAME-backend-clickhouse clickhouse-client" \
+ SHIRUDO="$S" "$BACKEND/jobs/tree-ingest" --cert "$KEYS/cert.der" \
+ "oci://$REGISTRY/shirudo/fleet-base" >"$W/tree-ingest.out" 2>&1 || {
+ cat "$W/tree-ingest.out" >&2
+ rm -f "$W/backend-tree.digest"
+ die "the tree ingest job did not load the example tree"
+ }
+else
+ say "no keepalive backend at ../backend and no BACKEND_DIR: t9107 skips"
+fi
+
say "the target, in $VM_NAME-end2end"
"$@"
diff --git a/testing/end2end/t9107-keepalive-backend.sh b/testing/end2end/t9107-keepalive-backend.sh
new file mode 100755
index 00000000..eac5ee0f
--- /dev/null
+++ b/testing/end2end/t9107-keepalive-backend.sh
@@ -0,0 +1,218 @@
+#!/bin/sh
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+#
+# t9107 -- the keepalive backend end to end. end2end/host.sh started the
+# backend that BACKEND_DIR names, with its schema, shirudo-quote-check as
+# tpm_quote_check and its collector, and loaded the example tree of
+# fixtures/keepalive/ through the backend's tree ingest job and the real
+# `bpm tree show`. The target sends the example keepalives of node A and
+# node B with their recorded quotes through that collector, and the
+# backend's checks give the example's results. A body altered in
+# transit is refused, a replayed record collapses and an older record
+# does not become a node's latest.
+
+cd "$(dirname "$0")/.."
+. ./integration-lib.sh
+target_guard
+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"
+command -v unshare >/dev/null 2>&1 || test_skip_all "no unshare"
+
+E2E=$PWD/../build/test-vm/end2end
+FIX=$PWD/fixtures/keepalive
+H=$PWD/helper/test-otel-map
+COLLECTOR=https://10.0.2.2:14320
+CLICKHOUSE=http://10.0.2.2:18125/
+[ -s "$E2E/backend-tree.digest" ] ||
+ test_skip_all "no keepalive backend: set BACKEND_DIR for make -C testing end2end"
+[ -x "$H" ] || test_skip_all "test-otel-map helper not built"
+W=$(mktemp -d)
+trap 'rm -rf "$W"' EXIT
+
+# Run the query $1 on the backend's ClickHouse and print its result.
+ch() {
+ python3 - "$CLICKHOUSE" "$1" <<-\PY
+ import sys, urllib.request
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+ request = urllib.request.Request(sys.argv[1], data=sys.argv[2].encode())
+ sys.stdout.write(opener.open(request, timeout=60).read().decode())
+ PY
+}
+
+# Wait up to 30 seconds for the query $1 to print $2.
+ch_wait() {
+ i=0
+ until [ "$(ch "$1")" = "$2" ]; do
+ i=$((i + 1))
+ [ "$i" -lt 60 ] || return 1
+ sleep 0.5
+ done
+}
+
+# Compare the query $1's result with file $2.
+ch_cmp() {
+ ch "$1" >"$2.out" && diff -u "$2" "$2.out" >&2
+}
+
+# Field $2 of the row of quotes.tsv for the fixture body $1: 2 attest,
+# 3 sig, 4 ak, 5 body_sha256.
+quote_field() {
+ awk -F '\t' -v name="$1" -v field="$2" '$1 == name { print $field }' \
+ "$FIX/quotes.tsv"
+}
+
+# The node's key name, 0x000b || SHA-256 of the AK of fixture body $1.
+ak_of() {
+ python3 -c 'import base64, hashlib, sys
+print("000b" + hashlib.sha256(base64.b64decode(sys.argv[1])).hexdigest())' \
+ "$(quote_field "$1" 4)"
+}
+
+# Send the body file $2 with the quote of fixture body $3 through the
+# collector, as the host named $1: the record's host.name is the
+# sender's, so the sender runs in a UTS namespace of its own.
+send() {
+ quote="attest=$(quote_field "$3" 2);sig=$(quote_field "$3" 3);ak=$(quote_field "$3" 4)"
+ OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE="$E2E/ca.pem" \
+ unshare --uts python3 -c 'import os, socket, sys
+socket.sethostname(sys.argv[1])
+os.execv(sys.argv[2], sys.argv[2:])' \
+ "$1" "$H" send-keepalive "$COLLECTOR" ok "$2" "$quote"
+}
+
+refresh() {
+ ch 'SYSTEM REFRESH VIEW shirudo.node_status_mv' &&
+ ch 'SYSTEM WAIT VIEW shirudo.node_status_mv'
+}
+
+AK_A=$(ak_of node-a-1.1.0.json)
+AK_B=$(ak_of node-b-1.1.0.json)
+DIGEST=$(cat "$E2E/backend-tree.digest")
+PARENT=4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942
+VERSION_ID=d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f
+
+Q_FUNCTION="SELECT count() FROM system.functions WHERE name = 'tpm_quote_check'"
+Q_TABLES="SELECT count() FROM system.tables WHERE (database, name) IN
+ (('otel', 'otel_logs'), ('shirudo', 'checked'), ('shirudo', 'keepalive'),
+ ('shirudo', 'rejected'), ('shirudo', 'node_status'), ('shirudo', 'tree_ops'))"
+Q_PUBS="SELECT tree_id, generation, manifest_digest, parent_manifest_digest,
+ head_seq FROM shirudo.tree_pubs FINAL"
+Q_OPS="SELECT seq, op, id, selector, repository, manifest_digest, layer_digest,
+ payload_sha256, operation_digest FROM shirudo.tree_ops FINAL
+ WHERE tree_id = 'fleet-base' ORDER BY seq"
+Q_FIXES="SELECT seq, id, advisory, source FROM shirudo.upatch_fixes FINAL
+ ORDER BY seq"
+Q_BUILD="INSERT INTO shirudo.expected_builds (version_id, note)
+ VALUES ('$VERSION_ID', 't9107')"
+Q_RECORDS="SELECT count() FROM shirudo.keepalive FINAL"
+Q_KEEPALIVE="SELECT host_name, ak_name, reset_count, clock,
+ lower(hex(SHA256(body))) FROM shirudo.keepalive FINAL ORDER BY host_name"
+Q_STATUS="SELECT node_id, status, trust, failed_check FROM shirudo.node_status
+ ORDER BY node_id"
+Q_LOG="SELECT node_id,
+ replaceRegexpOne(line, 'last record -?[0-9]+ s ago', 'last record N s ago')
+ FROM shirudo.node_status ARRAY JOIN log AS line ORDER BY node_id, line"
+Q_REJECTED="SELECT reason, host_name, lower(hex(SHA256(body))) FROM shirudo.rejected"
+Q_STATUS_A="SELECT status, failed_check FROM shirudo.node_status
+ WHERE ak_name = '$AK_A'"
+Q_LATEST_A="SELECT clock, generation, last_seq FROM shirudo.keepalive_latest FINAL
+ WHERE ak_name = '$AK_A'"
+Q_RECORDS_A="SELECT count() FROM shirudo.keepalive FINAL WHERE ak_name = '$AK_A'"
+
+test_expect_success 'the schema is loaded with the quote checker as tpm_quote_check' '
+ test "$(ch "$Q_FUNCTION")" = 1 &&
+ test "$(ch "$Q_TABLES")" = 6
+'
+
+test_expect_success 'the ingest job loaded the publication bpm tree show verified' '
+ printf "fleet-base\t3\t%s\t%s\t3\n" "${DIGEST#sha256:}" "$PARENT" \
+ >"$W/pubs" &&
+ ch_cmp "$Q_PUBS" "$W/pubs" &&
+ python3 - "$FIX/tree-1.1.0.json" >"$W/ops" <<-\PY &&
+ import json, sys
+ def strip(digest):
+ return digest.removeprefix("sha256:")
+ for op in json.load(open(sys.argv[1]))["operations"]:
+ a = op["artifact"]
+ print("\t".join([str(op["seq"]), op["op"], op["id"],
+ json.dumps(op["selector"], separators=(",", ":")),
+ a["repository"], strip(a["manifest_digest"]),
+ strip(a["layer_digest"]), strip(a["payload_sha256"]),
+ strip(op["operation_digest"])]))
+ PY
+ ch_cmp "$Q_OPS" "$W/ops" &&
+ printf "%s\txfs-fix\tEXAMPLE-0101\tfixes\n" 1 3 >"$W/fixes" &&
+ ch_cmp "$Q_FIXES" "$W/fixes"
+'
+
+test_expect_success 'the checker accepts the keepalives of node A and node B' '
+ ch "$Q_BUILD" &&
+ send edge-01 "$FIX/node-a-1.1.0.json" node-a-1.1.0.json &&
+ send core-01 "$FIX/node-b-1.1.0.json" node-b-1.1.0.json &&
+ ch_wait "$Q_RECORDS" 2 &&
+ printf "core-01\t%s\t0\t42\t%s\nedge-01\t%s\t0\t41\t%s\n" \
+ "$AK_B" "$(quote_field node-b-1.1.0.json 5)" \
+ "$AK_A" "$(quote_field node-a-1.1.0.json 5)" >"$W/keepalive" &&
+ ch_cmp "$Q_KEEPALIVE" "$W/keepalive" &&
+ test "$(ch "SELECT count() FROM shirudo.rejected")" = 0
+'
+
+test_expect_success 'node_status shows node A and node B as the example has them' '
+ refresh &&
+ printf "core-01\thealthy\tuntrusted\t0\nedge-01\thealthy\tuntrusted\t0\n" \
+ >"$W/status" &&
+ ch_cmp "$Q_STATUS" "$W/status" &&
+ cat >"$W/log" <<-\EOF &&
+ core-01 1 signed: pass, untrusted, 0 rejected in the last hour
+ core-01 2 fresh: pass, last record N s ago
+ core-01 3 reported: pass, verdict ok, cond 0x1555, flags 0, tamper +0, build d6d918ad
+ core-01 4 chain: pass, root 00000000
+ core-01 5 head: pass, seq 3 of 3, generation 3
+ core-01 6 set: pass, 0 loaded
+ core-01 7 peers: no peers, 1 in group
+ edge-01 1 signed: pass, untrusted, 0 rejected in the last hour
+ edge-01 2 fresh: pass, last record N s ago
+ edge-01 3 reported: pass, verdict ok, cond 0x1555, flags 0, tamper +0, build d6d918ad
+ edge-01 4 chain: pass, root 15452248
+ edge-01 5 head: pass, seq 3 of 3, generation 3
+ edge-01 6 set: pass, 1 loaded
+ edge-01 7 peers: no peers, 1 in group
+ EOF
+ ch_cmp "$Q_LOG" "$W/log"
+'
+
+test_expect_success 'a body altered in transit is rejected as body_mismatch' '
+ sed "s/\"boot_id\":\"1/\"boot_id\":\"2/" "$FIX/node-a-1.1.0.json" \
+ >"$W/altered.json" &&
+ ! cmp -s "$FIX/node-a-1.1.0.json" "$W/altered.json" &&
+ send edge-01 "$W/altered.json" node-a-1.1.0.json &&
+ ch_wait "SELECT count() FROM shirudo.rejected" 1 &&
+ printf "body_mismatch\tedge-01\t%s\n" \
+ "$(sha256sum "$W/altered.json" | cut -d " " -f 1)" >"$W/rejected" &&
+ ch_cmp "$Q_REJECTED" "$W/rejected" &&
+ test "$(ch "$Q_RECORDS")" = 2 &&
+ test "$(ch "$Q_LATEST_A")" = "$(printf "41\t3\t3")" &&
+ refresh &&
+ test "$(ch "$Q_STATUS_A")" = "$(printf "healthy\t0")"
+'
+
+# Merges stop so that the replay is seen to arrive before it collapses.
+test_expect_success 'a replayed record collapses into the one it repeats' '
+ ch "SYSTEM STOP MERGES shirudo.keepalive" &&
+ send edge-01 "$FIX/node-a-1.1.0.json" node-a-1.1.0.json &&
+ ch_wait "SELECT count() FROM shirudo.keepalive" 3 &&
+ test "$(ch "$Q_RECORDS")" = 2 &&
+ ch "SYSTEM START MERGES shirudo.keepalive" &&
+ ch "OPTIMIZE TABLE shirudo.keepalive FINAL" &&
+ test "$(ch "SELECT count() FROM shirudo.keepalive")" = 2
+'
+
+test_expect_success 'an older record is kept and does not become the latest' '
+ send edge-01 "$FIX/node-a-1.0.0.json" node-a-1.0.0.json &&
+ ch_wait "$Q_RECORDS_A" 2 &&
+ test "$(ch "$Q_LATEST_A")" = "$(printf "41\t3\t3")" &&
+ refresh &&
+ test "$(ch "$Q_STATUS_A")" = "$(printf "healthy\t0")"
+'
+
+test_done
diff --git a/testing/vm/stack-lib.sh b/testing/vm/stack-lib.sh
index 4ff69e7b..200622ea 100644
--- a/testing/vm/stack-lib.sh
+++ b/testing/vm/stack-lib.sh
@@ -92,11 +92,72 @@ stack_telemetry()
"https://$COLLECTOR/v1/logs"
}
+stack_backend_client()
+{
+ docker exec -i "$STACK_NAME-backend-clickhouse" clickhouse-client "$@"
+}
+
+# The keepalive backend of directory $1 beside the telemetry stack: a
+# ClickHouse of its own on $BACKEND_CLICKHOUSE with the backend's schema
+# and the quote checker $2 as tpm_quote_check, as its README installs
+# them, and a collector on $BACKEND_COLLECTOR with its configuration.
+stack_backend()
+{
+ backend=$1
+ checker=$2
+ container=$STACK_NAME-backend-clickhouse
+ docker network inspect "$STACK_NAME" >/dev/null 2>&1 ||
+ docker network create "$STACK_NAME" >/dev/null
+ stack_run "$container" --network "$STACK_NAME" \
+ --network-alias backend-clickhouse -p "$BACKEND_CLICKHOUSE:8123" \
+ -e CLICKHOUSE_SKIP_USER_SETUP=1 "$CLICKHOUSE_IMAGE"
+ attempt=0
+ until stack_backend_client --query 'SELECT 1' >/dev/null 2>&1; do
+ attempt=$((attempt + 1))
+ [ "$attempt" -lt 150 ] || return 1
+ sleep 0.2
+ done
+ docker exec "$container" mkdir -p /var/lib/clickhouse/user_scripts &&
+ docker cp "$checker" \
+ "$container:/var/lib/clickhouse/user_scripts/shirudo-quote-check" &&
+ docker exec "$container" \
+ chmod 0755 /var/lib/clickhouse/user_scripts/shirudo-quote-check &&
+ docker cp "$backend/clickhouse/tpm_quote_check_function.xml" \
+ "$container:/etc/clickhouse-server/tpm_quote_check_function.xml" &&
+ stack_backend_client --query 'SYSTEM RELOAD FUNCTIONS' || return 1
+ attempt=0
+ until stack_backend_client --query "SELECT name FROM system.functions
+ WHERE name = 'tpm_quote_check'" 2>/dev/null | grep -q .; do
+ attempt=$((attempt + 1))
+ [ "$attempt" -lt 150 ] || return 1
+ sleep 0.2
+ done
+ for file in "$backend"/sql/*.sql; do
+ stack_backend_client <"$file" || return 1
+ done
+ "$backend/sql/apply-retention.sh" docker exec -i "$container" \
+ clickhouse-client >/dev/null || return 1
+ stack_run "$STACK_NAME-backend-collector" --network "$STACK_NAME" \
+ -p "$BACKEND_COLLECTOR:4318" -v "$TLS_DIR:/certs:ro" \
+ -e CLICKHOUSE_ENDPOINT=tcp://backend-clickhouse:9000 \
+ -v "$backend/otelcol.yaml:/etc/otelcol-contrib/config.yaml:ro" \
+ "$COLLECTOR_IMAGE"
+ stack_wait_https -X POST -H 'Content-Type: application/json' -d '{}' \
+ "https://$BACKEND_COLLECTOR/v1/logs"
+}
+
stack_down()
{
docker logs "$STACK_NAME-collector" >"$W/collector.log" 2>&1 || true
docker logs "$STACK_NAME-clickhouse" >"$W/clickhouse.log" 2>&1 || true
+ for part in collector clickhouse; do
+ docker container inspect "$STACK_NAME-backend-$part" \
+ >/dev/null 2>&1 || continue
+ docker logs "$STACK_NAME-backend-$part" \
+ >"$W/backend-$part.log" 2>&1 || true
+ done
docker rm -fv "$STACK_NAME-registry" "$STACK_NAME-collector" \
- "$STACK_NAME-clickhouse" >/dev/null 2>&1 || true
+ "$STACK_NAME-clickhouse" "$STACK_NAME-backend-collector" \
+ "$STACK_NAME-backend-clickhouse" >/dev/null 2>&1 || true
docker network rm "$STACK_NAME" >/dev/null 2>&1 || true
}