eBPF-based security platform
backend: add a job that enrolls keys from a builder's records
John Fastabend5f3621fa48c9
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex 534d105b..f843b8aa 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -980,7 +980,9 @@ ingest job on a single publication and on a walk over sealed segments,the SBOM scan job on a store that holds an image in every state, theSBOM put job into a ``file://`` and an ``s3://`` store, again and withanother SBOM, and what it refuses (``test/sbom-put``), the label put job-and the labels each node reads from it (``test/labels-put``), and the queries+and the labels each node reads from it (``test/labels-put``), the+enroll put job, a key bound once and what it refuses+(``test/enroll-put``), and the queriesof :src:`tools/xtop/sql/`, with the names and types of their columns,over nodes healthy, unhealthy, stale and without a tree or an image, atree with one upatch deployed and one still rolling out, and thediff --git a/Documentation/operate/backend/enroll-put.rst b/Documentation/operate/backend/enroll-put.rstnew file mode 100644index 00000000..8529996b--- /dev/null+++ b/Documentation/operate/backend/enroll-put.rst@@ -0,0 +1,112 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators++Enroll keys from a builder+==========================++A node reads ``untrusted`` until the backend knows its attestation key+lives in a TPM. When a builder you trust created the key, as+:doc:`/operate/run/attest` describes under "Enroll from a builder's+records", :src:`tools/backend/jobs/enroll-put` loads the builder's+records into the backend: it raises each key's ``trust`` in+``shirudo.nodes`` to ``enrolled``, names its node, and keeps the binding+in ``shirudo.enrollments``. It is POSIX shell around+``clickhouse-client``, with :src:`tools/backend/jobs/enroll-rows.py` to+read the file, so the host that runs it needs ``python3`` and+``clickhouse-client``.++Run it before or after the node's first keepalive; the binding waits for+the key. Take the names from the builder, never from the node.++1. Write the bindings, one per key the builder created:++ .. code-block:: json++ {"source": "vm-host-1", "nodes": [+ {"ak_name": "000b5df9f114316811380fc4fcba38a6d03d306cb68efed75bc004f1bf8de9f75e78",+ "ek_name": "000b8c1f6e0d2a9b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4cd",+ "node_id": "edge-01"},+ {"ak_name": "000b0e4c7a2b9d1f3e5a7c9b1d3f5e7a9c1b3d5f7e9a1c3b5d7f9e1a3c5b7d9f1e3a"}+ ]}++ ``source`` names the builder, as you want to find it again: a host, a+ pipeline, a batch.++2. Check it against the bindings already loaded, which loads nothing:++ .. code-block:: console++ $ jobs/enroll-put --check bindings.json++3. Load it:++ .. code-block:: console++ $ jobs/enroll-put bindings.json+ enroll-put: 000b5df9…9f75e78 (ek_name 000b8c1f…a3b4cd, node_id edge-01): enrolled+ enroll-put: 000b0e4c…5b7d9f1e3a (ek_name none, node_id none): enrolled+ enroll-put: loaded bindings: 2++ The job prints each name whole; they are shortened here.++``-`` in place of the file reads standard input.++What a binding does+-------------------++A key is enrolled for good: ``trust`` only rises, and a key that is no+longer trusted, such as one whose TPM was replaced, comes back under a+new ``ak_name``, which starts ``untrusted``. ``enrolled`` says who+signed the records, not that what they say is true: only+``shirudo attest verify`` confirms a node's state.++A key is bound once. The same binding loaded again, from a builder that+sends its whole inventory each time, changes nothing and prints+``already enrolled``. A binding that gives an enrolled key another+``ek_name`` or ``node_id`` refuses the whole file: the builder saw one+TPM create the key, and a second answer means one of the two records is+wrong.++The ``node_id`` names the node in ``shirudo.nodes`` in place of the host+name its first record claimed, and is the name ``labels-put`` and xtop+use. A rename (:doc:`maintain`) still wins over it. Without one the node+keeps the host name. The ``ek_name`` is kept for the inventory that+``shirudo attest verify --ek-name`` reads; the backend checks nothing+against it.++What it refuses+---------------++The job refuses the whole file, with status 1 and a message naming the+binding, when:++- it is not UTF-8 JSON, or not an object whose keys are ``source``, 1+ to 255 characters with no control character, and ``nodes``, an array;+ or an object has a key twice;+- a binding is not an object with ``ak_name`` and, optionally,+ ``ek_name`` and ``node_id``; or has another key;+- an ``ak_name`` or ``ek_name`` is not a TPM name, ``000b`` and 64+ lowercase hex digits, or a ``node_id`` is not 1 to 255 characters with+ no control character;+- two bindings name the same ``ak_name``;+- a binding differs from the one loaded for its key.++Exit status+-----------++0 when every binding is loaded, or checked with ``--check``; 1 when the+file is refused or the load fails; 2 for wrong usage. The job raises+``trust`` before it records the bindings, so a load that fails between+the two is finished by running it again.++Connection+----------++As :src:`tools/backend/jobs/tree-ingest`, the job runs+``clickhouse-client`` or the command ``CLICKHOUSE_CLIENT`` names. Its user+needs ``SELECT`` and ``INSERT`` on ``shirudo.enrollments`` and ``INSERT``+on ``shirudo.nodes``.diff --git a/Documentation/operate/backend/index.rst b/Documentation/operate/backend/index.rstindex 6d09cf51..eb919e69 100644--- a/Documentation/operate/backend/index.rst+++ b/Documentation/operate/backend/index.rst@@ -81,6 +81,9 @@ Files* - :src:`tools/backend/jobs/labels-put`- Loads the labels the operator gives the nodes, out of band(:doc:`labels-put`).+ * - :src:`tools/backend/jobs/enroll-put`+ - Enrolls the attestation keys a builder created in TPMs, from its+ records (:doc:`enroll-put`).* - :src:`tools/backend/jobs/sbom-put`- Stores the CycloneDX SBOM of an image in the SBOM store, for animage pipeline to call (:doc:`sbom-put`).@@ -106,6 +109,7 @@ Filessbom-scansbom-putlabels-put+ enroll-putmaintainboot-baselinesxtopdiff --git a/Documentation/operate/backend/maintain.rst b/Documentation/operate/backend/maintain.rstindex c0026f01..d2c77f5d 100644--- a/Documentation/operate/backend/maintain.rst+++ b/Documentation/operate/backend/maintain.rst@@ -43,7 +43,8 @@ created the TPM's keys, raise it:INSERT INTO shirudo.nodes (ak_name, trust) VALUES ('<ak_name>', 'enrolled');-The row may come before the node's first record, as it does when a+A builder's records go in with :doc:`enroll-put`, which does the same for+each key, names its node and keeps the binding. The row may come before the node's first record, as it does when abuilder hands you the name before the node boots. It changes nothingbut ``trust``, and no row lowers it again: a key that is no longertrusted, such as one whose TPM was replaced, shows up under a newdiff --git a/Documentation/operate/backend/tables/reference.rst b/Documentation/operate/backend/tables/reference.rstindex 47a84ddd..fb530668 100644--- a/Documentation/operate/backend/tables/reference.rst+++ b/Documentation/operate/backend/tables/reference.rst@@ -10,8 +10,9 @@ ReferenceWhat the checks compare a record against, and what the operator says of anode. nodes fills itself from accepted records; tree-ingest loads the tree-tables; labels-put loads label_sets; the operator writes builds, manual-fixes and settings.+tables; labels-put loads label_sets; enroll-put loads enrollments and+raises trust in nodes; the operator writes builds, manual fixes and+settings.Schema: :src:`tools/backend/sql/20-reference.sql`@@ -36,6 +37,13 @@ Views, functions and jobsChecks a file of label sets and loads it into label_sets in one insert,all or nothing, each row with one put_at later than any before.+``jobs/enroll-put``+ external job.++ Checks a builder's file of key bindings against enrollments, raises+ each key's trust in nodes to enrolled and names its node there, then+ records the new bindings in enrollments. A key is bound once.+shirudo.nodes-------------@@ -58,7 +66,9 @@ shirudo.nodesthey don't change.- trust only ever rises. The operator inserts (ak_name, 'enrolled') oncecredential activation or a builder's records show the key is a TPM's,- before or after the node's first record. It is shown but never part+ before or after the node's first record; jobs/enroll-put does it from+ a builder's records, with the node_id it gave at+ toDateTime64(0.001, 3), which a rename at epoch 0 still beats. It is shown but never partof status.:ak_name: Node identity.@@ -230,3 +240,27 @@ shirudo.label_sets:node: The node_id, ak_name or config_root.:labels: The whole set, key to value.:put_at: When labels-put loaded it; the version ReplacingMergeTree keeps the newest of.++shirudo.enrollments+-------------------++.. clickhouse-table:: shirudo.enrollments+ :kind: ref+ :written-by: jobs/enroll-put+ :row-size: ~250 B (estimate: two TPM names, a node_id and a source).+ :scale: Every key a builder enrolled. No TTL.+ :reference: 10,000 rows ≈ 2.5 MB+ :bytes: 2.5e+06++ The attestation keys a builder created in a TPM, as it recorded them:+ what enrolled each key, where nodes only keeps that it is.++ - Read with FINAL. A key's binding is written once; enroll-put refuses+ another.+ - The row may come before the node's first record.++ :ak_name: The attestation key's name.+ :ek_name: The endorsement key's name the builder saw beside it, empty when it gave none. Nothing checks against it; attest verify --ek-name does.+ :node_id: The name the builder gave the node, empty when it gave none.+ :source: The builder, as the file named it.+ :put_at: When enroll-put loaded it.diff --git a/Documentation/operate/run/attest.rst b/Documentation/operate/run/attest.rstindex d4e02065..f4f38765 100644--- a/Documentation/operate/run/attest.rst+++ b/Documentation/operate/run/attest.rst@@ -340,14 +340,15 @@ one QEMU's or libvirt's swtpm will use.7. Record both names for this target in your inventory. Take them fromthe builder, never from the target.-8. If you run the keepalive backend, mark the key as enrolled. The row- can go in before the target first boots; its first keepalive joins- it:+8. If you run the keepalive backend, enroll the key from the builder's+ names with :doc:`/operate/backend/enroll-put`, which also names the+ node and keeps the binding. It can run before the target first boots;+ its first keepalive joins it:.. code-block:: console- operator$ clickhouse-client --query "INSERT INTO shirudo.nodes \- (ak_name, trust) VALUES ('<ak-name>', 'enrolled')"+ operator$ printf '{"source": "%s", "nodes": [{"ak_name": "%s", "ek_name": "%s", "node_id": "%s"}]}' \+ <builder> <ak-name> <ek-name> <node-id> | tools/backend/jobs/enroll-put -9. Verify every evidence document with the recorded names, as`Verify evidence`_ shows. There is no credential to expect:diff --git a/tools/backend/jobs/enroll-put b/tools/backend/jobs/enroll-putnew file mode 100755index 00000000..62d606fa--- /dev/null+++ b/tools/backend/jobs/enroll-put@@ -0,0 +1,97 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# jobs/enroll-put -- enroll the attestation keys a builder created in+# TPMs: record each key's binding in shirudo.enrollments and raise its+# trust in shirudo.nodes to enrolled.+#+# jobs/enroll-put [--check] <bindings.json>|-+#+# The file names the builder and, per key, its ak_name, and the ek_name+# and node_id the builder gave it, each optional. A key is bound once: a+# binding the backend already holds is enrolled again, which changes+# nothing, and one that differs from it refuses the file. The node_id+# names the node in shirudo.nodes until the operator renames it.+# --check reads and checks the file against the bindings loaded, and+# loads nothing.+#+# CLICKHOUSE_CLIENT the client command and its options, split at+# spaces. Default: clickhouse-client, which reads+# CLICKHOUSE_HOST, CLICKHOUSE_USER and+# CLICKHOUSE_PASSWORD itself.+#+# Exit status: 0 when every binding is loaded, or checked with --check;+# 1 when the file is refused or the load fails; 2 for wrong usage.++set -eu++here=$(cd "$(dirname "$0")" && pwd)+check=0+work=+columns='ak_name String, ek_name String, node_id String, source String, new UInt8'++die()+{+ printf 'enroll-put: %s\n' "$1" >&2+ exit 1+}++usage()+{+ printf '%s\n' 'usage: enroll-put [--check] <bindings.json>|-' >&2+ exit 2+}++cleanup()+{+ [ -z "$work" ] || rm -rf "$work"+}++client()+{+ # shellcheck disable=SC2086 # a command with its options, to be split+ ${CLICKHOUSE_CLIENT:-clickhouse-client} "$@"+}++[ "${1:-}" = --check ] && { check=1; shift; }+[ $# -eq 1 ] || usage+case "$1" in+-) ;;+-*) usage ;;+esac++trap cleanup EXIT+trap 'exit 1' HUP INT TERM+work=$(mktemp -d)+if [ "$1" = - ]; then+ cat >"$work/bindings.json"+else+ cp "$1" "$work/bindings.json" 2>/dev/null || die "cannot read $1, nothing loaded"+fi++client --query 'SELECT ak_name, ek_name, node_id FROM shirudo.enrollments FINAL+ FORMAT JSONEachRow' </dev/null >"$work/enrolled.jsonl" ||+ die 'cannot read shirudo.enrollments, nothing loaded'+python3 "$here/enroll-rows.py" "$work/bindings.json" "$work/enrolled.jsonl" \+ "$work/rows.jsonl" >"$work/summary" || exit 1+[ "$check" -eq 0 ] || { cat "$work/summary"; exit 0; }++# nodes first: its rows can go in again unchanged, so a load stopped+# before the bindings is finished by the next. A binding's node_id sorts+# after epoch 0, where the operator's rename goes, and before any host+# name a record claims.+if [ -s "$work/rows.jsonl" ]; then+ client --query "INSERT INTO shirudo.nodes (ak_name, node_id, trust)+ SELECT ak_name, argMinStateIf(node_id, toDateTime64(0.001, 3), node_id != ''),+ 'enrolled'+ FROM input('$columns') GROUP BY ak_name FORMAT JSONEachRow" \+ <"$work/rows.jsonl" || die 'cannot insert into shirudo.nodes, nothing loaded'+ client --query "INSERT INTO shirudo.enrollments (ak_name, ek_name, node_id, source)+ SELECT ak_name, ek_name, node_id, source+ FROM input('$columns') WHERE new FORMAT JSONEachRow" \+ <"$work/rows.jsonl" ||+ die 'the keys are enrolled, but their bindings are not recorded; run it again'+fi+cat "$work/summary"+printf 'enroll-put: loaded bindings: %d\n' "$(wc -l <"$work/rows.jsonl")"diff --git a/tools/backend/jobs/enroll-rows.py b/tools/backend/jobs/enroll-rows.pynew file mode 100644index 00000000..8da2b27b--- /dev/null+++ b/tools/backend/jobs/enroll-rows.py@@ -0,0 +1,180 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# jobs/enroll-rows.py -- the part of jobs/enroll-put that shell does not+# reach: reading and checking a builder's bindings against the ones+# shirudo.enrollments already holds.+#+# enroll-rows.py <bindings.json> <enrolled.jsonl> <rows.jsonl>+#+# Reads {"source": <builder>, "nodes": [{"ak_name": <name>, "ek_name":+# <name>, "node_id": <name>}, ...]}, where ek_name and node_id may be left+# out, and the enrollments already loaded, one JSONEachRow object of+# ak_name, ek_name and node_id per key. Writes one row per binding, with+# new set to 1 for a key not enrolled yet, and prints a line per binding.+# A key is bound once: a binding that differs from the one loaded is+# refused.+#+# Exit status: 0; 1 when the file is refused, named on standard error,+# with nothing written; 2 for wrong usage.++import json+import re+import sys++PROG = "enroll-put"+# 000b, TPM_ALG_SHA256, and the SHA-256 of the public area, as+# shirudo attest and shirudo-quote-check write a name.+TPM_NAME = re.compile(r"000b[0-9a-f]{64}")+TEXT = re.compile(r"[^\x00-\x1f\x7f]{1,255}")+KEYS = {"ak_name", "ek_name", "node_id"}+++class Refused(Exception):+ pass+++def unique_keys(pairs):+ seen = {}+ for key, value in pairs:+ if key in seen:+ raise Refused('the key "%s" is given twice in one object'+ % printable(key))+ seen[key] = value+ return seen+++def not_a_number(name):+ raise Refused("%s is not a JSON number" % name)+++def printable(text):+ return "".join(c if c.isprintable() else "?" for c in text)+++def parse(data):+ try:+ text = data.decode("utf-8")+ except UnicodeDecodeError:+ raise Refused("the file is not UTF-8")+ decoder = json.JSONDecoder(object_pairs_hook=unique_keys,+ parse_constant=not_a_number)+ try:+ return decoder.decode(text)+ except (ValueError, RecursionError):+ raise Refused("the file is not a JSON value")+++def name_of(where, entry, key):+ """The binding's TPM name under key, "" for an ek_name left out."""+ name = entry.get(key, "")+ if key == "ek_name" and key not in entry:+ return name+ if type(name) is not str or not TPM_NAME.fullmatch(name):+ raise Refused("%s: %s is not 000b and 64 lowercase hex digits"+ % (where, key))+ return name+++def binding_of(n, entry):+ where = "binding %d" % n+ if type(entry) is not dict:+ raise Refused("%s is not an object" % where)+ extra = set(entry) - KEYS+ if extra:+ raise Refused('%s has the key "%s", which is not ak_name, ek_name'+ ' or node_id' % (where, printable(sorted(extra)[0])))+ if "ak_name" not in entry:+ raise Refused("%s has no ak_name" % where)+ ak_name = name_of(where, entry, "ak_name")+ ek_name = name_of(where, entry, "ek_name")+ node_id = entry.get("node_id", "")+ if "node_id" in entry and (type(node_id) is not str+ or not TEXT.fullmatch(node_id)):+ raise Refused("%s: node_id is not 1 to 255 characters with no"+ " control character" % where)+ return ak_name, ek_name, node_id+++def bindings_of(doc):+ if type(doc) is not dict or set(doc) != {"source", "nodes"}:+ raise Refused('the file is not an object whose keys are "source"'+ ' and "nodes"')+ source = doc["source"]+ if type(source) is not str or not TEXT.fullmatch(source):+ raise Refused("source is not 1 to 255 characters with no control"+ " character")+ if type(doc["nodes"]) is not list:+ raise Refused("nodes is not an array")+ out, seen = [], set()+ for n, entry in enumerate(doc["nodes"], 1):+ binding = binding_of(n, entry)+ if binding[0] in seen:+ raise Refused("%s is bound twice" % binding[0])+ seen.add(binding[0])+ out.append(binding)+ return source, out+++def enrolled_of(path):+ enrolled = {}+ with open(path, encoding="utf-8") as f:+ for line in f:+ row = json.loads(line)+ enrolled[row["ak_name"]] = (row["ak_name"], row["ek_name"],+ row["node_id"])+ return enrolled+++def shown(binding):+ ak_name, ek_name, node_id = binding+ return "ek_name %s, node_id %s" % (ek_name or "none",+ printable(node_id) or "none")+++def check_against(bindings, enrolled):+ """Refuse a key bound otherwise before; return the new ones."""+ new = set()+ for binding in bindings:+ before = enrolled.get(binding[0])+ if before is None:+ new.add(binding[0])+ elif before != binding:+ raise Refused("%s is enrolled with %s, not %s"+ % (binding[0], shown(before), shown(binding)))+ return new+++def main():+ if len(sys.argv) != 4:+ print("usage: enroll-rows.py <bindings.json> <enrolled.jsonl>"+ " <rows.jsonl>", file=sys.stderr)+ return 2+ path, enrolled_path, rows = sys.argv[1:]+ try:+ with open(path, "rb") as f:+ source, bindings = bindings_of(parse(f.read()))+ new = check_against(bindings, enrolled_of(enrolled_path))+ except Refused as reason:+ print("%s: %s, nothing loaded" % (PROG, reason), file=sys.stderr)+ return 1+ except OSError as error:+ print("%s: cannot read %s, nothing loaded"+ % (PROG, printable(error.filename or path)), file=sys.stderr)+ return 1+ with open(rows, "w", encoding="utf-8") as f:+ for ak_name, ek_name, node_id in bindings:+ f.write(json.dumps({"ak_name": ak_name, "ek_name": ek_name,+ "node_id": node_id, "source": source,+ "new": int(ak_name in new)},+ ensure_ascii=False, separators=(",", ":")))+ f.write("\n")+ for binding in bindings:+ state = "enrolled" if binding[0] in new else "already enrolled"+ print("%s: %s (%s): %s" % (PROG, binding[0], shown(binding), state))+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/backend/sql/20-reference.sql b/tools/backend/sql/20-reference.sqlindex 399493d8..c330fd10 100644--- a/tools/backend/sql/20-reference.sql+++ b/tools/backend/sql/20-reference.sql@@ -148,3 +148,19 @@ INSERT INTO shirudo.settings (stale_seconds, stuck_seconds, window, keepalive_reboot_first_retention_seconds, sbom_stale_seconds)SELECT 600, 3600, 512, 3600, 2592000, 172800WHERE (SELECT count() FROM shirudo.settings) = 0;++-- The attestation keys a builder created in a TPM, as jobs/enroll-put+-- loads its records: the key's name, the endorsement key's name the+-- builder saw beside it, and the node_id it gave the node, empty when it+-- gave none. A key's binding is written once; the job raises the key's+-- trust in shirudo.nodes to enrolled and names its node there.+CREATE TABLE IF NOT EXISTS shirudo.enrollments+(+ ak_name String,+ ek_name String,+ node_id String,+ source String,+ put_at DateTime64(3) DEFAULT now64(3)+)+ENGINE = ReplacingMergeTree(put_at)+ORDER BY ak_name;diff --git a/tools/backend/test/enroll-put.expected b/tools/backend/test/enroll-put.expectednew file mode 100644index 00000000..5691ab1f--- /dev/null+++ b/tools/backend/test/enroll-put.expected@@ -0,0 +1,40 @@+enroll-put: 000baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa (ek_name 000beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, node_id edge-01): enrolled+enroll-put: 000bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb (ek_name none, node_id none): enrolled+enroll-put: loaded bindings: 2+first put: status 0+enroll-put: 000baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa (ek_name 000beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, node_id edge-01): already enrolled+enroll-put: 000bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb (ek_name none, node_id none): already enrolled+enroll-put: loaded bindings: 2+again: status 0+enroll-put: 000baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa is enrolled with ek_name 000beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, node_id edge-01, not ek_name 000beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, node_id edge-09, nothing loaded+rebound: status 1+enroll-put: 000bcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc (ek_name none, node_id none): enrolled+check: status 0+enroll-put: the file is not a JSON value, nothing loaded+not json: status 1+enroll-put: the file is not an object whose keys are "source" and "nodes", nothing loaded+no source: status 1+enroll-put: source is not 1 to 255 characters with no control character, nothing loaded+source empty: status 1+enroll-put: binding 1 has no ak_name, nothing loaded+no ak: status 1+enroll-put: binding 1: ak_name is not 000b and 64 lowercase hex digits, nothing loaded+short ak: status 1+enroll-put: binding 1: ak_name is not 000b and 64 lowercase hex digits, nothing loaded+upper ak: status 1+enroll-put: binding 1: ek_name is not 000b and 64 lowercase hex digits, nothing loaded+bad ek: status 1+enroll-put: binding 1 has the key "trust", which is not ak_name, ek_name or node_id, nothing loaded+unknown key: status 1+enroll-put: 000bcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc is bound twice, nothing loaded+bound twice: status 1+enroll-put: binding 1: node_id is not 1 to 255 characters with no control character, nothing loaded+control in node_id: status 1+enroll-put: cannot read none.json, nothing loaded+no file: status 1+usage: enroll-put [--check] <bindings.json>|-+no argument: status 2+aaaa edge-01 enrolled 2026-11-01 10:00:00.000+bbbb core-01 enrolled \N+aaaa eeee edge-01 vm-host-1+bbbb vm-host-1diff --git a/tools/backend/test/enroll-put.setup.sql b/tools/backend/test/enroll-put.setup.sqlnew file mode 100644index 00000000..71abfdd9--- /dev/null+++ b/tools/backend/test/enroll-put.setup.sql@@ -0,0 +1,9 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- One key the backend has a record of, under the host name it claimed,+-- and not enrolled.++INSERT INTO shirudo.nodes (ak_name, node_id, first_seen)+SELECT concat('000b', repeat('a', 64)), argMinState('host-a', toDateTime64('2026-11-01 10:00:00', 3)),+ toDateTime64('2026-11-01 10:00:00', 3);diff --git a/tools/backend/test/enroll-put.sh b/tools/backend/test/enroll-put.shnew file mode 100644index 00000000..ac4ca284--- /dev/null+++ b/tools/backend/test/enroll-put.sh@@ -0,0 +1,78 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# jobs/enroll-put: a builder's file enrolls a key the backend has seen,+# naming its node, and one it has not; the same file again changes+# nothing; a file that binds an enrolled key otherwise is refused whole;+# --check loads nothing; a rename after the enrollment wins over the+# builder's name. Then what it refuses, each with a message and nothing+# loaded: a file that is not JSON or not of the form, a name that is not+# a TPM name, a key bound twice, a node_id with a control character, a+# missing file and wrong usage.++set -eu++test=$(cd "$(dirname "$0")" && pwd)+job=$test/../jobs/enroll-put++work=$(mktemp -d)+trap 'rm -rf "$work"' EXIT++a=000b$(printf '%064d' 0 | tr 0 a)+b=000b$(printf '%064d' 0 | tr 0 b)+c=000b$(printf '%064d' 0 | tr 0 c)+e=000b$(printf '%064d' 0 | tr 0 e)++# run <what> <command>...: run a command, then name its status.+run()+{+ what=$1+ shift+ status=0+ "$@" 2>&1 || status=$?+ printf '%s: status %d\n' "$what" "$status"+}++# refused <what> <file content>: the job on that file.+refused()+{+ printf '%s\n' "$2" >"$work/bad.json"+ run "$1" "$job" "$work/bad.json"+}++cat >"$work/first.json" <<BINDINGS+{"source": "vm-host-1", "nodes": [+ {"ak_name": "$a", "ek_name": "$e", "node_id": "edge-01"},+ {"ak_name": "$b"}+]}+BINDINGS+run 'first put' "$job" "$work/first.json"+run 'again' "$job" - <"$work/first.json"++cat >"$work/other.json" <<BINDINGS+{"source": "vm-host-2", "nodes": [+ {"ak_name": "$c", "node_id": "edge-03"},+ {"ak_name": "$a", "ek_name": "$e", "node_id": "edge-09"}+]}+BINDINGS+run 'rebound' "$job" "$work/other.json"+printf '{"source": "vm-host-2", "nodes": [{"ak_name": "%s"}]}\n' "$c" >"$work/check.json"+run 'check' "$job" --check "$work/check.json"++# shellcheck disable=SC2086 # a command with its options, to be split+$CLICKHOUSE_CLIENT --query "INSERT INTO shirudo.nodes (ak_name, node_id)+ SELECT '$b', argMinState('core-01', toDateTime64(0, 3))"++refused 'not json' '{"nodes": ['+refused 'no source' '{"nodes": []}'+refused 'source empty' '{"source": "", "nodes": []}'+refused 'no ak' '{"source": "s", "nodes": [{"node_id": "x"}]}'+refused 'short ak' '{"source": "s", "nodes": [{"ak_name": "000b01"}]}'+refused 'upper ak' "{\"source\": \"s\", \"nodes\": [{\"ak_name\": \"000B${a#000b}\"}]}"+refused 'bad ek' "{\"source\": \"s\", \"nodes\": [{\"ak_name\": \"$c\", \"ek_name\": \"\"}]}"+refused 'unknown key' "{\"source\": \"s\", \"nodes\": [{\"ak_name\": \"$c\", \"trust\": \"enrolled\"}]}"+refused 'bound twice' "{\"source\": \"s\", \"nodes\": [{\"ak_name\": \"$c\"}, {\"ak_name\": \"$c\"}]}"+refused 'control in node_id' "{\"source\": \"s\", \"nodes\": [{\"ak_name\": \"$c\", \"node_id\": \"a\\u0007\"}]}"+(cd "$work" && run 'no file' "$job" none.json)+run 'no argument' "$job"diff --git a/tools/backend/test/enroll-put.sql b/tools/backend/test/enroll-put.sqlnew file mode 100644index 00000000..23ed839a--- /dev/null+++ b/tools/backend/test/enroll-put.sql@@ -0,0 +1,12 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- The keys after test/enroll-put.sh. The key the backend had seen as+-- host-a is enrolled and named edge-01, the builder's name; the one it+-- had not seen is enrolled and named core-01, the operator's rename. The+-- refused file, which named a third key, loaded nothing, and neither did+-- --check.++SELECT right(ak_name, 4), argMinMerge(node_id), max(trust), min(first_seen) FROM shirudo.nodes+GROUP BY ak_name ORDER BY ak_name;+SELECT right(ak_name, 4), right(ek_name, 4), node_id, source FROM shirudo.enrollments FINAL ORDER BY ak_name;diff --git a/tools/backend/test/schema.expected b/tools/backend/test/schema.expectedindex 313e31c2..28b2d091 100644--- a/tools/backend/test/schema.expected+++ b/tools/backend/test/schema.expected@@ -4,6 +4,7 @@ shirudo boot_first_keep_mv MaterializedViewshirudo boot_first_mv MaterializedViewshirudo checked Nullshirudo checked_mv MaterializedView+shirudo enrollments ReplacingMergeTree ak_nameshirudo expected_builds ReplacingMergeTree version_idshirudo history_conflicts Viewshirudo history_contradictions MergeTree ak_name, tree_id