eBPF-based security platform
backend: move the keepalive backend into tools/backend
John Fastabend02f1fc8ab4b9
diff --git a/.agents/skills/testing/SKILL.md b/.agents/skills/testing/SKILL.mdindex b7042667..54c0a45f 100644--- a/.agents/skills/testing/SKILL.md+++ b/.agents/skills/testing/SKILL.md@@ -29,10 +29,9 @@ PATH=$PWD/build/afl/bin:$PATH make -C testing afl [AFL_SECONDS=600]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 none of t9107 and t9109 to t9111 runs, so say so when-reporting the tier. The tier boots two VMs at once, each with its own+The end2end tier runs t9107, and t9109 to t9111 on the host, against+the keepalive backend of `tools/backend`, which `host.sh` starts for+every run. The tier boots two VMs at once, each with its ownswtpm: node A runs the tests, node B (`make -C testing vm-node-end2end`,node mode of `vm/run.sh`) takes `role=core` from `config-core` and waits.With a backend, a fresh edge node (`END2END_NODE=edge`, `role=edge` fromdiff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex c43a9ceb..b0d3e0e2 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -181,3 +181,14 @@ jobs:with:path: build/test-vm/cachekey: ${{ steps.images.outputs.cache-primary-key }}++ backend:+ name: Backend SQL tests+ runs-on: ubuntu-latest++ steps:+ - name: Check out repository+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1++ - name: Run the SQL tests in a ClickHouse container+ run: make -C tools/backend testsdiff --git a/Documentation/_ext/clickhouse_schema.py b/Documentation/_ext/clickhouse_schema.pynew file mode 100644index 00000000..658e9e51--- /dev/null+++ b/Documentation/_ext/clickhouse_schema.py@@ -0,0 +1,706 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# Sphinx extension for the backend's table reference: it reads the CREATE+# statements of tools/backend/sql/*.sql and documents each table from+# them, so that the engine, key, TTL, columns and the views around a+# table come from the schema and only the prose comes from the page.+#+# .. clickhouse-table:: shirudo.keepalive+# :kind: store+# :written-by: tests insert here directly+# :ttl: how the TTL is set, or why there is none+# :row-size: ~200 B per record+# :scale: nodes x 1,440 records per day x retention+# :reference: 600k rows, about 120 MB+# :bytes: 120e6+#+# What the table is for, then notes as a bullet list.+#+# :received: what the column holds+# :TraceId, SpanId: one meaning for several columns+#+# A column the schema has and the page does not describe, a column the+# page describes and the schema does not have, and a table of the schema no+# page documents are warnings, which -W turns into errors.+#+# .. clickhouse-sizes:: puts the row size, scale and reference figures+# of every table in one table with their total, and :table:`name` links+# a table from prose.+#+# .. clickhouse-flow:: draws how a record moves between tables. The page+# places the boxes and names the arrows; each arrow must be a view of+# sql/ that writes a table of the one box from a table of the other,+# and is solid when that view runs on insert and dashed when it is+# refreshed. A box takes the colour of its tables' kind.+#+# box <key> <x> <y> <width> <table>... [| <label>]+# edge <from> <r|l|t|b> <to> <r|l|t|b> [<label>]++import glob+import os+import re+from html import escape++from docutils import nodes+from docutils.parsers.rst import directives+from sphinx.util import logging+from sphinx.util.docutils import SphinxDirective, SphinxRole++logger = logging.getLogger(__name__)++KINDS = {+ "null": "Null engine: holds no rows, feeds the views on it",+ "store": "Stored",+ "ref": "Reference data",+ "derived": "Derived by a view",+ "ui": "Derived by a view, read by the UI",+}+++# -- reading the schema ------------------------------------------------++def strip_comments(text):+ out, i, quote = [], 0, False+ while i < len(text):+ c = text[i]+ if quote:+ out.append(c)+ if c == "\\" and i + 1 < len(text):+ out.append(text[i + 1])+ i += 1+ elif c == "'":+ quote = False+ elif c == "'":+ quote = True+ out.append(c)+ elif text.startswith("--", i):+ while i < len(text) and text[i] != "\n":+ i += 1+ continue+ else:+ out.append(c)+ i += 1+ return "".join(out)+++# Splits text at sep where it is outside quotes and brackets.+def split_top(text, sep):+ parts, depth, quote, start = [], 0, False, 0+ for i, c in enumerate(text):+ if quote:+ if c == "'" and text[i - 1] != "\\":+ quote = False+ elif c == "'":+ quote = True+ elif c in "([":+ depth += 1+ elif c in ")]":+ depth -= 1+ elif c == sep and depth == 0:+ parts.append(text[start:i])+ start = i + 1+ parts.append(text[start:])+ return [p.strip() for p in parts if p.strip()]+++def matching_paren(text, open_at):+ depth = 0+ for i in range(open_at, len(text)):+ if text[i] == "(":+ depth += 1+ elif text[i] == ")":+ depth -= 1+ if depth == 0:+ return i+ raise ValueError("unbalanced parentheses")+++COLUMN_TAIL = re.compile(r"\s+(DEFAULT|MATERIALIZED|ALIAS|EPHEMERAL|CODEC"+ r"|COMMENT|TTL)\b")+CLAUSES = ("ENGINE", "PARTITION BY", "PRIMARY KEY", "ORDER BY", "TTL",+ "SETTINGS")+NAME = r"[A-Za-z_][\w]*\.[A-Za-z_][\w]*"+++def parse_column(text):+ name, rest = text.split(None, 1)+ m = COLUMN_TAIL.search(rest)+ ctype = rest[:m.start()].strip() if m else rest.strip()+ tail = rest[m.start():].strip() if m else ""+ codec = re.search(r"CODEC\(([^)]*\)?)\)", tail)+ return {+ "name": name,+ "type": " ".join(ctype.split()),+ "default": " ".join(tail.split()) if re.match(+ r"(DEFAULT|MATERIALIZED|ALIAS)\b", tail) else "",+ "codec": codec.group(1) if codec else "",+ }+++def parse_clauses(text):+ found = []+ for clause in CLAUSES:+ for m in re.finditer(r"(?<![\w.])%s\b" % clause.replace(" ", r"\s+"),+ text):+ found.append((m.start(), m.end(), clause))+ found.sort()+ out = {}+ for n, (start, end, clause) in enumerate(found):+ stop = found[n + 1][0] if n + 1 < len(found) else len(text)+ value = text[end:stop].strip().lstrip("=").strip()+ out[clause] = " ".join(value.split())+ return out+++def parse_statement(text, path):+ m = re.match(r"CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(%s)\s*\(" %+ NAME, text)+ if m:+ close = matching_paren(text, m.end() - 1)+ cols = [parse_column(c)+ for c in split_top(text[m.end():close], ",")+ if not re.match(r"(INDEX|PROJECTION|CONSTRAINT)\b", c)]+ return {"what": "table", "name": m.group(1), "file": path,+ "columns": cols, "clauses": parse_clauses(text[close + 1:])}+ m = re.match(r"CREATE\s+(MATERIALIZED\s+)?VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?"+ r"(%s)\s+(.*?)\bAS\b(.*)" % NAME, text, re.S)+ if m:+ head = " ".join(m.group(3).split())+ refresh = re.search(r"REFRESH\s+(.*?)(?:\s+APPEND)?\s*(?:TO\b|$)",+ head)+ to = re.search(r"\bTO\s+(%s)" % NAME, head)+ body = re.sub(r"'(?:[^'\\]|\\.)*'", "''", m.group(4))+ sources = []+ for ref in re.findall(r"(?<![\w.])(%s)(?![\w(])" % NAME, body):+ if ref not in sources:+ sources.append(ref)+ return {"what": "mv" if m.group(1) else "view", "name": m.group(2),+ "file": path, "to": to.group(1) if to else None,+ "refresh": refresh.group(1).lower() if refresh else None,+ "append": " APPEND " in " %s " % head, "sources": sources}+ return None+++# The schema's directory, relative to the root of the checkout.+SCHEMA_DIR = os.path.join("tools", "backend", "sql")+++def read_schema(root):+ schema = {}+ for path in sorted(glob.glob(os.path.join(root, SCHEMA_DIR, "*.sql"))):+ with open(path, encoding="utf-8") as stream:+ text = strip_comments(stream.read())+ rel = os.path.relpath(path, root)+ for statement in split_top(text, ";"):+ parsed = parse_statement(statement, rel)+ if parsed:+ schema[parsed["name"]] = parsed+ # A qualified name in a query is a table only if the schema has it;+ # the others are columns of a table alias.+ for spec in schema.values():+ if "sources" in spec:+ spec["sources"] = [s for s in spec["sources"] if s in schema]+ return schema+++# -- the directive -----------------------------------------------------++class tableref(nodes.Inline, nodes.Element):+ """A table name, linked to its section once every page is read."""+++class flow(nodes.General, nodes.Element):+ """Filled with the diagram once every page is read."""+++class sizes(nodes.General, nodes.Element):+ """Filled with the size table once every page is read."""+++def short(name):+ return name.split(".", 1)[1] if name.startswith("shirudo.") else name+++def ref(name):+ node = tableref(target=name)+ node += nodes.literal(short(name), short(name))+ return node+++def para(*parts):+ p = nodes.paragraph()+ for part in parts:+ p += part if isinstance(part, nodes.Node) else nodes.Text(part)+ return p+++def table(headers, rows, widths, classes=()):+ tbl = nodes.table(classes=list(classes))+ group = nodes.tgroup(cols=len(headers))+ tbl += group+ for width in widths:+ group += nodes.colspec(colwidth=width)+ head = nodes.thead()+ group += head+ row = nodes.row()+ for h in headers:+ row += nodes.entry("", nodes.paragraph(text=h))+ head += row+ body = nodes.tbody()+ group += body+ for cells in rows:+ row = nodes.row(classes=cells.get("classes", []))+ for cell in cells["cells"]:+ entry = nodes.entry()+ entry += cell if isinstance(cell, list) else [cell]+ row += entry+ body += row+ return tbl+++def joined(items):+ p = nodes.paragraph()+ for n, item in enumerate(items):+ if n:+ p += nodes.Text("; ")+ for part in item:+ p += part if isinstance(part, nodes.Node) else nodes.Text(part)+ return p+++# An insert-triggered view fires on inserts into the first table its+# query reads, and only that one; the tables it joins it only queries.+def triggered_by(view):+ if view["what"] != "mv" or view["refresh"] or not view["sources"]:+ return None+ return view["sources"][0]+++def interval(text):+ m = re.match(r"every (\d+) (\w+)$", text)+ if m and m.group(1) != "1":+ return "every %s %ss" % m.groups()+ return text+++def schema_of(env):+ if not hasattr(env, "clickhouse_schema"):+ env.clickhouse_schema = read_schema(+ os.path.dirname(os.path.abspath(env.srcdir)))+ return env.clickhouse_schema+++class ClickHouseTable(SphinxDirective):++ required_arguments = 1+ has_content = True+ option_spec = {+ "kind": lambda arg: directives.choice(arg, tuple(KINDS)),+ "written-by": directives.unchanged,+ "queried-by": directives.unchanged,+ "ttl": directives.unchanged,+ "row-size": directives.unchanged,+ "scale": directives.unchanged,+ "reference": directives.unchanged,+ "bytes": float,+ }++ def inline(self, text):+ parsed, messages = self.state.inline_text(text, self.lineno)+ return parsed + messages++ def run(self):+ name = self.arguments[0]+ schema = schema_of(self.env)+ spec = schema.get(name)+ if spec is None or spec["what"] != "table":+ logger.warning("clickhouse-table: %s is not a table of the schema", name,+ location=self.get_location())+ return []++ content = nodes.container()+ self.state.nested_parse(self.content, self.content_offset, content)+ meanings = {}+ for fields in list(content.findall(nodes.field_list)):+ for field in fields.children:+ fname = field[0].astext()+ for col in re.split(r",\s*", fname):+ meanings[col] = (fname, field[1].children)+ fields.parent.remove(fields)++ out = []+ kind = self.options.get("kind")+ if kind:+ out.append(nodes.paragraph(text=KINDS[kind],+ classes=["meta", "kind-" + kind]))+ out += content.children++ clauses = spec["clauses"]+ views = [v for v in schema.values() if v["what"] in ("mv", "view")]+ writers = [v for v in views if v["what"] == "mv" and v["to"] == name]+ fires = [v for v in views if triggered_by(v) == name]+ readers = [v for v in views if name in v["sources"][1:]+ or (name in v["sources"] and not triggered_by(v))]++ def written(v):+ if v["refresh"]:+ how = "refresh %s, %s" % (+ interval(v["refresh"]),+ "append" if v["append"] else "replaces the table")+ return [nodes.literal(text=short(v["name"])), " (%s)" % how]+ return [nodes.literal(text=short(v["name"])), " on insert into ",+ ref(v["sources"][0])]++ def view_item(v):+ if v["what"] == "view":+ return [nodes.literal(text=short(v["name"])), " (view)"]+ return [nodes.literal(text=short(v["name"])), " into ",+ ref(v["to"])]++ facts = [("Engine", [nodes.literal(text=clauses.get("ENGINE", ""))])]+ for label, clause in (("Order by", "ORDER BY"),+ ("Partition by", "PARTITION BY"),+ ("Primary key", "PRIMARY KEY"),+ ("TTL", "TTL"), ("Settings", "SETTINGS")):+ value = [nodes.literal(text=clauses[clause])] \+ if clause in clauses else []+ if clause == "TTL" and "ttl" in self.options:+ value += ([nodes.Text(". ")] if value else []) + \+ self.inline(self.options["ttl"])+ if value:+ facts.append((label, value))+ facts.append(("Defined in", [nodes.literal(text=spec["file"])]))++ def extra(option, items):+ if option in self.options:+ items.append(self.inline(self.options[option]))+ return items++ wrote = extra("written-by", [written(v) for v in writers])+ facts.append(("Written by", joined(wrote) if wrote else "nothing"))+ facts.append(("Fires on insert",+ joined([view_item(v) for v in fires]) if fires+ else "nothing"))+ read = extra("queried-by", [view_item(v) for v in readers])+ facts.append(("Queried by", joined(read) if read else+ "nothing in the schema"))+ for label, option in (("Row size", "row-size"), ("Scale", "scale"),+ ("Reference fleet", "reference")):+ if option in self.options:+ facts.append((label, self.inline(self.options[option])))++ flist = nodes.field_list(classes=["facts"])+ for label, value in facts:+ body = nodes.field_body()+ if isinstance(value, str):+ body += nodes.paragraph(text=value)+ elif isinstance(value, nodes.paragraph):+ body += value+ else:+ body += para(*value)+ flist += nodes.field("", nodes.field_name(text=label), body)+ out.append(flist)++ rows, seen = [], set()+ for col in spec["columns"]:+ ctype = [nodes.literal(text=col["type"])]+ if col["codec"]:+ ctype.append(nodes.Text(" "))+ ctype.append(nodes.literal(text="CODEC(%s)" % col["codec"],+ classes=["codec"]))+ meaning = meanings.get(col["name"])+ cells = [para(nodes.literal(text=col["name"])), para(*ctype)]+ body = [n.deepcopy() for n in meaning[1]] if meaning else []+ if col["default"]:+ body.append(nodes.paragraph(+ "", "", nodes.literal(text=col["default"]),+ classes=["default"]))+ cells.append(body or nodes.paragraph())+ rows.append({"cells": cells})+ if meaning is None:+ logger.warning("clickhouse-table: %s.%s is not described",+ name, col["name"],+ location=self.get_location())+ seen.add(col["name"])+ for col in sorted(set(meanings) - seen):+ logger.warning("clickhouse-table: %s has no column %s", name, col,+ location=self.get_location())++ cols = nodes.container(classes=["columns"])+ cols += nodes.rubric(text="Columns (%d)" % len(spec["columns"]))+ cols += table(["Column", "Type", "Meaning"], rows, [22, 26, 52],+ classes=["columns"])+ out.append(cols)++ section = self.state.parent+ anchor = section["ids"][0] if section.get("ids") else ""+ tables = getattr(self.env, "clickhouse_tables", {})+ if name in tables and tables[name]["docname"] != self.env.docname:+ logger.warning("clickhouse-table: %s is documented twice", name,+ location=self.get_location())+ tables[name] = {+ "docname": self.env.docname, "anchor": anchor,+ "row_size": self.options.get("row-size", ""),+ "reference": self.options.get("reference", ""),+ "bytes": self.options.get("bytes"),+ "kind": self.options.get("kind", "store"),+ }+ self.env.clickhouse_tables = tables+ return out+++class ClickHouseSizes(SphinxDirective):++ def run(self):+ return [sizes()]+++class ClickHouseFlow(SphinxDirective):++ has_content = True+ option_spec = {"alt": directives.unchanged_required}++ def run(self):+ schema = schema_of(self.env)+ boxes, edges = {}, []+ for line in self.content:+ words = line.split("|", 1)+ fields = words[0].split()+ if not fields:+ continue+ if fields[0] == "box" and len(fields) >= 6:+ names = [n if "." in n else "shirudo." + n for n in fields[5:]]+ for n in names:+ if schema.get(n, {}).get("what") != "table":+ logger.warning("clickhouse-flow: %s is not a table "+ "of the schema", n,+ location=self.get_location())+ label = words[1].strip() if len(words) > 1 else \+ " / ".join(short(n) for n in names)+ boxes[fields[1]] = {"x": int(fields[2]), "y": int(fields[3]),+ "w": int(fields[4]), "tables": names,+ "label": label}+ elif fields[0] == "edge" and len(fields) >= 5:+ a, b = fields[1], fields[3]+ if a not in boxes or b not in boxes:+ logger.warning("clickhouse-flow: edge %s -> %s names an "+ "unknown box", a, b,+ location=self.get_location())+ continue+ views = edge_views(schema, boxes[a]["tables"],+ boxes[b]["tables"])+ if not views:+ logger.warning("clickhouse-flow: no view of the schema writes "+ "%s from %s", boxes[b]["label"],+ boxes[a]["label"],+ location=self.get_location())+ edges.append({"from": a, "fs": fields[2], "to": b,+ "ts": fields[4],+ "label": " ".join(fields[5:]),+ "refresh": bool(views) and+ all(v["refresh"] for v in views)})+ else:+ logger.warning("clickhouse-flow: cannot read %r", line,+ location=self.get_location())+ return [flow(boxes=boxes, edges=edges,+ alt=self.options.get("alt", ""))]+++# The tables a view reads, with the tables behind any view it reads.+def reads(schema, view, seen=()):+ out = set()+ for src in view["sources"]:+ spec = schema.get(src, {})+ if spec.get("what") == "view" and src not in seen:+ out |= reads(schema, spec, seen + (src,))+ else:+ out.add(src)+ return out+++# The views that write a table of dst from a table of src: an insert+# view only from the table it fires on, a refreshed one from any it reads.+def edge_views(schema, src, dst):+ found = []+ for v in schema.values():+ if v["what"] != "mv" or v["to"] not in dst:+ continue+ inputs = reads(schema, v) if v["refresh"] else {triggered_by(v)}+ if inputs & set(src):+ found.append(v)+ return found+++BOX_H = 30+++def side(box, where):+ x, y, w = box["x"], box["y"], box["w"]+ return {"r": (x + w, y + BOX_H / 2), "l": (x, y + BOX_H / 2),+ "b": (x + w / 2, y + BOX_H), "t": (x + w / 2, y)}[where]+++def flow_svg(app, docname, node):+ boxes, edges = node["boxes"], node["edges"]+ tables = getattr(app.env, "clickhouse_tables", {})+ width = max(b["x"] + b["w"] for b in boxes.values()) + 10+ height = max(b["y"] for b in boxes.values()) + BOX_H + 10+ out = ['<figure class="flow"><div class="flow-scroll">'+ '<svg viewBox="0 0 %d %d" role="img" aria-label="%s">'+ '<defs><marker id="flow-ah" viewBox="0 0 10 10" refX="9" '+ 'refY="5" markerWidth="7" markerHeight="7" orient="auto-start-'+ 'reverse"><path d="M0,0 L10,5 L0,10 z"/></marker></defs>'+ % (width, height, escape(node["alt"]))]+ for e in edges:+ (x1, y1) = side(boxes[e["from"]], e["fs"])+ (x2, y2) = side(boxes[e["to"]], e["ts"])+ if e["fs"] == "r" and e["ts"] == "l":+ mx = (x1 + x2) / 2+ d = "M%g,%g C%g,%g %g,%g %g,%g" % (x1, y1, mx, y1, mx, y2,+ x2 - 2, y2)+ else:+ d = "M%g,%g L%g,%g" % (x1, y1, x2, y2 + (-2 if y2 > y1 else 2))+ out.append('<path class="edge%s" d="%s" marker-end="url(#flow-ah)"/>'+ % (" dash" if e["refresh"] else "", d))+ if e["label"]:+ down = e["fs"] == "b"+ out.append('<text class="lbl" x="%g" y="%g" text-anchor="%s">%s'+ '</text>' % ((x1 + x2) / 2 + (6 if down else 0),+ (y1 + y2) / 2 - (0 if down else 6),+ "start" if down else "middle",+ escape(e["label"])))+ for b in boxes.values():+ kind = tables.get(b["tables"][0], {}).get("kind", "store")+ box = ('<rect class="box k-%s" x="%d" y="%d" width="%d" height="%d" '+ 'rx="4"/><text x="%g" y="%g" text-anchor="middle">%s</text>'+ % (kind, b["x"], b["y"], b["w"], BOX_H, b["x"] + b["w"] / 2,+ b["y"] + BOX_H / 2 + 4, escape(b["label"])))+ entry = tables.get(b["tables"][0])+ if entry:+ uri = app.builder.get_relative_uri(docname, entry["docname"])+ if entry["anchor"]:+ uri += "#" + entry["anchor"]+ box = '<a href="%s">%s</a>' % (escape(uri), box)+ out.append(box)+ out.append('</svg></div><figcaption><span class="key k-null"></span>Null '+ '<span class="key k-store"></span>stored '+ '<span class="key k-ref"></span>reference '+ '<span class="key k-derived"></span>derived '+ '<span class="key k-ui"></span>read by the UI · solid: on '+ 'insert · dashed: refreshed</figcaption></figure>')+ return "".join(out)+++class TableRole(SphinxRole):++ def run(self):+ name = self.text.strip()+ if "." not in name:+ name = "shirudo." + name+ if name not in schema_of(self.env):+ logger.warning("table: %s is not in the schema", name,+ location=self.get_location())+ return [ref(name)], []+++# -- resolving ---------------------------------------------------------++def link(app, fromdoc, name, inner):+ entry = getattr(app.env, "clickhouse_tables", {}).get(name)+ if entry is None:+ return inner+ uri = app.builder.get_relative_uri(fromdoc, entry["docname"])+ if entry["anchor"]:+ uri += "#" + entry["anchor"]+ node = nodes.reference("", "", internal=True, refuri=uri)+ node += inner+ return node+++def fmt_bytes(b):+ if b >= 1e9:+ return "%.0f GB" % (b / 1e9)+ if b >= 1e6:+ return "%.0f MB" % (b / 1e6)+ return "under 1 MB" if b > 0 else "0"+++def resolve(app, doctree, docname):+ for node in list(doctree.findall(tableref)):+ node.replace_self(link(app, docname, node["target"],+ node.children[0].deepcopy()))+ for node in list(doctree.findall(flow)):+ if app.builder.format == "html":+ node.replace_self(nodes.raw("", flow_svg(app, docname, node),+ format="html"))+ else:+ node.replace_self(nodes.paragraph(text=node["alt"]))+ tables = getattr(app.env, "clickhouse_tables", {})+ schema = schema_of(app.env)+ for node in list(doctree.findall(sizes)):+ order = [n for n in schema if n in tables]+ total = sum(tables[n]["bytes"] or 0 for n in order)+ rows = []+ for n in order:+ t = tables[n]+ rows.append({"cells": [+ para(link(app, docname, n, nodes.literal(text=n))),+ nodes.paragraph(text=t["reference"]),+ nodes.paragraph(text=fmt_bytes(t["bytes"] or 0),+ classes=["num"])]})+ rows.append({"classes": ["total"], "cells": [+ nodes.paragraph(text="Total, approximate"),+ nodes.paragraph(text="All tables at the reference fleet"),+ nodes.paragraph(text="about %.1f GB" % (total / 1e9),+ classes=["num"])]})+ node.replace_self(table(["Table", "Reference fleet", "Bytes"], rows,+ [30, 55, 15], classes=["sizes"]))+++def check(app, env):+ tables = getattr(env, "clickhouse_tables", {})+ for name, spec in schema_of(env).items():+ if spec["what"] == "table" and name not in tables:+ logger.warning("clickhouse-table: %s (%s) is not documented",+ name, spec["file"])+++def purge(app, env, docname):+ tables = getattr(env, "clickhouse_tables", {})+ for name in [n for n, t in tables.items() if t["docname"] == docname]:+ del tables[name]+++def merge(app, env, docnames, other):+ tables = getattr(env, "clickhouse_tables", {})+ tables.update(getattr(other, "clickhouse_tables", {}))+ env.clickhouse_tables = tables+++# The pages that document a table are read again whenever the schema+# changes, which Sphinx cannot see on its own.+def reread_schema(app, env, added, changed, removed):+ old = getattr(env, "clickhouse_schema", None)+ env.clickhouse_schema = read_schema(+ os.path.dirname(os.path.abspath(env.srcdir)))+ if old == env.clickhouse_schema:+ return []+ tables = getattr(env, "clickhouse_tables", {})+ return sorted({t["docname"] for t in tables.values()})+++def setup(app):+ app.add_node(tableref)+ app.add_node(flow)+ app.add_node(sizes)+ app.add_directive("clickhouse-table", ClickHouseTable)+ app.add_directive("clickhouse-sizes", ClickHouseSizes)+ app.add_directive("clickhouse-flow", ClickHouseFlow)+ app.add_role("table", TableRole())+ app.connect("env-get-outdated", reread_schema)+ app.connect("doctree-resolved", resolve)+ app.connect("env-check-consistency", check)+ app.connect("env-purge-doc", purge)+ app.connect("env-merge-info", merge)+ return {"parallel_read_safe": True, "parallel_write_safe": True}diff --git a/Documentation/_themes/shirudo/static/shirudo.css b/Documentation/_themes/shirudo/static/shirudo.cssindex 77433020..d9f1e60c 100644--- a/Documentation/_themes/shirudo/static/shirudo.css+++ b/Documentation/_themes/shirudo/static/shirudo.css@@ -260,3 +260,61 @@ aside.footnote-list { border-top: 1px solid var(--line); margin-top: 2em; paddin.body h1 { font-size: 1.7rem; }}@media (prefers-reduced-motion: reduce) { .tree .chev svg { transition: none; } }++/* table reference (clickhouse_schema) */+.body p.meta[class*="kind-"] { margin: -2px 0 12px; }+.body p.rubric { font-size: 13px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; margin: 8px 0 0; }+table.columns td:first-child code { white-space: nowrap; }+table.columns td code { overflow-wrap: anywhere; }+table.columns code.codec, table.columns p.default { color: var(--muted); }+table.columns p.default { font-size: 12.5px; }+table.sizes td:last-child, table.sizes th:last-child { text-align: right; padding-right: 0; }+table.sizes p.num { font-variant-numeric: tabular-nums; white-space: nowrap; }+table.sizes tr.total td { font-weight: 600; border-top: 2px solid var(--line); border-bottom: 0; }++/* flow diagram (clickhouse-flow): one colour per kind of table */+:root {+ --k-null: #8a6d1e; --k-null-bg: #f6eed6;+ --k-store: #1d6b57; --k-store-bg: #e2efe9;+ --k-ref: #3d5a9c; --k-ref-bg: #e4eaf7;+ --k-derived: #8a3f6b; --k-derived-bg: #f4e3ed;+ --k-ui: #a2461f; --k-ui-bg: #f9e5db;+}+@media (prefers-color-scheme: dark) {+ :root:not([data-theme="light"]) {+ --k-null: #e0c070; --k-null-bg: #332c17;+ --k-store: #6cc4a8; --k-store-bg: #1e332c;+ --k-ref: #93aee8; --k-ref-bg: #1f2840;+ --k-derived: #e39cc6; --k-derived-bg: #38202f;+ --k-ui: #f0a07b; --k-ui-bg: #3a2318;+ }+}+:root[data-theme="dark"] {+ --k-null: #e0c070; --k-null-bg: #332c17;+ --k-store: #6cc4a8; --k-store-bg: #1e332c;+ --k-ref: #93aee8; --k-ref-bg: #1f2840;+ --k-derived: #e39cc6; --k-derived-bg: #38202f;+ --k-ui: #f0a07b; --k-ui-bg: #3a2318;+}+figure.flow { margin: 16px 0 24px; }+.flow-scroll { overflow-x: auto; border: 1px solid var(--line); border-radius: 8px; padding: 12px; }+figure.flow svg { display: block; width: 100%; min-width: 640px; height: auto; }+figure.flow svg text { font: 500 12px var(--mono); fill: var(--fg); }+figure.flow svg text.lbl { font: 400 11px var(--sans); fill: var(--muted); paint-order: stroke; stroke: var(--bg); stroke-width: 4px; stroke-linejoin: round; }+figure.flow svg .edge { fill: none; stroke: var(--muted); stroke-width: 1.2; }+figure.flow svg .edge.dash { stroke-dasharray: 5 4; }+figure.flow svg marker path { fill: var(--muted); }+figure.flow svg rect.box { stroke-width: 1.2; }+figure.flow svg a:hover rect.box { stroke-width: 2.2; }+figure.flow svg .k-null { fill: var(--k-null-bg); stroke: var(--k-null); }+figure.flow svg .k-store { fill: var(--k-store-bg); stroke: var(--k-store); }+figure.flow svg .k-ref { fill: var(--k-ref-bg); stroke: var(--k-ref); }+figure.flow svg .k-derived { fill: var(--k-derived-bg); stroke: var(--k-derived); }+figure.flow svg .k-ui { fill: var(--k-ui-bg); stroke: var(--k-ui); }+figure.flow figcaption .key { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin: 0 4px 0 10px; vertical-align: -1px; }+figure.flow figcaption .key:first-child { margin-left: 0; }+figure.flow figcaption .k-null { background: var(--k-null); }+figure.flow figcaption .k-store { background: var(--k-store); }+figure.flow figcaption .k-ref { background: var(--k-ref); }+figure.flow figcaption .k-derived { background: var(--k-derived); }+figure.flow figcaption .k-ui { background: var(--k-ui); }diff --git a/Documentation/conf.py b/Documentation/conf.pyindex 477d62a4..0f74a110 100644--- a/Documentation/conf.py+++ b/Documentation/conf.py@@ -12,7 +12,7 @@ project = "shirudo"author = "Authors of shirudo"copyright = "2026, Authors of shirudo"-extensions = ["myst_parser", "shirudo_docs"]+extensions = ["myst_parser", "shirudo_docs", "clickhouse_schema"]source_suffix = {".rst": "restructuredtext"}root_doc = "index"exclude_patterns = ["output", "_ext", "_themes", "logos"]diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex 627d3bbf..00bd1e47 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -745,13 +745,13 @@ signed config image.unlabeled files; socket-storage bits allow 127.0.0.1 for policy Aand 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+ - The backend of ``tools/backend``: 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* - ``t9109-pipeline``- The whole keepalive pipeline on a fresh edge node and node B, runby ``host.sh`` on the host: ``bpm build`` and ``bpm tree append``@@ -864,6 +864,17 @@ the functional tests run.* - ``upatch``- A ``.upatch`` container and its decoder table+Backend tests+~~~~~~~~~~~~~++The SQL tests of :src:`tools/backend/test/` cover the backend's schema+against a ClickHouse container (:ref:`testing-backend`): the quote+check of every record and the reasons a record is refused, each status+check and the history it reads, ``node_vulns`` and its inputs, the+retention script and the views that keep boot baselines, the tree+ingest job on a single publication and on a walk over sealed segments,+and the SBOM scan job on a store that holds an image in every state.+Coverage by area----------------diff --git a/Documentation/contribute/testing/testing.rst b/Documentation/contribute/testing/testing.rstindex 6685d4ba..f99965eb 100644--- a/Documentation/contribute/testing/testing.rst+++ b/Documentation/contribute/testing/testing.rst@@ -98,12 +98,16 @@ Test tiers- :src:`testing/proofs/`- On the build host, with CBMC and Lean 4, hours of CPU for all- ``make proofs``+ * - Backend+ - :src:`tools/backend/test/`+ - On the build host, against a ClickHouse container+ - ``make -C tools/backend tests````make tests`` in the checkout root, or ``make -C testing``, runs theunit, CI check, functional and end-to-end tiers in that order. The fuzz-targets and the proofs run on their own. CI runs the proofs only after-a push to main, in the ``Proofs`` workflow, never on a pull request:-:doc:`proofs` says which to run for a change.+targets, the proofs and the backend tests run on their own. CI runs the+proofs only after a push to main, in the ``Proofs`` workflow, never on a+pull request: :doc:`proofs` says which to run for a change.Each functional family with target tests gets a fresh VM. The VM runnercaches the generated dracut initrd in ``build/test-vm/cache/initrd/``@@ -799,12 +803,9 @@ The guests reach the registry and collector through QEMU's address forthe host. ClickHouse is available to the collector on the test's Dockernetwork.-``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+``t9107`` runs the backend of :src:`tools/backend/`+(:doc:`/operate/integrations/backend`). ``host.sh`` starts a ClickHouse+of the backend's own on ``http://127.0.0.1:18125``, with the backend's schemaand ``shirudo-quote-check`` as ``tpm_quote_check``, and a collector withthe backend's configuration on ``https://127.0.0.1:14320``. It publishesthe example tree of :src:`testing/fixtures/keepalive/` signed with the@@ -814,17 +815,12 @@ with their recorded quotes through that collector and queriesClickHouse, both through QEMU's address for the host. After node A,``host.sh`` runs ``t9109``, ``t9110`` and ``t9111`` against the samebackend, see :ref:`testing-pipeline`, :ref:`testing-history` and-:ref:`testing-walk`. Without ``BACKEND_DIR`` and without ``../backend``,-none of ``t9107`` and ``t9109`` to ``t9111`` runs: ``host.sh`` writes the-example tree's digest to ``build/test-vm/end2end/backend-tree.digest``-only when it started the backend, and without it-:src:`testing/run-target-tests.sh` leaves ``t9107`` out with-``not run without a keepalive backend`` rather than failing the family-on its skip:--.. code-block:: console-- # make -C testing end2end BACKEND_DIR=/path/to/backend+:ref:`testing-walk`. ``host.sh`` writes the example tree's digest to+``build/test-vm/end2end/backend-tree.digest`` once the backend has loaded+it. Without that file, as in a run of the family without ``host.sh``,+:src:`testing/run-target-tests.sh` leaves ``t9107`` out with ``not run+without a keepalive backend`` rather than failing the family on its+skip... _testing-two-nodes:@@ -1106,6 +1102,61 @@ An empty filter selects everything; invalid expressions fail with statussuite executable names. Filtering preserves order and does not addprerequisite scripts or skip the normal build and VM setup.+.. _testing-backend:++Run the backend tests+---------------------++The SQL tests of the backend start a ClickHouse container with docker+or podman, at the image :src:`testing/vm/stack-lib.sh` pins, install+:src:`tools/backend/test/stub-quote-check.sh` as ``tpm_quote_check``,+and run every ``test/<name>.sql`` against a freshly loaded schema,+comparing what it prints with ``test/<name>.expected``:++.. code-block:: console++ $ make -C tools/backend tests++``tools/backend/test/run.sh <name>...`` runs only the tests named. The+runner loads the schema as an installation does,+``sql/apply-retention.sh`` included. A test that needs other settings+in place when that script runs puts them in ``test/<name>.setup.sql``.++A test that has a ``test/<name>.sh`` runs that script before its SQL,+with ``CLICKHOUSE_CLIENT`` set to the client of the test's server, and+what the script prints comes first in ``test/<name>.expected``. The+tests of ``jobs/tree-ingest`` run the job this way, on+``test/tree-show-1.1.0.json``, a ``bpm tree show`` output built from+:src:`testing/fixtures/keepalive/tree-1.1.0.json` with a made-up+manifest digest, and on ``test/tree-show-walk.json``, a ``bpm tree show+--walk`` output of the same three operations and two more in three+segments of two, two and one operation, at generations 2, 4 and 5. Its+manifest digests and the artifacts of operations 4 and 5 are made up.+Its operation digests and history roots are computed from them with+shirudo's formulas. ``test/stub-shirudo.sh`` stands in for ``shirudo``.+The tests need ``python3`` on the host.++The tests of ``jobs/sbom-scan`` run the job the same way, on the store+``test/sbom-store``, which holds an image in every state and objects out+of place, with ``test/stub-trivy.sh`` in place of Trivy and+``test/stub-aws.sh`` in place of ``aws``. The stub matches nothing: it+prints the report in ``test/trivy/`` named by the SHA-256 of the SBOM it+is given. A script that exits with status 77 skips its test and says+why. ``test/sbom-scan-trivy`` is skipped unless ``trivy`` is on the host+and ``SBOM_TRIVY_CACHE`` names a Trivy cache directory with a database,+since its findings would change with every database CI could fetch.+With them it runs the job with Trivy and checks what does not depend on+the database.++The stub quote checker verifies nothing. It reads the checker's rows and+prints the checker's answers, steered by fields that only look like+base64: ``attest`` is ``<reset_count>/<clock>/<body_sha256>``, ``sig`` is+``good`` or anything else for ``bad_signature``, and ``ak`` is any text.+With ``SHIRUDO_QUOTE_CHECK=<path>`` the runner installs that program+instead. It has to run inside the container, so it needs the libraries+it links there. A test named ``<name>-stub`` feeds quotes in the stub's+form and is skipped then.+Write a test------------diff --git a/Documentation/operate/integrations/backend.rst b/Documentation/operate/integrations/backend.rstnew file mode 100644index 00000000..f8cd6779--- /dev/null+++ b/Documentation/operate/integrations/backend.rst@@ -0,0 +1,158 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: Operators, SecOps++Backend+=======++The other pages of this section store what targets send and alert on+it. The 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 :src:`tools/backend/`: an OpenTelemetry Collector+configuration, a ClickHouse schema, the jobs that load trees and SBOMs,+and their tests. It also serves as the end-to-end tester of shirudo+itself, at the scale of many nodes and many upatches.++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.++What a keepalive is+-------------------++Once a minute ``shirudo status --otel`` sends one OTLP log record with+the event name ``shirudo.keepalive``. Its body is a compact JSON object,+sent as a string, and its only attribute, ``shirudo.quote``, is a TPM+quote over the SHA-256 of that string:++.. code-block:: none++ attest=<base64 TPMS_ATTEST>;sig=<base64 TPMT_SIGNATURE>;ak=<base64 TPMT_PUBLIC>++A node is known by the name of its attestation key, ``ak_name``, never+by the host name it claims, and its records are ordered by the quote's+``reset_count`` and ``clock``, never by a wall clock.++How a record flows+------------------++The collector writes every record into a table that stores nothing,+and a materialized view checks its quote on the way in:++.. code-block:: none++ target --OTLP/HTTPS--> otelcol-contrib --> otel.otel_logs (Null)+ | checked_mv, one tpm_quote_check call per record+ v+ shirudo.checked (Null)+ accepted | refused+ +------------+---------------+-------------+ |+ v v v v v+ keepalive nodes keepalive_latest boot_first rejected++Neither ``otel.otel_logs`` nor ``shirudo.checked`` stores anything. A+record is stored once it is checked, in ``shirudo.keepalive``, or with+the reason it was refused, in ``shirudo.rejected``. Log records of any+other event name are dropped.++Once a minute ``shirudo.node_ops_mv`` adds to ``shirudo.node_ops`` what+each node's newest record says it did at operations the backend had not+seen it reach, ``shirudo.history_contradictions_mv`` marks each node+whose newest record contradicts that history, and+``shirudo.node_status_mv`` runs the checks over ``keepalive_latest``,+``boot_first`` and that history for every node and replaces the rows of+``shirudo.node_status``, which is what a UI reads+(:doc:`backend/status`). Every five minutes ``shirudo.node_vulns_mv``+does the same for ``shirudo.node_vulns`` (:doc:`backend/exposure`).++Files+-----++.. list-table::+ :header-rows: 1++ * - Path+ - Purpose+ * - :src:`tools/backend/otelcol.yaml`+ - Collector configuration: OTLP over HTTPS in, ``otel.otel_logs``+ out.+ * - :src:`tools/backend/clickhouse/tpm_quote_check_function.xml`+ - Declares the ``tpm_quote_check`` function over the+ ``shirudo-quote-check`` program.+ * - :src:`tools/backend/sql/`+ - The schema, loaded in the order of the file names, and+ ``apply-retention.sh``, which sets how long ``shirudo.keepalive``+ keeps a record and ``shirudo.boot_first`` a boot.+ * - :src:`tools/backend/jobs/tree-ingest`+ - Loads every segment of an upatch tree into the reference tables.+ * - :src:`tools/backend/jobs/sbom-scan`+ - Scans the SBOM of every image in the SBOM store and loads the+ outcome into ``sbom_images`` and ``sbom_vulns``.+ * - :src:`tools/backend/test/`+ - The SQL tests and their runner, ``test/run.sh``+ (:ref:`testing-backend`).++.. toctree::+ :titlesonly:++ backend/set-up+ backend/status+ backend/exposure+ backend/tree-ingest+ backend/sbom-scan+ backend/maintain+ backend/boot-baselines+ backend/tables/indexdiff --git a/Documentation/operate/integrations/backend/boot-baselines.rst b/Documentation/operate/integrations/backend/boot-baselines.rstnew file mode 100644index 00000000..92d30b53--- /dev/null+++ b/Documentation/operate/integrations/backend/boot-baselines.rst@@ -0,0 +1,158 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: Operators++Boot baselines and their retention+==================================++Check 3 asks whether a node's tamper counters have risen since it+booted. The answer needs the counters' total at the start of the boot,+and ``shirudo.boot_first`` holds it. This page says how a row gets+there, when it leaves, and why the table needs a view that writes rows+again. The commands are in :doc:`maintain`.++What the table holds+--------------------++One row per attestation key and ``boot_id``:++.. list-table::+ :header-rows: 1++ * - Column+ - Holds+ * - ``tamper_first``+ - The total of the tamper counters in the boot's first record that could read them. This is the baseline.+ * - ``first_order_key``+ - The order key of the boot's first record.+ * - ``last_used``+ - When the boot was last used: see below. The TTL counts from it.++A record that could not read its counters arrives with an empty+``tamper`` array. It neither sets the baseline nor is compared with it;+the first readable total of the boot becomes the baseline.++How a row is written and read+-----------------------------++- ``shirudo.boot_first_mv`` writes a row for every accepted record as it+ is ingested, keyed by the record's ``ak_name`` and ``boot_id``. The table+ is an AggregatingMergeTree: the rows of one boot merge into one, which+ keeps the total of the earliest record.+- The refresh of ``node_status`` joins a node's newest record to the row+ with the same ``ak_name`` and ``boot_id``, and check 3 compares the+ record's total with that baseline. A rise fails the check.++The backend receives no event for a reboot. It learns of one when a+record arrives with a ``boot_id`` it has not seen for that key.++Why a TTL alone is not enough+-----------------------------++The table gains a row per node per boot, so rows have to leave. A TTL on+the time the boot started would remove the baseline of a boot that is+still running:++1. Day 0: a node boots with a total of 3. The baseline is 3.+2. Day 30, with thirty days of retention: the TTL removes that row. The+ node is still up.+3. Day 35: the total rises to 5, a rise of 2 that check 3 must fail.+4. The oldest row the table still has for the boot is now a later one,+ so the baseline reads 5, and the check reports ``tamper +0``.++A retention shorter than a node's uptime would therefore hide a rise on+the nodes that have run longest.++Counting the TTL from the newest record of the boot does not help.+ClickHouse keeps the rows of one boot in separate parts until it merges+them, and a TTL removes a row from the part it is in, whatever newer+parts hold for the same key. The part with the day 0 row still carries a+day 0 time and still loses it. This was observed on the pinned server: a+background merge dropped the oldest row and the baseline of a boot that+was still sending moved from 3 to 5.++The keep view+-------------++``shirudo.boot_first_keep_mv`` runs once an hour. For every node it+takes the boot of the node's newest record in ``keepalive_latest``, the+node's current boot, and writes that boot's merged baseline again as a+new row with ``last_used`` set to the time of the run. It never changes+a baseline; it only gives the current one a fresh time.++``last_used`` is thus the later of two times: when a record of the boot+last arrived, and when the keep view last found the boot to be its+node's current one. The TTL removes a row+``boot_first_retention_seconds`` after it.++What follows:++- The baseline of a node's current boot never expires, however long the+ boot runs.+- The setting decides how long the rows of earlier boots stay after a+ reboot. No check reads those rows.++A reboot, step by step+----------------------++1. The node sends records with ``boot_id`` X. The table has a row for X+ with baseline 3, and the keep view writes it again every hour.+2. The node reboots. The backend sees nothing.+3. The first record after the reboot carries ``boot_id`` Y.+ ``boot_first_mv`` writes a row for Y at ingest, with that record's+ total as the baseline.+4. From that record on check 3 compares with the baseline of Y. The row+ for X is not read again.+5. At its next run the keep view finds Y to be the node's current boot,+ writes the row for Y again and leaves the row for X alone.+6. ``last_used`` of X no longer moves, and the TTL removes the row when+ the retention has passed.++The setting+-----------++``boot_first_retention_seconds`` in ``shirudo.settings``, 2592000+(thirty days) by default. A ClickHouse TTL cannot read a table, so+:src:`tools/backend/sql/apply-retention.sh` applies a change, as it does+for ``keepalive_retention_seconds``. The script refuses less than a day+(86400), so that an hourly run that is late cannot let a current+baseline go, and it checks both values before it changes either table.++Cases to know+-------------++- A node that stops sending. Its newest record still names its last+ boot, so the keep view keeps that boot's row for good. A node that is+ gone leaves one row in ``boot_first`` and one in ``keepalive_latest``+ until an operator deletes them; :doc:`maintain` gives the statements.+- The server down, or the view stopped, for longer than the+ retention. A current baseline can expire before the next run. Check+ 3 then compares with what is left: the boot's oldest remaining row,+ or zero when none is left, so that counters above zero fail rather+ than become the baseline. The thirty-day default is the margin for+ this case.+- After ``TPM2_Clear``. The node's new records sort before its old+ ones. Delete the node's rows as :doc:`maintain` says.++:src:`tools/backend/test/retention-boot.sql` pins a boot forty days old+that keeps its baseline, a node that went silent, an earlier boot whose+row is gone and a lost baseline.+:src:`tools/backend/test/retention-refused.sh` pins the values the+script refuses.++Why not one row per node+------------------------++One row per node, replaced when the node reboots, would bound the table+by the number of nodes and need neither a TTL nor a setting nor the keep+view. To replace a row the backend has to know which of two boots is the+newer, and ``boot_id`` is a random value with no order: the row would have+to be ordered by the TPM's ``reset_count``. That is only right when every+new ``boot_id`` comes with a higher ``reset_count``. Where a node could+start a new boot without a TPM reset, the earlier baseline would stay+while the counters start again from zero, and a rise would go unseen+until it passed the old total. Keying by ``boot_id`` assumes nothing about+``reset_count``, at the cost of the keep view.diff --git a/Documentation/operate/integrations/backend/exposure.rst b/Documentation/operate/integrations/backend/exposure.rstnew file mode 100644index 00000000..e905c3ca--- /dev/null+++ b/Documentation/operate/integrations/backend/exposure.rst@@ -0,0 +1,346 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators, SecOps++Exposure+========++Which nodes run a vulnerable package or kernel, and whether an upatch+shields them. A node carries no scanner and sends no package list: its+keepalive names the image it booted (``image_id``, ``image_version``,+``image_root``) and the kernel it runs (``kernel_release``), and the+backend knows the rest. In :src:`tools/backend/sql/50-vulns.sql`:++.. list-table::+ :header-rows: 1++ * - Object+ - Engine+ - Holds+ * - ``shirudo.sbom_images``+ - ReplacingMergeTree by ``scanned_at``, ``ORDER BY (image_id, image_version, image_root)``+ - One row per image whose SBOM the scan job found, with the ``state`` of its last scan.+ * - ``shirudo.sbom_vulns``+ - MergeTree, ``ORDER BY (sbom_sha256, vuln_id, package)``, 7-day TTL+ - The findings of every scan of an SBOM.+ * - ``shirudo.kernel_vulns``+ - ReplacingMergeTree, ``ORDER BY (vuln_id, introduced)``+ - Kernel advisories, one row per affected range of releases.+ * - ``kver(release)``+ - function+ - The numbers a kernel release starts with, as an array.+ * - ``shirudo.node_vulns``+ - MergeTree, ``ORDER BY (node_id, ak_name, vuln_id, package)``+ - One row per node and finding: what a UI reads.+ * - ``shirudo.node_vulns_mv``+ - refreshable materialized view, every five minutes+ - Computes the rows for all nodes and replaces those of ``node_vulns`` in one step.++``shirudo.upatch_fixes``, which links an operation's upatch to the+advisories it shields against, is among the reference tables+(:doc:`tables/reference`).++Inputs+------++:src:`tools/backend/jobs/sbom-scan` writes ``sbom_images`` and+``sbom_vulns``, see :doc:`sbom-scan`. Nothing in the backend fills+``kernel_vulns``: the operator writes it.++``shirudo.sbom_images``:++.. list-table::+ :header-rows: 1++ * - Column+ - Value+ * - ``image_id``, ``image_version``+ - The image, as its build and the keepalive name it.+ * - ``image_root``+ - Its dm-verity root, 64 hex digits; empty for an image built without verity. A rebuild that keeps the version has another root and is another row.+ * - ``sbom_format``+ - The format the image's ``image.json`` names, ``cyclonedx-json`` when it names none.+ * - ``sbom_sha256``+ - The SHA-256 of the SBOM, which ``sbom_vulns`` is keyed by; empty unless ``state`` is ``ok``.+ * - ``state``+ - ``ok``, or why there are no findings: ``missing``, ``hash_mismatch``, ``parse_error``, ``unsupported_format``.+ * - ``built_at``, ``db_version``, ``scanned_at``+ - When the image was built, and the advisory database and time of the last scan. ``db_version`` is empty unless ``state`` is ``ok``.++``shirudo.sbom_vulns`` has ``sbom_sha256``, ``vuln_id``, ``package``,+``installed``, ``fixed`` (empty while no fixed version exists),+``severity`` and the ``scanned_at`` of the scan the row is from. The+findings of an image are the rows with the ``scanned_at`` its+``sbom_images`` row has, so a new scan replaces the old one's findings+by writing its own, and the TTL removes what no row points to any more.++A scan older than ``sbom_stale_seconds`` of ``shirudo.settings``, two+days by default, is stale: the rows of the nodes on that image say so in+``sbom_stale``, see below. Its findings are still shown, since they are+the newest known, and a node without findings reads ``unknown``, not+``none``, so an image whose scans stopped never reads as clean, also+once the TTL has removed its findings after seven days. Keep the setting+below seven days (604800) and scan more often than it allows; the job+below runs daily.++``shirudo.kernel_vulns`` has ``vuln_id``, ``introduced`` and ``fixed``+as arrays of numbers and ``severity``. A kernel is affected from+``introduced``, inclusive, to ``fixed``, exclusive; an empty ``fixed``+is a range without an end, and an advisory with several ranges has+several rows:++.. code-block:: sql++ INSERT INTO shirudo.kernel_vulns (vuln_id, introduced, fixed, severity) VALUES+ ('EXAMPLE-0101', [7, 0], [7, 4, 5], 'HIGH');++``kver()`` turns the ``kernel_release`` of a keepalive into such an+array: ``kver('7.4.2-shirudo')`` is ``[7, 4, 2]``. Arrays compare+element by element and a prefix sorts before what extends it, so ``[7,+4, 2]`` is at least ``[7, 0]`` and below ``[7, 4, 5]``, and ``[7, 5,+0]`` is not below ``[7, 5]``. A release that starts with no number gives+``[]`` and matches no range; a number of more than 32 bits reads as 0.+The match is on the upstream numbers alone: a distribution kernel that+carries a fix under an older number reads as affected.++Packages of the kernel in an SBOM (``linux-image-*``, ``kernel``,+``kernel-core``) are left out: the SBOM shows the kernel installed in+the image, and the node may run another.++To link an upatch to an advisory by hand, for one published without+``fixes``, add a row with source ``manual`` for the upatch's newest+``add``:++.. code-block:: sql++ INSERT INTO shirudo.upatch_fixes (tree_id, seq, id, advisory, source)+ VALUES ('fleet-base', 3, 'xfs-fix', 'EXAMPLE-0303', 'manual');++A link belongs to an operation, not to an upatch's name: a later ``add``+of the same upatch shields against what its own rows say.++node_vulns+----------++.. list-table::+ :header-rows: 1++ * - Column+ - Value+ * - ``node_id``, ``ak_name``, ``host_name``, ``status``, ``trust``+ - The node, as ``node_status`` has it. A stale node keeps its last known rows, with ``stale`` beside them.+ * - ``image_id``, ``image_version``+ - The image the node's newest record names; empty when it names none.+ * - ``binding``+ - How far the SBOM can be trusted to describe the node, see below.+ * - ``sbom_stale``+ - True when ``binding`` is ``verified``, ``declared`` or ``root_mismatch`` and the newest scan of that SBOM is more than ``sbom_stale_seconds`` old. The same on every row of the node, kernel rows included; false when there is no SBOM to scan.+ * - ``source``+ - ``sbom``, ``kernel``, or ``none`` on the one row of a node without findings.+ * - ``vuln_id``, ``severity``, ``package``, ``installed``, ``fixed``+ - The finding. For a kernel finding ``package`` is ``linux``, ``installed`` the node's ``kernel_release`` and ``fixed`` the end of the range. All empty on the row of a node without findings.+ * - ``exposure``+ - What stands between the node and the vulnerability, see below.+ * - ``upatch_id``+ - The upatch ``exposure`` is read from; empty when no upatch is linked to the advisory.+ * - ``applied_seq``, ``applied_op``+ - Where the node is: the ``seq`` of the newest operation of that upatch the node has applied, which is one at or below its ``last_seq``, and whether it is an ``add`` or a ``delete``. 0 and empty when the node has applied none.+ * - ``next_seq``, ``next_op``+ - Where the tree is: the newest operation of that upatch in the node's tree. When the node is up to date they equal ``applied_seq`` and ``applied_op``; something is coming when ``next_seq`` is above ``applied_seq``.+ * - ``next_shields``+ - Whether the operation ``next_seq`` names is an ``add`` linked to the advisory in ``upatch_fixes``: false when it is a ``delete`` or an ``add`` that drops the link, and false when no upatch is linked. A ``shielded`` row with ``next_shields`` false loses its shield when the node reaches ``next_seq``.+ * - ``shield_link``+ - Where the link to the advisory comes from: ``fixes``, signed by the operator in the publication, ``manual``, a row somebody added here, or ``none``.+ * - ``updated_at``+ - When the row was computed.++A node with nothing found still has one row, so that "clean" differs+from "no data".++``binding``:++.. list-table::+ :header-rows: 1++ * - Value+ - When+ * - ``verified``+ - The node's ``image_root`` equals the SBOM's: the SBOM describes what booted.+ * - ``declared``+ - Matched on ``image_id`` and ``image_version`` only, because the node or the image has no root. Root on the node can edit ``os-release``.+ * - ``root_mismatch``+ - Same id and version, another root: a rebuild that kept its version, or a modified image. The rows are those of the newest build; flag them.+ * - ``no_sbom``+ - The node names an image that has no row in ``sbom_images``, or one whose ``state`` is not ``ok``. Kernel rows still appear.+ * - ``no_image``+ - The node reports no image. Kernel rows still appear.++When several builds share an id and a version, a node gets the one with+its own root, else the newest by ``built_at``.++``exposure`` says what stands between the node and the vulnerability+now. It is read from the newest operation the node has applied of an+upatch linked to the advisory in ``upatch_fixes``, and from the node's+mask, or from its history in ``node_ops`` when that operation is below+the record's window, so that a shield older than the window keeps its+state; what the tree holds beyond the node's ``last_seq`` is in+``next_seq`` and ``next_op``, not here:++.. list-table::+ :header-rows: 1++ * - Value+ - When+ * - ``shielded``+ - The node has applied an ``add`` and its mask marks it applied: the upatch is loaded.+ * - ``shield_pending``+ - The node has applied no operation of the upatch and the tree's newest one is an ``add``: nothing is loaded and a shield is coming. A rollout; check 5 says when it is stuck.+ * - ``shield_module_absent``+ - The node has applied an ``add`` whose selector matched, but the module it attaches to is not loaded, so nothing is attached.+ * - ``shield_excludes_node``+ - The node has applied an ``add`` whose selector left it out. Either the node is not affected in a way a version cannot show, or the selector is too narrow.+ * - ``shield_withdrawn``+ - The node has applied a ``delete`` of the upatch: a shield was published and taken back. Also when the node has applied nothing and the tree's newest operation is a ``delete``, which the node will reach without ever having had the shield.+ * - ``exposed_no_shield``+ - No upatch is linked to the advisory, or the node follows no tree. ``upatch_id`` is empty, the two ``seq`` are 0, the two operations empty, ``next_shields`` false and ``shield_link`` ``none``.+ * - ``none``+ - There is data for the node and nothing was found.+ * - ``unknown``+ - On the row of a node without findings: no usable SBOM for the node, see ``binding``, or one whose scan is stale, and no kernel finding. On a finding: the node has applied an ``add`` of the linked upatch, but its record has no mask, or one that does not cover that operation, so what the ``add`` did there is not known; such a record fails the status checks. Also when the ``add`` is below the record's window and the node's history has no row for it, because the backend never saw the node reach it, see :doc:`status`.++A row does not run ahead of its node. A node that has applied the+``add`` of an upatch whose ``delete`` is published stays ``shielded``+until it applies the ``delete``, with ``next_op`` ``delete`` saying that+it will; a node with an older build loaded is ``shielded`` by that build+while the newer ``add`` is still coming. When that newer ``add`` no+longer carries the advisory, the row reads ``shielded`` with+``next_shields`` false, and turns ``exposed_no_shield`` once the node+applies it.++What each value asks of the operator: ``exposed_no_shield`` means no+known shield, because none was ever published for the advisory or none+is linked to it, and a node that has the right upatch loaded reads so+too when nothing links that upatch to the advisory. ``shield_withdrawn``+is the other way to be without one, and the question is why the upatch+was deleted and whether its successor is on the way, which ``next_op``+``add`` says. ``shield_pending`` asks for nothing but time, unless check+5 calls the node stuck. ``shield_module_absent`` and+``shield_excludes_node`` are a published shield that does nothing on+this node, and ``unknown`` on a finding is a node to repair before its+row can be read.++Which upatches count: one whose newest ``add`` the node has applied, or+whose newest ``add`` in the tree, is linked to the advisory. Only the+first says what is loaded. When just the coming ``add`` is linked, a+newer build that shields against more than the one before, what the node+has applied is no shield against this advisory: the row is+``shield_pending``, or ``shield_withdrawn`` when the tree ends with a+``delete``, while ``applied_seq`` still names what the node applied.+``shield_link`` is the link of the applied ``add`` when it has one, else+of the coming one. A link on an ``add`` the node has left behind does+not count.++The values are in the order they are ranked in, which is also the order+of the enum. Of several upatches linked to one advisory the best outcome+counts: any ``add`` that is still published, even one whose selector+leaves the node out, before a withdrawn upatch, since it says more about+what can be done for the node, and an outcome that is not known last. Of+a ``fixes`` and a ``manual`` link to the same operation the ``fixes``+one is shown. Sorting the findings by ``exposure`` descending, as the+fleet query below does, puts ``unknown`` first, then+``exposed_no_shield`` and ``shield_withdrawn``, ahead of every outcome+of a published shield.++The two nodes of the example in :src:`testing/fixtures/keepalive/`, both+on image ``fleet-os`` 2026.11.1 and kernel 7.4.2, and a third installed+by hand, with :src:`tools/backend/test/vulns-fixtures.sql` showing the+same:++.. code-block:: none++ node_id binding source vuln_id package installed fixed exposure upatch_id applied_seq applied_op next_seq next_op+ node-a verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shielded xfs-fix 3 add 3 add+ node-a verified sbom EXAMPLE-0202 openssl 3.5.1-1 3.5.1-2 exposed_no_shield 0 0+ node-b declared kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shield_excludes_node xfs-fix 3 add 3 add+ node-b declared sbom EXAMPLE-0202 openssl 3.5.1-1 3.5.1-2 exposed_no_shield 0 0+ node-c no_image none unknown 0 0++Node B is the pairing the table is for: it runs the vulnerable kernel, a+shield exists, and the selector that keeps it to edge nodes leaves B+out.++What the refresh costs: it matches the kernel advisories once for each+distinct ``kernel_release`` and reads the operations once for each+distinct ``tree_id``, ``base_seq``, ``last_seq`` and ``mask``, then+joins both to the nodes. For a linked upatch whose newest applied+operation is below the window it reads one row of ``node_ops`` per node.+Like the status refresh it never reads ``shirudo.keepalive``. It takes+``status`` and ``trust`` from ``node_status`` as that table is, so a+node appears here after its first status refresh. To run it at once:++.. code-block:: sql++ SYSTEM REFRESH VIEW shirudo.node_vulns_mv;+ SYSTEM WAIT VIEW shirudo.node_vulns_mv;++What a UI runs+--------------++All from the one table. Nodes are counted by ``ak_name``, since two keys+can claim one ``node_id``.++The fleet, worst first:++.. code-block:: sql++ SELECT vuln_id, severity, exposure, uniq(ak_name) AS nodes+ FROM shirudo.node_vulns+ WHERE vuln_id != ''+ GROUP BY ALL+ ORDER BY severity = 'CRITICAL' DESC, severity = 'HIGH' DESC, exposure DESC, nodes DESC;++One node:++.. code-block:: sql++ SELECT vuln_id, severity, package, installed, fixed, exposure, upatch_id, binding, status+ FROM shirudo.node_vulns+ WHERE node_id = 'node-b';++Shields whose selector leaves nodes out:++.. code-block:: sql++ SELECT upatch_id, vuln_id, groupArray(node_id) AS left_out+ FROM shirudo.node_vulns+ WHERE exposure = 'shield_excludes_node'+ GROUP BY upatch_id, vuln_id;++Coverage, how much is known:++.. code-block:: sql++ SELECT binding, uniq(ak_name) AS nodes+ FROM shirudo.node_vulns+ GROUP BY binding;++Images whose newest scan is stale, and how many nodes run them:++.. code-block:: sql++ SELECT image_id, image_version, uniq(ak_name) AS nodes+ FROM shirudo.node_vulns+ WHERE sbom_stale+ GROUP BY image_id, image_version;++Nodes that are shielded now and about to lose it, because the delete of+their shield is published and they have not applied it yet:++.. code-block:: sql++ SELECT node_id, vuln_id, upatch_id, applied_seq, next_seq+ FROM shirudo.node_vulns+ WHERE exposure = 'shielded' AND next_seq > applied_seq AND next_op = 'delete';diff --git a/Documentation/operate/integrations/backend/maintain.rst b/Documentation/operate/integrations/backend/maintain.rstnew file mode 100644index 00000000..13755dd8--- /dev/null+++ b/Documentation/operate/integrations/backend/maintain.rst@@ -0,0 +1,160 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators++Maintain the backend+====================++Run the statements with ``clickhouse-client``, and the scripts from+:src:`tools/backend/`.++See a node now+--------------++The refresh runs every minute. To run it at once:++.. code-block:: sql++ SYSTEM REFRESH VIEW shirudo.node_status_mv;+ SYSTEM WAIT VIEW shirudo.node_status_mv;++Allow a build+-------------++Check 3 fails a node whose ``version_id`` is not listed:++.. code-block:: sql++ INSERT INTO shirudo.expected_builds (version_id, note) VALUES ('<version_id>', 'shirudo 2026.11');++Node trust+----------++Every node is ``untrusted``: a keepalive proves that one key signed each+record, not what hardware holds the key. Nothing in the backend raises+``trust``.++Rename a node+-------------++``node_id`` is the first host name a key claimed. To set another, insert+one that sorts before it:++.. code-block:: sql++ INSERT INTO shirudo.nodes (ak_name, node_id)+ SELECT '<ak_name>', argMinState('<name>', toDateTime64(0, 3));++Change a threshold+------------------++``stale_seconds``, ``stuck_seconds`` and ``sbom_stale_seconds`` are read+at every refresh; tune ``stale_seconds`` to the longest tree sync your+nodes run, ``stuck_seconds`` to the size of the fleet and to how long a+rollout takes, and the third to how often+:src:`tools/backend/jobs/sbom-scan` runs. Insert the whole row again and+read the table with ``FINAL``:++.. code-block:: sql++ INSERT INTO shirudo.settings (stale_seconds, stuck_seconds, window, keepalive_retention_seconds,+ boot_first_retention_seconds, sbom_stale_seconds)+ VALUES (600, 3600, 512, 3600, 2592000, 172800);++A column the statement leaves out goes back to its default.++Reset a node after ``TPM2_Clear``+---------------------------------++Clearing a TPM restarts its ``reset_count`` and ``clock`` under the same+attestation key, so the node's new records sort before its old ones and+never become its latest. Delete the node's rows afterwards:++.. code-block:: sql++ DELETE FROM shirudo.keepalive WHERE ak_name = '<ak_name>';+ DELETE FROM shirudo.keepalive_latest WHERE ak_name = '<ak_name>';+ DELETE FROM shirudo.boot_first WHERE ak_name = '<ak_name>';++The node's history in ``node_ops`` and ``node_sets`` stays, and so does+a mark in ``history_contradictions``: the node and its tree state are+the same, only the TPM's counters restarted.++The same statements remove a node that is gone for good, whose newest+record and current baseline otherwise stay; remove its history with+them:++.. code-block:: sql++ DELETE FROM shirudo.node_ops WHERE ak_name = '<ak_name>';+ DELETE FROM shirudo.node_sets WHERE ak_name = '<ak_name>';+ DELETE FROM shirudo.history_contradictions WHERE ak_name = '<ak_name>';++The node's row leaves ``node_status`` at the next refresh and comes back+with its next record.++Set the retention+-----------------++``shirudo.rejected`` keeps a row for seven days. ``shirudo.keepalive``+keeps a record for ``keepalive_retention_seconds`` of+``shirudo.settings`` after it was received, one hour by default. Nothing+reads those records but an audit: the newest record of every node stays+in ``keepalive_latest`` and the baseline of its boot in ``boot_first``,+whatever this retention. A ClickHouse TTL cannot read a table, so a+setting takes effect when the script applies it. To keep thirty days, at+about 200 bytes a record:++.. code-block:: sql++ INSERT INTO shirudo.settings (stale_seconds, stuck_seconds, window, keepalive_retention_seconds,+ boot_first_retention_seconds, sbom_stale_seconds)+ VALUES (600, 3600, 512, 2592000, 2592000, 172800);++.. code-block:: console++ $ sql/apply-retention.sh++The script refuses 0. ClickHouse then rewrites the table's parts in the+background, dropping what is older.++Clear a contradiction mark+--------------------------++A node whose record contradicted its history fails check 4 until its row+in ``shirudo.history_contradictions`` is deleted (:doc:`status`):++.. code-block:: sql++ DELETE FROM shirudo.history_contradictions WHERE ak_name = '<ak_name>';++History retention+-----------------++``shirudo.node_ops`` and ``shirudo.node_sets`` keep every row.+:doc:`status` says why, how fast they grow and why no retention is chosen.++Boot baseline retention+-----------------------++``shirudo.boot_first`` gains a row per node per boot. It keeps one for+``boot_first_retention_seconds`` after the boot was last used, thirty+days by default, and the same script applies a change. A boot is used+when one of its records arrives and, once an hour, when+``shirudo.boot_first_keep_mv`` finds it to be the boot of its node's+newest record. The baseline of a node's current boot therefore never+expires, however long the boot runs and whether the node still sends or+not; what the setting decides is how long the rows of the boots before+it stay, which no check reads. The script refuses less than a day+(86400), so that an hourly refresh that runs late cannot let a current+baseline go. The margin matters for one case: after the server was down,+or the view stopped, for longer than the retention, a baseline can+expire before the next refresh. Check 3 then compares with what is left:+the boot's oldest remaining record, or zero when no row is left, so that+counters above zero fail rather than become the baseline.+:src:`tools/backend/test/retention-boot.sql` shows a boot forty days old+and a lost baseline. :doc:`boot-baselines` gives the reasoning and a+reboot step by step.diff --git a/Documentation/operate/integrations/backend/sbom-scan.rst b/Documentation/operate/integrations/backend/sbom-scan.rstnew file mode 100644index 00000000..dd3a276a--- /dev/null+++ b/Documentation/operate/integrations/backend/sbom-scan.rst@@ -0,0 +1,184 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators++Scan the SBOMs+==============++``node_vulns`` takes a node's packages from the SBOM of the image it+booted. :src:`tools/backend/jobs/sbom-scan` reads those SBOMs from the store the image+build pipeline writes them to, has a matcher find the advisories that+affect their packages and writes the outcome to ``sbom_images`` and+``sbom_vulns``. It is POSIX shell around Trivy, the matcher, and+``clickhouse-client``, with :src:`tools/backend/jobs/sbom-rows.py` to read the JSON, so the+host that runs it needs ``python3``, ``clickhouse-client``, ``trivy`` and, for+a store in S3, the AWS command line ``aws``.++.. code-block:: console++ $ trivy image --download-db-only --cache-dir /var/cache/trivy+ $ jobs/sbom-scan --store s3://fleet-sboms --cache-dir /var/cache/trivy+ $ jobs/sbom-scan --store file:///srv/sboms --cache-dir /var/cache/trivy++What it reads+-------------++One directory per image, which the image pipeline writes once and never+changes; neither shirudo nor this job writes it:++.. code-block:: none++ <store>/<image_id>/<image_version>/<image_root or ->/image.json+ <store>/<image_id>/<image_version>/<image_root or ->/sbom.cdx.json++with an ``image.json`` like++.. code-block:: json++ {"image_id": "fleet-os", "image_version": "2026.11.1",+ "image_root": "a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c",+ "sbom_format": "cyclonedx-json",+ "sbom_sha256": "<64 lowercase hex digits, the SHA-256 of sbom.cdx.json>",+ "built_at": "2026-11-02T08:00:00Z"}++The path is the image's key, the same as the keepalive's ``image_id``,+``image_version`` and ``image_root``: a rebuild that keeps its version+has another root and is another image, and an image built without verity+has ``-`` in the path and an empty ``image_root``. ``image_id`` and+``image_version`` are 1 to 255 characters of ``[A-Za-z0-9._~+-]`` that+do not start with a dot, and the root is 64 lowercase hex digits. An+``image.json`` anywhere else in the store is named on standard error and+left out. ``built_at`` is UTC in exactly that form. ``sbom_format``+names the format of the SBOM and so its file: ``cyclonedx-json``, in+``sbom.cdx.json``, is the only one the job reads, and what an+``image.json`` without the key means. Other keys are ignored.++Image states+------------++The first row that applies:++.. list-table::+ :header-rows: 1++ * - ``state``+ - When+ * - ``parse_error``+ - ``image.json`` is not a JSON object, lacks one of the keys above, has one in another form, or names another image than its path. ``sbom_format`` is then ``cyclonedx-json`` and ``built_at`` 0.+ * - ``unsupported_format``+ - ``sbom_format`` names a format the job has no reader for. The job never guesses one from the file.+ * - ``missing``+ - There is no file of that format beside ``image.json``.+ * - ``hash_mismatch``+ - The SHA-256 of the file is not ``sbom_sha256``.+ * - ``parse_error``+ - The format's reader refuses the file. A CycloneDX SBOM must be JSON with ``"bomFormat": "CycloneDX"`` and components that have names; any ``specVersion`` is read.+ * - ``ok``+ - The reader turned the file into its components, and the matcher scanned it.++Only an image whose state is ``ok`` has ``sbom_sha256``, ``db_version``+and findings. The matcher reads a copy of the bytes that were hashed,+not the store again. Each reader is one function in+:src:`tools/backend/jobs/sbom-rows.py` that turns a file into component+rows, beside the name of the format's file: a second format is one more+reader there, and one the matcher reads too. Nothing after the job+depends on the format.++Matcher+-------++For each image that is ``ok`` the job runs ``trivy sbom --format json+--skip-db-update --quiet <copy>``, and ``trivy version --format json``+once, whose ``VulnerabilityDB.UpdatedAt`` becomes ``db_version``, both+with ``--cache-dir`` when it is given. Every vulnerability in the+``Results`` of the report becomes a row of ``sbom_vulns``:++.. list-table::+ :header-rows: 1++ * - ``sbom_vulns``+ - From+ * - ``vuln_id``+ - ``VulnerabilityID``+ * - ``package``+ - ``PkgName``+ * - ``installed``+ - ``InstalledVersion``+ * - ``fixed``+ - ``FixedVersion``, empty when the report has none+ * - ``severity``+ - ``Severity``, ``UNKNOWN`` when the report has none++Findings of the kernel's packages, ``linux-image-*``, ``kernel`` and+``kernel-core``, are left out, since the node may run another kernel+than the image installs, and a row the report gives twice is written+once. Images whose SBOMs are the same bytes share their findings: the+job writes them once per run, for the first of those images, and names+that image on the line of each other one. A report that is not in that+form is refused. Trivy is this job's choice, not the tables': another+matcher takes the place of the command and of that mapping. The job+never updates Trivy's database: update it before a run, as above. Trivy+reads further options from its own ``TRIVY_*`` environment variables.++What it writes+--------------++Every run scans every image again. All rows of a run carry one+``scanned_at``, later than that of any scan before it, and the job+inserts the findings before the rows of ``sbom_images``, which make a+node read them. The last scan of an image is the one ``node_vulns``+reads; the findings of earlier ones leave with the TTL. It prints a line+per image loaded, with its state and why, or the number of its+components and findings.++When something fails+--------------------++An image whose scan fails, or whose report is refused, is named on+standard error and left out of the run, as is an ``image.json`` out of+place: its row stays that of its last scan, which turns stale. The job+loads the rest and exits with status 1. A store it cannot read, a copy+from S3 that fails or a matcher that cannot say its version loads+nothing, with status 1. Wrong usage is status 2.++Connection+----------++As :src:`tools/backend/jobs/tree-ingest`, the job runs+``clickhouse-client`` or the command ``CLICKHOUSE_CLIENT`` names. Its+user needs ``SELECT`` on ``shirudo.sbom_images`` and ``INSERT`` on+``shirudo.sbom_images`` and ``shirudo.sbom_vulns``. For an+``s3://<bucket>[/<prefix>]`` store it runs ``aws s3 cp --recursive`` for+the objects it reads, every one of them for every run, with the+credentials and region of AWS's own environment and configuration;+``S3_CLIENT`` names another command with its options, split at spaces,+for example ``aws --endpoint-url https://s3.example.com`` for an S3+store not at AWS. ``SBOM_STORE``, ``TRIVY`` and ``TRIVY_CACHE_DIR``+stand in for ``--store``, ``--trivy`` and ``--cache-dir``.++When to run it+--------------++Daily, after updating Trivy's database, and more often than+``sbom_stale_seconds`` allows; and, if you like, when the image pipeline+has stored a new image, which is otherwise scanned at the next run. With+``SBOM_STORE`` and ``TRIVY_CACHE_DIR``, which Trivy reads too, in+``/etc/shirudo-backend/sbom-scan.env``:++.. code-block:: ini++ # sbom-scan.service+ [Service]+ Type=oneshot+ EnvironmentFile=/etc/shirudo-backend/sbom-scan.env+ ExecStartPre=/usr/bin/trivy image --download-db-only+ ExecStart=/opt/shirudo-backend/jobs/sbom-scan++ # sbom-scan.timer+ [Timer]+ OnCalendar=daily+ [Install]+ WantedBy=timers.targetdiff --git a/Documentation/operate/integrations/backend/set-up.rst b/Documentation/operate/integrations/backend/set-up.rstnew file mode 100644index 00000000..83ff3007--- /dev/null+++ b/Documentation/operate/integrations/backend/set-up.rst@@ -0,0 +1,60 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators++Set up the backend+==================++You need a ClickHouse server, the OpenTelemetry Collector Contrib+distribution (``otelcol-contrib``) and ``shirudo-quote-check`` from+shirudo's operator package on the ClickHouse host. Run the commands+from :src:`tools/backend/` of a shirudo checkout.++1. Install the quote checker as the ``tpm_quote_check`` function. Copy+ the declaration beside the server's ``config.xml`` and the program+ into the server's ``user_scripts`` directory, then have the server+ read it:++ .. code-block:: console++ # install -m 0644 clickhouse/tpm_quote_check_function.xml /etc/clickhouse-server/+ # install -m 0755 "$(command -v shirudo-quote-check)" /var/lib/clickhouse/user_scripts/+ $ clickhouse-client --query 'SYSTEM RELOAD FUNCTIONS'++ The server starts up to four checker processes and keeps them. Each+ reads rows of ``attest``, ``sig``, ``ak`` and the body's SHA-256+ separated by tabs, and answers every row with one line of JSON. The+ checker keeps no state and no list of keys: a pass says that the body+ is what this key signed, not that the key lives in a genuine TPM.++2. Load the schema. The function has to exist first, because+ ``shirudo.checked_mv`` names it:++ .. code-block:: console++ $ for file in sql/*.sql; do clickhouse-client <"$file"; done+ $ sql/apply-retention.sh++ Loading it again changes nothing. ``sql/apply-retention.sh`` gives+ ``shirudo.keepalive`` and ``shirudo.boot_first`` the retention that+ ``shirudo.settings`` names (:doc:`maintain`). It runs+ ``clickhouse-client``, or the command given as its arguments:++ .. code-block:: console++ $ sql/apply-retention.sh clickhouse-client --host ch.example.com --secure++3. Run the collector with ``otelcol.yaml``. It reads its TLS certificate+ and key from ``/certs/server.pem`` and ``/certs/server.key`` and+ writes to ``tcp://clickhouse:9000`` as ``default``, unless+ ``OTLP_TLS_CERT``, ``OTLP_TLS_KEY``, ``CLICKHOUSE_ENDPOINT``,+ ``CLICKHOUSE_USER`` and ``CLICKHOUSE_PASSWORD`` say otherwise. The+ collector's user needs ``INSERT`` on ``otel.otel_logs`` and nothing+ else. Targets require TLS 1.3 with a hybrid ML-KEM key exchange, which+ a collector built with Go 1.24 or later offers.++4. Point the targets at the collector, as :doc:`/operate/run/telemetry`+ describes.diff --git a/Documentation/operate/integrations/backend/status.rst b/Documentation/operate/integrations/backend/status.rstnew file mode 100644index 00000000..60645c39--- /dev/null+++ b/Documentation/operate/integrations/backend/status.rst@@ -0,0 +1,412 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators, SecOps++Node status+===========++Once a minute the backend decides, for every node, whether it is+healthy, from the node's newest record, its history and the tree it+follows. The objects that do it are in :src:`tools/backend/sql/40-status.sql`, and+:doc:`tables/status` gives their columns and cost:++.. list-table::+ :header-rows: 1++ * - Object+ - Kind+ - Holds+ * - ``mask_code(mask, i)``+ - function+ - The outcome pair of the operation at index ``i``, from 0, of a mask's window: 1 applied, 2 selector did not match, 3 attach module not loaded, 0 not reached. ClickHouse functions have no database, so the name is global. A mask that is not base64, or too short, reads as 0.+ * - ``shirudo.latest``+ - view+ - The newest record of every node, from ``keepalive_latest``, with the node's ``node_id`` and ``trust``.+ * - ``shirudo.node_ops``+ - ReplacingMergeTree, ``ORDER BY (ak_name, tree_id, seq)``, no TTL+ - The history of every node: what it did at each operation of its tree the backend has seen it reach, see `History`_.+ * - ``shirudo.node_ops_mv``+ - refreshable materialized view, every minute, appending+ - Adds the operations each node's newest record reaches past its stored history, unless the record contradicts that history or the node is marked.+ * - ``shirudo.history_conflicts``+ - view+ - Per node whose newest record contradicts its stored history, whether at ``base_seq`` (``base``) or inside the window (``window``), and the first ``seq`` where it does, see `History`_.+ * - ``shirudo.history_contradictions``+ - MergeTree, ``ORDER BY (ak_name, tree_id)``, no TTL+ - The marks: one row per node and tree whose record once contradicted its history, with ``seq``, ``reason`` and ``marked_at``. Only an operator removes one.+ * - ``shirudo.history_contradictions_mv``+ - refreshable materialized view, every minute, appending+ - Marks every node in ``history_conflicts`` that has no mark for that tree yet.+ * - ``shirudo.node_sets``+ - ReplacingMergeTree by ``last_seq``, ``ORDER BY (ak_name, tree_id, id)``, no TTL+ - Per node, the newest operation of every upatch it applied, from ``node_ops``.+ * - ``shirudo.node_sets_mv``+ - materialized view+ - Writes a row of ``node_sets`` for every row of ``node_ops`` with code 1.+ * - ``shirudo.node_status``+ - MergeTree, ``ORDER BY (node_id, ak_name)``+ - One row per node: the outcome of the checks.+ * - ``shirudo.node_status_mv``+ - refreshable materialized view, every minute+ - Runs the checks for all nodes and replaces the rows of ``node_status`` in one step.++A UI reads ``node_status`` as often as it likes:++.. code-block:: sql++ SELECT node_id, host_name, status, trust, failed_check, log, last_seen, updated_at+ FROM shirudo.node_status+ ORDER BY status = 'healthy', node_id;++.. list-table::+ :header-rows: 1++ * - Column+ - Value+ * - ``node_id``, ``ak_name``, ``host_name``+ - The node's label, its key and the host name its newest record claimed.+ * - ``status``+ - ``stale``, ``unhealthy`` or ``healthy``, see below.+ * - ``trust``+ - The node's ``trust`` from ``shirudo.nodes``, ``untrusted`` for every node. It is never part of ``status``: a healthy node is one whose records are consistent and match the tree, a trusted one would be one whose key is known to live in a TPM. Show both.+ * - ``failed_check``+ - The first check that failed: 2 for ``stale``, 3 to 7 for ``unhealthy``, 0 for ``healthy``.+ * - ``log``+ - Seven lines, one per check in order.+ * - ``last_seen``+ - When the newest record was received.+ * - ``generation``, ``last_seq``+ - From the newest record; ``NULL`` for a node that follows no tree.+ * - ``head_seq``+ - The head of the newest publication loaded for the node's tree, ``NULL`` when there is none.+ * - ``loaded``, ``set_sha256``+ - ``count`` and ``set_sha256`` of the newest record.+ * - ``updated_at``+ - When the row was computed.++Checks+------++``status`` is:++- ``stale`` when the newest record was received more than ``stale_seconds``+ ago, 10 minutes by default. It wins over everything else, because the+ other lines then describe old data; the ``log`` still shows what that+ record said. A node whose records are all refused gets no new record+ and turns stale.++ A node sends a record a minute, but not while it syncs its tree:+ every shirudo command on a target holds the config operation lock for+ its whole run, and ``bpm tree sync`` holds it until its last operation+ is applied. A keepalive that cannot take the lock within 30 seconds+ sends nothing, so a sync that runs for minutes leaves a gap of that+ length. The default allows for syncs of a few minutes; it is a first+ guess, to be tuned against the sync durations seen on real clusters.+- ``unhealthy`` when the record is fresh and one of checks 3 to 7 fails.+- ``healthy`` otherwise. A node behind the head of its tree is healthy+ until ``stuck_seconds`` have passed since the oldest publication it has+ not finished was loaded: that is a rollout, and line 5 says ``behind``.++The checks, in order. Each only means something if those before it+passed:++.. list-table::+ :header-rows: 1++ * - #+ - Line starts+ - Passes when+ - Fails as+ * - 1+ - ``1 signed:``+ - Always, here: a record whose quote fails never becomes a node's newest. The line gives the node's trust and how many records under its key were refused in the last hour.+ - Never fails+ * - 2+ - ``2 fresh:``+ - The newest record, by the quote's ``reset_count`` and ``clock``, was received at most ``stale_seconds`` ago.+ - ``FAIL``+ * - 3+ - ``3 reported:``+ - ``verdict`` is ``ok``, each of the seven condition pairs of ``cond`` is OK (``0x1555``; pairs above the seventh are not read), bits 0 to 3 of ``flags`` are clear, the total of ``tamper`` is what it was in the first record of this boot that could read the counters, and ``version_id`` is in ``shirudo.expected_builds``.+ - ``FAIL``, with every item on the line; an unexpected build is marked ``(not expected)``+ * - 4+ - ``4 chain:``+ - Folding the published operation digests that the mask marks 1 or 3, from ``base_root``, each step SHA-256 of the previous root and the digest, gives ``projection_root``; no operation up to ``last_seq`` is marked 0; every operation from ``base_seq + 1`` to ``last_seq`` is in ``tree_ops``; the tree keys are readable; when ``base_seq`` is above 0, ``base_root`` is the root the node's history has at ``base_seq``; at every operation of the window the history reaches, the code and the root folded from ``base_root`` are the stored ones; and the node has no mark. Where the history has no row at ``base_seq``, the line adds ``base unverified (gap)`` and the check does not fail on that account. A marked node fails even when its record cannot be held against the tree.+ - ``FAIL``, with ``base differs from history``, ``window differs from history at seq <seq>`` or ``marked: contradicted history at seq <seq>`` when that is why+ * - 5+ - ``5 head:``+ - ``last_seq`` is at the head of the newest publication of the tree, or the oldest publication the node has not finished was loaded at most ``stuck_seconds`` ago (``behind``).+ - ``FAIL stuck``+ * - 6+ - ``6 set:``+ - Folding the operations the mask marks 1 into the set they leave loaded, an ``add`` loading its payload under its ``id`` and a ``delete`` removing it, and hashing one line ``<payload_sha256> <id>`` per upatch sorted by ``id``, gives ``set_sha256``. When ``base_seq`` is above 0 the fold starts from what the node's history leaves loaded at ``base_seq``, from ``node_sets``; where the history does not reach ``base_seq`` without a gap, the line reads ``set unverified (gap)`` and the check passes.+ - ``FAIL drift``+ * - 7+ - ``7 peers:``+ - The node's ``base_root`` and its mask up to ``last_seq`` are the most common pair among the nodes with the same ``tree_id``, ``base_seq``, ``last_seq``, ``config_root`` and ``kernel_release``, or one of several equally common ones. Alone in its group it has ``no peers``.+ - ``FAIL outlier``++The baseline of check 3 is a boot's first readable total. A record+whose ``tamper`` is ``null`` could not read the counters: it says so in+``flags`` bit 3 and fails the check for that, its line reads ``tamper +0``,+and it neither sets the baseline nor is compared with it. The next+record that reads them is held against the first one that did, so a+boot that begins with an unreadable record does not fail later for+counters it had from the start.++Check 6 is exact. A node sends a record of one point in time or flags+it: with ``flags`` bit 4 (a tree operation was in flight) the line reads+``sync in progress``, with bit 5 ``snapshot unsettled``, and the set is not+compared. Neither hides a node for long. An operation in flight has a+``seq`` above ``last_seq``, so bit 4 on a node at the head is a+contradiction and fails at once, as ``FAIL sync in progress at head``; a+node that stays behind the head fails check 5 as stuck, with or without+the bits. Bits 4 and 5 do not fail check 3.++The stuck clock of check 5 belongs to the node, not to the tree. It+starts at the ``published_at`` of the earliest-loaded publication of the+node's tree whose ``head_seq`` is beyond the node's ``last_seq``, so a+publication that follows does not start it again: an operator who+publishes more often than ``stuck_seconds`` still sees a node that never+moves, ``stuck_seconds`` after the first publication it failed to finish.+A node that moves, but never as far as the head, starts a new clock+with every publication it finishes. :src:`tools/backend/test/status-stuck.sql` shows both.++Three kinds of node are not held against the tree. Checks 4 to 7 pass+for them and their lines say why:++.. list-table::+ :header-rows: 1++ * - Line reads+ - When+ * - ``no tree``+ - The record's ``tree_id`` is ``null``: the node follows no tree. Checks 1 to 3 still run.+ * - ``no mask``+ - The node follows a tree but its record has no ``mask``: its record of outcomes is damaged. The node says so in ``flags`` bit 2, so check 3 fails.+ * - ``publication unknown``+ - The record names a generation newer than the newest in ``tree_pubs`` for its tree, or a tree with no publication there: the ingest job is behind, and ``tree_ops`` may end before the record does. A record naming an older generation that was never loaded is checked as usual, since operations never change and no check looks a generation up.++The two nodes of the example in :src:`testing/fixtures/keepalive/`, after release 1.1.0 of the upatch+their tree carries, with :src:`tools/backend/test/status-fixtures.sql` showing the same:++.. code-block:: none++ node_id: edge-01+ status: healthy+ trust: untrusted+ failed_check: 0+ log: 1 signed: pass, untrusted, 0 rejected in the last hour+ 2 fresh: pass, last record 21 s ago+ 3 reported: pass, verdict ok, cond 0x1555, flags 0, tamper +0, build d6d918ad+ 4 chain: pass, root 15452248+ 5 head: pass, seq 3 of 3, generation 3+ 6 set: pass, 1 loaded+ 7 peers: no peers, 1 in group++ node_id: core-01+ status: healthy+ trust: untrusted+ failed_check: 0+ log: 1 signed: pass, untrusted, 0 rejected in the last hour+ 2 fresh: pass, last record 21 s ago+ 3 reported: pass, verdict ok, cond 0x1555, flags 0, tamper +0, build d6d918ad+ 4 chain: pass, root 00000000+ 5 head: pass, seq 3 of 3, generation 3+ 6 set: pass, 0 loaded+ 7 peers: no peers, 1 in group++What the checks cost: checks 4 and 6 depend on the tree and the mask,+not on the node, so the refresh folds each distinct path, the+combination of ``tree_id``, ``base_seq``, ``last_seq``, ``base_root`` and+``mask``, once and joins the result to the nodes on it. It reads+``keepalive_latest`` and ``boot_first``, one row per node and per boot,+and never ``shirudo.keepalive``. Of the history it reads, per node, the+projection that says how far it reaches, the rows of ``node_ops`` from+``base_seq`` to where the window or the history ends, whichever comes+first, at most 513 per node, and, for a node whose window starts past+seq 0, its rows of ``node_sets``, one per upatch it ever applied. The+rows of the window are read through ``history_conflicts``, which+``node_ops_mv`` and ``history_contradictions_mv`` read too, so each refresh+reads them once per node. :src:`tools/backend/test/status-cost.sql` asserts what the+refresh reads.++An outlier is a reason to attest a node, not an alarm by itself: a node+whose labels changed partway through a tree differs from its peers for+a good reason.++History+-------++A keepalive's ``mask`` covers a window of the last 512 operations of the+node's tree, from ``base_seq + 1``, and ``base_root`` is the node's root+before it. Below the window a record says nothing, so the backend keeps+what each node's records said while it could: ``shirudo.node_ops`` has a+row for every node, tree and operation the backend has seen the node+reach, and ``shirudo.node_sets`` what that leaves loaded. Checks 4 and 6+read them for a record whose ``base_seq`` is above 0, and ``node_vulns``+for an upatch whose newest operation is below the window. A tree of up+to 512 operations has ``base_seq`` 0 and needs none of it.++``shirudo.node_ops``:++.. list-table::+ :header-rows: 1++ * - Column+ - Value+ * - ``ak_name``, ``tree_id``, ``seq``+ - The node, its tree and the operation.+ * - ``code``+ - What the node did there, as its mask said: 1 applied, 2 selector did not match, 3 attach module not loaded. 0 marks a gap, see below.+ * - ``root``+ - The node's ``projection_root`` after ``seq``, 32 bytes: ``hex(root)`` gives the form of a keepalive.++``shirudo.node_sets`` has, per node, tree and upatch ``id``, the newest+operation the node applied: ``last_seq``, ``last_op`` (``add`` or ``delete``)+and the ``last_payload`` of that operation.++Once a minute ``node_ops_mv`` takes each node's newest record and adds the+operations it reaches past the node's stored history, from the row after+the last stored one to ``last_seq``, with their codes from the mask and+their roots folded from the last stored root. It adds them only when+every one of them is in ``tree_ops``, none is marked 0 and the fold ends+at the record's ``projection_root``: a record that does not extend the+history consistently adds nothing. Nor does a record that contradicts+the history, or any record of a marked node, see below. The rows of an+operation never change once added.+``node_sets_mv`` follows every row with code 1. The fold runs once per+distinct path and starting point, not per node.++Gaps+~~~~++When a record's window starts past the stored history, because+the node is new to the backend or was not heard from while its tree+moved on by more than the window, the operations in between are not in+any record the node will send. The refresh then starts again at the+record's ``base_seq``, with a row of code 0 that holds the record's+``base_root``, and continues from there. Rows are only ever added past the+last one, so the history up to a ``seq`` is whole when it reaches that+``seq`` and has no gap at or below it. For a record whose ``base_seq`` is+above 0:++- check 4 compares ``base_root`` with the root stored at ``base_seq``. When+ there is no row there, or only the gap row, which holds the value of+ the record that found the gap and is verified by nothing, the line+ adds ``base unverified (gap)`` and the check passes if the rest does. A+ ``base_root`` other than the stored one, a gap row's included, fails+ as ``base differs from history``: the node tells another story of the+ same operations. So does an operation of the window that the history+ reaches with another code or another root, see below;+- check 6 reads ``set unverified (gap)`` and passes when the history does+ not reach ``base_seq`` whole: what the node applied in the gap would be+ in its set, and the backend cannot know it. Otherwise the expected set+ is that of ``node_sets`` at or below ``base_seq``, with the operations the+ window marks 1 on top;+- ``node_vulns`` reads an operation below the window from the history,+ and is ``unknown`` when the history has no row for it, see :doc:`exposure`.++:src:`tools/backend/test/history-base.sql` shows nodes followed from seq 0 through four+windows, :src:`tools/backend/test/history-gap.sql` nodes first seen, or seen again, past+their history, and :src:`tools/backend/test/vulns-history.sql` a shield older than the+window.++The order of the refreshes does not matter: check 6 reads the history+at or below ``base_seq``, which an earlier record put there, and check 4+also the rows of the window, which match the record they were folded+from. Check 4 and ``node_ops_mv`` find a contradiction from+``history_conflicts`` themselves and do not wait for the mark.++A keepalive reports a node's outcomes for the last 512+operations of its tree only (U20 of :doc:`/security/threat-model`). A node first+heard from after its tree has grown past that window never tells the+backend which earlier operations it applied. Check 4 anchors its+history at that first record's ``base_root`` and verifies the records+after it; comparing it with its peers (check 7) works from the start;+but check 6 stays ``set unverified (gap)`` for as long as the node+follows that tree, and ``node_vulns`` is ``unknown`` for shields added+before the window. Every node that joins a tree of more than 512+operations is in that case, and so is one that the backend did not+hear from while its tree moved on by more than 512 operations. Attest such a node with ``shirudo attest`` when its+loaded set matters.++Contradictions+~~~~~~~~~~~~~~++A record that does not extend a node's history adds no rows. Two rules+decide when it fails:++1. Where a record's window overlaps the node's stored history, it has+ to match the stored rows at every seq they share, not only at+ ``base_seq``: ``base_root`` the root at ``base_seq``, and at every seq from+ ``base_seq + 1`` to the lower of ``last_seq`` and the end of the stored+ history, the mask's code the stored code and the root folded from+ ``base_root`` the stored root. A gap row has no code, so only its root+ is compared. This holds for a window from seq 0 too. A mismatch+ fails check 4 as ``base differs from history`` at ``base_seq``, or as+ ``window differs from history at seq <seq>``, naming the first seq+ that differs. The roots alone would miss an operation the node calls+ applied (1) in one record and attach module not loaded (3) in+ another: both chain the operation, and only the code tells them+ apart. ``shirudo.history_conflicts`` finds these records.+2. A node whose record once contradicted its history keeps failing+ until an operator clears its mark, so that a later gap cannot+ launder it: without the mark, a node whose window has moved past its+ stored history would start a gap like one not heard from, and pass.+ Once a minute ``history_contradictions_mv`` adds a row to+ ``shirudo.history_contradictions`` for every node and tree in+ ``history_conflicts`` that has none. While a node has a mark, check 4+ fails as ``marked: contradicted history at seq <seq>``, unless its+ record contradicts its history now, which the line names instead,+ and ``node_ops_mv`` adds nothing to its history, gap rows included.++The mark is stricter than the record that set it in three ways: it+holds for the node whatever tree its newest record follows and whatever+boot it comes from, and it fails check 4 even for a node whose record+check 4 otherwise skips (``no tree``, ``no mask``, ``publication unknown``).+A new boot does not clear it, since a node that lies once can reboot,+and nor does a gap.++Clear a mark once the node has been looked at, for example attested+with ``shirudo attest``:++.. code-block:: sql++ DELETE FROM shirudo.history_contradictions WHERE ak_name = '<ak_name>';++Its history then grows again from where it stopped. A record that+still contradicts it is marked again at the next refresh; one whose+window has moved past it starts a gap, as for a node not heard from.+To hold the node's next records against nothing it said before, delete+its history with the mark, as for a node that is gone, see :doc:`maintain`.+:src:`tools/backend/test/history-base.sql` shows both rules with ``edge-liar``, which lies+about its base, and ``edge-swap``, which lies inside its window. Watch+for gaps on nodes the backend heard from all along.++Size+~~~~++``node_ops`` gains a row per node for every+operation the node processes, whatever its outcome, about 34 bytes on+disk, mostly the root: a publication of one operation to 10,000 nodes+adds 10,000 rows, and 10,000 nodes that each go through a tree of+65,000 operations hold about 650 million rows, some 22 GB. ``node_sets``+holds a row per node and upatch the node ever applied, about 70 bytes.+Neither has a TTL, and nothing removes their rows but the operator:+trimming them would reopen the gaps they close, turning the base of+check 4, the set of check 6 and older shields in ``node_vulns`` back into+``gap`` and ``unknown``. A refresh reads one row of the projection per node+to find where its history ends, and the rows it needs at ``base_seq``,+not the whole table.++No retention is chosen for ``node_ops`` and ``node_sets``. It needs+measurements on real clusters, together with ``stale_seconds``, which+decides how long a node may be silent, and the two grow as above.++``window`` of ``shirudo.settings`` is not read: a node chooses its window+and says where it starts in ``base_seq``, and the checks read what the+record has.diff --git a/Documentation/operate/integrations/backend/tables/index.rst b/Documentation/operate/integrations/backend/tables/index.rstnew file mode 100644index 00000000..527e4961--- /dev/null+++ b/Documentation/operate/integrations/backend/tables/index.rst@@ -0,0 +1,25 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++Tables+======++Every table of :src:`tools/backend/sql/`, one page per file. The+engine, key, TTL and columns of each table, and the views that write, fire on and read it,+are read from the schema when the documentation is built; the pages add+only what the schema cannot say. A table the schema has and these pages+do not document, or a column either side lacks, fails the build.++:doc:`overview` draws how a keepalive moves through the tables and+sums what they cost at a reference fleet.++.. toctree::+ :maxdepth: 1++ overview+ ingest+ reference+ latest+ status+ vulnsdiff --git a/Documentation/operate/integrations/backend/tables/ingest.rst b/Documentation/operate/integrations/backend/tables/ingest.rstnew file mode 100644index 00000000..3c17f13f--- /dev/null+++ b/Documentation/operate/integrations/backend/tables/ingest.rst@@ -0,0 +1,253 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++Ingest+======++The collector writes into otel.otel_logs. checked_mv verifies each record's+TPM quote once, and the result is routed either to the audit store or to the+reject log. Neither otel_logs nor checked keeps a row.++Schema: :src:`tools/backend/sql/10-ingest.sql`++Views, functions and jobs+-------------------------++``shirudo.checked_mv``+ materialized view, on insert.++ Splits the quote with a regex, calls tpm_quote_check(attest, sig, ak,+ sha256(body)) once per record and writes the parsed JSON answer to+ checked.++``shirudo.keepalive_mv``+ materialized view, on insert.++ checked → keepalive for accepted rows.++``shirudo.rejected_mv``+ materialized view, on insert.++ checked → rejected for refused rows, with reject as reason.++``tpm_quote_check()``+ executable_pool UDF, clickhouse/tpm_quote_check_function.xml.++ Runs shirudo-quote-check (pool of 4). Returns one JSON line: ok, reason,+ ak_name, ak_public, reset_count, clock.++otel.otel_logs+--------------++.. clickhouse-table:: otel.otel_logs+ :kind: null+ :written-by: otelcol-contrib, configured by :src:`tools/backend/otelcol.yaml`+ :row-size: 0 B stored. About 2 KB per record on the wire (body ~0.9 KB plus+ quote).+ :scale: Nodes × 1 record per minute, passing through: 10,000 nodes ≈ 170+ inserts/s.+ :reference: 0 B+ :bytes: 0++ Landing table for the OpenTelemetry Collector's ClickHouse exporter. It+ holds nothing; it exists so the exporter has a target and checked_mv has+ a source.++ - The columns match what the exporter inserts. Only Timestamp,+ ResourceAttributes['host.name'], LogAttributes['shirudo.quote'], Body+ and EventName are used.+ - Log records with any other event name are dropped.++ :Timestamp: Becomes checked.time.+ :TraceId, SpanId, TraceFlags: OTLP trace context. Unused.+ :SeverityText, SeverityNumber: Unused.+ :ServiceName: Unused.+ :Body: The keepalive body: a compact JSON string that the quote signs.+ :ResourceSchemaUrl, ScopeSchemaUrl, ScopeName, ScopeVersion: Unused.+ :ResourceAttributes: host.name is taken from here.+ :ScopeAttributes: Unused.+ :LogAttributes: shirudo.quote: attest=…;sig=…;ak=… (base64 TPM structures).+ :EventName: Must be shirudo.keepalive.++shirudo.checked+---------------++.. clickhouse-table:: shirudo.checked+ :kind: null+ :written-by: tests, which insert here directly+ :row-size: 0 B stored.+ :scale: Same rate as otel_logs. Each row costs one tpm_quote_check call (pool+ of 4 processes).+ :reference: 0 B+ :bytes: 0++ One row per keepalive, accepted or not, with the checker's answer and+ every body field split into its own column. The body fields and+ order_key/reject are DEFAULT expressions, so a test can insert just the+ first eleven columns and get the same row a real record would.++ - order_key = reset_count << 40 \| clock. That leaves 24 bits for+ reset_count and 40 for clock; a record outside that range is rejected+ as clock_range.+ - reject is computed in order: checker failure (bad_signature,+ body_mismatch, malformed), then schema, then clock_range. Empty means+ accepted.++ :received: When the backend received the record. Freshness (check 2) and+ retention count from it.+ :time: The OTLP Timestamp the target put on the log record. Not trusted for+ ordering.+ :host_name: host.name resource attribute: what the node claims to be called. Not+ an identity.+ :quote: The shirudo.quote attribute as sent.+ :body: The JSON body as sent.+ :ok: 1 when tpm_quote_check accepted the quote.+ :reason: The checker's reason on failure.+ :ak_name: Attestation key name, from the checker.+ :ak_public: Public area of the attestation key, from the checker. Goes only to+ nodes.+ :reset_count: TPM reset counter from the quote.+ :clock: TPM clock from the quote.+ :schema: Body schema. Must be shirudo.keepalive/1 or 1.x, else the record is+ rejected as schema.+ :boot_id: Identifies the boot that sent the record. Tamper baselines in+ boot_first are per boot.+ :version_id: Build identifier of the shirudo binary: SHA-256 over its git commit+ (with -dirty), config.mk and Makefile.shirudo. Printed by shirudo+ version --version-id. Check 3 requires it to be in expected_builds.+ :config_root: Digest of the node's configuration. One of the keys that groups peers+ for check 7.+ :kernel_release: Running kernel, e.g. 7.4.2. Groups peers (check 7) and is matched+ against kernel_vulns via kver().+ :image_id: OS image the node says it booted. Joins to sbom_images.+ :image_version: Version of that image.+ :image_root: Verity root of the image. When it matches the SBOM's root the binding+ is verified.+ :verdict: The node's own overall verdict. Check 3 requires ok.+ :cond: Condition pairs, two bits each. Check 3 requires the low seven pairs+ to read 0x1555 (all OK).+ :flags: Bits 0–3 are faults and fail check 3 (bit 2: outcomes file damaged,+ bit 3: tamper counters unreadable). Bit 4: sync in progress. Bit 5:+ snapshot unsettled.+ :tamper: Tamper counters. Their sum must not rise within a boot (check 3).+ Empty when unreadable.+ :tree_id: The upatch tree the node follows. NULL means no tree, and checks 4–7+ are skipped.+ :generation: Publication generation of the tree the node has seen.+ :base_seq: The record's window starts after this operation seq (exclusive).+ :last_seq: Last operation the node has applied (inclusive end of the window).+ :base_root: Hash-chain root at base_seq, 64 hex digits.+ :projection_root: Hash-chain root after last_seq. Check 4 refolds the tree to reproduce+ it.+ :mask: Base64, two bits per operation in the window: 1 applied, 2 selector+ did not match, 3 attach module not loaded, 0 not reached. Decoded by+ mask_code().+ :set_sha256: Hash of the upatch set the node has loaded. Check 6 recomputes it.+ :count: Number of upatches loaded. Shown as loaded in node_status.+ :not_ok: Reported by the node and stored. No check reads it.+ :order_key: reset_count << 40 \| clock. The TPM's own ordering, never a wall+ clock.+ :reject: Empty if accepted, else malformed, bad_signature, body_mismatch,+ schema or clock_range.++shirudo.keepalive+-----------------++.. clickhouse-table:: shirudo.keepalive+ :kind: store+ :queried-by: audit and ad-hoc queries only+ :ttl: The default of ``keepalive_retention_seconds`` in :table:`settings`;+ :src:`tools/backend/sql/apply-retention.sh` rewrites it from the setting+ :row-size: ~200 B per record compressed (README).+ :scale: Nodes × 1,440 records per day × retention. 30 days of retention is+ 432M rows ≈ 86 GB.+ :reference: 600k rows ≈ 120 MB at the default 1 hour+ :bytes: 1.2e+08++ Every accepted record with its quote and body, kept for audit. No check+ reads this table.++ - A record sent twice has the same key and collapses into one row on+ merge.+ - quote and body are ZSTD-compressed.++ :received: When the backend received the record. Freshness (check 2) and+ retention count from it.+ :time: The OTLP Timestamp the target put on the log record. Not trusted for+ ordering.+ :host_name: host.name resource attribute: what the node claims to be called. Not+ an identity.+ :quote: The signed quote, ZSTD(1).+ :body: The signed body, ZSTD(1).+ :ak_name: Name of the TPM attestation key. This is the node's identity+ everywhere in the schema.+ :reset_count: TPM reset counter from the quote. First half of the ordering.+ :clock: TPM clock from the quote. Second half of the ordering.+ :schema: Body schema. Must be shirudo.keepalive/1 or 1.x, else the record is+ rejected as schema.+ :boot_id: Identifies the boot that sent the record. Tamper baselines in+ boot_first are per boot.+ :version_id: Build identifier of the shirudo binary: SHA-256 over its git commit+ (with -dirty), config.mk and Makefile.shirudo. Printed by shirudo+ version --version-id. Check 3 requires it to be in expected_builds.+ :config_root: Digest of the node's configuration. One of the keys that groups peers+ for check 7.+ :kernel_release: Running kernel, e.g. 7.4.2. Groups peers (check 7) and is matched+ against kernel_vulns via kver().+ :image_id: OS image the node says it booted. Joins to sbom_images.+ :image_version: Version of that image.+ :image_root: Verity root of the image. When it matches the SBOM's root the binding+ is verified.+ :verdict: The node's own overall verdict. Check 3 requires ok.+ :cond: Condition pairs, two bits each. Check 3 requires the low seven pairs+ to read 0x1555 (all OK).+ :flags: Bits 0–3 are faults and fail check 3 (bit 2: outcomes file damaged,+ bit 3: tamper counters unreadable). Bit 4: sync in progress. Bit 5:+ snapshot unsettled.+ :tamper: Tamper counters. Their sum must not rise within a boot (check 3).+ Empty when unreadable.+ :tree_id: The upatch tree the node follows. NULL means no tree, and checks 4–7+ are skipped.+ :generation: Publication generation of the tree the node has seen.+ :base_seq: The record's window starts after this operation seq (exclusive).+ :last_seq: Last operation the node has applied (inclusive end of the window).+ :base_root: Hash-chain root at base_seq, 64 hex digits.+ :projection_root: Hash-chain root after last_seq. Check 4 refolds the tree to reproduce+ it.+ :mask: Base64, two bits per operation in the window: 1 applied, 2 selector+ did not match, 3 attach module not loaded, 0 not reached. Decoded by+ mask_code().+ :set_sha256: Hash of the upatch set the node has loaded. Check 6 recomputes it.+ :count: Number of upatches loaded. Shown as loaded in node_status.+ :not_ok: Reported by the node and stored. No check reads it.++shirudo.rejected+----------------++.. clickhouse-table:: shirudo.rejected+ :kind: store+ :row-size: ~1 KB (estimate: raw quote and body, sorted by time so little+ cross-row compression).+ :scale: Refused records × 7 days. Near zero normally; one bad node at 1 per+ minute adds ~10,000 rows a week.+ :reference: ≈ 10 MB per misbehaving node+ :bytes: 1e+07++ Every refused record and why. Check 1 counts a node's rejections in the+ last hour.++ :received: When it arrived.+ :reason: malformed: quote missing or unparseable. bad_signature: does not+ verify or wrong signer. body_mismatch: quote is over a different body.+ schema: unknown major version. clock_range: counters too large for+ order_key.+ :host_name: Claimed host name.+ :ak_name: Key name, when the checker got far enough to read one.+ :reset_count: From the quote, if parsed.+ :clock: From the quote, if parsed.+ :quote: As sent, ZSTD(1).+ :body: As sent, ZSTD(1).diff --git a/Documentation/operate/integrations/backend/tables/latest.rst b/Documentation/operate/integrations/backend/tables/latest.rstnew file mode 100644index 00000000..e03b4f1e--- /dev/null+++ b/Documentation/operate/integrations/backend/tables/latest.rst@@ -0,0 +1,131 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++Latest state+============++Small tables kept current on every insert so the checks never scan the audit+store: each node's newest record, and each boot's first tamper total.++Schema: :src:`tools/backend/sql/30-latest.sql`++Views, functions and jobs+-------------------------++``shirudo.keepalive_latest_mv``+ materialized view, on insert.++ checked → keepalive_latest for accepted rows.++``shirudo.boot_first_mv``+ materialized view, on insert.++ checked → boot_first, aggregating per (ak_name, boot_id).++``shirudo.boot_first_keep_mv``+ refreshable MV, every 1 hour, APPEND.++ Rewrites the baseline of every node's current boot with last_used =+ now(), so the TTL only removes boots a node has left.++shirudo.keepalive_latest+------------------------++.. clickhouse-table:: shirudo.keepalive_latest+ :kind: store+ :row-size: ~1.5 KB per node (estimate: body plus its parsed columns; one row per+ node, so little cross-row compression).+ :scale: Nodes after a merge. Before one, up to one row per record received+ since the last merge.+ :reference: ≈ 15 MB+ :bytes: 1.5e+07++ The newest record of each node by the TPM's own counters. A late or+ repeated record never replaces a newer one.++ - Read with FINAL.+ - Same columns as keepalive, minus quote, plus order_key.++ :ak_name: Node identity; the sort key.+ :order_key: reset_count << 40 \| clock. Highest wins.+ :received: When the backend received the record. Freshness (check 2) and+ retention count from it.+ :time: The OTLP Timestamp the target put on the log record. Not trusted for+ ordering.+ :host_name: host.name resource attribute: what the node claims to be called. Not+ an identity.+ :body: The newest record's signed body.+ :reset_count: TPM reset counter of the newest record.+ :clock: TPM clock of the newest record.+ :schema: Body schema. Must be shirudo.keepalive/1 or 1.x, else the record is+ rejected as schema.+ :boot_id: Identifies the boot that sent the record. Tamper baselines in+ boot_first are per boot.+ :version_id: Build identifier of the shirudo binary: SHA-256 over its git commit+ (with -dirty), config.mk and Makefile.shirudo. Printed by shirudo+ version --version-id. Check 3 requires it to be in expected_builds.+ :config_root: Digest of the node's configuration. One of the keys that groups peers+ for check 7.+ :kernel_release: Running kernel, e.g. 7.4.2. Groups peers (check 7) and is matched+ against kernel_vulns via kver().+ :image_id: OS image the node says it booted. Joins to sbom_images.+ :image_version: Version of that image.+ :image_root: Verity root of the image. When it matches the SBOM's root the binding+ is verified.+ :verdict: The node's own overall verdict. Check 3 requires ok.+ :cond: Condition pairs, two bits each. Check 3 requires the low seven pairs+ to read 0x1555 (all OK).+ :flags: Bits 0–3 are faults and fail check 3 (bit 2: outcomes file damaged,+ bit 3: tamper counters unreadable). Bit 4: sync in progress. Bit 5:+ snapshot unsettled.+ :tamper: Tamper counters. Their sum must not rise within a boot (check 3).+ Empty when unreadable.+ :tree_id: The upatch tree the node follows. NULL means no tree, and checks 4–7+ are skipped.+ :generation: Publication generation of the tree the node has seen.+ :base_seq: The record's window starts after this operation seq (exclusive).+ :last_seq: Last operation the node has applied (inclusive end of the window).+ :base_root: Hash-chain root at base_seq, 64 hex digits.+ :projection_root: Hash-chain root after last_seq. Check 4 refolds the tree to reproduce+ it.+ :mask: Base64, two bits per operation in the window: 1 applied, 2 selector+ did not match, 3 attach module not loaded, 0 not reached. Decoded by+ mask_code().+ :set_sha256: Hash of the upatch set the node has loaded. Check 6 recomputes it.+ :count: Number of upatches loaded. Shown as loaded in node_status.+ :not_ok: Reported by the node and stored. No check reads it.++shirudo.boot_first+------------------++.. clickhouse-table:: shirudo.boot_first+ :kind: store+ :ttl: The default of ``boot_first_retention_seconds`` in :table:`settings`,+ set by :src:`tools/backend/sql/apply-retention.sh`+ :row-size: ~150 B (estimate).+ :scale: Nodes × boots with a record in the last 30 days, plus each node's+ current boot, which is kept indefinitely.+ :reference: ~3 boots each: 30k rows ≈ 5 MB+ :bytes: 5e+06++ Per node and boot, the tamper total of the first record that could read+ the counters. Check 3 fails if the current total is higher.++ - A record with empty tamper does not set the baseline (argMinStateIf …+ notEmpty(tamper)).+ - A TTL drops a row from its part regardless of newer parts. Without the+ hourly rewrite, a boot longer than the retention would lose its oldest+ row and its baseline would move later, hiding a rise.+ docs/boot-baselines.md explains it.++ :ak_name: Node.+ :boot_id: Boot.+ :first_order_key: order_key of the boot's first record.+ :tamper_first: arraySum(tamper) at the lowest order_key with readable counters. Read+ with argMinMerge.+ :last_used: Last record received for the boot, or last time the hourly job found+ it to be the node's current boot.diff --git a/Documentation/operate/integrations/backend/tables/overview.rst b/Documentation/operate/integrations/backend/tables/overview.rstnew file mode 100644index 00000000..257498d6--- /dev/null+++ b/Documentation/operate/integrations/backend/tables/overview.rst@@ -0,0 +1,78 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++Overview+========++How the tables connect and what they cost. The arrows and the colours+of the diagram are checked against :src:`tools/backend/sql/` and the table pages when+the documentation is built.++How a keepalive moves through the schema+----------------------------------------++A keepalive enters at :table:`otel.otel_logs`, is checked once on its way+into :table:`checked`, and from there fans out on insert to+:table:`keepalive`, :table:`rejected`, :table:`nodes`,+:table:`keepalive_latest` and :table:`boot_first`. Refreshed views then+build :table:`node_ops`, :table:`history_contradictions` and+:table:`node_status` every minute and :table:`node_vulns` every five.+Each box links to its table.++.. clickhouse-flow::+ :alt: Data flow from otel_logs through checked into keepalive,+ rejected, nodes, keepalive_latest and boot_first, then into+ node_ops, node_sets, history_contradictions, node_status and+ node_vulns++ box otel 10 30 140 otel.otel_logs | otel_logs+ box checked 240 30 130 checked+ box rej 240 130 130 rejected+ box ka 420 10 150 keepalive+ box nodes 420 70 150 nodes+ box latest 420 130 150 keepalive_latest+ box boot 420 190 150 boot_first+ box tree 10 250 150 tree_pubs tree_ops+ box ops 420 270 150 node_ops+ box sets 420 330 150 node_sets+ box status 640 160 150 node_status+ box contra 610 240 180 history_contradictions+ box sbom 640 330 150 sbom_images sbom_vulns kernel_vulns | sbom_* / kernel_vulns+ box vulns 840 250 150 node_vulns+ edge otel r checked l quote check+ edge checked b rej t refused+ edge checked r ka l+ edge checked r nodes l+ edge checked r latest l accepted+ edge checked r boot l+ edge latest b ops t+ edge tree r ops l 1 min+ edge ops b sets t+ edge latest r status l 1 min+ edge boot r status l+ edge ops r status l+ edge rej r status l+ edge sets r status l+ edge ops r contra l+ edge contra t status b+ edge status r vulns l 5 min+ edge sbom r vulns l++Where the bytes go+------------------++At a reference fleet of 10,000 nodes sending one keepalive a minute,+following one tree of 65,000 operations, with 50 SBOMs of 500 findings+each. :table:`keepalive` is counted at its default retention of one+hour; it grows by about 2.9 GB a day of retention at this fleet.++.. clickhouse-sizes::++.. admonition:: TODO++ :table:`node_ops` grows unbounded with the number of tree operations.+ The figure above is for 65,000.diff --git a/Documentation/operate/integrations/backend/tables/reference.rst b/Documentation/operate/integrations/backend/tables/reference.rstnew file mode 100644index 00000000..ed41b364--- /dev/null+++ b/Documentation/operate/integrations/backend/tables/reference.rst@@ -0,0 +1,197 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++Reference+=========++What the checks compare a record against. nodes fills itself from accepted+records; tree-ingest loads the tree tables; the operator writes builds,+manual fixes and settings.++Schema: :src:`tools/backend/sql/20-reference.sql`++Views, functions and jobs+-------------------------++``shirudo.nodes_mv``+ materialized view, on insert.++ checked → nodes for accepted rows, grouped by ak_name.++``jobs/tree-ingest``+ external job.++ Runs shirudo bpm tree show --walk and loads every verified segment not+ yet loaded into tree_pubs, tree_ops and upatch_fixes (source fixes). All+ or nothing on a conflict.++shirudo.nodes+-------------++.. clickhouse-table:: shirudo.nodes+ :kind: ref+ :written-by: the operator, to relabel a node+ :row-size: ~0.5 KB (estimate: ak_public dominates).+ :scale: Every key ever seen. No TTL: a reprovisioned TPM adds a row and the+ old one stays.+ :reference: 10,000 rows ≈ 5 MB+ :bytes: 5e+06++ One row per attestation key: its public area, a human label, when it was+ first seen and its trust level.++ - Read through aggregates: argMinMerge(node_id), max(ak_public),+ min(first_seen), max(trust), GROUP BY ak_name.+ - To relabel, insert argMinState('<name>', toDateTime64(0, 3)) for the+ ak_name. Epoch 0 wins argMin. Leave ak_public and first_seen out so+ they don't change.+ - trust only ever rises, and nothing sets it above untrusted today. It is+ shown but never part of status.++ :ak_name: Node identity.+ :ak_public: Public area of the key.+ :node_id: Label: the host name the key claimed first, unless relabeled.+ :first_seen: First accepted record.+ :trust: Defaults to untrusted.++shirudo.expected_builds+-----------------------++.. clickhouse-table:: shirudo.expected_builds+ :kind: ref+ :written-by: the operator+ :row-size: ~100 B (estimate).+ :scale: Builds you allow.+ :reference: tens of rows, negligible+ :bytes: 1000++ The builds a node is allowed to run, by version_id. A node whose+ version_id is missing fails check 3 with (not expected).++ :version_id: Build identifier of the shirudo binary, as in the keepalive body.+ :note: Free text for the operator.+ :added: Defaults to now().++shirudo.tree_pubs+-----------------++.. clickhouse-table:: shirudo.tree_pubs+ :kind: ref+ :written-by: :src:`tools/backend/jobs/tree-ingest`, from the verified output of ``shirudo bpm+ tree show --walk``: the newest publication and every sealed segment+ before it, back to seq 0+ :row-size: ~450 B (estimate: six 64-hex digests and roots).+ :scale: Publications (segments) per tree. Not per node.+ :reference: hundreds of rows, negligible+ :bytes: 100000++ One row per publication of an upatch tree. A publication is a segment of+ the tree holding the operations past segment_base_seq. Gives each tree's+ head for check 5 and the time a node's stuck clock starts.++ - published_at is when ingest loaded the row, not when the operator+ published. Ingest lag delays the stuck clock by the same amount.+ - Digests are 64 lowercase hex digits without a sha256: prefix.+ - The job holds every segment against what is loaded before inserting+ anything. One generation already loaded under a different manifest+ digest refuses the whole run, and nothing loads.++ :tree_id: Tree name.+ :generation: Publication number within the tree.+ :manifest_digest: OCI manifest of this publication.+ :parent_manifest_digest: Previous publication's manifest; empty for the first.+ :head_seq: Seq of the last operation in this publication.+ :segment_base_seq: The segment holds the operations after this seq. 0 for the first+ segment.+ :segment_manifest_digest: The sealed segment before this one; empty for the first.+ :history_root: The tree's history root at segment_base_seq; 64 zeros for the first+ segment.+ :published_at: Load time, default now64(3).++shirudo.tree_ops+----------------++.. clickhouse-table:: shirudo.tree_ops+ :kind: ref+ :written-by: :src:`tools/backend/jobs/tree-ingest`, from every segment of the tree+ :row-size: ~350 B (estimate: four 64-hex digests, selector JSON).+ :scale: Operations across all trees. Not per node.+ :reference: 65,000 rows ≈ 23 MB+ :bytes: 2.3e+07++ One row per operation of a tree. Operations never change once published,+ so reloading a publication replaces rows with identical ones.++ - selector is stored as JSON text and never evaluated. Whether it matched+ is read from the node's mask, where code 2 means it did not.++ :tree_id: Tree name.+ :seq: Position in the tree, from 1.+ :op: Load or remove an upatch.+ :id: Upatch id the operation acts on.+ :selector: Which nodes it targets, as JSON. Read with JSONExtract for display.+ :repository: OCI repository of the payload.+ :manifest_digest: Payload manifest.+ :layer_digest: Payload layer.+ :payload_sha256: Hash of the payload. Feeds the set hash in check 6.+ :operation_digest: Hash of the operation. Folded into the chain root in check 4.++shirudo.upatch_fixes+--------------------++.. clickhouse-table:: shirudo.upatch_fixes+ :kind: ref+ :written-by: :src:`tools/backend/jobs/tree-ingest` (source ``fixes``, from the operation's fixes+ key); the operator (source ``manual``)+ :row-size: ~60 B (estimate).+ :scale: Advisory links across all operations.+ :reference: negligible+ :bytes: 100000++ Which advisory an operation's upatch shields against. This is what turns+ a vulnerability into shielded, pending or withdrawn in node_vulns.++ - When both exist for the same operation, fixes (signed in the+ publication) ranks above manual.++ :tree_id: Tree name.+ :seq: The add operation that carries the shield.+ :id: Upatch id.+ :advisory: Vulnerability id, matching sbom_vulns / kernel_vulns vuln_id.+ :source: Where the link came from.++shirudo.settings+----------------++.. clickhouse-table:: shirudo.settings+ :kind: ref+ :written-by: the operator; seeded once by :src:`tools/backend/sql/20-reference.sql` if empty+ :queried-by: :src:`tools/backend/sql/apply-retention.sh`+ :row-size: ~50 B.+ :scale: Always one row (more until a merge).+ :reference: negligible+ :bytes: 50++ Thresholds and retention, in exactly one row. Read with FINAL. To change+ a value, insert the whole row again with id 1.++ - Retention values take effect when apply-retention.sh runs (it ALTERs+ the TTL of keepalive and boot_first). The rest apply at the next+ refresh.+ - Keep sbom_stale_seconds below 7 days, the sbom_vulns TTL, so an image+ reads stale before its findings expire and it reads clean.++ :id: Always 1.+ :stale_seconds: 600. A node with no record for this long is stale (check 2). Ten+ minutes because a tree sync holds the lock that keepalive needs.+ :stuck_seconds: 3600. How long a node may stay behind its tree's head (check 5).+ :window: 512. Operations a keepalive's mask covers.+ :keepalive_retention_seconds: 3600. TTL of shirudo.keepalive.+ :boot_first_retention_seconds: 2592000 (30 days). TTL of shirudo.boot_first.+ :sbom_stale_seconds: 172800 (2 days). Age after which a scan marks node_vulns rows+ sbom_stale.+ :updated: Version column: the newest row wins.diff --git a/Documentation/operate/integrations/backend/tables/status.rst b/Documentation/operate/integrations/backend/tables/status.rstnew file mode 100644index 00000000..0997f741--- /dev/null+++ b/Documentation/operate/integrations/backend/tables/status.rst@@ -0,0 +1,198 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++Status+======++Once a minute: extend each node's operation history, mark nodes whose+records contradict it, then run checks 1–7 for every node and replace+node_status in one step. Nothing here reads shirudo.keepalive.++Schema: :src:`tools/backend/sql/40-status.sql`++Views, functions and jobs+-------------------------++``mask_code(mask, i)``+ SQL function (global).++ Outcome pair of the i-th operation of a mask's window: 1, 2, 3, or 0 for+ not reached. Bad base64 or a short mask reads as 0, so one forged record+ can't break the refresh.++``shirudo.latest``+ view.++ keepalive_latest FINAL joined to nodes: the newest record of every node+ with node_id and trust.++``shirudo.history_conflicts``+ view.++ Nodes whose newest record contradicts their stored history: base_root+ against the root at base_seq, and every code and folded root of the+ window against the stored rows it overlaps. Gives the first differing seq+ and reason base or window.++``shirudo.node_ops_mv``+ refreshable MV, every 1 minute, APPEND.++ Appends to node_ops what each node's newest record adds past its stored+ history, folding roots once per distinct path. Skips nodes in+ history_conflicts or history_contradictions.++``shirudo.history_contradictions_mv``+ refreshable MV, every 1 minute, APPEND.++ Adds a mark to history_contradictions for each node and tree in+ history_conflicts that has none yet.++``shirudo.node_sets_mv``+ materialized view, on insert.++ node_ops (code 1) joined to tree_ops → node_sets.++``shirudo.node_status_mv``+ refreshable MV, every 1 minute.++ Runs checks 1–7 for all nodes and replaces node_status.++shirudo.node_ops+----------------++.. clickhouse-table:: shirudo.node_ops+ :kind: derived+ :ttl: None: rows are never removed (README.md, History, explains the cost)+ :row-size: ~34 B (README), mostly the 32-byte root, which does not compress.+ :scale: Nodes × operations each node reaches, every outcome counted, including+ selector misses. No TTL. Grows with publishing, not with keepalive+ rate.+ :reference: 650M rows ≈ 22 GB (README)+ :bytes: 2.2e+10++ Each node's history: what it did at every tree operation the backend has+ seen it reach. Lets checks 4 and 6 and node_vulns look below the+ 512-operation window a keepalive covers.++ - code 0 is a gap: the node's record started past the stored history, so+ nothing below that seq is known. The gap row holds the unverified+ base_root of that record.+ - Rows are only appended when every operation is in tree_ops, none up to+ last_seq is unreached, and the fold ends at the record's+ projection_root. An inconsistent record adds nothing.+ - A record that contradicts the stored rows (history_conflicts) adds+ nothing, and neither does any record of a node marked in+ history_contradictions, gap rows included.+ - Projection reach keeps max(seq), argMax(root, seq) and the first gap+ per (ak_name, tree_id), so a refresh reads one row per node.+ deduplicate_merge_projection_mode = 'rebuild' is required for a+ ReplacingMergeTree to keep it.++ :ak_name: Node.+ :tree_id: Tree.+ :seq: Operation.+ :code: 1 applied, 2 selector did not match, 3 attach module not loaded, 0+ gap.+ :root: The node's projection root after this seq (raw SHA-256 bytes).++shirudo.node_sets+-----------------++.. clickhouse-table:: shirudo.node_sets+ :kind: derived+ :ttl: None+ :row-size: ~70 B (README).+ :scale: Nodes × upatches each node ever applied. No TTL.+ :reference: 1,000 upatches each: 10M rows ≈ 700 MB+ :bytes: 7e+08++ Per node, the newest operation of every upatch it applied, from node_ops+ rows with code 1. This is what the node's history leaves loaded, used by+ check 6 when a window starts past seq 0.++ :ak_name: Node.+ :tree_id: Tree.+ :id: Upatch.+ :last_seq: Newest applied operation for that upatch.+ :last_op: Whether it was loaded or removed.+ :last_payload: payload_sha256 of that operation.++shirudo.history_contradictions+------------------------------++.. clickhouse-table:: shirudo.history_contradictions+ :kind: derived+ :ttl: None: cleared only by an operator's ``DELETE``+ :row-size: ~80 B (estimate).+ :scale: Marked nodes × trees. Grows only when nodes lie; cleared by the+ operator.+ :reference: negligible+ :bytes: 1000++ Marks on nodes whose record once contradicted their stored history, one+ row per node and tree. A mark fails check 4 and stops the node's history+ from growing until an operator deletes it.++ - The mark is stricter than the record that set it. It holds whatever+ tree the node's newest record follows and whatever boot it comes from,+ and it fails check 4 even when check 4 would otherwise skip the node+ (no tree, no mask, publication unknown).+ - Neither a reboot nor a gap clears it, so a node that lied once cannot+ launder the lie by staying silent until its window moves past the+ history.+ - Clear it after looking at the node, for example with shirudo attest:+ DELETE FROM shirudo.history_contradictions WHERE ak_name = '<ak_name>'.++ :ak_name: Node.+ :tree_id: Tree whose history it contradicted.+ :seq: First seq where it differed. Shown in check 4 as 'marked: contradicted+ history at seq <seq>'.+ :reason: base: base_root differs from the stored root at base_seq. window: a+ code or folded root inside the window differs from a stored row.+ :marked_at: When the mark was set; default now().++shirudo.node_status+-------------------++.. clickhouse-table:: shirudo.node_status+ :kind: ui+ :queried-by: the UI+ :row-size: ~0.7 KB (estimate: seven log lines dominate).+ :scale: Nodes. The whole table is rewritten every minute.+ :reference: 10,000 rows ≈ 7 MB, rewritten every minute+ :bytes: 7e+06++ One row per node with the outcome of all seven checks. This is what a UI+ reads, as often as it likes.++ - Checks: 1 signed, 2 fresh, 3 reported, 4 chain, 5 head, 6 set, 7 peers.+ Each only means something if the ones before it passed.+ - Checks 4–7 pass with a reason when the node cannot be held against a+ tree: no tree, no mask, or publication unknown (ingest is behind).+ - A node behind the head is healthy until stuck_seconds after the+ earliest publication it has not finished was loaded; line 5 reads+ behind.+ - Check 4 also fails when the record contradicts the stored history+ ('base differs from history', 'window differs from history at seq N')+ or the node carries a mark ('marked: contradicted history at seq N'). A+ mark fails it even for a node check 4 would otherwise skip.++ :node_id: Label from nodes.+ :ak_name: Identity.+ :host_name: Host name the newest record claimed.+ :status: stale wins over everything; unhealthy if any of checks 3–7 fails.+ :trust: From nodes. Never part of status.+ :failed_check: First failing check: 2 for stale, 3–7 for unhealthy, 0 for healthy.+ :log: Seven lines, one per check, e.g. '5 head: pass, seq 3 of 3, generation+ 3'.+ :last_seen: received of the newest record.+ :generation: From the newest record. NULL with no tree.+ :last_seq: From the newest record.+ :head_seq: Head of the newest loaded publication of the node's tree.+ :loaded: count from the record.+ :set_sha256: From the record.+ :updated_at: When the row was computed.diff --git a/Documentation/operate/integrations/backend/tables/vulns.rst b/Documentation/operate/integrations/backend/tables/vulns.rstnew file mode 100644index 00000000..dace4de5--- /dev/null+++ b/Documentation/operate/integrations/backend/tables/vulns.rst@@ -0,0 +1,156 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++Exposure+========++Every five minutes: which nodes run a vulnerable package or kernel, and+whether an upatch from their tree shields them. Packages come from the SBOM+of the booted image, the kernel from kernel_release, the shield from the+mask and node_ops.++Schema: :src:`tools/backend/sql/50-vulns.sql`++Views, functions and jobs+-------------------------++``kver(release)``+ SQL function (global).++ Leading numbers of a kernel release: '7.4.2-shirudo' → [7, 4, 2]. Arrays+ compare element-wise, so ranges work. A release with no leading number is+ [].++``shirudo.node_vulns_mv``+ refreshable MV, every 5 minutes.++ Joins node_status, latest, sbom_images, sbom_vulns, kernel_vulns,+ tree_ops, upatch_fixes and node_ops into node_vulns. Work is done per+ image, per kernel release and per tree path, then joined to nodes.++``jobs/sbom-scan``+ external job.++ Scans every image in the SBOM store with Trivy and loads sbom_images and+ sbom_vulns.++shirudo.sbom_images+-------------------++.. clickhouse-table:: shirudo.sbom_images+ :kind: ref+ :written-by: :src:`tools/backend/jobs/sbom-scan` (``file://`` or ``s3://`` store, Trivy as+ matcher)+ :row-size: ~300 B (estimate).+ :scale: Images × versions × builds in the SBOM store.+ :reference: negligible+ :bytes: 100000++ One row per image in the SBOM store, with the outcome of its newest scan.++ - Only an image with state ok has findings in sbom_vulns.+ - A node's SBOM is the one with the node's own image_root if present,+ else the newest build of that id and version.++ :image_id: Image name, e.g. fleet-os.+ :image_version: e.g. 2026.11.1.+ :image_root: Verity root. Empty for an image built without verity.+ :sbom_format: From image.json; cyclonedx-json when it names none.+ :sbom_sha256: Hash of the SBOM file. Empty unless state is ok. Joins to sbom_vulns.+ :state: Outcome of reading the SBOM.+ :built_at: Image build time. Breaks ties between builds.+ :db_version: Trivy advisory database version used.+ :scanned_at: When this scan ran.++shirudo.sbom_vulns+------------------++.. clickhouse-table:: shirudo.sbom_vulns+ :kind: ref+ :written-by: :src:`tools/backend/jobs/sbom-scan`+ :row-size: ~80 B (estimate: sorted by SBOM, repeated strings compress).+ :scale: Distinct SBOMs × findings × scans in the last 7 days.+ :reference: 50 × 500 × 7 daily scans: 175k rows ≈ 15 MB+ :bytes: 1.5e+07++ Findings of every scan of an SBOM. An image's current findings are the+ rows whose scanned_at equals its newest scan in sbom_images.++ - Kernel packages (linux-image-\*, kernel, kernel-core) are ignored here:+ the node may run a different kernel than the image ships, so kernel+ findings come from kernel_vulns only.++ :sbom_sha256: Which SBOM.+ :vuln_id: Advisory id, e.g. a CVE.+ :package: Affected package.+ :installed: Installed version.+ :fixed: First fixed version; empty when none exists.+ :severity: As Trivy reports it.+ :scanned_at: Which scan produced the row.++shirudo.kernel_vulns+--------------------++.. clickhouse-table:: shirudo.kernel_vulns+ :kind: ref+ :written-by: the operator+ :row-size: ~60 B (estimate).+ :scale: Affected release ranges of kernel advisories.+ :reference: thousands of rows, negligible+ :bytes: 200000++ Kernel advisories, one row per affected range of releases. Matched+ against each distinct kernel_release with kver().++ :vuln_id: Advisory id.+ :introduced: First affected release, inclusive, e.g. [7, 0].+ :fixed: First fixed release, exclusive. Empty means no end.+ :severity: As the advisory gives it.++shirudo.node_vulns+------------------++.. clickhouse-table:: shirudo.node_vulns+ :kind: ui+ :queried-by: the UI+ :row-size: ~60 B (estimate: sorted by node; repeated strings compress well).+ :scale: Nodes × (findings on their image and kernel + 1). The whole table is+ rewritten every 5 minutes.+ :reference: 10,000 × 500: 5M rows ≈ 300 MB, rewritten every 5 minutes+ :bytes: 3e+08++ One row per node and finding, plus one row with an empty vuln_id for a+ node with none, so a clean node differs from a missing one. This is what+ a UI reads for exposure.++ - A row says where the node is, not where the tree is.+ - A stale scan keeps its findings and sets sbom_stale. It never makes a+ node read clean: a node without findings then reads unknown.+ - With several upatches linked to one advisory, the best exposure wins,+ in enum order.++ :node_id, ak_name, host_name: Node, as in node_status.+ :status, trust: Copied from node_status.+ :image_id, image_version: From the node's newest record.+ :binding: How far the SBOM can be trusted to describe the node. verified:+ image_root matches the SBOM's.+ :sbom_stale: Newest scan is older than sbom_stale_seconds.+ :source: Where the finding came from.+ :vuln_id: Empty for the 'no findings' row.+ :severity, package, installed, fixed: From sbom_vulns, or linux / kernel_release / fixed release for kernel+ findings.+ :exposure: Best first: shielded, shield_pending, shield_module_absent,+ shield_excludes_node, shield_withdrawn, exposed_no_shield, none,+ unknown.+ :upatch_id: Linked upatch the outcome is read from.+ :applied_seq, applied_op: Newest operation of that upatch the node has applied; 0 and empty if+ none.+ :next_seq, next_op: Newest operation of that upatch in the tree. next_seq > applied_seq+ means something is coming.+ :next_shields: The newest operation is an add linked to this advisory.+ :shield_link: Where the advisory link comes from.+ :updated_at: When the row was computed.diff --git a/Documentation/operate/integrations/backend/tree-ingest.rst b/Documentation/operate/integrations/backend/tree-ingest.rstnew file mode 100644index 00000000..3f31ead4--- /dev/null+++ b/Documentation/operate/integrations/backend/tree-ingest.rst@@ -0,0 +1,154 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators++Load a tree's publications+==========================++The checks compare what a node reports with the tree it follows, so the+backend needs every operation of that tree. A long tree is a chain of+signed segments: the publication its tag names holds only the operations+after its ``base.seq``, and names the sealed segment before it by manifest+digest. :src:`tools/backend/jobs/tree-ingest` loads them all. It is POSIX shell around+``clickhouse-client`` and ``shirudo bpm tree show --walk``, with+:src:`tools/backend/jobs/tree-rows.py` to parse the JSON, so the host that runs it needs+``python3``, ``clickhouse-client`` and, to fetch a publication, ``shirudo``+from the operator package.++.. code-block:: console++ $ jobs/tree-ingest --cert /etc/shirudo/operator.pem oci://registry.example.com/shirudo/fleet-base+ $ shirudo bpm tree show oci://registry.example.com/shirudo/fleet-base --cert /etc/shirudo/operator.pem --walk >show.json+ $ jobs/tree-ingest --input show.json++The first form runs ``shirudo bpm tree show oci://<repository>+[--reference <ref>] --cert <file> --walk`` itself; the second reads a+stored output of that command, from standard input with ``--input -``.++What it reads+-------------++One JSON object per segment, oldest first, from the segment whose+``base.seq`` is 0 to the publication the tag names, each+``{"manifest_digest":"sha256:<hex>","document":<publication document>}``+followed by a newline, as ``bpm tree show --walk`` prints them once it+has fetched every segment and verified its signature against the+certificate. A document may span lines, so the job reads a stream of+JSON values, not lines. A tree that was never sealed is one segment, so+the output of ``bpm tree show`` without ``--walk`` for it is read the+same way.++The job verifies nothing itself and trusts its input for that reason:+feed it only what ``bpm tree show`` printed, and keep a stored output+where nobody else can write. It checks only that the segments join up:+the first has ``base.seq`` 0 and neither+``base.segment_manifest_digest`` nor ``base.history_root``; every later+one has both, at least one operation, the same ``tree_id``, a+``base.seq`` equal to the ``head.seq`` of the one before, a+``segment_manifest_digest`` naming the manifest of the one before and a+higher ``generation``; and every operation's ``seq`` is above its+segment's ``base.seq`` and at most its ``head.seq``. Input of another+shape, or a walk that does not join up, is refused with a message and+exit status 1, and nothing is inserted.++What it writes+--------------++.. list-table::+ :header-rows: 1++ * - Table+ - Rows+ * - ``shirudo.tree_pubs``+ - One per segment: ``tree_id``, ``generation``, ``manifest_digest``, ``parent_manifest_digest`` (empty for a first publication), ``head_seq``, ``segment_base_seq`` (its ``base.seq``), ``segment_manifest_digest`` (empty for the first segment) and ``history_root``, the tree's history root at ``segment_base_seq`` as the document carries it, 64 zeros for the first segment.+ * - ``shirudo.tree_ops``+ - One per operation: ``seq``, ``op``, ``id``, the ``selector``, and the artifact's ``repository``, ``manifest_digest``, ``layer_digest`` and ``payload_sha256`` with the ``operation_digest``.+ * - ``shirudo.upatch_fixes``+ - One per advisory ID in an operation's ``fixes``, with ``source`` ``fixes``.++Digests are stored as 64 hex digits, without ``sha256:``. A selector is+stored as compact JSON text with its keys in the document's order, and+is not interpreted: read a key with ``JSONExtract``. ``published_at`` is+when the job loaded the publication, not when the operator published it,+because the document carries no time: run the job soon after a+publication, since the time a node is given to catch up counts from+there.++``fixes`` is a convention between the operator and this backend, which+shirudo's nodes ignore. An operation whose ``fixes`` is not an array of+strings is loaded without fixes and named on standard error; the rest of+the publication loads.++Running it again+----------------++A segment is loaded once. The job first looks up the generations of the+tree in ``tree_pubs`` and skips every segment that is there with the+same manifest digest, so a sealed segment is loaded by the first run+that sees it, a later run adds only the segments that are new, and+``published_at`` of a loaded one stays. It inserts the operations and+fixes of the new segments before their own rows: a run that stops+halfway leaves those segments out of ``tree_pubs``, and the next run+inserts them again, which ReplacingMergeTree collapses into the same+rows. A segment whose generation is loaded under another manifest digest+is refused with status 1 and none of the walk is loaded, since two+publications cannot share a generation; look at the registry before+deleting the row. The job only adds: an advisory that a later+publication no longer names stays in ``upatch_fixes``.++Connection+----------++The job runs ``clickhouse-client``, which takes the server from+``CLICKHOUSE_HOST``, ``CLICKHOUSE_USER`` and ``CLICKHOUSE_PASSWORD``.+For anything else, ``CLICKHOUSE_CLIENT`` names the command with its+options, split at spaces, for example ``clickhouse-client --secure+--port 9440`` or ``docker exec -i clickhouse clickhouse-client``. The+job's user needs ``SELECT`` on ``shirudo.tree_pubs`` and ``INSERT`` on+the three tables. ``SHIRUDO``, ``TREE_REPOSITORY``, ``TREE_REFERENCE``+and ``TREE_CERT`` stand in for ``--shirudo``, the repository,+``--reference`` and ``--cert``.++When to run it+--------------++That is yours to choose; the job is one shot and keeps no state of its+own, so both of these work, also together:++- *On a timer.* Run it every minute or so for each tree, from cron or a+ systemd timer. A run that finds nothing new costs one fetch and one+ query. For example, with the environment above in+ ``/etc/shirudo-backend/fleet-base.env``:++ .. code-block:: ini++ [Service]+ Type=oneshot+ EnvironmentFile=/etc/shirudo-backend/%i.env+ ExecStart=/opt/shirudo-backend/jobs/tree-ingest++ [Timer]+ OnCalendar=minutely+ [Install]+ WantedBy=timers.target++- *On a registry webhook.* Have the registry's push notification for the+ tree's repository start the same command, through whatever receives+ your webhooks. The job takes nothing from the notification: it+ fetches the publication and has it verified like any other run, so a+ forged notification loads nothing that is not signed.++A timer reads the newest publication and the sealed segments behind it,+so a generation published and replaced within its segment between two+runs is never loaded. Nothing is lost with it: the segments together+carry every operation of the tree, and no check looks a generation up.+The time a node is given to catch up then counts from the first+publication beyond it that was loaded. Each run fetches every segment+back to ``base.seq`` 0, one registry request per segment, and parses all+of them, also those loaded already; on a long tree, run it from a+webhook or a slower timer.diff --git a/Documentation/operate/integrations/clickhouse.rst b/Documentation/operate/integrations/clickhouse.rstindex e51217b5..c164f625 100644--- a/Documentation/operate/integrations/clickhouse.rst+++ b/Documentation/operate/integrations/clickhouse.rst@@ -17,7 +17,7 @@ This is a do-it-yourself example to get started from, not anintegration that shirudo ships or maintains. Adapt retention, accesscontrol and sizing to your deployment. To check the keepalives' quotesand compare each target with its upatch tree as well, start from the-:doc:`keepalive-backend` instead.+:doc:`backend` instead.Before you begin----------------@@ -204,7 +204,7 @@ Next steps- :doc:`/upatches/write/decoders` to turn a map into log records ormetrics- :doc:`grafana` to chart the same data-- :doc:`keepalive-backend` to check the quotes and the tree state the+- :doc:`backend` to check the quotes and the tree state thekeepalives report- :doc:`/concepts/background/siem-export` for how the records reach abackend and what to build on themdiff --git a/Documentation/operate/integrations/index.rst b/Documentation/operate/integrations/index.rstindex fd8cef40..66c4332f 100644--- a/Documentation/operate/integrations/index.rst+++ b/Documentation/operate/integrations/index.rst@@ -14,8 +14,8 @@ tamper attempts. Adapt them to your deployment.Splunk and Elastic Security are SIEMs, ClickHouse keeps records foranalysis 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.+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 hybridpost-quantum key exchange, and nothing else. Each page puts an@@ -31,7 +31,7 @@ post-quantum support.elasticsearchgrafanasplunk- keepalive-backend+ backend:doc:`/concepts/background/siem-export` explains how the records reach abackend and what to build on them.diff --git a/Documentation/operate/integrations/keepalive-backend.rst b/Documentation/operate/integrations/keepalive-backend.rstdeleted file mode 100644index b5669033..00000000--- a/Documentation/operate/integrations/keepalive-backend.rst+++ /dev/null@@ -1,70 +0,0 @@-..- 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/testing/end2end/host.sh b/testing/end2end/host.shindex 39aff859..bd0386ed 100755--- a/testing/end2end/host.sh+++ b/testing/end2end/host.sh@@ -34,6 +34,7 @@ BACKEND_CLICKHOUSE=127.0.0.1:18125STACK_NAME=shirudo-end2endSTACK_PERSIST=0S=$REPO/shirudo+BACKEND=$REPO/tools/backendexport SHIRUDO_BUILD="$REPO/tools/shirudo-build/shirudo-build"export BPM_OCI_CA_FILE="$W/ca.pem"MAKE=${MAKE:-make}@@ -184,27 +185,6 @@ second_pair() {die "the second pair is not labelled role=edge and role=core"}-# 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@@ -265,19 +245,17 @@ if [ $# -eq 1 ]; thensay "the operator builds, pushes and publishes kernel-obs"operator "$OPERATOR_SH" publishoperator cat "$OPERATOR_OUT/nonce" >"$W/nonce"- if [ -n "${BACKEND-}" ]; then- say "the keepalive backend of $BACKEND loads the example tree"- operator cat "$OPERATOR_OUT/pkg/kernel-obs-1.0.0.bee" >"$BEE"- 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"- }- fi+ say "the keepalive backend of tools/backend loads the example tree"+ operator cat "$OPERATOR_OUT/pkg/kernel-obs-1.0.0.bee" >"$BEE"+ 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"+ }# Node B outlives this run, which ends with its boot over, or with it# stopped when the run fails.trap '[ $? -eq 0 ] || node_down b "$NODE_B_PID"' EXIT@@ -315,16 +293,10 @@ say "the registry, collector and ClickHouse"stack_oci || die "the registry did not come up"stack_telemetry || die "the telemetry stack did not come up"-BACKEND=-if backend_find; then- say "the keepalive backend of $BACKEND"- [ -x "$CHECKER" ] || die "no quote checker: $CHECKER"- stack_backend "$BACKEND" "$CHECKER" ||- die "the keepalive backend did not come up"-else- say "no keepalive backend at ../backend and no BACKEND_DIR: t9107 and t9109 to t9111 do not run"-fi-export BACKEND+say "the keepalive backend of tools/backend"+[ -x "$CHECKER" ] || die "no quote checker: $CHECKER"+stack_backend "$BACKEND" "$CHECKER" ||+ die "the keepalive backend did not come up"say "the operator, in $E2E_VM-operator"# Each VM's name goes on make's command line, where a VM_NAME the callerdiff --git a/testing/end2end/t9107-keepalive-backend.sh b/testing/end2end/t9107-keepalive-backend.shindex eac5ee0f..b0e60e2b 100755--- a/testing/end2end/t9107-keepalive-backend.sh+++ b/testing/end2end/t9107-keepalive-backend.sh@@ -3,14 +3,14 @@# 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+# backend of tools/backend, 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.+# 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@@ -24,7 +24,7 @@ H=$PWD/helper/test-otel-mapCOLLECTOR=https://10.0.2.2:14320CLICKHOUSE=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"+ test_skip_all "no keepalive backend: end2end/host.sh started none"[ -x "$H" ] || test_skip_all "test-otel-map helper not built"W=$(mktemp -d)trap 'rm -rf "$W"' EXITdiff --git a/tools/backend/Makefile b/tools/backend/Makefilenew file mode 100644index 00000000..b582b423--- /dev/null+++ b/tools/backend/Makefile@@ -0,0 +1,16 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# The backend has nothing to build; this runs its SQL tests. Its+# documentation is Documentation/operate/integrations/backend.++.DEFAULT_GOAL := help++.PHONY: help tests++help:+ @printf '%s\n' \+ 'make tests run the SQL tests (test/run.sh)'++tests:+ test/run.shdiff --git a/tools/backend/clickhouse/tpm_quote_check_function.xml b/tools/backend/clickhouse/tpm_quote_check_function.xmlnew file mode 100644index 00000000..f7f0c79a--- /dev/null+++ b/tools/backend/clickhouse/tpm_quote_check_function.xml@@ -0,0 +1,37 @@+<?xml version="1.0"?>+<!--+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++ Declares tpm_quote_check(attest, sig, ak, body_sha256) over the+ shirudo-quote-check program of the shirudo operator package. Install+ this file beside the server's config.xml and the program in the+ server's user_scripts directory.+-->+<clickhouse>+ <function>+ <type>executable_pool</type>+ <name>tpm_quote_check</name>+ <command>shirudo-quote-check</command>+ <format>TabSeparated</format>+ <argument>+ <type>String</type>+ <name>attest</name>+ </argument>+ <argument>+ <type>String</type>+ <name>sig</name>+ </argument>+ <argument>+ <type>String</type>+ <name>ak</name>+ </argument>+ <argument>+ <type>String</type>+ <name>body_sha256</name>+ </argument>+ <return_type>String</return_type>+ <pool_size>4</pool_size>+ <deterministic>true</deterministic>+ </function>+</clickhouse>diff --git a/tools/backend/jobs/sbom-rows.py b/tools/backend/jobs/sbom-rows.pynew file mode 100755index 00000000..5c262a4c--- /dev/null+++ b/tools/backend/jobs/sbom-rows.py@@ -0,0 +1,422 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# jobs/sbom-rows.py -- the parts of jobs/sbom-scan that shell does not+# reach: reading image.json and the SBOMs, and the matcher's JSON.+#+# sbom-rows.py files+# sbom-rows.py images <store directory> <work directory>+# sbom-rows.py rows <work directory> <scanned_at>+#+# files prints the names of the objects an image directory may hold that+# the job reads, one per line.+#+# images finds every <image_id>/<image_version>/<image_root or ->/image.json+# under the store and decides the state of each image. It copies every+# SBOM it accepts into the work directory, where the matcher reads it,+# and writes there images.json, what the next step needs, and+# images.tsv: per image its number, state, SBOM copy ("-" for none) and+# directory in the store, separated by tabs.+#+# rows reads those, the matcher's version.json and its output for each+# image, trivy-<number>.json, and writes sbom_images.jsonl and+# sbom_vulns.jsonl in ClickHouse's JSONEachRow format, with scanned_at,+# seconds since the epoch, on every row, and summary, one line per image+# loaded.+#+# Exit status: 0; 3 when an object or a matcher's output was left out and+# named on standard error, the rest written; 1 when nothing could be done;+# 2 for wrong usage.++import calendar+import hashlib+import json+import os+import re+import sys++PROG = "sbom-scan"+SEGMENT = re.compile(r"[A-Za-z0-9_~+-][A-Za-z0-9._~+-]{0,254}")+HEX64 = re.compile(r"[0-9a-f]{64}")+BUILT_AT = re.compile(r"([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z")+DEFAULT_FORMAT = "cyclonedx-json"+UINT32_MAX = 2**32 - 1+LEFT_OUT = 3+++class Refused(Exception):+ pass+++def unique_keys(pairs):+ seen = {}+ for key, value in pairs:+ if key in seen:+ raise Refused("a key is given twice in one object")+ seen[key] = value+ return seen+++def not_a_number(name):+ raise Refused("%s is not a JSON number" % name)+++def parse_json(data, what):+ try:+ text = data.decode("utf-8")+ except UnicodeDecodeError:+ raise Refused("%s is not UTF-8" % what)+ decoder = json.JSONDecoder(object_pairs_hook=unique_keys,+ parse_constant=not_a_number)+ try:+ return decoder.decode(text)+ except (ValueError, RecursionError):+ raise Refused("%s is not a JSON value" % what)+++def printable(text):+ return "".join(c if c.isprintable() else "?" for c in text)+++def text_of(obj, key, where, required=False):+ """A string member; absent or null is empty unless it is required."""+ value = obj.get(key)+ if value is None:+ value = ""+ if type(value) is not str:+ raise Refused("%s of %s is not a string" % (key, where))+ if required and not value:+ raise Refused("%s has no %s" % (where, key))+ return value+++def read_cyclonedx(data):+ """The components of a CycloneDX JSON SBOM, nested ones included."""+ bom = parse_json(data, "sbom.cdx.json")+ if type(bom) is not dict or bom.get("bomFormat") != "CycloneDX":+ raise Refused('bomFormat of sbom.cdx.json is not "CycloneDX"')+ components = []+ pending = [bom.get("components", [])]+ while pending:+ level = pending.pop()+ if type(level) is not list:+ raise Refused("components of sbom.cdx.json is not an array")+ for component in level:+ if type(component) is not dict:+ raise Refused("a component of sbom.cdx.json is not an object")+ where = "a component of sbom.cdx.json"+ components.append({+ "type": text_of(component, "type", where),+ "name": text_of(component, "name", where, required=True),+ "version": text_of(component, "version", where),+ "purl": text_of(component, "purl", where),+ })+ pending.append(component.get("components", []))+ return components+++# Each SBOM format the job reads: the name of its file in the image's+# directory and the reader that turns the file into component rows. A+# second format is one more line and one more reader; the matcher has to+# read the file too.+FORMATS = {+ "cyclonedx-json": ("sbom.cdx.json", read_cyclonedx),+}+++def epoch(built_at):+ match = BUILT_AT.fullmatch(built_at)+ if not match:+ raise Refused('built_at of image.json is not "YYYY-MM-DDThh:mm:ssZ"')+ year, month, day, hour, minute, second = map(int, match.groups())+ if not (1 <= month <= 12 and 1 <= day <= 31 and hour <= 23+ and minute <= 59 and second <= 59):+ raise Refused("built_at of image.json is not a time")+ try:+ calendar.weekday(year, month, day)+ except ValueError:+ raise Refused("built_at of image.json is not a time")+ seconds = calendar.timegm((year, month, day, hour, minute, second))+ if not 0 <= seconds <= UINT32_MAX:+ raise Refused("built_at of image.json is out of range")+ return seconds+++def read_image_json(path, image_id, image_version, image_root):+ """The format, SBOM hash and build time image.json names."""+ with open(path, "rb") as f:+ meta = parse_json(f.read(), "image.json")+ if type(meta) is not dict:+ raise Refused("image.json is not an object")+ for key, expected in (("image_id", image_id),+ ("image_version", image_version),+ ("image_root", image_root)):+ if key not in meta:+ raise Refused("image.json has no %s" % key)+ if meta[key] != expected:+ raise Refused("%s of image.json is not the one of its path" % key)+ sbom_format = meta.get("sbom_format", DEFAULT_FORMAT)+ if type(sbom_format) is not str or not sbom_format:+ raise Refused("sbom_format of image.json is not a string")+ sbom_sha256 = meta.get("sbom_sha256")+ if type(sbom_sha256) is not str or not HEX64.fullmatch(sbom_sha256):+ raise Refused("sbom_sha256 of image.json is not 64 lowercase hex digits")+ built_at = meta.get("built_at")+ if type(built_at) is not str:+ raise Refused("built_at of image.json is not a string")+ return sbom_format, sbom_sha256, epoch(built_at)+++def image(store, work, n, directory):+ """The row of one image, its state, and the SBOM copy when it is ok."""+ image_id, image_version, root = directory.split("/")+ image_root = "" if root == "-" else root+ row = {+ "image_id": image_id,+ "image_version": image_version,+ "image_root": image_root,+ "sbom_format": DEFAULT_FORMAT,+ "sbom_sha256": "",+ "state": "parse_error",+ "built_at": 0,+ }+ where = os.path.join(store, image_id, image_version, root)+ try:+ sbom_format, sbom_sha256, built_at = read_image_json(+ os.path.join(where, "image.json"), image_id, image_version,+ image_root)+ except Refused as reason:+ return row, "-", str(reason), 0+ row["sbom_format"] = sbom_format+ row["built_at"] = built_at++ if sbom_format not in FORMATS:+ row["state"] = "unsupported_format"+ return row, "-", 'sbom_format "%s" has no reader' % sbom_format, 0+ name, reader = FORMATS[sbom_format]+ if not os.path.isfile(os.path.join(where, name)):+ row["state"] = "missing"+ return row, "-", "no %s" % name, 0+ with open(os.path.join(where, name), "rb") as f:+ data = f.read()+ if hashlib.sha256(data).hexdigest() != sbom_sha256:+ row["state"] = "hash_mismatch"+ return row, "-", "the SHA-256 of %s is not sbom_sha256" % name, 0+ try:+ components = reader(data)+ except Refused as reason:+ return row, "-", str(reason), 0++ # The matcher reads the bytes that were hashed, not the store again.+ copy = os.path.join(work, "%d.%s" % (n, name))+ with open(copy, "wb") as f:+ f.write(data)+ row["state"] = "ok"+ row["sbom_sha256"] = sbom_sha256+ return row, copy, "", len(components)+++def image_directories(store):+ """The image directories under the store; other image.json are named."""+ found = []+ left_out = False+ for top, dirs, files in os.walk(store):+ dirs.sort()+ if "image.json" not in files:+ continue+ path = os.path.relpath(os.path.join(top, "image.json"), store)+ parts = path.split(os.sep)+ if (len(parts) == 4 and SEGMENT.fullmatch(parts[0])+ and SEGMENT.fullmatch(parts[1])+ and (parts[2] == "-" or HEX64.fullmatch(parts[2]))):+ found.append("/".join(parts[:3]))+ continue+ print("%s: %s is not <image_id>/<image_version>/<image_root or ->"+ "/image.json, left out" % (PROG, printable(path)),+ file=sys.stderr)+ left_out = True+ return sorted(found), left_out+++def images_main(store, work):+ if not os.path.isdir(store):+ print("%s: no store directory %s" % (PROG, printable(store)),+ file=sys.stderr)+ return 1+ directories, left_out = image_directories(store)+ images = []+ with open(os.path.join(work, "images.tsv"), "w", encoding="utf-8") as tsv:+ for n, directory in enumerate(directories, 1):+ try:+ row, copy, reason, components = image(store, work, n,+ directory)+ except OSError as error:+ print("%s: %s: cannot read %s, left out" % (+ PROG, directory, printable(error.filename or "a file")),+ file=sys.stderr)+ left_out = True+ continue+ images.append({"n": n, "directory": directory, "row": row,+ "reason": reason, "components": components})+ tsv.write("%d\t%s\t%s\t%s\n" % (n, row["state"], copy, directory))+ with open(os.path.join(work, "images.json"), "w", encoding="ascii") as f:+ json.dump(images, f)+ return LEFT_OUT if left_out else 0+++def kernel_package(name):+ """A package of the kernel: the node may run another one."""+ return name.startswith("linux-image-") or name in ("kernel", "kernel-core")+++def findings(data):+ """The findings of Trivy's JSON report, and how many were of the kernel."""+ report = parse_json(data, "the report")+ if type(report) is not dict:+ raise Refused("the report is not an object")+ results = report.get("Results")+ if results is None:+ results = []+ if type(results) is not list:+ raise Refused("Results of the report is not an array")+ rows = set()+ kernel = 0+ for result in results:+ if type(result) is not dict:+ raise Refused("a result of the report is not an object")+ vulnerabilities = result.get("Vulnerabilities")+ if vulnerabilities is None:+ continue+ if type(vulnerabilities) is not list:+ raise Refused("Vulnerabilities of a result is not an array")+ for v in vulnerabilities:+ if type(v) is not dict:+ raise Refused("a vulnerability of the report is not an object")+ where = "a vulnerability of the report"+ vuln_id = text_of(v, "VulnerabilityID", where, required=True)+ package = text_of(v, "PkgName", where, required=True)+ installed = text_of(v, "InstalledVersion", where)+ fixed = text_of(v, "FixedVersion", where)+ severity = text_of(v, "Severity", where) or "UNKNOWN"+ if kernel_package(package):+ kernel += 1+ continue+ rows.add((vuln_id, package, installed, fixed, severity))+ return sorted(rows), kernel+++def db_version(work):+ """When the matcher's advisory database was built, as it says."""+ path = os.path.join(work, "version.json")+ if not os.path.exists(path):+ return ""+ with open(path, "rb") as f:+ version = parse_json(f.read(), "the matcher's version")+ if type(version) is not dict:+ raise Refused("the matcher's version is not an object")+ database = version.get("VulnerabilityDB")+ if type(database) is not dict or type(database.get("UpdatedAt")) is not str:+ return ""+ return database["UpdatedAt"]+++def write_rows(path, table):+ with open(path, "w", encoding="ascii") as out:+ for row in table:+ out.write(json.dumps(row, separators=(",", ":")) + "\n")+++def rows_main(work, scanned_at):+ try:+ scanned_at = int(scanned_at)+ except ValueError:+ scanned_at = -1+ if not 0 <= scanned_at <= UINT32_MAX:+ print("%s: scanned_at is not a time" % PROG, file=sys.stderr)+ return 1+ with open(os.path.join(work, "images.json"), encoding="ascii") as f:+ images = json.load(f)+ try:+ database = db_version(work)+ except Refused as reason:+ print("%s: %s, nothing loaded" % (PROG, reason), file=sys.stderr)+ return 1++ image_rows = []+ vuln_rows = []+ summary = []+ left_out = False+ # sbom_vulns is keyed by the SBOM, not the image: images built from+ # the same packages share one SBOM, whose findings a node reads once.+ loaded_by = {}+ for image in images:+ row = dict(image["row"], db_version="", scanned_at=scanned_at)+ directory = image["directory"]+ if row["state"] != "ok":+ image_rows.append(row)+ summary.append("%s: %s, %s" % (directory, row["state"],+ image["reason"]))+ continue+ report = os.path.join(work, "trivy-%d.json" % image["n"])+ if not os.path.exists(report):+ continue+ try:+ with open(report, "rb") as f:+ found, kernel = findings(f.read())+ except Refused as reason:+ print("%s: %s: the matcher's report is refused, not loaded: %s"+ % (PROG, directory, reason), file=sys.stderr)+ left_out = True+ continue+ row["db_version"] = database+ image_rows.append(row)+ line = "%s: ok, components: %d, findings: %d" % (+ directory, image["components"], len(found))+ if kernel:+ line += ", of kernel packages left out: %d" % kernel+ if row["sbom_sha256"] in loaded_by:+ summary.append("%s, the SBOM of %s" % (+ line, loaded_by[row["sbom_sha256"]]))+ continue+ loaded_by[row["sbom_sha256"]] = directory+ summary.append(line)+ for vuln_id, package, installed, fixed, severity in found:+ vuln_rows.append({+ "sbom_sha256": row["sbom_sha256"],+ "vuln_id": vuln_id,+ "package": package,+ "installed": installed,+ "fixed": fixed,+ "severity": severity,+ "scanned_at": scanned_at,+ })++ write_rows(os.path.join(work, "sbom_images.jsonl"), image_rows)+ write_rows(os.path.join(work, "sbom_vulns.jsonl"), vuln_rows)+ summary.append("loaded images: %d, findings: %d" % (len(image_rows),+ len(vuln_rows)))+ with open(os.path.join(work, "summary"), "w", encoding="utf-8") as f:+ for line in summary:+ f.write("%s: %s\n" % (PROG, line))+ return LEFT_OUT if left_out else 0+++def main():+ args = sys.argv[1:]+ if args == ["files"]:+ print("image.json")+ for name, _ in FORMATS.values():+ print(name)+ return 0+ if len(args) == 3 and args[0] == "images":+ return images_main(args[1], args[2])+ if len(args) == 3 and args[0] == "rows":+ return rows_main(args[1], args[2])+ print("usage: sbom-rows.py files | images <store> <work> | "+ "rows <work> <scanned_at>", file=sys.stderr)+ return 2+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/backend/jobs/sbom-scan b/tools/backend/jobs/sbom-scannew file mode 100755index 00000000..75036575--- /dev/null+++ b/tools/backend/jobs/sbom-scan@@ -0,0 +1,170 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# jobs/sbom-scan -- scan the SBOM of every image in the SBOM store and+# load the outcome into shirudo.sbom_images and shirudo.sbom_vulns.+#+# jobs/sbom-scan [--store <url>] [--trivy <path>] [--cache-dir <dir>]+#+# The store is file://<directory> or s3://<bucket>[/<prefix>], holding+# <image_id>/<image_version>/<image_root or ->/image.json and the SBOM+# beside it. Every run scans every image again, with Trivy as the matcher+# and an advisory database it does not update: update it before the run.+#+# SBOM_STORE the store, in place of --store.+# TRIVY the trivy binary. Default: trivy.+# TRIVY_CACHE_DIR the cache with Trivy's database, in place of+# --cache-dir. Default: Trivy's.+# S3_CLIENT the AWS command line and its options, split at+# spaces, for an s3:// store. Default: aws.+# 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 image was loaded; 1 when an object or an+# image was left out, each named on standard error with the rest loaded,+# or when nothing could be loaded; 2 for wrong usage.++set -eu++here=$(cd "$(dirname "$0")" && pwd)+store=${SBOM_STORE:-}+trivy=${TRIVY:-trivy}+cache=${TRIVY_CACHE_DIR:-}+incomplete=0+work=++die()+{+ printf 'sbom-scan: %s\n' "$1" >&2+ exit 1+}++usage()+{+ printf '%s\n' \+ 'usage: sbom-scan [--store <url>] [--trivy <path>] [--cache-dir <dir>]' >&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} "$@"+}++s3()+{+ # shellcheck disable=SC2086 # a command with its options, to be split+ ${S3_CLIENT:-aws} "$@"+}++insert()+{+ [ -s "$work/$1.jsonl" ] || return 0+ client --query "INSERT INTO shirudo.$1 FORMAT JSONEachRow" \+ <"$work/$1.jsonl" || die "cannot insert into shirudo.$1"+}++# step <step> <arguments>...: run a step of sbom-rows.py, where status 3+# says that something was left out and the rest is done.+step()+{+ status=0+ python3 "$here/sbom-rows.py" "$@" || status=$?+ case "$status" in+ 0) ;;+ 3) incomplete=1 ;;+ *) exit 1 ;;+ esac+}++# matcher <command> <arguments>...: run Trivy with the options every run+# gives it.+matcher()+{+ command=$1+ shift+ if [ -n "$cache" ]; then+ "$trivy" "$command" --format json --cache-dir "$cache" "$@" </dev/null+ else+ "$trivy" "$command" --format json "$@" </dev/null+ fi+}++while [ $# -gt 0 ]; do+ case "$1" in+ --store|--trivy|--cache-dir)+ [ $# -ge 2 ] || usage+ case "$1" in+ --store) store=$2 ;;+ --trivy) trivy=$2 ;;+ --cache-dir) cache=$2 ;;+ esac+ shift 2 ;;+ *)+ usage ;;+ esac+done+[ -n "$store" ] || usage++trap cleanup EXIT+trap 'exit 1' HUP INT TERM+work=$(mktemp -d)++case "$store" in+file://?*)+ directory=${store#file://} ;;+s3://?*)+ # Only the objects the job reads, every one of them: each run+ # scans every image again.+ set --+ for name in $(python3 "$here/sbom-rows.py" files); do+ set -- "$@" --include "*/$name"+ done+ directory=$work/store+ mkdir "$directory"+ s3 s3 cp --recursive --only-show-errors "$store" "$directory" \+ --exclude '*' "$@" </dev/null ||+ die "cannot copy $store, nothing loaded" ;;+*)+ die "the store $store is neither file://<directory> nor s3://<bucket>" ;;+esac++step images "$directory" "$work"++if cut -f 2 "$work/images.tsv" | grep -qx ok; then+ matcher version >"$work/version.json" ||+ die 'trivy version failed, nothing loaded'+fi+while IFS=' ' read -r n state copy label; do+ [ "$state" = ok ] || continue+ matcher sbom --skip-db-update --quiet "$copy" \+ >"$work/trivy-$n.json" 2>"$work/trivy-$n.err" && continue+ printf 'sbom-scan: %s: trivy sbom failed, not loaded:\n' "$label" >&2+ sed 's/^/ /' "$work/trivy-$n.err" >&2+ rm -f "$work/trivy-$n.json"+ incomplete=1+done <"$work/images.tsv"++# Every scan gets a time of its own, after every scan before it, so that+# the findings of two runs never share the scanned_at sbom_vulns is+# joined on.+scanned_at=$(client --query 'SELECT toUnixTimestamp(greatest(now(),+ (SELECT max(scanned_at) FROM shirudo.sbom_images) + 1))' </dev/null) ||+ die 'cannot read shirudo.sbom_images, nothing loaded'+step rows "$work" "$scanned_at"++# The findings go first: a row of sbom_images is what makes a node read+# them, and one without its findings would read as clean.+insert sbom_vulns+insert sbom_images+cat "$work/summary"+exit "$incomplete"diff --git a/tools/backend/jobs/tree-ingest b/tools/backend/jobs/tree-ingestnew file mode 100755index 00000000..79bf5342--- /dev/null+++ b/tools/backend/jobs/tree-ingest@@ -0,0 +1,161 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# jobs/tree-ingest -- load every segment of an upatch tree into+# shirudo.tree_pubs, shirudo.tree_ops and shirudo.upatch_fixes.+#+# jobs/tree-ingest [--shirudo <path>] [--reference <ref>] [--cert <file>]+# [oci://<repository>]+# jobs/tree-ingest --input <file>|-+#+# The first form runs `shirudo bpm tree show --walk`, which fetches the+# publication and every sealed segment before it back to base.seq 0 and+# verifies each against the certificate. The second reads a stored+# output of that command, from standard input when the file is "-". The+# job verifies nothing itself and trusts what it reads for that reason:+# give it only what `bpm tree show` printed.+#+# SHIRUDO the shirudo binary. Default: shirudo.+# TREE_REPOSITORY the tree's repository, oci://<repository>.+# TREE_REFERENCE the tag or digest to read. Default: shirudo's.+# TREE_CERT the certificate the publication is signed under.+# 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 segment is loaded or was loaded before, 1+# when the input is refused or a command fails, 2 for wrong usage.++set -eu++here=$(cd "$(dirname "$0")" && pwd)+shirudo=${SHIRUDO:-shirudo}+repository=${TREE_REPOSITORY:-}+reference=${TREE_REFERENCE:-}+cert=${TREE_CERT:-}+input=+work=++die()+{+ printf 'tree-ingest: %s\n' "$1" >&2+ exit 1+}++usage()+{+ printf '%s\n' \+ 'usage: tree-ingest [--shirudo <path>] [--reference <ref>] [--cert <file>] [oci://<repository>]' \+ ' tree-ingest --input <file>|-' >&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} "$@"+}++insert()+{+ [ -s "$work/new.$1.jsonl" ] || return 0+ client --query "INSERT INTO shirudo.$2 FORMAT JSONEachRow" \+ <"$work/new.$1.jsonl" || die "cannot insert into shirudo.$2"+}++while [ $# -gt 0 ]; do+ case "$1" in+ --shirudo|--reference|--cert|--input)+ [ $# -ge 2 ] || usage+ case "$1" in+ --shirudo) shirudo=$2 ;;+ --reference) reference=$2 ;;+ --cert) cert=$2 ;;+ --input) input=$2 ;;+ esac+ shift 2 ;;+ oci://*)+ repository=$1+ shift ;;+ *)+ usage ;;+ esac+done++trap cleanup EXIT+trap 'exit 1' HUP INT TERM+work=$(mktemp -d)++if [ "$input" = - ]; then+ cat >"$work/show"+elif [ -n "$input" ]; then+ [ -f "$input" ] || die "no input file $input"+ cat "$input" >"$work/show"+else+ [ -n "$repository" ] || usage+ [ -n "$cert" ] || die 'needs --cert or TREE_CERT'+ set -- bpm tree show "$repository"+ [ -z "$reference" ] || set -- "$@" --reference "$reference"+ "$shirudo" "$@" --cert "$cert" --walk >"$work/show" ||+ die 'bpm tree show failed, nothing loaded'+fi++tree_id=$(python3 "$here/tree-rows.py" "$work" <"$work/show") || exit 1++client --param_tree_id="$tree_id" \+ --query 'SELECT generation, manifest_digest FROM shirudo.tree_pubs FINAL+ WHERE tree_id = {tree_id:String}' >"$work/loaded" ||+ die 'cannot read shirudo.tree_pubs'++# Every segment is held against what is loaded before anything is+# inserted, so a conflict in any of them loads none.+: >"$work/new.pub.jsonl"+: >"$work/new.ops.jsonl"+: >"$work/new.fixes.jsonl"+: >"$work/new"+already=0+newest=+awk -F ' ' -v OFS=' ' -v loaded="$work/loaded" '+ BEGIN { while ((getline line <loaded) > 0) {+ split(line, f, "\t"); digest[f[1]] = f[2] } }+ { print $0, digest[$2] }' "$work/segments.tsv" \+ >"$work/segments"+while IFS=' ' read -r k generation digest ops fixes loaded; do+ if [ "$loaded" = "$digest" ]; then+ already=$((already + 1))+ newest=$generation+ continue+ fi+ [ -z "$loaded" ] ||+ die "$tree_id generation $generation is loaded with manifest $loaded, this one is $digest; nothing loaded"+ cat "$work/$k.pub.jsonl" >>"$work/new.pub.jsonl"+ cat "$work/$k.ops.jsonl" >>"$work/new.ops.jsonl"+ cat "$work/$k.fixes.jsonl" >>"$work/new.fixes.jsonl"+ printf '%s\t%s\t%s\n' "$generation" "$ops" "$fixes" >>"$work/new"+done <"$work/segments"++if [ "$already" -eq 1 ]; then+ printf 'tree-ingest: %s generation %s is loaded already\n' \+ "$tree_id" "$newest"+elif [ "$already" -gt 1 ]; then+ printf 'tree-ingest: %s: %d segments up to generation %s are loaded already\n' \+ "$tree_id" "$already" "$newest"+fi++# The publications' own rows go last: they are what says a segment is+# loaded, so a run that stops earlier is done again by the next one,+# and no reader finds a publication without its operations.+insert ops tree_ops+insert fixes upatch_fixes+insert pub tree_pubs+while IFS=' ' read -r generation ops fixes; do+ printf 'tree-ingest: loaded %s generation %s (operations: %d, fixes: %d)\n' \+ "$tree_id" "$generation" "$ops" "$fixes"+done <"$work/new"diff --git a/tools/backend/jobs/tree-rows.py b/tools/backend/jobs/tree-rows.pynew file mode 100755index 00000000..52f1722f--- /dev/null+++ b/tools/backend/jobs/tree-rows.py@@ -0,0 +1,277 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# jobs/tree-rows.py -- turn the output of `shirudo bpm tree show --walk`,+# read from standard input, into the rows jobs/tree-ingest inserts. It is+# the part of that job shell does not reach: parsing JSON.+#+# tree-rows.py <directory>+#+# For the k-th segment, oldest first, writes <k>.pub.jsonl, <k>.ops.jsonl+# and <k>.fixes.jsonl into the directory, in ClickHouse's JSONEachRow+# format, and segments.tsv with k, generation, manifest digest and the+# number of operations and fixes of each, and prints the tree_id. Input+# that is not in the expected shape is refused with exit status 1 before+# anything is written. Nothing is verified here: `bpm tree show` has done+# that.++import json+import os+import re+import sys++PROG = "tree-ingest"+DIGEST = re.compile(r"sha256:([0-9a-f]{64})")+ROOT = re.compile(r"[0-9a-f]{64}")+TREE_ID = re.compile(r"[A-Za-z0-9._-]{1,255}")+ZERO_ROOT = "0" * 64+UINT64_MAX = 2**64 - 1+++class Refused(Exception):+ pass+++def unique_keys(pairs):+ seen = {}+ for key, value in pairs:+ if key in seen:+ raise Refused("a key is given twice in one object")+ seen[key] = value+ return seen+++def not_a_number(name):+ raise Refused("%s is not a JSON number" % name)+++def member(obj, key, kind, where):+ if key not in obj:+ raise Refused("%s has no %s" % (where, key))+ return typed(obj[key], kind, "%s of %s" % (key, where))+++def typed(value, kind, what):+ if kind is int:+ if type(value) is not int or not 0 <= value <= UINT64_MAX:+ raise Refused("%s is not an unsigned 64-bit integer" % what)+ elif type(value) is not kind:+ names = {str: "a string", dict: "an object", list: "an array"}+ raise Refused("%s is not %s" % (what, names[kind]))+ return value+++def digest(obj, key, where):+ match = DIGEST.fullmatch(member(obj, key, str, where))+ if not match:+ raise Refused('%s of %s is not "sha256:" and 64 lowercase hex digits'+ % (key, where))+ return match.group(1)+++def compact(value):+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))+++def fixes_of(operation, seq):+ """The advisory IDs of an operation; a malformed list costs only itself."""+ if "fixes" not in operation:+ return []+ fixes = operation["fixes"]+ if type(fixes) is not list or any(type(i) is not str for i in fixes):+ print("%s: operation %d: fixes is not an array of strings, "+ "loaded without fixes" % (PROG, seq), file=sys.stderr)+ return []+ return sorted(set(fixes))+++def segment_base(doc):+ """base.seq, the predecessor's manifest digest and history_root there."""+ base = member(doc, "base", dict, "the document")+ base_seq = member(base, "seq", int, "base")+ if base_seq == 0:+ for key in ("segment_manifest_digest", "history_root"):+ if key in base:+ raise Refused("base has %s but its seq is 0" % key)+ return 0, "", ZERO_ROOT+ previous = digest(base, "segment_manifest_digest", "base")+ root = member(base, "history_root", str, "base")+ if not ROOT.fullmatch(root):+ raise Refused("history_root of base is not 64 lowercase hex digits")+ return base_seq, previous, root+++def rows(show):+ typed(show, dict, "the input")+ manifest_digest = digest(show, "manifest_digest", "the input")+ doc = member(show, "document", dict, "the input")++ if member(doc, "schema", int, "the document") != 1:+ raise Refused("schema of the document is not 1")+ tree_id = member(doc, "tree_id", str, "the document")+ if not TREE_ID.fullmatch(tree_id):+ raise Refused("tree_id of the document is not 1 to 255 characters "+ "of [A-Za-z0-9._-]")+ generation = member(doc, "generation", int, "the document")+ if generation < 1:+ raise Refused("generation of the document is 0")+ parent = ""+ if "parent_manifest_digest" in doc:+ parent = digest(doc, "parent_manifest_digest", "the document")+ base_seq, previous, history_root = segment_base(doc)+ head = member(doc, "head", dict, "the document")+ head_seq = member(head, "seq", int, "head")+ if head_seq < base_seq:+ raise Refused("seq of head is below base.seq")++ pub = {+ "tree_id": tree_id,+ "generation": generation,+ "manifest_digest": manifest_digest,+ "parent_manifest_digest": parent,+ "head_seq": head_seq,+ "segment_base_seq": base_seq,+ "segment_manifest_digest": previous,+ "history_root": history_root,+ }+ ops = []+ fixes = []+ seen = set()+ for n, operation in enumerate(member(doc, "operations", list,+ "the document"), 1):+ where = "operation %d of the document" % n+ typed(operation, dict, where)+ seq = member(operation, "seq", int, where)+ if seq in seen:+ raise Refused("seq of %s is used twice" % where)+ if not base_seq < seq <= head_seq:+ raise Refused("seq of %s is not above base.seq and at most "+ "the seq of head" % where)+ seen.add(seq)+ where = "the operation with seq %d" % seq+ op = member(operation, "op", str, where)+ if op not in ("add", "delete"):+ raise Refused("op of %s is neither add nor delete" % where)+ op_id = member(operation, "id", str, where)+ selector = member(operation, "selector", dict, where)+ artifact = member(operation, "artifact", dict, where)+ ops.append({+ "tree_id": tree_id,+ "seq": seq,+ "op": op,+ "id": op_id,+ "selector": compact(selector),+ "repository": member(artifact, "repository", str,+ "artifact of " + where),+ "manifest_digest": digest(artifact, "manifest_digest",+ "artifact of " + where),+ "layer_digest": digest(artifact, "layer_digest",+ "artifact of " + where),+ "payload_sha256": digest(artifact, "payload_sha256",+ "artifact of " + where),+ "operation_digest": digest(operation, "operation_digest", where),+ })+ for advisory in fixes_of(operation, seq):+ fixes.append({+ "tree_id": tree_id,+ "seq": seq,+ "id": op_id,+ "advisory": advisory,+ "source": "fixes",+ })+ if base_seq > 0 and not ops:+ raise Refused("the document has no operations but its base.seq "+ "is above 0")+ return pub, ops, fixes+++def follows(pub, prev, k):+ """A walk's segment k (from 1) must continue segment k - 1 exactly."""+ where = "segment %d of the walk" % k+ if prev is None:+ if pub["segment_base_seq"] != 0:+ raise Refused("%s has base.seq %d: the walk does not reach "+ "base.seq 0" % (where, pub["segment_base_seq"]))+ return+ if pub["tree_id"] != prev["tree_id"]:+ raise Refused("tree_id of %s is not that of segment %d"+ % (where, k - 1))+ if pub["segment_base_seq"] != prev["head_seq"]:+ raise Refused("base.seq of %s is not the seq of head of segment %d"+ % (where, k - 1))+ if pub["segment_manifest_digest"] != prev["manifest_digest"]:+ raise Refused("segment_manifest_digest of %s is not the manifest "+ "digest of segment %d" % (where, k - 1))+ if pub["generation"] <= prev["generation"]:+ raise Refused("generation of %s is not above that of segment %d"+ % (where, k - 1))+++def walk(shows):+ segments = []+ prev = None+ for k, show in enumerate(shows, 1):+ try:+ segment = rows(show)+ except Refused as reason:+ if len(shows) == 1:+ raise+ raise Refused("segment %d of the walk: %s" % (k, reason))+ follows(segment[0], prev, k)+ prev = segment[0]+ segments.append(segment)+ return segments+++def parse(data):+ try:+ text = data.decode("utf-8")+ except UnicodeDecodeError:+ raise Refused("it is not UTF-8")+ decoder = json.JSONDecoder(object_pairs_hook=unique_keys,+ parse_constant=not_a_number)+ shows = []+ end = 0+ while True:+ start = len(text) - len(text[end:].lstrip(" \t\r\n"))+ if start == len(text) and shows:+ return shows+ try:+ show, end = decoder.raw_decode(text, start)+ except (ValueError, RecursionError):+ raise Refused("it is not a JSON value")+ shows.append(show)+++def write_rows(path, table):+ with open(path, "w", encoding="ascii") as out:+ for row in table:+ out.write(json.dumps(row, separators=(",", ":")) + "\n")+++def main():+ if len(sys.argv) != 2:+ print("usage: tree-rows.py <directory>", file=sys.stderr)+ return 2+ try:+ segments = walk(parse(sys.stdin.buffer.read()))+ except Refused as reason:+ print("%s: input refused: %s" % (PROG, reason), file=sys.stderr)+ return 1+ with open(os.path.join(sys.argv[1], "segments.tsv"), "w",+ encoding="ascii") as out:+ for k, (pub, ops, fixes) in enumerate(segments, 1):+ path = os.path.join(sys.argv[1], "%d." % k)+ write_rows(path + "pub.jsonl", [pub])+ write_rows(path + "ops.jsonl", ops)+ write_rows(path + "fixes.jsonl", fixes)+ out.write("%d\t%d\t%s\t%d\t%d\n" % (k, pub["generation"],+ pub["manifest_digest"],+ len(ops), len(fixes)))+ print(segments[0][0]["tree_id"])+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/backend/otelcol.yaml b/tools/backend/otelcol.yamlnew file mode 100644index 00000000..2a6cd538--- /dev/null+++ b/tools/backend/otelcol.yaml@@ -0,0 +1,29 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# Collector for shirudo's keepalive: OTLP over HTTPS in, every log+# record written to ClickHouse's otel.otel_logs, which sql/ creates. Run+# it with otelcol-contrib, which has the ClickHouse exporter. The+# environment may name another certificate, key or ClickHouse server.+receivers:+ otlp:+ protocols:+ http:+ endpoint: 0.0.0.0:4318+ tls:+ cert_file: ${env:OTLP_TLS_CERT:-/certs/server.pem}+ key_file: ${env:OTLP_TLS_KEY:-/certs/server.key}+ min_version: "1.3"+exporters:+ clickhouse:+ endpoint: ${env:CLICKHOUSE_ENDPOINT:-tcp://clickhouse:9000}+ username: ${env:CLICKHOUSE_USER:-default}+ password: ${env:CLICKHOUSE_PASSWORD:-}+ database: otel+ logs_table_name: otel_logs+ create_schema: false+service:+ pipelines:+ logs:+ receivers: [otlp]+ exporters: [clickhouse]diff --git a/tools/backend/sql/00-databases.sql b/tools/backend/sql/00-databases.sqlnew file mode 100644index 00000000..debda914--- /dev/null+++ b/tools/backend/sql/00-databases.sql@@ -0,0 +1,9 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- The two databases: otel takes what the collector writes, shirudo holds+-- everything derived from it. Every file under sql/ can be loaded again+-- without changing what is there.++CREATE DATABASE IF NOT EXISTS otel;+CREATE DATABASE IF NOT EXISTS shirudo;diff --git a/tools/backend/sql/10-ingest.sql b/tools/backend/sql/10-ingest.sqlnew file mode 100644index 00000000..35db4ae6--- /dev/null+++ b/tools/backend/sql/10-ingest.sql@@ -0,0 +1,186 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- Ingest: a keepalive enters at otel.otel_logs, is checked once by+-- tpm_quote_check on its way into shirudo.checked and from there lands+-- either in shirudo.keepalive or in shirudo.rejected. Neither otel_logs+-- nor checked stores a row; both only feed the views behind them.++-- The columns the collector's ClickHouse exporter inserts.+CREATE TABLE IF NOT EXISTS otel.otel_logs+(+ Timestamp DateTime64(9),+ TraceId String,+ SpanId String,+ TraceFlags UInt8,+ SeverityText LowCardinality(String),+ SeverityNumber UInt8,+ ServiceName LowCardinality(String),+ Body String,+ ResourceSchemaUrl LowCardinality(String),+ ResourceAttributes Map(LowCardinality(String), String),+ ScopeSchemaUrl LowCardinality(String),+ ScopeName String,+ ScopeVersion LowCardinality(String),+ ScopeAttributes Map(LowCardinality(String), String),+ LogAttributes Map(LowCardinality(String), String),+ EventName String+)+ENGINE = Null;++-- One row per keepalive, accepted or not. A writer gives the columns up+-- to clock; the others are read from the body, so that a test which+-- inserts here gets the same rows as a record that came through+-- checked_mv. reject is empty for an accepted record and otherwise the+-- reason it lands in shirudo.rejected under.+CREATE TABLE IF NOT EXISTS shirudo.checked+(+ received DateTime64(3) DEFAULT now64(3),+ time DateTime64(9),+ host_name String,+ quote String,+ body String,+ ok UInt8,+ reason LowCardinality(String),+ ak_name String,+ ak_public String,+ reset_count UInt64,+ clock UInt64,++ schema String DEFAULT JSONExtractString(body, 'schema'),+ boot_id String DEFAULT JSONExtractString(body, 'boot_id'),+ version_id String DEFAULT JSONExtractString(body, 'version_id'),+ config_root Nullable(String) DEFAULT JSONExtract(body, 'config_root', 'Nullable(String)'),+ kernel_release String DEFAULT JSONExtractString(body, 'kernel_release'),+ image_id Nullable(String) DEFAULT JSONExtract(body, 'image_id', 'Nullable(String)'),+ image_version Nullable(String) DEFAULT JSONExtract(body, 'image_version', 'Nullable(String)'),+ image_root Nullable(String) DEFAULT JSONExtract(body, 'image_root', 'Nullable(String)'),+ verdict LowCardinality(String) DEFAULT JSONExtractString(body, 'verdict'),+ cond UInt64 DEFAULT JSONExtractUInt(body, 'cond'),+ flags UInt64 DEFAULT JSONExtractUInt(body, 'flags'),+ tamper Array(UInt64) DEFAULT JSONExtract(body, 'tamper', 'Array(UInt64)'),+ tree_id Nullable(String) DEFAULT JSONExtract(body, 'tree_id', 'Nullable(String)'),+ generation Nullable(UInt64) DEFAULT JSONExtract(body, 'generation', 'Nullable(UInt64)'),+ base_seq Nullable(UInt64) DEFAULT JSONExtract(body, 'base_seq', 'Nullable(UInt64)'),+ last_seq Nullable(UInt64) DEFAULT JSONExtract(body, 'last_seq', 'Nullable(UInt64)'),+ base_root Nullable(String) DEFAULT JSONExtract(body, 'base_root', 'Nullable(String)'),+ projection_root Nullable(String) DEFAULT JSONExtract(body, 'projection_root', 'Nullable(String)'),+ mask Nullable(String) DEFAULT JSONExtract(body, 'mask', 'Nullable(String)'),+ set_sha256 String DEFAULT JSONExtractString(body, 'set_sha256'),+ count UInt64 DEFAULT JSONExtractUInt(body, 'count'),+ not_ok UInt64 DEFAULT JSONExtractUInt(body, 'not_ok'),++ -- keepalive_latest orders by this, which leaves 24 bits for+ -- reset_count and 40 for clock: a record beyond either is refused.+ order_key UInt64 DEFAULT bitOr(bitShiftLeft(reset_count, 40), clock),+ reject LowCardinality(String) DEFAULT multiIf(+ ok != 1, if(reason = '', 'malformed', reason),+ schema != 'shirudo.keepalive/1' AND NOT startsWith(schema, 'shirudo.keepalive/1.'), 'schema',+ reset_count >= 16777216 OR clock >= 1099511627776, 'clock_range',+ '')+)+ENGINE = Null;++-- tpm_quote_check answers with one JSON line per record, which the+-- outer query takes apart. The subquery keeps it at one call per record.+CREATE MATERIALIZED VIEW IF NOT EXISTS shirudo.checked_mv TO shirudo.checked AS+SELECT+ time,+ host_name,+ quote,+ body,+ JSONExtractUInt(answer, 'ok') = 1 AS ok,+ JSONExtractString(answer, 'reason') AS reason,+ JSONExtractString(answer, 'ak_name') AS ak_name,+ JSONExtractString(answer, 'ak_public') AS ak_public,+ JSONExtractUInt(answer, 'reset_count') AS reset_count,+ JSONExtractUInt(answer, 'clock') AS clock+FROM+(+ SELECT+ Timestamp AS time,+ ResourceAttributes['host.name'] AS host_name,+ LogAttributes['shirudo.quote'] AS quote,+ Body AS body,+ extractGroups(quote, '^attest=([A-Za-z0-9+/=]+);sig=([A-Za-z0-9+/=]+);ak=([A-Za-z0-9+/=]+)$') AS field,+ tpm_quote_check(field[1], field[2], field[3], lower(hex(SHA256(body)))) AS answer+ FROM otel.otel_logs+ WHERE EventName = 'shirudo.keepalive'+);++-- Every accepted record, kept for audit: no check reads this table. A+-- record sent twice has the same key and collapses into one row. The TTL+-- here is the default of shirudo.settings; sql/apply-retention.sh sets+-- the one the settings name, since a TTL cannot read a table.+CREATE TABLE IF NOT EXISTS shirudo.keepalive+(+ received DateTime64(3),+ time DateTime64(9),+ host_name String,+ quote String CODEC(ZSTD(1)),+ body String CODEC(ZSTD(1)),+ ak_name String,+ reset_count UInt32,+ clock UInt64,+ schema LowCardinality(String),+ boot_id String,+ version_id String,+ config_root Nullable(String),+ kernel_release LowCardinality(String),+ image_id Nullable(String),+ image_version Nullable(String),+ image_root Nullable(String),+ verdict LowCardinality(String),+ cond UInt64,+ flags UInt64,+ tamper Array(UInt64),+ tree_id Nullable(String),+ generation Nullable(UInt64),+ base_seq Nullable(UInt64),+ last_seq Nullable(UInt64),+ base_root Nullable(String),+ projection_root Nullable(String),+ mask Nullable(String),+ set_sha256 String,+ count UInt64,+ not_ok UInt64+)+ENGINE = ReplacingMergeTree+ORDER BY (ak_name, reset_count, clock)+TTL toDateTime(received) + INTERVAL 3600 SECOND;++CREATE MATERIALIZED VIEW IF NOT EXISTS shirudo.keepalive_mv TO shirudo.keepalive AS+SELECT * EXCEPT (ok, reason, ak_public, order_key, reject)+FROM shirudo.checked+WHERE reject = '';++-- What was refused and why: bad_signature, body_mismatch and malformed+-- from the checker, schema for a body of an unknown major version and+-- clock_range for counters order_key cannot hold.+CREATE TABLE IF NOT EXISTS shirudo.rejected+(+ received DateTime64(3),+ reason LowCardinality(String),+ host_name String,+ ak_name String,+ reset_count UInt64,+ clock UInt64,+ quote String CODEC(ZSTD(1)),+ body String CODEC(ZSTD(1))+)+ENGINE = MergeTree+ORDER BY received+TTL toDateTime(received) + INTERVAL 7 DAY;++CREATE MATERIALIZED VIEW IF NOT EXISTS shirudo.rejected_mv TO shirudo.rejected AS+SELECT+ received,+ reject AS reason,+ host_name,+ ak_name,+ reset_count,+ clock,+ quote,+ body+FROM shirudo.checked+WHERE reject != '';diff --git a/tools/backend/sql/20-reference.sql b/tools/backend/sql/20-reference.sqlnew file mode 100644index 00000000..9624993d--- /dev/null+++ b/tools/backend/sql/20-reference.sql@@ -0,0 +1,132 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- Reference: what the checks compare a keepalive with. nodes fills+-- itself from the accepted records; the operator and the ingest job+-- write the others.++-- One row per attestation key. node_id is the host name the key first+-- claimed; to relabel a node, insert argMinState('<name>',+-- toDateTime64(0, 3)) for its ak_name, which is why a row that leaves+-- ak_public and first_seen out must not change them. trust only ever+-- rises: a keepalive never sets it, so a node stays untrusted until+-- something else says more.+CREATE TABLE IF NOT EXISTS shirudo.nodes+(+ ak_name String,+ ak_public SimpleAggregateFunction(max, String),+ node_id AggregateFunction(argMin, String, DateTime64(3)),+ first_seen SimpleAggregateFunction(min, Nullable(DateTime64(3))),+ trust SimpleAggregateFunction(max, Enum8('untrusted' = 0)) DEFAULT 'untrusted'+)+ENGINE = AggregatingMergeTree+ORDER BY ak_name;++CREATE MATERIALIZED VIEW IF NOT EXISTS shirudo.nodes_mv TO shirudo.nodes AS+SELECT+ ak_name,+ max(ak_public) AS ak_public,+ argMinState(host_name, received) AS node_id,+ min(received) AS first_seen+FROM shirudo.checked+WHERE reject = ''+GROUP BY ak_name;++-- The builds a node may run, by the version_id of its keepalive.+CREATE TABLE IF NOT EXISTS shirudo.expected_builds+(+ version_id String,+ note String,+ added DateTime DEFAULT now()+)+ENGINE = ReplacingMergeTree+ORDER BY version_id;++-- One row per publication of a tree. Digests are 64 lowercase hex digits+-- without "sha256:", as in the keepalive body. published_at is when the+-- ingest job first loaded the publication, which is all the backend+-- knows: the publication document carries no time. A publication is a+-- segment of its tree, holding the operations past segment_base_seq;+-- segment_manifest_digest names the sealed segment before it, empty for+-- the first, and history_root is the tree's history root at+-- segment_base_seq, 64 zeros for the first.+CREATE TABLE IF NOT EXISTS shirudo.tree_pubs+(+ tree_id String,+ generation UInt64,+ manifest_digest String,+ parent_manifest_digest String,+ head_seq UInt64,+ segment_base_seq UInt64 DEFAULT 0,+ segment_manifest_digest String DEFAULT '',+ history_root String DEFAULT repeat('0', 64),+ published_at DateTime64(3) DEFAULT now64(3)+)+ENGINE = ReplacingMergeTree+ORDER BY (tree_id, generation);++-- One row per operation of a tree. An operation never changes once+-- published, so loading a publication again replaces rows with equal ones.+-- selector is the operation's selector as JSON text, copied and never+-- evaluated: what an operation did on a node is read from the node's mask.+CREATE TABLE IF NOT EXISTS shirudo.tree_ops+(+ tree_id String,+ seq UInt64,+ op Enum8('add' = 1, 'delete' = 2),+ id String,+ selector String,+ repository String,+ manifest_digest String,+ layer_digest String,+ payload_sha256 String,+ operation_digest String+)+ENGINE = ReplacingMergeTree+ORDER BY (tree_id, seq);++-- Which advisory an operation's upatch shields against. source is fixes+-- for a row the ingest job took from the operation's fixes key and+-- manual for one an operator added.+CREATE TABLE IF NOT EXISTS shirudo.upatch_fixes+(+ tree_id String,+ seq UInt64,+ id String,+ advisory String,+ source Enum8('fixes' = 1, 'manual' = 2)+)+ENGINE = ReplacingMergeTree+ORDER BY (tree_id, seq, advisory, source);++-- The thresholds of the checks, the retention of shirudo.keepalive and+-- shirudo.boot_first and the age at which an SBOM's scan is stale, in one+-- row. Read it with FINAL; to change a value, insert the whole row again+-- with id 1. The two retention values take effect when+-- sql/apply-retention.sh runs, the others at the next refresh. A scan+-- older than sbom_stale_seconds marks the rows of its image's nodes in+-- node_vulns; keep it below the 7 days after which shirudo.sbom_vulns+-- drops the findings, so that an image reads stale before it reads clean.+-- stale_seconds is 10 minutes: a keepalive cannot run while a tree sync+-- holds the target's config operation lock, so a node that syncs sends+-- nothing for as long as the sync runs. The node status page of the+-- backend documentation says why.+CREATE TABLE IF NOT EXISTS shirudo.settings+(+ id UInt8 DEFAULT 1,+ stale_seconds UInt32,+ stuck_seconds UInt32,+ window UInt32,+ keepalive_retention_seconds UInt32 DEFAULT 3600,+ boot_first_retention_seconds UInt32 DEFAULT 2592000,+ sbom_stale_seconds UInt32 DEFAULT 172800,+ updated DateTime64(3) DEFAULT now64(3),+ CONSTRAINT one_row CHECK id = 1+)+ENGINE = ReplacingMergeTree(updated)+ORDER BY id;++INSERT INTO shirudo.settings (stale_seconds, stuck_seconds, window, keepalive_retention_seconds,+ boot_first_retention_seconds, sbom_stale_seconds)+SELECT 600, 3600, 512, 3600, 2592000, 172800+WHERE (SELECT count() FROM shirudo.settings) = 0;diff --git a/tools/backend/sql/30-latest.sql b/tools/backend/sql/30-latest.sqlnew file mode 100644index 00000000..475024fb--- /dev/null+++ b/tools/backend/sql/30-latest.sql@@ -0,0 +1,104 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- The tables that keep the checks from reading shirudo.keepalive: the+-- newest record of every node and the first record of every boot, both+-- kept up to date as records arrive.++-- The record with the highest order_key of each node, which is its+-- newest by the TPM's own counters. A record that arrives late or again+-- does not replace a newer one.+CREATE TABLE IF NOT EXISTS shirudo.keepalive_latest+(+ ak_name String,+ order_key UInt64,+ received DateTime64(3),+ time DateTime64(9),+ host_name String,+ body String CODEC(ZSTD(1)),+ reset_count UInt32,+ clock UInt64,+ schema LowCardinality(String),+ boot_id String,+ version_id String,+ config_root Nullable(String),+ kernel_release LowCardinality(String),+ image_id Nullable(String),+ image_version Nullable(String),+ image_root Nullable(String),+ verdict LowCardinality(String),+ cond UInt64,+ flags UInt64,+ tamper Array(UInt64),+ tree_id Nullable(String),+ generation Nullable(UInt64),+ base_seq Nullable(UInt64),+ last_seq Nullable(UInt64),+ base_root Nullable(String),+ projection_root Nullable(String),+ mask Nullable(String),+ set_sha256 String,+ count UInt64,+ not_ok UInt64+)+ENGINE = ReplacingMergeTree(order_key)+ORDER BY ak_name;++CREATE MATERIALIZED VIEW IF NOT EXISTS shirudo.keepalive_latest_mv TO shirudo.keepalive_latest AS+SELECT * EXCEPT (ok, reason, ak_public, quote, reject)+FROM shirudo.checked+WHERE reject = '';++-- What check 3 compares a record with: the total of the tamper counters+-- in the boot's first record, by order_key, that could read them. They+-- start at zero with every boot and must not rise within one. A record+-- whose tamper is null has no total and does not set the baseline; it+-- reads as an empty array here.+--+-- last_used is when a record of the boot was last received, or when+-- boot_first_keep_mv last found the boot to be its node's current one,+-- and a row leaves that long after it as the TTL says. The TTL here is+-- the default of shirudo.settings; sql/apply-retention.sh sets the one+-- the settings name.+CREATE TABLE IF NOT EXISTS shirudo.boot_first+(+ ak_name String,+ boot_id String,+ first_order_key SimpleAggregateFunction(min, UInt64),+ tamper_first AggregateFunction(argMin, UInt64, UInt64),+ last_used SimpleAggregateFunction(max, DateTime)+)+ENGINE = AggregatingMergeTree+ORDER BY (ak_name, boot_id)+TTL last_used + INTERVAL 2592000 SECOND;++CREATE MATERIALIZED VIEW IF NOT EXISTS shirudo.boot_first_mv TO shirudo.boot_first AS+SELECT+ ak_name,+ boot_id,+ min(order_key) AS first_order_key,+ argMinStateIf(arraySum(tamper), order_key, notEmpty(tamper)) AS tamper_first,+ max(toDateTime(received)) AS last_used+FROM shirudo.checked+WHERE reject = ''+GROUP BY ak_name, boot_id;++-- A TTL removes a row from the part it is in, whatever newer parts say+-- of the same boot, and the row that holds a boot's baseline is its+-- oldest: left alone, the baseline of a boot that runs longer than the+-- retention would move to a later record and hide a rise before it. So+-- once an hour the baseline of every node's current boot, the boot of+-- its newest record, is written again with the time of the refresh. That+-- boot's baseline never leaves, whether the node still sends or not; the+-- rows of the boots before it do.+CREATE MATERIALIZED VIEW IF NOT EXISTS shirudo.boot_first_keep_mv+REFRESH EVERY 1 HOUR APPEND TO shirudo.boot_first AS+SELECT+ b.ak_name AS ak_name,+ b.boot_id AS boot_id,+ min(b.first_order_key) AS first_order_key,+ argMinMergeState(b.tamper_first) AS tamper_first,+ now() AS last_used+FROM shirudo.boot_first AS b+INNER JOIN shirudo.keepalive_latest AS k FINAL ON k.ak_name = b.ak_name AND k.boot_id = b.boot_id+GROUP BY b.ak_name, b.boot_id;diff --git a/tools/backend/sql/40-status.sql b/tools/backend/sql/40-status.sqlnew file mode 100644index 00000000..fa597651--- /dev/null+++ b/tools/backend/sql/40-status.sql@@ -0,0 +1,589 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- Status: the checks over the newest record of every node, run once a+-- minute for all nodes and kept in shirudo.node_status, which is what a+-- UI reads, with the history of every node that the checks read below+-- the window a record covers. Nothing here reads shirudo.keepalive.++-- The outcome pair of the i-th operation of a mask's window, i from 0:+-- 1 applied, 2 selector did not match, 3 attach module not loaded and+-- 0 not reached. A function has no database, so the name is global. A+-- mask that is not base64, or too short for i, reads as 0: a record is+-- signed by a key anyone can make, and one bad mask must not stop the+-- refresh for every node.+CREATE OR REPLACE FUNCTION mask_code AS (mask, i) ->+ bitAnd(bitShiftRight(reinterpretAsUInt8(substring(tryBase64Decode(mask), intDiv(i, 4) + 1, 1)),+ 6 - 2 * (i % 4)), 3);++-- The newest record of every node with the node's label and trust.+CREATE VIEW IF NOT EXISTS shirudo.latest AS+SELECT n.node_id AS node_id, n.trust AS trust, k.*+FROM shirudo.keepalive_latest AS k FINAL+INNER JOIN+(+ SELECT ak_name, argMinMerge(node_id) AS node_id, max(trust) AS trust+ FROM shirudo.nodes+ GROUP BY ak_name+) AS n ON n.ak_name = k.ak_name;++-- History: what each node did at every operation of its tree that the+-- backend has seen it reach, so that checks 4 and 6 and node_vulns can+-- look below the window of the last 512 operations a keepalive covers.+-- One row per node, tree and seq: code is the outcome pair of the mask,+-- 1 to 3, and root the node's projection_root after that seq. A row of+-- code 0 is a gap: it stands at the base_seq of a record whose window+-- starts past the history stored for the node, holds the base_root that+-- record gave, and nothing below it is known. Rows are never removed;+-- the node status page of the backend documentation says why and what+-- that costs.+--+-- The projection keeps, per node and tree, how far the history reaches,+-- the root there and the seq of its first gap, so that a refresh reads+-- one row per node and not the node's whole history. A ReplacingMergeTree+-- keeps a projection only when told to rebuild it after a merge.+CREATE TABLE IF NOT EXISTS shirudo.node_ops+(+ ak_name String,+ tree_id String,+ seq UInt64,+ code UInt8,+ root FixedString(32),+ PROJECTION reach+ (+ SELECT ak_name, tree_id, max(seq), argMax(root, seq), minIf(seq, code = 0)+ GROUP BY ak_name, tree_id+ )+)+ENGINE = ReplacingMergeTree+ORDER BY (ak_name, tree_id, seq)+SETTINGS deduplicate_merge_projection_mode = 'rebuild';++-- The newest operation of every upatch that each node applied, from the+-- rows of node_ops with code 1: what the node's history leaves loaded.+CREATE TABLE IF NOT EXISTS shirudo.node_sets+(+ ak_name String,+ tree_id String,+ id String,+ last_seq UInt64,+ last_op Enum8('add' = 1, 'delete' = 2),+ last_payload String+)+ENGINE = ReplacingMergeTree(last_seq)+ORDER BY (ak_name, tree_id, id);++CREATE MATERIALIZED VIEW IF NOT EXISTS shirudo.node_sets_mv TO shirudo.node_sets AS+SELECT h.ak_name AS ak_name, h.tree_id AS tree_id, o.id AS id, h.seq AS last_seq,+ o.op AS last_op, o.payload_sha256 AS last_payload+FROM shirudo.node_ops AS h+INNER JOIN shirudo.tree_ops AS o FINAL ON o.tree_id = h.tree_id AND o.seq = h.seq+WHERE h.code = 1;++-- The marks of nodes whose record contradicted their history, one row+-- per node and tree, set by node_ops_mv when it finds the contradiction:+-- the seq it found first and whether that was the base or an operation+-- of the window. A mark fails check 4 for the node, whatever tree and+-- boot its newest record has, and stops its history from growing, until+-- an operator deletes it; the node status page of the backend+-- documentation says how and why.+CREATE TABLE IF NOT EXISTS shirudo.history_contradictions+(+ ak_name String,+ tree_id String,+ seq UInt64,+ reason Enum8('base' = 1, 'window' = 2),+ marked_at DateTime DEFAULT now()+)+ENGINE = MergeTree+ORDER BY (ak_name, tree_id);++-- Where the newest record of a node contradicts the history stored for+-- it: one row per node whose base_root differs from the root stored at+-- base_seq (reason base), or whose code or folded root differs from the+-- stored row at an operation of its window that the history reaches+-- (reason window), with the first such seq. A gap row holds a root but+-- no code, so only its root is compared. The roots are folded from+-- base_root once per distinct path, as far as tree_ops has every+-- operation, and only the rows of node_ops the windows overlap are read.+CREATE VIEW IF NOT EXISTS shirudo.history_conflicts AS+WITH+ reach AS+ (+ SELECT ak_name, tree_id, max(seq) AS stored_max+ FROM shirudo.node_ops+ GROUP BY ak_name, tree_id+ ),+ node AS+ (+ SELECT k.ak_name AS ak_name,+ ifNull(k.tree_id, '') AS p_tree,+ ifNull(k.base_seq, 0) AS p_base,+ ifNull(k.mask, '') AS p_mask,+ ifNull(k.base_root, '') AS p_root,+ least(ifNull(k.last_seq, 0), r.stored_max) AS p_upto+ FROM shirudo.keepalive_latest AS k FINAL+ INNER JOIN reach AS r ON r.ak_name = k.ak_name AND r.tree_id = ifNull(k.tree_id, '')+ WHERE k.tree_id IS NOT NULL AND k.mask IS NOT NULL AND k.base_seq IS NOT NULL+ AND k.last_seq IS NOT NULL AND k.last_seq >= k.base_seq+ AND match(p_root, '^[0-9a-f]{64}$') AND r.stored_max >= p_base+ ),+ stored AS+ (+ SELECT ak_name, tree_id, seq, any(code) AS code, any(root) AS root+ FROM shirudo.node_ops+ WHERE (ak_name, tree_id, seq) IN (SELECT ak_name, p_tree, arrayJoin(range(p_base, p_upto + 1)) FROM node)+ GROUP BY ak_name, tree_id, seq+ ),+ folded AS+ (+ SELECT p.p_tree AS p_tree, p.p_base AS p_base, p.p_upto AS p_upto,+ p.p_root AS p_root, p.p_mask AS p_mask,+ arraySort(groupArray((o.seq, mask_code(p.p_mask, o.seq - p.p_base - 1),+ unhex(o.operation_digest)))) AS steps,+ arrayFold((acc, x) -> arrayPushBack(acc, if(has([1, 3], x.2),+ SHA256(concat(acc[-1], x.3)), acc[-1])),+ steps, [toFixedString(unhex(any(p.p_root)), 32)]) AS roots+ FROM (SELECT DISTINCT p_tree, p_base, p_upto, p_root, p_mask FROM node) AS p+ INNER JOIN shirudo.tree_ops AS o FINAL ON o.tree_id = p.p_tree+ WHERE o.seq > p.p_base AND o.seq <= p.p_upto+ GROUP BY p.p_tree, p.p_base, p.p_upto, p.p_root, p.p_mask+ ),+ -- What each record says: its base_root at base_seq, and the code and+ -- root after every operation of its window up to the first one+ -- missing from tree_ops.+ claims AS+ (+ SELECT ak_name, p_tree AS tree_id, p_base AS seq, 'base' AS kind, toUInt8(0) AS code,+ toFixedString(unhex(p_root), 32) AS root+ FROM node+ WHERE p_base > 0+ UNION ALL+ SELECT n.ak_name, n.p_tree, step.1, 'window', step.2, step.3+ FROM node AS n+ INNER JOIN folded AS f ON f.p_tree = n.p_tree AND f.p_base = n.p_base AND f.p_upto = n.p_upto+ AND f.p_root = n.p_root AND f.p_mask = n.p_mask+ ARRAY JOIN arrayFilter((x, i) -> x.1 = f.p_base + i,+ arrayMap((x, r) -> (x.1, x.2, r), f.steps, arrayPopFront(f.roots)),+ arrayEnumerate(f.steps)) AS step+ )+SELECT c.ak_name AS ak_name, c.tree_id AS tree_id,+ min((c.kind, c.seq)).1 AS reason, min((c.kind, c.seq)).2 AS seq+FROM claims AS c+INNER JOIN stored AS s ON s.ak_name = c.ak_name AND s.tree_id = c.tree_id AND s.seq = c.seq+WHERE s.root != c.root OR (c.kind = 'window' AND s.code != 0 AND s.code != c.code)+GROUP BY c.ak_name, c.tree_id;++-- Once a minute, the rows that each node's newest record adds past the+-- history stored for it. They continue the history from its last row+-- when the record's window starts at or below that row, and otherwise+-- start with a gap at the record's base_seq: the backend has not heard+-- from the node since before its window, or never, and what the node did+-- in between is lost. The roots are folded from the stored root, or from+-- base_root after a gap. The rows are added only when every operation is+-- in tree_ops, none up to last_seq is unreached and the fold ends at the+-- record's projection_root: a record that does not extend the history+-- consistently adds nothing. Nor does a record that contradicts the+-- history, or any record of a marked node: what such a node says is not+-- kept. The fold runs once per distinct path and start, not per node.+CREATE MATERIALIZED VIEW IF NOT EXISTS shirudo.node_ops_mv+REFRESH EVERY 1 MINUTE APPEND TO shirudo.node_ops AS+WITH+ reach AS+ (+ SELECT ak_name, tree_id, max(seq) AS stored_max, argMax(root, seq) AS stored_root+ FROM shirudo.node_ops+ GROUP BY ak_name, tree_id+ ),+ node AS+ (+ SELECT k.ak_name AS ak_name,+ ifNull(k.tree_id, '') AS p_tree,+ ifNull(k.base_seq, 0) AS p_base,+ ifNull(k.last_seq, 0) AS p_last,+ ifNull(k.mask, '') AS p_mask,+ ifNull(k.base_root, '') AS p_root,+ ifNull(k.projection_root, '') AS p_end,+ r.ak_name = '' AS unknown,+ if(unknown, 0, r.stored_max) AS stored_max,+ stored_max < p_base AS gap,+ if(gap, p_base, stored_max) AS p_start,+ toFixedString(if(gap, unhex(p_root), if(unknown, repeat('\0', 32), r.stored_root)), 32)+ AS start_root+ FROM shirudo.keepalive_latest AS k FINAL+ LEFT JOIN reach AS r ON r.ak_name = k.ak_name AND r.tree_id = ifNull(k.tree_id, '')+ WHERE k.tree_id IS NOT NULL AND k.mask IS NOT NULL AND k.base_seq IS NOT NULL+ AND k.last_seq IS NOT NULL AND match(p_root, '^[0-9a-f]{64}$')+ AND match(p_end, '^[0-9a-f]{64}$') AND p_last > p_start+ ),+ folded AS+ (+ SELECT p.p_tree AS p_tree, p.p_base AS p_base, p.p_last AS p_last, p.p_mask AS p_mask,+ p.p_end AS p_end, p.gap AS gap, p.p_start AS p_start, p.start_root AS start_root,+ arraySort(groupArray((o.seq, mask_code(p.p_mask, o.seq - p.p_base - 1),+ unhex(o.operation_digest)))) AS steps,+ arrayFold((acc, x) -> arrayPushBack(acc, if(has([1, 3], x.2),+ SHA256(concat(acc[-1], x.3)), acc[-1])),+ steps, [any(p.start_root)]) AS roots+ FROM (SELECT DISTINCT p_tree, p_base, p_last, p_mask, p_end, gap, p_start, start_root FROM node) AS p+ INNER JOIN shirudo.tree_ops AS o FINAL ON o.tree_id = p.p_tree+ WHERE o.seq > p.p_start AND o.seq <= p.p_last+ GROUP BY p.p_tree, p.p_base, p.p_last, p.p_mask, p.p_end, p.gap, p.p_start, p.start_root+ HAVING length(steps) = p_last - p_start AND arrayAll(x -> x.2 != 0, steps)+ AND lower(hex(roots[-1])) = p_end+ )+SELECT n.ak_name AS ak_name, n.p_tree AS tree_id, row.1 AS seq, row.2 AS code, row.3 AS root+FROM node AS n+INNER JOIN folded AS f+ ON f.p_tree = n.p_tree AND f.p_base = n.p_base AND f.p_last = n.p_last AND f.p_mask = n.p_mask+ AND f.p_end = n.p_end AND f.gap = n.gap AND f.p_start = n.p_start AND f.start_root = n.start_root+ARRAY JOIN arrayConcat(if(f.gap, [(f.p_base, toUInt8(0), f.start_root)], []),+ arrayMap((x, r) -> (x.1, x.2, r), f.steps, arrayPopFront(f.roots))) AS row+WHERE n.ak_name NOT IN (SELECT ak_name FROM shirudo.history_contradictions)+ AND (n.ak_name, n.p_tree) NOT IN (SELECT ak_name, tree_id FROM shirudo.history_conflicts);++-- Once a minute, a mark for every node whose newest record contradicts+-- its history and that has none for the tree yet.+CREATE MATERIALIZED VIEW IF NOT EXISTS shirudo.history_contradictions_mv+REFRESH EVERY 1 MINUTE APPEND TO shirudo.history_contradictions AS+SELECT ak_name, tree_id, seq, reason+FROM shirudo.history_conflicts+WHERE (ak_name, tree_id) NOT IN (SELECT ak_name, tree_id FROM shirudo.history_contradictions);++-- One row per node. status is stale when the newest record is older than+-- stale_seconds, whatever it says, else unhealthy when one of checks 3+-- to 7 fails and healthy otherwise. failed_check is the first check that+-- fails, 2 for stale and 0 for none, and log has one line per check, 1+-- to 7. trust is not part of status. head_seq is the head of the newest+-- publication known for the node's tree.+CREATE TABLE IF NOT EXISTS shirudo.node_status+(+ node_id String,+ ak_name String,+ host_name String,+ status Enum8('healthy' = 1, 'unhealthy' = 2, 'stale' = 3),+ trust Enum8('untrusted' = 0),+ failed_check UInt8,+ log Array(String),+ last_seen DateTime64(3),+ generation Nullable(UInt64),+ last_seq Nullable(UInt64),+ head_seq Nullable(UInt64),+ loaded UInt64,+ set_sha256 String,+ updated_at DateTime+)+ENGINE = MergeTree+ORDER BY (node_id, ak_name);++-- Each refresh replaces the rows of node_status in one step.+--+-- Checks 4 to 7 are only evaluated for a node whose record can be held+-- against the tree; skip names why another is not, and such a node+-- passes them: it follows no tree, its record has no mask (its outcomes+-- file is damaged, which flags bit 2 says and check 3 fails), or it+-- names a generation the ingest job has not loaded yet, so that+-- tree_ops may end before the record does.+--+-- The root and the set a mask leads to depend on the tree and the mask,+-- not on the node, so both are folded once per distinct path and joined+-- back to the nodes on it.+--+-- A record whose window starts past seq 0 is also held against the+-- node's history in node_ops: its base_root against the root stored at+-- base_seq (check 4), and its set against what node_sets leaves loaded+-- there, under what the window changes (check 6). Where the backend has+-- not seen the node reach base_seq, without a gap since, the line says+-- so and the check does not fail on that account. Every record, from+-- seq 0 or not, is also held against the rows its window overlaps+-- (history_conflicts), and a node that has a mark fails check 4 whether+-- its record can be held against the tree or not.+CREATE MATERIALIZED VIEW IF NOT EXISTS shirudo.node_status_mv+REFRESH EVERY 1 MINUTE TO shirudo.node_status AS+WITH+ (SELECT stale_seconds FROM shirudo.settings FINAL) AS stale_after,+ (SELECT stuck_seconds FROM shirudo.settings FINAL) AS stuck_after,+ head AS+ (+ SELECT tree_id,+ max(generation) AS newest,+ argMax(head_seq, generation) AS head_seq+ FROM shirudo.tree_pubs FINAL+ GROUP BY tree_id+ ),+ node AS+ (+ SELECT l.*,+ h.newest AS newest,+ h.head_seq AS head,+ multiIf(l.tree_id IS NULL, 'no tree',+ l.mask IS NULL, 'no mask',+ h.newest = 0 OR ifNull(l.generation, 0) > h.newest, 'publication unknown',+ '') AS skip,+ ifNull(l.tree_id, '') AS p_tree,+ ifNull(l.base_seq, 0) AS p_base,+ ifNull(l.last_seq, 0) AS p_last,+ ifNull(l.base_root, '') AS p_root,+ ifNull(l.mask, '') AS p_mask,+ ifNull(l.config_root, '') AS p_config,+ l.base_seq IS NOT NULL AND l.last_seq IS NOT NULL AND p_last >= p_base+ AND match(p_root, '^[0-9a-f]{64}$')+ AND match(ifNull(l.projection_root, ''), '^[0-9a-f]{64}$') AS well_formed,+ -- The pairs up to last_seq: what peers at the same point+ -- of a tree have in common, whatever head each has seen.+ if(p_last > p_base,+ substring(tryBase64Decode(p_mask), 1, intDiv(p_last - p_base + 3, 4)), '') AS walked+ FROM shirudo.latest AS l+ LEFT JOIN head AS h ON h.tree_id = l.tree_id+ ),+ -- When the publication a node has not finished was loaded: the+ -- earliest one whose head is beyond the node's last_seq. The stuck+ -- clock of check 5 starts there and not at the newest publication,+ -- which an operator who publishes often would keep moving.+ unfinished AS+ (+ SELECT n.p_tree AS p_tree, n.p_last AS p_last, min(t.published_at) AS behind_since+ FROM (SELECT DISTINCT p_tree, p_last FROM node WHERE skip = '') AS n+ INNER JOIN shirudo.tree_pubs AS t FINAL ON t.tree_id = n.p_tree+ WHERE t.head_seq > n.p_last+ GROUP BY n.p_tree, n.p_last+ ),+ paths AS+ (+ SELECT DISTINCT p_tree, p_base, p_last, p_root, p_mask+ FROM node+ WHERE skip = '' AND well_formed+ ),+ -- How far each node's stored history reaches and the seq of its first+ -- gap, 0 when it has none: rows are only ever added past the last, so+ -- the history up to a seq is whole when it reaches that seq and has no+ -- gap at or below it.+ reach AS+ (+ SELECT ak_name, tree_id, max(seq) AS stored_max, minIf(seq, code = 0) AS first_gap+ FROM shirudo.node_ops+ GROUP BY ak_name, tree_id+ ),+ -- The stored row at the base_seq of each record whose window starts+ -- past seq 0.+ based AS+ (+ SELECT ak_name, tree_id, seq, any(code) AS code, lower(hex(any(root))) AS root+ FROM shirudo.node_ops+ WHERE (ak_name, tree_id, seq) IN (SELECT ak_name, p_tree, p_base FROM node WHERE skip = '' AND p_base > 0)+ GROUP BY ak_name, tree_id, seq+ ),+ ops AS+ (+ SELECT p.p_tree AS p_tree, p.p_base AS p_base, p.p_last AS p_last,+ p.p_root AS p_root, p.p_mask AS p_mask,+ o.seq AS seq, o.id AS id, o.op AS op,+ o.payload_sha256 AS payload_sha256, o.operation_digest AS operation_digest,+ mask_code(p.p_mask, o.seq - p.p_base - 1) AS code+ FROM paths AS p+ INNER JOIN shirudo.tree_ops AS o FINAL ON o.tree_id = p.p_tree+ WHERE o.seq > p.p_base AND o.seq <= p.p_last+ ),+ chain AS+ (+ SELECT p_tree, p_base, p_last, p_root, p_mask,+ count() AS ops,+ countIf(code = 0) AS unreached,+ lower(hex(arrayFold((acc, digest) -> SHA256(concat(acc, unhex(digest))),+ arrayMap(x -> x.2, arraySort(groupArrayIf((seq, operation_digest), code IN (1, 3)))),+ toFixedString(unhex(any(p_root)), 32)))) AS root+ FROM ops+ GROUP BY p_tree, p_base, p_last, p_root, p_mask+ ),+ applied AS+ (+ SELECT p_tree, p_base, p_last, p_root, p_mask, id,+ max(seq) AS last_seq,+ argMax(op, seq) AS last_op,+ argMax(payload_sha256, seq) AS last_payload+ FROM ops+ WHERE code = 1+ GROUP BY p_tree, p_base, p_last, p_root, p_mask, id+ ),+ sets AS+ (+ SELECT p_tree, p_base, p_last, p_root, p_mask,+ lower(hex(SHA256(arrayStringConcat(arrayMap(x -> x.2, arraySort(+ groupArrayIf((id, concat(last_payload, ' ', id, '\n')), last_op = 'add'))))))) AS expected_set+ FROM applied+ GROUP BY p_tree, p_base, p_last, p_root, p_mask+ ),+ -- The set of a node whose window starts past seq 0: per upatch the+ -- newest operation it applied, from the window where the window has+ -- one and else from node_sets at or below base_seq. node_sets keeps+ -- only an upatch's newest operation, which may be in the window; the+ -- window then has it too.+ long_sets AS+ (+ SELECT ak_name,+ lower(hex(SHA256(arrayStringConcat(arrayMap(x -> x.2, arraySort(+ groupArrayIf((id, concat(payload, ' ', id, '\n')), op = 'add'))))))) AS expected_set+ FROM+ (+ SELECT ak_name, id, argMax(last_op, last_seq) AS op, argMax(last_payload, last_seq) AS payload+ FROM+ (+ SELECT k.ak_name AS ak_name, a.id AS id, a.last_seq AS last_seq,+ toString(a.last_op) AS last_op, a.last_payload AS last_payload+ FROM node AS k+ INNER JOIN applied AS a ON a.p_tree = k.p_tree AND a.p_base = k.p_base AND a.p_last = k.p_last+ AND a.p_root = k.p_root AND a.p_mask = k.p_mask+ WHERE k.skip = '' AND k.p_base > 0+ UNION ALL+ SELECT k.ak_name, s.id, s.last_seq, toString(s.last_op), s.last_payload+ FROM node AS k+ INNER JOIN+ (+ SELECT *+ FROM shirudo.node_sets FINAL+ WHERE (ak_name, tree_id) IN (SELECT ak_name, p_tree FROM node WHERE skip = '' AND p_base > 0)+ ) AS s ON s.ak_name = k.ak_name AND s.tree_id = k.p_tree+ WHERE k.skip = '' AND k.p_base > 0 AND s.last_seq <= k.p_base+ )+ GROUP BY ak_name, id+ )+ GROUP BY ak_name+ ),+ peers AS+ (+ SELECT ak_name, n, same,+ max(same) OVER (PARTITION BY p_tree, p_base, p_last, p_config, kernel_release) AS most+ FROM+ (+ SELECT ak_name, p_tree, p_base, p_last, p_config, kernel_release,+ count() OVER (PARTITION BY p_tree, p_base, p_last, p_config, kernel_release) AS n,+ count() OVER (PARTITION BY p_tree, p_base, p_last, p_config, kernel_release, p_root, walked)+ AS same+ FROM node+ WHERE skip = ''+ )+ ),+ boot AS+ (+ SELECT ak_name, boot_id, argMinMerge(tamper_first) AS tamper_first+ FROM shirudo.boot_first+ GROUP BY ak_name, boot_id+ ),+ conflicts AS+ (+ SELECT ak_name, tree_id, reason, seq+ FROM shirudo.history_conflicts+ ),+ marks AS+ (+ SELECT ak_name, argMin(seq, marked_at) AS seq+ FROM shirudo.history_contradictions+ GROUP BY ak_name+ ),+ refused AS+ (+ SELECT ak_name, count() AS rejected+ FROM shirudo.rejected+ WHERE received >= now() - INTERVAL 1 HOUR+ GROUP BY ak_name+ ),+ result AS+ (+ SELECT k.node_id AS node_id, k.ak_name AS ak_name, k.host_name AS host_name, k.trust AS trust,+ k.received AS received, k.generation AS generation, k.last_seq AS last_seq,+ k.count AS count, k.set_sha256 AS set_sha256, k.verdict AS verdict, k.cond AS cond,+ k.flags AS flags, k.version_id AS version_id, k.projection_root AS projection_root,+ k.skip AS skip, k.newest AS newest, k.head AS head, k.p_last AS p_last,+ p.n AS n,+ r.rejected AS rejected,+ dateDiff('second', k.received, now64(3)) AS age_s,+ age_s > stale_after AS stale,+ -- A record that could not read its counters has no total+ -- to compare; flags bit 3 says so and fails the check.+ if(empty(k.tamper), 0,+ toInt64(arraySum(k.tamper)) - toInt64(b.tamper_first)) AS tamper_rise,+ k.version_id IN (SELECT version_id FROM shirudo.expected_builds) AS build_ok,+ -- The seven condition pairs this schema knows, all OK,+ -- and flags bits 0 to 3; bits 4 and 5 say busy, not broken.+ k.verdict = 'ok' AND bitAnd(k.cond, 0x3FFF) = 0x1555 AND bitAnd(k.flags, 15) = 0+ AND tamper_rise = 0 AND build_ok AS ok3,+ -- A gap row holds the base_root of the record that found+ -- the gap, which nothing verified: the same value again+ -- is no more verified, another one is a changed story.+ multiIf(k.skip != '' OR k.p_base = 0, '',+ bs.ak_name = '' OR (bs.code = 0 AND bs.root = k.p_root), 'gap',+ bs.root = k.p_root, '',+ 'differs') AS base_state,+ multiIf(base_state = 'differs' OR cf.reason = 'base', 'base differs from history',+ cf.reason = 'window', concat('window differs from history at seq ', toString(cf.seq)),+ mk.ak_name != '', concat('marked: contradicted history at seq ', toString(mk.seq)),+ base_state = 'gap', 'base unverified (gap)',+ '') AS history_state,+ (k.skip != '' OR (k.well_formed AND c.ops = k.p_last - k.p_base AND c.unreached = 0+ AND if(c.ops = 0, k.p_root, c.root) = k.projection_root AND base_state != 'differs'))+ AND cf.ak_name = '' AND mk.ak_name = '' AS ok4,+ k.p_base > 0 AND NOT (h.stored_max >= k.p_base AND (h.first_gap = 0 OR h.first_gap > k.p_base))+ AS set_gap,+ if(k.p_base > 0, ls.expected_set, s.expected_set) AS expected_set,+ k.p_last >= k.head AS at_head,+ k.skip != '' OR at_head+ OR dateDiff('second', u.behind_since, now64(3)) <= stuck_after AS ok5,+ -- An operation in flight has a seq above last_seq, so a+ -- pending one at the head is a contradiction.+ multiIf(k.skip != '', '',+ bitTest(k.flags, 4) AND at_head, 'FAIL sync in progress at head',+ bitTest(k.flags, 4), 'sync in progress',+ bitTest(k.flags, 5), 'snapshot unsettled',+ set_gap, 'set unverified (gap)',+ if(expected_set = '', lower(hex(SHA256(''))), expected_set) = k.set_sha256, 'pass',+ 'FAIL drift') AS set_state,+ NOT startsWith(set_state, 'FAIL') AS ok6,+ k.skip != '' OR p.n = 1 OR p.same = p.most AS ok7+ FROM node AS k+ LEFT JOIN boot AS b ON b.ak_name = k.ak_name AND b.boot_id = k.boot_id+ LEFT JOIN refused AS r ON r.ak_name = k.ak_name+ LEFT JOIN peers AS p ON p.ak_name = k.ak_name+ LEFT JOIN unfinished AS u ON u.p_tree = k.p_tree AND u.p_last = k.p_last+ LEFT JOIN chain AS c ON c.p_tree = k.p_tree AND c.p_base = k.p_base AND c.p_last = k.p_last+ AND c.p_root = k.p_root AND c.p_mask = k.p_mask+ LEFT JOIN sets AS s ON s.p_tree = k.p_tree AND s.p_base = k.p_base AND s.p_last = k.p_last+ AND s.p_root = k.p_root AND s.p_mask = k.p_mask+ LEFT JOIN reach AS h ON h.ak_name = k.ak_name AND h.tree_id = k.p_tree+ LEFT JOIN based AS bs ON bs.ak_name = k.ak_name AND bs.tree_id = k.p_tree AND bs.seq = k.p_base+ LEFT JOIN long_sets AS ls ON ls.ak_name = k.ak_name+ LEFT JOIN conflicts AS cf ON cf.ak_name = k.ak_name AND cf.tree_id = k.p_tree+ LEFT JOIN marks AS mk ON mk.ak_name = k.ak_name+ )+SELECT+ node_id,+ ak_name,+ host_name,+ multiIf(stale, 'stale', ok3 AND ok4 AND ok5 AND ok6 AND ok7, 'healthy', 'unhealthy') AS status,+ trust,+ multiIf(stale, 2, NOT ok3, 3, NOT ok4, 4, NOT ok5, 5, NOT ok6, 6, NOT ok7, 7, 0) AS failed_check,+ [+ concat('1 signed: pass, ', toString(trust), ', ', toString(rejected), ' rejected in the last hour'),+ concat('2 fresh: ', if(stale, 'FAIL', 'pass'), ', last record ', toString(age_s), ' s ago'),+ concat('3 reported: ', if(ok3, 'pass', 'FAIL'), ', verdict ', verdict, ', cond 0x', hex(cond),+ ', flags ', toString(flags), ', tamper ', if(tamper_rise < 0, '', '+'), toString(tamper_rise),+ ', build ', substring(version_id, 1, 8), if(build_ok, '', ' (not expected)')),+ concat('4 chain: ', if(skip != '' AND history_state = '', skip,+ concat(if(ok4, 'pass', 'FAIL'),+ if(skip != '', concat(', ', skip),+ concat(', root ', substring(ifNull(projection_root, ''), 1, 8))),+ if(history_state = '', '', concat(', ', history_state))))),+ concat('5 head: ', if(skip != '', skip,+ concat(multiIf(at_head, 'pass', ok5, 'behind', 'FAIL stuck'), ', seq ', toString(p_last),+ ' of ', toString(head), ', generation ', toString(ifNull(generation, 0))))),+ concat('6 set: ', if(skip != '', skip, concat(set_state, ', ', toString(count), ' loaded'))),+ concat('7 peers: ', if(skip != '', skip,+ concat(multiIf(n = 1, 'no peers', ok7, 'pass', 'FAIL outlier'), ', ', toString(n), ' in group')))+ ] AS log,+ received AS last_seen,+ generation,+ last_seq,+ if(newest = 0, NULL, head) AS head_seq,+ count AS loaded,+ set_sha256,+ now() AS updated_at+FROM result;diff --git a/tools/backend/sql/50-vulns.sql b/tools/backend/sql/50-vulns.sqlnew file mode 100644index 00000000..71f52a2f--- /dev/null+++ b/tools/backend/sql/50-vulns.sql@@ -0,0 +1,339 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- Exposure: which nodes run a vulnerable package or kernel, and whether+-- an upatch of their tree shields them. Packages come from the SBOM of+-- the image a node says it booted, the kernel from the release it+-- reports, the shield from its mask and its history in node_ops.+-- shirudo.node_vulns is what a UI reads; the tables before it are its+-- inputs.++-- One row per image the SBOM store holds, written by jobs/sbom-scan.+-- image_root is empty for an image built without verity and sbom_sha256+-- is empty unless state is ok. sbom_format is the value of image.json,+-- cyclonedx-json when it names none. Only an image whose state is ok has+-- findings in sbom_vulns.+CREATE TABLE IF NOT EXISTS shirudo.sbom_images+(+ image_id String,+ image_version String,+ image_root String,+ sbom_format LowCardinality(String) DEFAULT 'cyclonedx-json',+ sbom_sha256 String,+ state Enum8('ok' = 1, 'missing' = 2, 'hash_mismatch' = 3, 'parse_error' = 4,+ 'unsupported_format' = 5),+ built_at DateTime,+ db_version String,+ scanned_at DateTime+)+ENGINE = ReplacingMergeTree(scanned_at)+ORDER BY (image_id, image_version, image_root);++-- The findings of every scan of an SBOM. scanned_at is that of the scan,+-- as sbom_images has it: the findings of an image are the rows of its+-- newest scan, and those of older scans leave with the TTL. fixed is+-- empty while no fixed version exists.+CREATE TABLE IF NOT EXISTS shirudo.sbom_vulns+(+ sbom_sha256 String,+ vuln_id String,+ package String,+ installed String,+ fixed String,+ severity LowCardinality(String),+ scanned_at DateTime+)+ENGINE = MergeTree+ORDER BY (sbom_sha256, vuln_id, package)+TTL scanned_at + INTERVAL 7 DAY;++-- Kernel advisories, one row per affected range of releases: from+-- introduced, inclusive, to fixed, exclusive, each a release as kver()+-- gives it. An empty fixed is a range without an end.+CREATE TABLE IF NOT EXISTS shirudo.kernel_vulns+(+ vuln_id String,+ introduced Array(UInt32),+ fixed Array(UInt32),+ severity LowCardinality(String)+)+ENGINE = ReplacingMergeTree+ORDER BY (vuln_id, introduced);++-- The numbers a kernel release starts with: '7.4.2-shirudo' is+-- [7, 4, 2]. Arrays compare element by element and a prefix sorts before+-- what extends it, so [7, 4, 2] is at least [7, 0] and below [7, 4, 5].+-- A release that starts with no number is []: a record is signed by a+-- key anyone can make, and one bad kernel_release must not stop the+-- refresh for every node. A number UInt32 cannot hold reads as 0. A+-- function has no database, so the name is global.+CREATE OR REPLACE FUNCTION kver AS (r) ->+ arrayMap(x -> toUInt32OrZero(x), extractAll(extract(r, '^[0-9]+(?:[.][0-9]+)*'), '[0-9]+'));++-- One row per node and finding, and one row with an empty vuln_id for a+-- node with none, so that a node without findings differs from a node+-- that is not there. binding says how far the SBOM can be trusted to+-- describe the node, sbom_stale that the newest scan of that SBOM is+-- older than sbom_stale_seconds of shirudo.settings, and exposure what+-- stands between the node and the vulnerability now. upatch_id names the+-- upatch that is read from; applied_seq and applied_op are its newest+-- operation the node has applied, 0 and empty when it has applied none,+-- and next_seq and next_op its newest operation in the tree, equal to+-- those two when nothing is coming, so that next_seq above applied_seq+-- says something is.+-- next_shields says whether that newest operation is an add linked to the+-- advisory, false when it is a delete or an add that drops the link.+-- shield_link is where the link to the advisory comes from. All of them+-- are empty, 0, false and none when no upatch is linked. The exposure+-- values are in the order they are ranked in, best first. status and+-- trust are the node's in node_status.+CREATE TABLE IF NOT EXISTS shirudo.node_vulns+(+ node_id String,+ ak_name String,+ host_name String,+ status Enum8('healthy' = 1, 'unhealthy' = 2, 'stale' = 3),+ trust Enum8('untrusted' = 0),+ image_id String,+ image_version String,+ binding Enum8('verified' = 1, 'declared' = 2, 'root_mismatch' = 3, 'no_sbom' = 4, 'no_image' = 5),+ sbom_stale Bool,+ source Enum8('sbom' = 1, 'kernel' = 2, 'none' = 3),+ vuln_id String,+ severity LowCardinality(String),+ package String,+ installed String,+ fixed String,+ exposure Enum8('shielded' = 1, 'shield_pending' = 2, 'shield_module_absent' = 3,+ 'shield_excludes_node' = 4, 'shield_withdrawn' = 5, 'exposed_no_shield' = 6,+ 'none' = 7, 'unknown' = 8),+ upatch_id String,+ applied_seq UInt64,+ applied_op Enum8('' = 0, 'add' = 1, 'delete' = 2),+ next_seq UInt64,+ next_op Enum8('' = 0, 'add' = 1, 'delete' = 2),+ next_shields Bool,+ shield_link Enum8('none' = 0, 'fixes' = 1, 'manual' = 2),+ updated_at DateTime+)+ENGINE = MergeTree+ORDER BY (node_id, ak_name, vuln_id, package);++-- Each refresh replaces the rows of node_vulns in one step. Five minutes+-- are enough: an SBOM's findings change once a day at most, and+-- node_status follows the tree every minute.+--+-- The work is per image, per kernel release and per path through a tree,+-- not per node: the kernel advisories are matched once for each distinct+-- kernel_release, and the newest operation of every upatch is found once+-- for each distinct tree_id, base_seq, last_seq and mask, then joined to+-- the nodes. Only what an operation below the window did is per node: the+-- mask does not cover it, so it is read from the node's history in+-- node_ops, one row per node and linked upatch.+--+-- A stale scan keeps its findings, which are still the newest known, and+-- marks them sbom_stale. It never makes a node read clean: the row of a+-- node without findings is unknown then, as for a node without an SBOM,+-- since the findings may have expired with sbom_vulns' TTL.+--+-- A row says where the node is, not where the tree is. For an upatch+-- linked to the advisory, the node has applied the operations up to its+-- last_seq. When the newest of them is an add, the mask says what it+-- did there, or the node's history when the add is below the window:+-- shielded, shield_module_absent or shield_excludes_node, and unknown+-- when neither says, because the record has no mask or marks the+-- operation as not reached, or the backend never saw the node reach it. When it is a delete, the shield is+-- withdrawn. When the node has applied none, nothing is loaded:+-- shield_pending when the tree's newest operation is an add, and+-- shield_withdrawn when it is a delete, which the node will reach+-- without ever having had the shield.+--+-- An upatch counts for an advisory when upatch_fixes links the newest+-- add the node has applied or the newest add of the tree. Only the+-- first says what is loaded: when just the coming add is linked, what+-- the node has applied is no shield against this advisory and the row+-- reads as if it had applied none. shield_link is the applied add's+-- link when there is one, else the coming add's.+--+-- Of several upatches linked to one advisory the best outcome counts, in+-- the order of the exposure values, and of two links to the same+-- operation the signed one, fixes, before manual.+CREATE MATERIALIZED VIEW IF NOT EXISTS shirudo.node_vulns_mv+REFRESH EVERY 5 MINUTE TO shirudo.node_vulns AS+WITH+ (SELECT sbom_stale_seconds FROM shirudo.settings FINAL) AS sbom_stale_after,+ node AS+ (+ SELECT ak_name, kernel_release,+ ifNull(image_id, '') AS image_id,+ ifNull(image_version, '') AS image_version,+ ifNull(image_root, '') AS image_root,+ ifNull(tree_id, '') AS p_tree,+ ifNull(base_seq, 0) AS p_base,+ ifNull(last_seq, 0) AS p_last,+ ifNull(mask, '') AS p_mask+ FROM shirudo.latest+ ),+ -- The SBOM of each node's image: the one with the node's own root+ -- when there is one, else the newest build of that id and version.+ img AS+ (+ SELECT n.ak_name AS ak_name, i.sbom_sha256 AS sbom_sha256, i.scanned_at AS scanned_at,+ multiIf(n.image_id = '', 'no_image',+ i.image_id = '' OR i.state != 'ok' OR i.sbom_sha256 = '', 'no_sbom',+ n.image_root != '' AND n.image_root = i.image_root, 'verified',+ n.image_root != '' AND i.image_root != '', 'root_mismatch',+ 'declared') AS binding,+ binding IN ('verified', 'declared', 'root_mismatch')+ AND dateDiff('second', i.scanned_at, now()) > sbom_stale_after AS sbom_stale+ FROM node AS n+ LEFT JOIN shirudo.sbom_images AS i FINAL+ ON i.image_id = n.image_id AND i.image_version = n.image_version+ ORDER BY n.ak_name, i.image_root = n.image_root DESC, i.built_at DESC, i.image_root+ LIMIT 1 BY n.ak_name+ ),+ kmatch AS+ (+ SELECT r.kernel_release AS kernel_release, k.vuln_id AS vuln_id, k.severity AS severity,+ arrayStringConcat(arrayMap(x -> toString(x), k.fixed), '.') AS fixed+ FROM (SELECT DISTINCT kernel_release, kver(kernel_release) AS release FROM node) AS r+ CROSS JOIN shirudo.kernel_vulns AS k FINAL+ WHERE notEmpty(r.release) AND r.release >= k.introduced+ AND (empty(k.fixed) OR r.release < k.fixed)+ ORDER BY r.kernel_release, k.vuln_id, k.introduced+ LIMIT 1 BY r.kernel_release, k.vuln_id+ ),+ -- The SBOM describes the kernel installed in the image, and the node+ -- may run another: kernel findings come from kernel_vulns alone.+ found AS+ (+ SELECT g.ak_name AS ak_name, 'sbom' AS source, v.vuln_id AS vuln_id, v.severity AS severity,+ v.package AS package, v.installed AS installed, v.fixed AS fixed+ FROM img AS g+ INNER JOIN shirudo.sbom_vulns AS v+ ON v.sbom_sha256 = g.sbom_sha256 AND v.scanned_at = g.scanned_at+ WHERE g.binding IN ('verified', 'declared', 'root_mismatch')+ AND NOT match(v.package, '^(linux-image-|kernel$|kernel-core$)')+ UNION ALL+ SELECT n.ak_name, 'kernel', m.vuln_id, m.severity, 'linux', n.kernel_release, m.fixed+ FROM node AS n+ INNER JOIN kmatch AS m ON m.kernel_release = n.kernel_release+ ),+ paths AS+ (+ SELECT DISTINCT p_tree, p_base, p_last, p_mask+ FROM node+ WHERE p_tree != ''+ ),+ -- code is what the node did at applied_seq when the mask covers it,+ -- and 255 when the operation is below the window and the node's+ -- history has to say.+ upatch AS+ (+ SELECT p.p_tree AS p_tree, p.p_base AS p_base, p.p_last AS p_last, p.p_mask AS p_mask,+ o.id AS upatch_id,+ max(o.seq) AS next_seq,+ argMax(toString(o.op), o.seq) AS next_op,+ maxIf(o.seq, o.op = 'add') AS next_add,+ maxIf(o.seq, o.seq <= p.p_last) AS applied_seq,+ argMaxIf(toString(o.op), o.seq, o.seq <= p.p_last) AS applied_op,+ maxIf(o.seq, o.op = 'add' AND o.seq <= p.p_last) AS applied_add,+ if(applied_seq > p.p_base OR applied_seq = 0,+ argMaxIf(mask_code(p.p_mask, o.seq - p.p_base - 1), o.seq,+ o.seq > p.p_base AND o.seq <= p.p_last),+ 255) AS code+ FROM paths AS p+ INNER JOIN shirudo.tree_ops AS o FINAL ON o.tree_id = p.p_tree+ GROUP BY p.p_tree, p.p_base, p.p_last, p.p_mask, o.id+ ),+ linked AS+ (+ SELECT u.p_tree AS p_tree, u.p_base AS p_base, u.p_last AS p_last, u.p_mask AS p_mask,+ u.upatch_id AS upatch_id, f.advisory AS vuln_id,+ any(u.next_seq) AS next_seq, any(u.next_op) AS next_op,+ any(u.applied_seq) AS applied_seq, any(u.applied_op) AS applied_op,+ minIf(toInt8(f.source), f.seq = u.applied_add) AS applied_link,+ minIf(toInt8(f.source), f.seq = u.next_add) AS next_link,+ if(applied_link != 0, applied_link, next_link) AS link,+ next_op = 'add' AND next_link != 0 AS next_shields,+ any(u.code) AS code+ FROM upatch AS u+ INNER JOIN shirudo.upatch_fixes AS f FINAL ON f.tree_id = u.p_tree+ WHERE f.seq = u.applied_add OR f.seq = u.next_add+ GROUP BY u.p_tree, u.p_base, u.p_last, u.p_mask, u.upatch_id, f.advisory+ ),+ -- Per node, the links of its path, with the code of an operation+ -- below the window taken from the node's history: 0, and so unknown,+ -- when the backend never saw the node reach it.+ reached AS+ (+ SELECT n.ak_name AS ak_name, l.vuln_id AS vuln_id, l.upatch_id AS upatch_id,+ l.applied_seq AS applied_seq, l.applied_op AS applied_op,+ l.next_seq AS next_seq, l.next_op AS next_op, l.link AS link, l.next_shields AS next_shields,+ if(l.code = 255, h.code, l.code) AS code,+ multiIf(l.applied_link != 0 AND l.applied_op = 'add',+ transform(code, [1, 2, 3],+ ['shielded', 'shield_excludes_node', 'shield_module_absent'], 'unknown'),+ l.applied_link != 0, 'shield_withdrawn',+ l.next_op = 'add', 'shield_pending',+ 'shield_withdrawn') AS exposure+ FROM node AS n+ INNER JOIN linked AS l ON l.p_tree = n.p_tree AND l.p_base = n.p_base AND l.p_last = n.p_last+ AND l.p_mask = n.p_mask+ LEFT JOIN+ (+ SELECT ak_name, tree_id, seq, any(code) AS code+ FROM shirudo.node_ops+ WHERE (ak_name, tree_id, seq) IN+ (SELECT n.ak_name, n.p_tree, l.applied_seq+ FROM node AS n+ INNER JOIN linked AS l ON l.p_tree = n.p_tree AND l.p_base = n.p_base+ AND l.p_last = n.p_last AND l.p_mask = n.p_mask+ WHERE l.code = 255)+ GROUP BY ak_name, tree_id, seq+ ) AS h ON h.ak_name = n.ak_name AND h.tree_id = n.p_tree AND h.seq = l.applied_seq+ ),+ shield AS+ (+ SELECT ak_name, vuln_id,+ argMin((exposure, upatch_id, applied_seq, applied_op, next_seq, next_op,+ if(link = 1, 'fixes', 'manual'), next_shields),+ (indexOf(['shielded', 'shield_pending', 'shield_module_absent',+ 'shield_excludes_node', 'shield_withdrawn', 'unknown'], exposure),+ link, upatch_id)) AS best+ FROM reached+ GROUP BY ak_name, vuln_id+ )+SELECT+ s.node_id AS node_id,+ s.ak_name AS ak_name,+ s.host_name AS host_name,+ s.status AS status,+ s.trust AS trust,+ n.image_id AS image_id,+ n.image_version AS image_version,+ g.binding AS binding,+ g.sbom_stale AS sbom_stale,+ if(v.vuln_id = '', 'none', v.source) AS source,+ v.vuln_id AS vuln_id,+ v.severity AS severity,+ v.package AS package,+ v.installed AS installed,+ v.fixed AS fixed,+ multiIf(v.vuln_id = '' AND (g.binding IN ('no_image', 'no_sbom') OR g.sbom_stale), 'unknown',+ v.vuln_id = '', 'none',+ h.best.1 = '', 'exposed_no_shield',+ h.best.1) AS exposure,+ h.best.2 AS upatch_id,+ h.best.3 AS applied_seq,+ h.best.4 AS applied_op,+ h.best.5 AS next_seq,+ h.best.6 AS next_op,+ if(h.best.1 = '', 'none', h.best.7) AS shield_link,+ h.best.1 != '' AND h.best.8 AS next_shields,+ now() AS updated_at+FROM shirudo.node_status AS s+INNER JOIN node AS n ON n.ak_name = s.ak_name+INNER JOIN img AS g ON g.ak_name = s.ak_name+LEFT JOIN found AS v ON v.ak_name = s.ak_name+LEFT JOIN shield AS h ON h.ak_name = s.ak_name AND h.vuln_id = v.vuln_id;diff --git a/tools/backend/sql/apply-retention.sh b/tools/backend/sql/apply-retention.shnew file mode 100755index 00000000..23ac2782--- /dev/null+++ b/tools/backend/sql/apply-retention.sh@@ -0,0 +1,58 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# sql/apply-retention.sh -- give shirudo.keepalive and shirudo.boot_first+# the retention that shirudo.settings names. A ClickHouse TTL cannot read+# a table, so run this after loading the schema and after every change+# of keepalive_retention_seconds or boot_first_retention_seconds.+#+# sql/apply-retention.sh [<client command>...]+#+# The arguments are the command that reaches the server, by default+# clickhouse-client; --query '<SQL>' is appended to it. A value that is+# refused changes neither table.++set -eu++# shirudo.boot_first_keep_mv writes the baseline of a node's current boot+# again once an hour. A retention near that hour could remove one between+# two refreshes, so a day is the least the script applies.+BOOT_FIRST_MINIMUM=86400++[ $# -gt 0 ] || set -- clickhouse-client++setting()+{+ name=$1+ shift+ "$@" --query "SELECT $name FROM shirudo.settings FINAL" </dev/null+}++refuse()+{+ printf 'apply-retention.sh: %s is "%s", need a number of seconds %s\n' \+ "$1" "$2" "$3" >&2+ exit 1+}++keepalive=$(setting keepalive_retention_seconds "$@")+boot_first=$(setting boot_first_retention_seconds "$@")++case "$keepalive" in+''|0|*[!0-9]*)+ refuse keepalive_retention_seconds "$keepalive" 'above 0' ;;+esac+case "$boot_first" in+''|*[!0-9]*)+ refuse boot_first_retention_seconds "$boot_first" \+ "of at least $BOOT_FIRST_MINIMUM" ;;+esac+[ "$boot_first" -ge "$BOOT_FIRST_MINIMUM" ] ||+ refuse boot_first_retention_seconds "$boot_first" \+ "of at least $BOOT_FIRST_MINIMUM"++"$@" --query "ALTER TABLE shirudo.keepalive+ MODIFY TTL toDateTime(received) + INTERVAL $keepalive SECOND" </dev/null+"$@" --query "ALTER TABLE shirudo.boot_first+ MODIFY TTL last_used + INTERVAL $boot_first SECOND" </dev/nulldiff --git a/tools/backend/test/history-base.expected b/tools/backend/test/history-base.expectednew file mode 100644index 00000000..8880fdf9--- /dev/null+++ b/tools/backend/test/history-base.expected@@ -0,0 +1,80 @@+round 1+core-01 healthy 0 4 chain: pass, root 00000000 6 set: pass, 0 loaded 7 peers: no peers, 1 in group+edge-01 healthy 0 4 chain: pass, root a042a582 6 set: pass, 0 loaded 7 peers: pass, 3 in group+edge-02 healthy 0 4 chain: pass, root a042a582 6 set: pass, 0 loaded 7 peers: pass, 3 in group+edge-liar healthy 0 4 chain: pass, root a042a582 6 set: pass, 0 loaded 7 peers: pass, 3 in group+edge-swap healthy 0 4 chain: pass, root a042a582 6 set: pass, 0 loaded 7 peers: no peers, 1 in group+round 2+core-01 healthy 0 4 chain: pass, root 00000000 6 set: pass, 0 loaded 7 peers: no peers, 1 in group+edge-01 healthy 0 4 chain: pass, root 61fc83b3 6 set: pass, 2 loaded 7 peers: pass, 3 in group+edge-02 healthy 0 4 chain: pass, root 61fc83b3 6 set: pass, 2 loaded 7 peers: pass, 3 in group+edge-liar healthy 0 4 chain: pass, root 61fc83b3 6 set: pass, 2 loaded 7 peers: pass, 3 in group+edge-swap healthy 0 4 chain: pass, root 61fc83b3 6 set: pass, 2 loaded 7 peers: no peers, 1 in group+round 3+core-01 healthy 0 4 chain: pass, root 7eb926ee 6 set: pass, 1 loaded 7 peers: no peers, 1 in group+edge-01 healthy 0 4 chain: pass, root c7a9860a 6 set: pass, 2 loaded 7 peers: pass, 3 in group+edge-02 healthy 0 4 chain: pass, root c7a9860a 6 set: pass, 2 loaded 7 peers: pass, 3 in group+edge-liar unhealthy 4 4 chain: FAIL, root 78b6a625, base differs from history 6 set: FAIL drift, 1 loaded 7 peers: FAIL outlier, 3 in group+edge-swap healthy 0 4 chain: pass, root c7a9860a 6 set: pass, 2 loaded 7 peers: no peers, 1 in group+round 4+core-01 healthy 0 4 chain: pass, root 2b11a79d 6 set: pass, 0 loaded 7 peers: no peers, 1 in group+edge-01 healthy 0 4 chain: pass, root 7abe8b4e 6 set: pass, 1 loaded 7 peers: pass, 3 in group+edge-02 healthy 0 4 chain: pass, root 7abe8b4e 6 set: pass, 1 loaded 7 peers: pass, 3 in group+edge-liar unhealthy 4 4 chain: FAIL, root 7abe8b4e, marked: contradicted history at seq 4 6 set: set unverified (gap), 1 loaded 7 peers: pass, 3 in group+edge-swap unhealthy 4 4 chain: FAIL, root 7abe8b4e, window differs from history at seq 6 6 set: pass, 1 loaded 7 peers: no peers, 1 in group+marks+edge-liar fleet-long 4 base+edge-swap fleet-long 6 window+cleared+edge-liar healthy 0 4 chain: pass, root 7abe8b4e, base unverified (gap) 6 set: set unverified (gap), 1 loaded 7 peers: pass, 3 in group+edge-swap unhealthy 4 4 chain: FAIL, root 7abe8b4e, window differs from history at seq 6 6 set: pass, 1 loaded 7 peers: no peers, 1 in group+marks+edge-swap fleet-long 6 window+history+core-01 1 2 00000000+core-01 2 2 00000000+core-01 3 2 00000000+core-01 4 2 00000000+core-01 5 1 7eb926ee+core-01 6 2 7eb926ee+core-01 7 1 2b11a79d+core-01 8 2 2b11a79d+edge-01 1 1 04f83540+edge-01 2 1 a042a582+edge-01 3 1 15452248+edge-01 4 1 61fc83b3+edge-01 5 2 61fc83b3+edge-01 6 1 c7a9860a+edge-01 7 2 c7a9860a+edge-01 8 1 7abe8b4e+edge-02 1 1 04f83540+edge-02 2 1 a042a582+edge-02 3 1 15452248+edge-02 4 1 61fc83b3+edge-02 5 2 61fc83b3+edge-02 6 1 c7a9860a+edge-02 7 2 c7a9860a+edge-02 8 1 7abe8b4e+edge-liar 1 1 04f83540+edge-liar 2 1 a042a582+edge-liar 3 1 15452248+edge-liar 4 1 61fc83b3+edge-liar 6 0 c7a9860a+edge-liar 7 2 c7a9860a+edge-liar 8 1 7abe8b4e+edge-swap 1 1 04f83540+edge-swap 2 1 a042a582+edge-swap 3 1 15452248+edge-swap 4 1 61fc83b3+edge-swap 5 2 61fc83b3+edge-swap 6 1 c7a9860a+core-01 log-tap 7 delete 8b0e0931+edge-01 net-guard 8 delete 45517a96+edge-01 xfs-fix 3 add 82db4a71+edge-02 net-guard 8 delete 45517a96+edge-02 xfs-fix 3 add 82db4a71+edge-liar net-guard 8 delete 45517a96+edge-liar xfs-fix 3 add 82db4a71+edge-swap net-guard 6 add 04327d1d+edge-swap xfs-fix 3 add 82db4a71+rows 37diff --git a/tools/backend/test/history-base.sql b/tools/backend/test/history-base.sqlnew file mode 100644index 00000000..72e2a50b--- /dev/null+++ b/tools/backend/test/history-base.sql@@ -0,0 +1,180 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- A tree of eight operations, published two at a time, with keepalives+-- whose window is the last two operations, as a node built with a+-- window of 2 sends them: base_seq is the head of the publication before.+-- node_ops records what each node did at every operation as its records+-- arrive, and node_sets what that leaves loaded. Once a window starts past+-- seq 0, check 4 holds base_root against the root stored at base_seq and+-- check 6 takes the upatches applied below the window from node_sets.+-- edge-liar reports a base_root that hides what it applied before its+-- window, and a mask, root and set that agree with that story: only+-- the history shows it, and check 7 compares base_root with its peers'.+-- The contradiction marks the node, and the mark keeps check 4 failing+-- and the history from growing after its window has moved past what the+-- backend stored, until an operator deletes it. edge-swap sends a wider+-- window that starts at the right base_root but calls an operation the+-- history has as applied one whose attach module was not loaded: the+-- roots agree, the code at that seq does not.++INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-long', 1, '1111111111111111111111111111111111111111111111111111111111111111', '', 2, now64(3) - INTERVAL 40 MINUTE),+('fleet-long', 2, '2222222222222222222222222222222222222222222222222222222222222222', '1111111111111111111111111111111111111111111111111111111111111111', 4, now64(3) - INTERVAL 30 MINUTE),+('fleet-long', 3, '3333333333333333333333333333333333333333333333333333333333333333', '2222222222222222222222222222222222222222222222222222222222222222', 6, now64(3) - INTERVAL 20 MINUTE),+('fleet-long', 4, '4444444444444444444444444444444444444444444444444444444444444444', '3333333333333333333333333333333333333333333333333333333333333333', 8, now64(3) - INTERVAL 10 MINUTE);+-- Operations 1 to 3 are those of+-- testing/fixtures/keepalive/tree-1.1.0.json; the digests of the others+-- are made up.+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-long', 1, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', '98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144', '9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6', '59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885', '13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43'),+('fleet-long', 2, 'delete', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', '4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b', 'e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55', 'f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1', '5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b'),+('fleet-long', 3, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', 'b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a', '653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97', '82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf', 'bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc'),+('fleet-long', 4, 'add', 'net-guard', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', '4444444444444444444444444444444444444444444444444444444444444404', '4444444444444444444444444444444444444444444444444444444444444414', 'c1a4ce09e5b1fb14befa6c31b1686c93d65751a5f7882a70ba74ae53eff1c445', 'b5a7fd0926194d53c3c38d9a9f33191d22dbcf421eabb6a095af1b0dda854017'),+('fleet-long', 5, 'add', 'log-tap', '{"labels":{"role":["core"]}}', 'oci://registry.example.com/shirudo/fleet-long', '5555555555555555555555555555555555555555555555555555555555555505', '5555555555555555555555555555555555555555555555555555555555555515', '1c838773b1a663e05f30a70eb492a091cf7edf9e8636c0467bf4c75bc6492b60', '7e7d4e53558bdf3a32dad9b9cb76617d8c4d72df92da85bae8b80ea39dbc8de3'),+('fleet-long', 6, 'add', 'net-guard', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', '6666666666666666666666666666666666666666666666666666666666666606', '6666666666666666666666666666666666666666666666666666666666666616', '04327d1d09b5fd365976ae08b7868ce475c7e05ea06e7953298dc49f0b49a73e', '9482a7501c078b476df790ad7f3d293fc33c8fac98656b942fa9c04066fe6701'),+('fleet-long', 7, 'delete', 'log-tap', '{"labels":{"role":["core"]}}', 'oci://registry.example.com/shirudo/fleet-long', '7777777777777777777777777777777777777777777777777777777777777707', '7777777777777777777777777777777777777777777777777777777777777717', '8b0e09319c7612405a657c8adb8ddae1094224cfe816b63ee7713f982014736b', '48c8470b6db1077529650c52be2eada465d1ec6795565532a79aa0432e268152'),+('fleet-long', 8, 'delete', 'net-guard', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', '8888888888888888888888888888888888888888888888888888888888888808', '8888888888888888888888888888888888888888888888888888888888888818', '45517a96247744dacfcb009e9b9a1393feb7593641b463b8bb60a8bec3a545b2', 'a7e69500fd7613e54bcbd7dccffe0d8a081145e93a59f2230114d08b9c8a81cd');+INSERT INTO shirudo.expected_builds (version_id, note) VALUES+('d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f', 'shirudo 2026.11');++-- The bodies of node A and node B of testing/fixtures/keepalive/ with+-- the tree keys left for each record to fill in.+CREATE TEMPORARY TABLE fixture (name String, body String);+INSERT INTO fixture VALUES+('a', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],@TREE@,"not_ok":0}'),+('b', '{"schema":"shirudo.keepalive/1","boot_id":"9a6f14ea-0cc2-45e1-8e23-7b887120cf54","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"ff2cbeff5d0e9c41a7b36f28d14ce09b73a5182e6fc40d97b5e2a1683c0f7ff8","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":null,"verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],@TREE@,"not_ok":0}');++-- edge-swap is an edge node of its own configuration, so that it has no+-- peers.+INSERT INTO fixture+SELECT 'c', replaceOne(body, '1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807',+ 'cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc')+FROM fixture WHERE name = 'a';++-- The tree keys of each record: an edge node applies every edge+-- operation and passes the core ones over, a core node the other way+-- round. Generation g has its head at 2g and the window starts at 2g - 2.+CREATE TEMPORARY TABLE tree_keys (path String, generation UInt64, base_root String, projection_root String, mask String, set_sha256 String, count UInt64);+INSERT INTO tree_keys VALUES+('edge', 1, '0000000000000000000000000000000000000000000000000000000000000000', 'a042a582b3a3d8c1b633b8ed0356e0b52f1f5aa25af85b06cc3f481562dcda93', 'UA==', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 0),+('edge', 2, 'a042a582b3a3d8c1b633b8ed0356e0b52f1f5aa25af85b06cc3f481562dcda93', '61fc83b3a0ac0db078d815d7a1d5656d1c1b86969c33b2502a9d4553a475f75f', 'UA==', '55fe60cc8e2f809e798c3f733a1186a1a4a5d3c23bafce8278d9f6613fd24f20', 2),+('edge', 3, '61fc83b3a0ac0db078d815d7a1d5656d1c1b86969c33b2502a9d4553a475f75f', 'c7a9860aeaaa41c9b5960ea49d36bf8493829fe711d6ee041615a59e3e4a160b', 'kA==', '39cfdd2bbb3ee01e93c5f663d4f5b416ed5eac60af43d1a88d075b4d352fd352', 2),+('edge', 4, 'c7a9860aeaaa41c9b5960ea49d36bf8493829fe711d6ee041615a59e3e4a160b', '7abe8b4e5b09b24d541e029f0c21b7fddc42088b538544b28874d20820edfcd4', 'kA==', '74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf', 1),+('core', 1, '0000000000000000000000000000000000000000000000000000000000000000', '0000000000000000000000000000000000000000000000000000000000000000', 'oA==', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 0),+('core', 2, '0000000000000000000000000000000000000000000000000000000000000000', '0000000000000000000000000000000000000000000000000000000000000000', 'oA==', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 0),+('core', 3, '0000000000000000000000000000000000000000000000000000000000000000', '7eb926ee3992a1b56d01db3f58713440ca1c7378b02a9c6354e59d2e32cd577f', 'YA==', '885e4806c48d2d850267ee7f714abd8da2bd679483f6d60323fe8499fe8af7f9', 1),+('core', 4, '7eb926ee3992a1b56d01db3f58713440ca1c7378b02a9c6354e59d2e32cd577f', '2b11a79d680e7ebfe4ac646730b29f6247080ecd765d2b1d83538f21f011030a', 'YA==', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 0),+-- An edge node at generation 3 that says it applied nothing before seq 4.+('liar', 3, '0000000000000000000000000000000000000000000000000000000000000000', '78b6a625584ca000a0b7821895cb9441563e4d00f4ec0193ee1395976e16593e', 'kA==', 'fee50b592ea40c6ae2f6ecf6bed6fa2781e1a791e1b9b7a443f2f7f38c6ee650', 1),+-- An edge node at generation 4 with a window from seq 4 that marks seq 6+-- 3 instead of 1.+('swap', 4, '61fc83b3a0ac0db078d815d7a1d5656d1c1b86969c33b2502a9d4553a475f75f', '7abe8b4e5b09b24d541e029f0c21b7fddc42088b538544b28874d20820edfcd4', 'uQ==', '74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf', 1);++-- The records of each round: in round g every node sends its record of+-- generation g, or the one its line names, with its window from+-- 2g - 2 but for edge-swap's at generation 4.+CREATE TEMPORARY TABLE records (round UInt64, host String, body String);+INSERT INTO records+SELECT r.4, r.1,+ replaceOne(f.body, '@TREE@',+ format('"tree_id":"fleet-long","generation":{},"base_seq":{},"last_seq":{},"base_root":"{}","projection_root":"{}","mask":"{}","set_sha256":"{}","count":{}',+ toString(t.generation), toString(if(t.path = 'swap', 4, 2 * t.generation - 2)), toString(2 * t.generation),+ t.base_root, t.projection_root, t.mask, t.set_sha256, toString(t.count)))+FROM (SELECT arrayJoin(arrayFlatten(arrayMap(g -> [+ ('edge-01', 'a', 'edge', g), ('edge-02', 'a', 'edge', g),+ ('edge-liar', 'a', if(g = 3, 'liar', 'edge'), g), ('edge-swap', 'c', if(g = 4, 'swap', 'edge'), g),+ ('core-01', 'b', 'core', g)], range(1, 5)))) AS r) AS x+INNER JOIN fixture AS f ON f.name = r.2+INNER JOIN tree_keys AS t ON t.path = r.3 AND t.generation = r.4;++-- Round 1: windows from seq 0, held against the tree alone.+INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT host, body, 1, concat('000b', host), 'QUtB', 1, 1000 * round FROM records WHERE round = 1;+SYSTEM REFRESH VIEW shirudo.node_ops_mv;+SYSTEM WAIT VIEW shirudo.node_ops_mv;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SELECT 'round 1';+SELECT node_id, status, failed_check, log[4], log[6], log[7] FROM shirudo.node_status ORDER BY node_id;++-- Round 2: base_seq 2, which the history of round 1 reaches.+INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT host, body, 1, concat('000b', host), 'QUtB', 1, 1000 * round FROM records WHERE round = 2;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SYSTEM REFRESH VIEW shirudo.node_ops_mv;+SYSTEM WAIT VIEW shirudo.node_ops_mv;+SELECT 'round 2';+SELECT node_id, status, failed_check, log[4], log[6], log[7] FROM shirudo.node_status ORDER BY node_id;++-- Round 3: edge-liar gives another base_root than its history has, and+-- is marked for it.+INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT host, body, 1, concat('000b', host), 'QUtB', 1, 1000 * round FROM records WHERE round = 3;+SYSTEM REFRESH VIEW shirudo.node_ops_mv;+SYSTEM WAIT VIEW shirudo.node_ops_mv;+SYSTEM REFRESH VIEW shirudo.history_contradictions_mv;+SYSTEM WAIT VIEW shirudo.history_contradictions_mv;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SELECT 'round 3';+SELECT node_id, status, failed_check, log[4], log[6], log[7] FROM shirudo.node_status ORDER BY node_id;++-- Round 4: the window of an edge node no longer holds xfs-fix, which+-- the set still has. edge-liar's window starts past its history, which+-- would be a gap, but its mark stays. edge-swap contradicts its history+-- inside the window, though base_root, the roots and the set agree.+INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT host, body, 1, concat('000b', host), 'QUtB', 1, 1000 * round FROM records WHERE round = 4;+SYSTEM REFRESH VIEW shirudo.node_ops_mv;+SYSTEM WAIT VIEW shirudo.node_ops_mv;+SYSTEM REFRESH VIEW shirudo.history_contradictions_mv;+SYSTEM WAIT VIEW shirudo.history_contradictions_mv;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SELECT 'round 4';+SELECT node_id, status, failed_check, log[4], log[6], log[7] FROM shirudo.node_status ORDER BY node_id;+SELECT 'marks';+SELECT n.node_id, m.tree_id, m.seq, m.reason+FROM shirudo.history_contradictions AS m+INNER JOIN shirudo.node_status AS n ON n.ak_name = m.ak_name+ORDER BY n.node_id;++-- An operator clears both marks, as the backend documentation says.+-- edge-liar's next refresh starts a gap and it passes; edge-swap's+-- record still contradicts its history and marks it again.+DELETE FROM shirudo.history_contradictions WHERE ak_name = '000bedge-liar';+DELETE FROM shirudo.history_contradictions WHERE ak_name = '000bedge-swap';+SYSTEM REFRESH VIEW shirudo.node_ops_mv;+SYSTEM WAIT VIEW shirudo.node_ops_mv;+SYSTEM REFRESH VIEW shirudo.history_contradictions_mv;+SYSTEM WAIT VIEW shirudo.history_contradictions_mv;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SELECT 'cleared';+SELECT node_id, status, failed_check, log[4], log[6], log[7] FROM shirudo.node_status+WHERE node_id IN ('edge-liar', 'edge-swap') ORDER BY node_id;+SELECT 'marks';+SELECT n.node_id, m.tree_id, m.seq, m.reason+FROM shirudo.history_contradictions AS m+INNER JOIN shirudo.node_status AS n ON n.ak_name = m.ak_name+ORDER BY n.node_id;++-- What the backend stored: edge-liar's history stops where its story+-- changed and starts again with a gap once its mark is cleared;+-- edge-swap's stops at seq 6, since its records no longer extend it.+SELECT 'history';+SELECT n.node_id, h.seq, h.code, substring(lower(hex(h.root)), 1, 8)+FROM shirudo.node_ops AS h FINAL+INNER JOIN shirudo.node_status AS n ON n.ak_name = h.ak_name+ORDER BY n.node_id, h.seq;+SELECT n.node_id, s.id, s.last_seq, s.last_op, substring(s.last_payload, 1, 8)+FROM shirudo.node_sets AS s FINAL+INNER JOIN shirudo.node_status AS n ON n.ak_name = s.ak_name+ORDER BY n.node_id, s.id;++-- A refresh that finds nothing new adds nothing.+SYSTEM REFRESH VIEW shirudo.node_ops_mv;+SYSTEM WAIT VIEW shirudo.node_ops_mv;+SELECT 'rows', count() FROM shirudo.node_ops;diff --git a/tools/backend/test/history-gap.expected b/tools/backend/test/history-gap.expectednew file mode 100644index 00000000..d429f427--- /dev/null+++ b/tools/backend/test/history-gap.expected@@ -0,0 +1,26 @@+first seen+edge-late healthy 0 4 chain: pass, root c7a9860a, base unverified (gap) 6 set: set unverified (gap), 2 loaded+edge-quiet healthy 0 4 chain: pass, root a042a582 6 set: pass, 0 loaded+edge-turncoat healthy 0 4 chain: pass, root c7a9860a, base unverified (gap) 6 set: set unverified (gap), 2 loaded+anchored+edge-late healthy 0 4 chain: pass, root c7a9860a, base unverified (gap) 6 set: set unverified (gap), 2 loaded+edge-quiet healthy 0 4 chain: pass, root a042a582 6 set: pass, 0 loaded+edge-turncoat healthy 0 4 chain: pass, root c7a9860a, base unverified (gap) 6 set: set unverified (gap), 2 loaded+next record+edge-late healthy 0 4 chain: pass, root 7abe8b4e 6 set: set unverified (gap), 1 loaded+edge-quiet healthy 0 4 chain: pass, root 7abe8b4e, base unverified (gap) 6 set: set unverified (gap), 1 loaded+edge-turncoat unhealthy 4 4 chain: FAIL, root 78b6a625, base differs from history 6 set: set unverified (gap), 1 loaded+history+edge-late 4 0 61fc83b3+edge-late 5 2 61fc83b3+edge-late 6 1 c7a9860a+edge-late 7 2 c7a9860a+edge-late 8 1 7abe8b4e+edge-quiet 1 1 04f83540+edge-quiet 2 1 a042a582+edge-quiet 6 0 c7a9860a+edge-quiet 7 2 c7a9860a+edge-quiet 8 1 7abe8b4e+edge-turncoat 4 0 61fc83b3+edge-turncoat 5 2 61fc83b3+edge-turncoat 6 1 c7a9860adiff --git a/tools/backend/test/history-gap.sql b/tools/backend/test/history-gap.sqlnew file mode 100644index 00000000..74e36af6--- /dev/null+++ b/tools/backend/test/history-gap.sql@@ -0,0 +1,108 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- The tree of test/history-base.sql, with nodes the backend did not see+-- reach their window. edge-late is first heard from at generation 3,+-- when its window already starts at seq 4: what it did before is not in+-- any record it will send, so check 4 anchors its history at that+-- base_root and check 6 cannot know the upatches it applied below it.+-- Both say so and pass. From its next record on, check 4 verifies the+-- base against the history folded from the anchor, while check 6 stays+-- unverified. edge-quiet was heard from at generation 1 and then not+-- until its window had moved past what it had reported: the same gap,+-- in the middle of its history. edge-turncoat gives another base_root+-- at the anchor than the record that set it.++INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-long', 1, '1111111111111111111111111111111111111111111111111111111111111111', '', 2, now64(3) - INTERVAL 40 MINUTE),+('fleet-long', 2, '2222222222222222222222222222222222222222222222222222222222222222', '1111111111111111111111111111111111111111111111111111111111111111', 4, now64(3) - INTERVAL 30 MINUTE),+('fleet-long', 3, '3333333333333333333333333333333333333333333333333333333333333333', '2222222222222222222222222222222222222222222222222222222222222222', 6, now64(3) - INTERVAL 20 MINUTE),+('fleet-long', 4, '4444444444444444444444444444444444444444444444444444444444444444', '3333333333333333333333333333333333333333333333333333333333333333', 8, now64(3) - INTERVAL 10 MINUTE);+-- Operations 1 to 3 are those of+-- testing/fixtures/keepalive/tree-1.1.0.json; the digests of the others+-- are made up.+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-long', 1, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', '98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144', '9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6', '59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885', '13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43'),+('fleet-long', 2, 'delete', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', '4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b', 'e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55', 'f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1', '5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b'),+('fleet-long', 3, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', 'b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a', '653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97', '82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf', 'bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc'),+('fleet-long', 4, 'add', 'net-guard', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', '4444444444444444444444444444444444444444444444444444444444444404', '4444444444444444444444444444444444444444444444444444444444444414', 'c1a4ce09e5b1fb14befa6c31b1686c93d65751a5f7882a70ba74ae53eff1c445', 'b5a7fd0926194d53c3c38d9a9f33191d22dbcf421eabb6a095af1b0dda854017'),+('fleet-long', 5, 'add', 'log-tap', '{"labels":{"role":["core"]}}', 'oci://registry.example.com/shirudo/fleet-long', '5555555555555555555555555555555555555555555555555555555555555505', '5555555555555555555555555555555555555555555555555555555555555515', '1c838773b1a663e05f30a70eb492a091cf7edf9e8636c0467bf4c75bc6492b60', '7e7d4e53558bdf3a32dad9b9cb76617d8c4d72df92da85bae8b80ea39dbc8de3'),+('fleet-long', 6, 'add', 'net-guard', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', '6666666666666666666666666666666666666666666666666666666666666606', '6666666666666666666666666666666666666666666666666666666666666616', '04327d1d09b5fd365976ae08b7868ce475c7e05ea06e7953298dc49f0b49a73e', '9482a7501c078b476df790ad7f3d293fc33c8fac98656b942fa9c04066fe6701'),+('fleet-long', 7, 'delete', 'log-tap', '{"labels":{"role":["core"]}}', 'oci://registry.example.com/shirudo/fleet-long', '7777777777777777777777777777777777777777777777777777777777777707', '7777777777777777777777777777777777777777777777777777777777777717', '8b0e09319c7612405a657c8adb8ddae1094224cfe816b63ee7713f982014736b', '48c8470b6db1077529650c52be2eada465d1ec6795565532a79aa0432e268152'),+('fleet-long', 8, 'delete', 'net-guard', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', '8888888888888888888888888888888888888888888888888888888888888808', '8888888888888888888888888888888888888888888888888888888888888818', '45517a96247744dacfcb009e9b9a1393feb7593641b463b8bb60a8bec3a545b2', 'a7e69500fd7613e54bcbd7dccffe0d8a081145e93a59f2230114d08b9c8a81cd');+INSERT INTO shirudo.expected_builds (version_id, note) VALUES+('d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f', 'shirudo 2026.11');++-- The bodies of node A and node B of testing/fixtures/keepalive/ with+-- the tree keys left for each record to fill in.+CREATE TEMPORARY TABLE fixture (name String, body String);+INSERT INTO fixture VALUES+('a', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],@TREE@,"not_ok":0}'),+('b', '{"schema":"shirudo.keepalive/1","boot_id":"9a6f14ea-0cc2-45e1-8e23-7b887120cf54","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"ff2cbeff5d0e9c41a7b36f28d14ce09b73a5182e6fc40d97b5e2a1683c0f7ff8","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":null,"verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],@TREE@,"not_ok":0}');++-- The tree keys of each record: an edge node applies every edge+-- operation and passes the core ones over, a core node the other way+-- round. Generation g has its head at 2g and the window starts at 2g - 2.+CREATE TEMPORARY TABLE tree_keys (path String, generation UInt64, base_root String, projection_root String, mask String, set_sha256 String, count UInt64);+INSERT INTO tree_keys VALUES+('edge', 1, '0000000000000000000000000000000000000000000000000000000000000000', 'a042a582b3a3d8c1b633b8ed0356e0b52f1f5aa25af85b06cc3f481562dcda93', 'UA==', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 0),+('edge', 2, 'a042a582b3a3d8c1b633b8ed0356e0b52f1f5aa25af85b06cc3f481562dcda93', '61fc83b3a0ac0db078d815d7a1d5656d1c1b86969c33b2502a9d4553a475f75f', 'UA==', '55fe60cc8e2f809e798c3f733a1186a1a4a5d3c23bafce8278d9f6613fd24f20', 2),+('edge', 3, '61fc83b3a0ac0db078d815d7a1d5656d1c1b86969c33b2502a9d4553a475f75f', 'c7a9860aeaaa41c9b5960ea49d36bf8493829fe711d6ee041615a59e3e4a160b', 'kA==', '39cfdd2bbb3ee01e93c5f663d4f5b416ed5eac60af43d1a88d075b4d352fd352', 2),+('edge', 4, 'c7a9860aeaaa41c9b5960ea49d36bf8493829fe711d6ee041615a59e3e4a160b', '7abe8b4e5b09b24d541e029f0c21b7fddc42088b538544b28874d20820edfcd4', 'kA==', '74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf', 1),+('core', 1, '0000000000000000000000000000000000000000000000000000000000000000', '0000000000000000000000000000000000000000000000000000000000000000', 'oA==', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 0),+('core', 2, '0000000000000000000000000000000000000000000000000000000000000000', '0000000000000000000000000000000000000000000000000000000000000000', 'oA==', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 0),+('core', 3, '0000000000000000000000000000000000000000000000000000000000000000', '7eb926ee3992a1b56d01db3f58713440ca1c7378b02a9c6354e59d2e32cd577f', 'YA==', '885e4806c48d2d850267ee7f714abd8da2bd679483f6d60323fe8499fe8af7f9', 1),+('core', 4, '7eb926ee3992a1b56d01db3f58713440ca1c7378b02a9c6354e59d2e32cd577f', '2b11a79d680e7ebfe4ac646730b29f6247080ecd765d2b1d83538f21f011030a', 'YA==', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 0),+-- An edge node at generation 3 that says it applied nothing before seq 4.+('liar', 3, '0000000000000000000000000000000000000000000000000000000000000000', '78b6a625584ca000a0b7821895cb9441563e4d00f4ec0193ee1395976e16593e', 'kA==', 'fee50b592ea40c6ae2f6ecf6bed6fa2781e1a791e1b9b7a443f2f7f38c6ee650', 1);++-- The records of each round, in the order they are sent.+CREATE TEMPORARY TABLE records (round UInt64, host String, body String);+INSERT INTO records+SELECT r.1, r.2,+ replaceOne(f.body, '@TREE@',+ format('"tree_id":"fleet-long","generation":{},"base_seq":{},"last_seq":{},"base_root":"{}","projection_root":"{}","mask":"{}","set_sha256":"{}","count":{}',+ toString(t.generation), toString(2 * t.generation - 2), toString(2 * t.generation),+ t.base_root, t.projection_root, t.mask, t.set_sha256, toString(t.count)))+FROM (SELECT arrayJoin([+ (1, 'edge-quiet', 'edge', 1),+ (2, 'edge-late', 'edge', 3), (2, 'edge-turncoat', 'edge', 3),+ (3, 'edge-late', 'edge', 4), (3, 'edge-quiet', 'edge', 4), (3, 'edge-turncoat', 'liar', 3)]) AS r) AS x+INNER JOIN fixture AS f ON f.name = 'a'+INNER JOIN tree_keys AS t ON t.path = r.3 AND t.generation = r.4;++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT host, body, 1, concat('000b', host), 'QUtB', 1, 1000 * round FROM records WHERE round = 1;+SYSTEM REFRESH VIEW shirudo.node_ops_mv;+SYSTEM WAIT VIEW shirudo.node_ops_mv;++-- Round 2: first records past seq 0, before and after the history has+-- taken them in.+INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT host, body, 1, concat('000b', host), 'QUtB', 1, 1000 * round FROM records WHERE round = 2;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SELECT 'first seen';+SELECT node_id, status, failed_check, log[4], log[6] FROM shirudo.node_status ORDER BY node_id;+SYSTEM REFRESH VIEW shirudo.node_ops_mv;+SYSTEM WAIT VIEW shirudo.node_ops_mv;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SELECT 'anchored';+SELECT node_id, status, failed_check, log[4], log[6] FROM shirudo.node_status ORDER BY node_id;++-- Round 3: the next records.+INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT host, body, 1, concat('000b', host), 'QUtB', 1, 1000 * round FROM records WHERE round = 3;+SYSTEM REFRESH VIEW shirudo.node_ops_mv;+SYSTEM WAIT VIEW shirudo.node_ops_mv;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SELECT 'next record';+SELECT node_id, status, failed_check, log[4], log[6] FROM shirudo.node_status ORDER BY node_id;++SELECT 'history';+SELECT n.node_id, h.seq, h.code, substring(lower(hex(h.root)), 1, 8)+FROM shirudo.node_ops AS h FINAL+INNER JOIN shirudo.node_status AS n ON n.ak_name = h.ak_name+ORDER BY n.node_id, h.seq;diff --git a/tools/backend/test/ingest-accepted.expected b/tools/backend/test/ingest-accepted.expectednew file mode 100644index 00000000..e3abd703--- /dev/null+++ b/tools/backend/test/ingest-accepted.expected@@ -0,0 +1,95 @@+keepalive+Row 1:+──────+received: 2026-11-11 10:00:00.000+time: 2026-11-11 09:59:59.000000000+host_name: edge-01+quote: q1+ak_name: 000baa+reset_count: 7+clock: 60000+schema: shirudo.keepalive/1+boot_id: 168d20a1-5011-4e1b-9924-d8b73c85aa4e+version_id: d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f+config_root: 1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807+kernel_release: 7.4.2+image_id: fleet-os+image_version: 2026.11.1+image_root: a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c+verdict: ok+cond: 5461+flags: 0+tamper: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7]+tree_id: fleet-base+generation: 3+base_seq: 0+last_seq: 3+base_root: 0000000000000000000000000000000000000000000000000000000000000000+projection_root: 154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1+mask: VA==+set_sha256: 74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf+count: 1+not_ok: 0++Row 2:+──────+received: 2026-11-11 10:00:01.000+time: 2026-11-11 10:00:00.000000000+host_name: core-01+quote: q2+ak_name: 000bbb+reset_count: 2+clock: 500+schema: shirudo.keepalive/1+boot_id: 9a6f14ea-0cc2-45e1-8e23-7b887120cf54+version_id: d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f+config_root: ᴺᵁᴸᴸ+kernel_release: 7.4.2+image_id: ᴺᵁᴸᴸ+image_version: ᴺᵁᴸᴸ+image_root: ᴺᵁᴸᴸ+verdict: init-pending+cond: 5465+flags: 8+tamper: []+tree_id: ᴺᵁᴸᴸ+generation: ᴺᵁᴸᴸ+base_seq: ᴺᵁᴸᴸ+last_seq: ᴺᵁᴸᴸ+base_root: ᴺᵁᴸᴸ+projection_root: ᴺᵁᴸᴸ+mask: ᴺᵁᴸᴸ+set_sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855+count: 0+not_ok: 0+000baa 1912e143044b15f804370b52671c134813c07e7933b7251d13ba3424b0f280d4+000bbb 4ecb6092008ead7a33c0d6194c614db93419350e14f46d4839d2737a6c820167+nodes+000baa QUtB edge-01 2026-11-11 10:00:00.000 untrusted+000bbb QUtC core-01 2026-11-11 10:00:01.000 untrusted+keepalive_latest+000baa 7696581454432 7 60000 edge-01 ok 3 VA== 1+000bbb 2199023256052 2 500 core-01 init-pending \N \N 0+boot_first+000baa 168d20a1-5011-4e1b-9924-d8b73c85aa4e 7696581454432 7+000bbb 9a6f14ea-0cc2-45e1-8e23-7b887120cf54 2199023256052 0+a record sent twice is one row+6 900000 ok+7 30000 reboot-pending+7 60000 ok+7 120000 degraded+the newest record by the quote stays latest+000baa 7696581514432 7 120000 renamed degraded 3+000bbb 2199023256052 2 500 core-01 init-pending \N+a node keeps its first name and its trust+000baa edge-01 2026-11-11 10:00:00.000 untrusted+000bbb core-01 2026-11-11 10:00:01.000 untrusted+each boot keeps its first record+000baa 00000000-0000-4000-8000-000000000006 6597070666656 0+000baa 168d20a1-5011-4e1b-9924-d8b73c85aa4e 7696581424432 3+000bbb 9a6f14ea-0cc2-45e1-8e23-7b887120cf54 2199023256052 0+nothing was rejected+0+a relabelled node keeps everything but its name+000baa QUtB edge-01 2026-11-11 10:00:00.000 untrusted+000bbb QUtC rack-7 2026-11-11 10:00:01.000 untrusteddiff --git a/tools/backend/test/ingest-accepted.sql b/tools/backend/test/ingest-accepted.sqlnew file mode 100644index 00000000..03633830--- /dev/null+++ b/tools/backend/test/ingest-accepted.sql@@ -0,0 +1,68 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- A record inserted into shirudo.checked as the checker passed it lands+-- in keepalive, nodes, keepalive_latest and boot_first, with every field+-- of the body in a column, and boot_first keeps the tamper total of each+-- boot's first record. The first body is that of a node on a tree,+-- the second that of a node that follows none.++-- The records below carry fixed times, long past the retention of+-- shirudo.keepalive.+SYSTEM STOP TTL MERGES shirudo.keepalive;++INSERT INTO shirudo.checked (received, time, host_name, quote, body, ok, ak_name, ak_public, reset_count, clock) VALUES+('2026-11-11 10:00:00', '2026-11-11 09:59:59', 'edge-01', 'q1', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1","mask":"VA==","set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1,"not_ok":0}', 1, '000baa', 'QUtB', 7, 60000),+('2026-11-11 10:00:01', '2026-11-11 10:00:00', 'core-01', 'q2', '{"schema":"shirudo.keepalive/1","boot_id":"9a6f14ea-0cc2-45e1-8e23-7b887120cf54","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":null,"kernel_release":"7.4.2","image_id":null,"image_version":null,"image_root":null,"verdict":"init-pending","cond":5465,"flags":8,"tamper":null,"tree_id":null,"generation":null,"base_seq":null,"last_seq":null,"base_root":null,"projection_root":null,"mask":null,"set_sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","count":0,"not_ok":0,"later_key":1}', 1, '000bbb', 'QUtC', 2, 500);++SELECT 'keepalive';+SELECT * EXCEPT (body) FROM shirudo.keepalive FINAL ORDER BY ak_name FORMAT Vertical;+SELECT ak_name, lower(hex(SHA256(body))) FROM shirudo.keepalive FINAL ORDER BY ak_name;++SELECT 'nodes';+SELECT ak_name, max(ak_public), argMinMerge(node_id), min(first_seen), max(trust)+FROM shirudo.nodes GROUP BY ak_name ORDER BY ak_name;++SELECT 'keepalive_latest';+SELECT ak_name, order_key, reset_count, clock, host_name, verdict, last_seq, mask, count+FROM shirudo.keepalive_latest FINAL ORDER BY ak_name;++SELECT 'boot_first';+SELECT ak_name, boot_id, min(first_order_key), argMinMerge(tamper_first)+FROM shirudo.boot_first GROUP BY ak_name, boot_id ORDER BY ak_name, boot_id;++-- The same node again: a newer record under another host name, the+-- newer record a second time, then an older record of the same boot and+-- one of an earlier boot, both arriving late.+INSERT INTO shirudo.checked (received, host_name, body, ok, ak_name, ak_public, reset_count, clock) VALUES+('2026-11-11 10:01:00', 'renamed', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","verdict":"degraded","last_seq":3,"count":1}', 1, '000baa', 'QUtB', 7, 120000);+INSERT INTO shirudo.checked (received, host_name, body, ok, ak_name, ak_public, reset_count, clock) VALUES+('2026-11-11 10:01:05', 'renamed', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","verdict":"degraded","last_seq":3,"count":1}', 1, '000baa', 'QUtB', 7, 120000);+INSERT INTO shirudo.checked (received, host_name, body, ok, ak_name, ak_public, reset_count, clock) VALUES+('2026-11-11 10:02:00', 'edge-01', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","verdict":"reboot-pending","tamper":[1,0,2],"last_seq":2,"count":1}', 1, '000baa', 'QUtB', 7, 30000);+INSERT INTO shirudo.checked (received, host_name, body, ok, ak_name, ak_public, reset_count, clock) VALUES+('2026-11-11 10:03:00', 'edge-01', '{"schema":"shirudo.keepalive/1","boot_id":"00000000-0000-4000-8000-000000000006","verdict":"ok","last_seq":1,"count":1}', 1, '000baa', 'QUtB', 6, 900000);++SELECT 'a record sent twice is one row';+SELECT reset_count, clock, verdict FROM shirudo.keepalive FINAL WHERE ak_name = '000baa' ORDER BY reset_count, clock;++SELECT 'the newest record by the quote stays latest';+SELECT ak_name, order_key, reset_count, clock, host_name, verdict, last_seq+FROM shirudo.keepalive_latest FINAL ORDER BY ak_name;++SELECT 'a node keeps its first name and its trust';+SELECT ak_name, argMinMerge(node_id), min(first_seen), max(trust)+FROM shirudo.nodes GROUP BY ak_name ORDER BY ak_name;++SELECT 'each boot keeps its first record';+SELECT ak_name, boot_id, min(first_order_key), argMinMerge(tamper_first)+FROM shirudo.boot_first GROUP BY ak_name, boot_id ORDER BY ak_name, min(first_order_key);++SELECT 'nothing was rejected';+SELECT count() FROM shirudo.rejected;++SELECT 'a relabelled node keeps everything but its name';+INSERT INTO shirudo.nodes (ak_name, node_id)+SELECT '000bbb', argMinState('rack-7', toDateTime64(0, 3));+SELECT ak_name, max(ak_public), argMinMerge(node_id), min(first_seen), max(trust)+FROM shirudo.nodes GROUP BY ak_name ORDER BY ak_name;diff --git a/tools/backend/test/ingest-otlp-stub.expected b/tools/backend/test/ingest-otlp-stub.expectednew file mode 100644index 00000000..24e812df--- /dev/null+++ b/tools/backend/test/ingest-otlp-stub.expected@@ -0,0 +1,11 @@+keepalive+good 2026-11-11 10:00:00.000000000 000bcb89b50ad47313877815c714aa19926c4e4f7211dbed37c4e8000df4fb1b81a8 7 60000 168d20a1-5011-4e1b-9924-d8b73c85aa4e ok 1 1+nodes+000bcb89b50ad47313877815c714aa19926c4e4f7211dbed37c4e8000df4fb1b81a8 QUtB good untrusted+rejected+altered body_mismatch 0 0+forged bad_signature 0 0+reordered malformed 0 0+spaced malformed 0 0+unquoted malformed 0 0+wrapped clock_range 000bcb89b50ad47313877815c714aa19926c4e4f7211dbed37c4e8000df4fb1b81a8 16777216 5diff --git a/tools/backend/test/ingest-otlp-stub.sql b/tools/backend/test/ingest-otlp-stub.sqlnew file mode 100644index 00000000..f8383c5f--- /dev/null+++ b/tools/backend/test/ingest-otlp-stub.sql@@ -0,0 +1,40 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- A keepalive written to otel.otel_logs as the collector writes it goes+-- through tpm_quote_check once and on to keepalive or rejected. The+-- quotes are in the form test/stub-quote-check.sh reads, hence the name:+-- test/run.sh skips a test named *-stub when it installs a real checker.++INSERT INTO otel.otel_logs (Timestamp, SeverityText, SeverityNumber, ServiceName, Body, ResourceAttributes, ScopeName, LogAttributes, EventName)+WITH+ '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","verdict":"ok","count":1}' AS body,+ lower(hex(SHA256(body))) AS digest+SELECT '2026-11-11 10:00:00', 'INFO', 9, 'shirudo', record.3,+ map('service.name', 'shirudo', 'host.name', record.1), 'shirudo.keepalive',+ if(record.4 = '', map(), map('shirudo.quote', record.4)), record.2+FROM+(+ SELECT arrayJoin([+ ('good', 'shirudo.keepalive', body, concat('attest=7/60000/', digest, ';sig=good;ak=QUtB')),+ ('altered', 'shirudo.keepalive', replaceOne(body, '"count":1', '"count":2'), concat('attest=7/60001/', digest, ';sig=good;ak=QUtB')),+ ('forged', 'shirudo.keepalive', body, concat('attest=7/60002/', digest, ';sig=AAAA;ak=QUtB')),+ ('reordered', 'shirudo.keepalive', body, concat('sig=good;attest=7/60003/', digest, ';ak=QUtB')),+ ('spaced', 'shirudo.keepalive', body, concat('attest=7/60004/', digest, '; sig=good;ak=QUtB')),+ ('unquoted', 'shirudo.keepalive', body, ''),+ ('wrapped', 'shirudo.keepalive', body, concat('attest=16777216/5/', digest, ';sig=good;ak=QUtB')),+ ('snapshot', 'shirudo.bpf.map.snapshot', body, concat('attest=7/60005/', digest, ';sig=good;ak=QUtB'))+ ]) AS record+);++SELECT 'keepalive';+SELECT host_name, time, ak_name, reset_count, clock, boot_id, verdict, count,+ quote LIKE concat('attest=7/60000/', lower(hex(SHA256(body))), ';%')+FROM shirudo.keepalive FINAL;++SELECT 'nodes';+SELECT ak_name, max(ak_public), argMinMerge(node_id), max(trust)+FROM shirudo.nodes GROUP BY ak_name;++SELECT 'rejected';+SELECT host_name, reason, ak_name, reset_count, clock FROM shirudo.rejected ORDER BY host_name;diff --git a/tools/backend/test/ingest-rejected.expected b/tools/backend/test/ingest-rejected.expectednew file mode 100644index 00000000..c2ca64e9--- /dev/null+++ b/tools/backend/test/ingest-rejected.expected@@ -0,0 +1,14 @@+rejected+2026-11-11 10:00:00.000 bad_signature n1 0 0 q1 {"schema":"shirudo.keepalive/1"}+2026-11-11 10:00:01.000 body_mismatch n2 0 0 q2 {"schema":"shirudo.keepalive/1"}+2026-11-11 10:00:02.000 malformed n3 0 0 q3 {"schema":"shirudo.keepalive/1"}+2026-11-11 10:00:03.000 malformed n4 0 0 q4 {"schema":"shirudo.keepalive/1"}+2026-11-11 10:00:04.000 schema n5 000b05 1 1 q5 {"schema":"shirudo.keepalive/2"}+2026-11-11 10:00:05.000 schema n6 000b06 1 1 q6 not json+2026-11-11 10:00:06.000 clock_range n7 000b07 16777216 1 q7 {"schema":"shirudo.keepalive/1"}+2026-11-11 10:00:07.000 clock_range n8 000b08 1 1099511627776 q8 {"schema":"shirudo.keepalive/1"}+accepted+000b09 16777215 1099511627775+000b09 18446744073709551615+000b09+000b09 18446744073709551615diff --git a/tools/backend/test/ingest-rejected.sql b/tools/backend/test/ingest-rejected.sqlnew file mode 100644index 00000000..d67ce0fa--- /dev/null+++ b/tools/backend/test/ingest-rejected.sql@@ -0,0 +1,31 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- A record the checker refused, one of an unknown schema and one whose+-- counters order_key cannot hold land in shirudo.rejected with their+-- reason, and nowhere else. The largest counters that fit are accepted.++-- The records below carry fixed times, long past the retention of+-- shirudo.keepalive.+SYSTEM STOP TTL MERGES shirudo.keepalive;++INSERT INTO shirudo.checked (received, host_name, quote, body, ok, reason, ak_name, ak_public, reset_count, clock) VALUES+('2026-11-11 10:00:00', 'n1', 'q1', '{"schema":"shirudo.keepalive/1"}', 0, 'bad_signature', '', '', 0, 0),+('2026-11-11 10:00:01', 'n2', 'q2', '{"schema":"shirudo.keepalive/1"}', 0, 'body_mismatch', '', '', 0, 0),+('2026-11-11 10:00:02', 'n3', 'q3', '{"schema":"shirudo.keepalive/1"}', 0, 'malformed', '', '', 0, 0),+('2026-11-11 10:00:03', 'n4', 'q4', '{"schema":"shirudo.keepalive/1"}', 0, '', '', '', 0, 0),+('2026-11-11 10:00:04', 'n5', 'q5', '{"schema":"shirudo.keepalive/2"}', 1, '', '000b05', 'QQ==', 1, 1),+('2026-11-11 10:00:05', 'n6', 'q6', 'not json', 1, '', '000b06', 'QQ==', 1, 1),+('2026-11-11 10:00:06', 'n7', 'q7', '{"schema":"shirudo.keepalive/1"}', 1, '', '000b07', 'QQ==', 16777216, 1),+('2026-11-11 10:00:07', 'n8', 'q8', '{"schema":"shirudo.keepalive/1"}', 1, '', '000b08', 'QQ==', 1, 1099511627776),+('2026-11-11 10:00:08', 'n9', 'q9', '{"schema":"shirudo.keepalive/1"}', 1, '', '000b09', 'QQ==', 16777215, 1099511627775);++SELECT 'rejected';+SELECT received, reason, host_name, ak_name, reset_count, clock, quote, body+FROM shirudo.rejected ORDER BY received;++SELECT 'accepted';+SELECT ak_name, reset_count, clock FROM shirudo.keepalive FINAL;+SELECT ak_name, order_key FROM shirudo.keepalive_latest FINAL;+SELECT ak_name FROM shirudo.nodes FINAL;+SELECT ak_name, first_order_key FROM shirudo.boot_first FINAL;diff --git a/tools/backend/test/kver.expected b/tools/backend/test/kver.expectednew file mode 100644index 00000000..03706d0f--- /dev/null+++ b/tools/backend/test/kver.expected@@ -0,0 +1,33 @@+7.4.2 [7,4,2]+7.4.2-shirudo [7,4,2]+7.4.0-rc3+ [7,4,0]+7.4 [7,4]+7 [7]+6.12.57+deb13-amd64 [6,12,57]+10.0.100.el10 [10,0,100]+7.4.2.1 [7,4,2,1]+7..4 [7]+7.4. [7,4]+.7.4 []+ []+next-20261111 []+ 7.4.2 []+007.04.02 [7,4,2]+7.4294967295.1 [7,4294967295,1]+7.4294967296.1 [7,0,1]+7.99999999999999999999999.1 [7,0,1]+in a range from 7.0 to 7.4.5+6.18.9 0+7.0.0 1+7.0.0-rc1 1+7.4.2 1+7.4.4-shirudo 1+7.4.5 0+7.4.10 0+7.5.1 0+7 0+from 7.5 on+7.4.99 0+7.5.0 1+7.5 1+7.10.0 1diff --git a/tools/backend/test/kver.sql b/tools/backend/test/kver.sqlnew file mode 100644index 00000000..8a4ae367--- /dev/null+++ b/tools/backend/test/kver.sql@@ -0,0 +1,21 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- kver() reads the numbers a kernel release starts with and stops at the+-- first character that continues none. A release that starts with no+-- number is empty, and a number UInt32 cannot hold is 0: neither throws.+-- Arrays compare element by element, a prefix before what extends it,+-- which is what a range of kernel_vulns relies on.++SELECT r, kver(r)+FROM (SELECT arrayJoin(['7.4.2', '7.4.2-shirudo', '7.4.0-rc3+', '7.4', '7', '6.12.57+deb13-amd64', '10.0.100.el10',+ '7.4.2.1', '7..4', '7.4.', '.7.4', '', 'next-20261111', ' 7.4.2', '007.04.02',+ '7.4294967295.1', '7.4294967296.1', '7.99999999999999999999999.1']) AS r);++SELECT 'in a range from 7.0 to 7.4.5';+SELECT r, kver(r) >= [7, 0] AND kver(r) < [7, 4, 5]+FROM (SELECT arrayJoin(['6.18.9', '7.0.0', '7.0.0-rc1', '7.4.2', '7.4.4-shirudo', '7.4.5', '7.4.10', '7.5.1', '7']) AS r);++SELECT 'from 7.5 on';+SELECT r, kver(r) >= [7, 5]+FROM (SELECT arrayJoin(['7.4.99', '7.5.0', '7.5', '7.10.0']) AS r);diff --git a/tools/backend/test/mask-code.expected b/tools/backend/test/mask-code.expectednew file mode 100644index 00000000..a01a8a27--- /dev/null+++ b/tools/backend/test/mask-code.expected@@ -0,0 +1,9 @@+QA== [1]+gA== [2]+VA== [1,1,1,0]+qA== [2,2,2,0]+WdlZAA== [1,1,2,1,3,1,2,1,1,1,2,1,0,0,0,0]+ [0]+VA== [1,1,1,0,0,0]+not base64 [0,0,0,0]+\Ndiff --git a/tools/backend/test/mask-code.sql b/tools/backend/test/mask-code.sqlnew file mode 100644index 00000000..da118726--- /dev/null+++ b/tools/backend/test/mask-code.sql@@ -0,0 +1,16 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- mask_code reads the outcome pair of one operation from a mask: the masks+-- of the example, the 16-operation mask of the record page, and what must+-- not stop a refresh: an index past the mask, a mask that is not base64+-- and no mask.++SELECT mask, arrayMap(i -> mask_code(mask, i), range(count)) AS codes+FROM+(+ SELECT arrayJoin([('QA==', 1), ('gA==', 1), ('VA==', 4), ('qA==', 4), ('WdlZAA==', 16), ('', 1),+ ('VA==', 6), ('not base64', 4)]) AS vector,+ vector.1 AS mask, vector.2 AS count+);+SELECT mask_code(CAST(NULL AS Nullable(String)), 0);diff --git a/tools/backend/test/retention-boot.expected b/tools/backend/test/retention-boot.expectednew file mode 100644index 00000000..bd91532a--- /dev/null+++ b/tools/backend/test/retention-boot.expected@@ -0,0 +1,10 @@+boot_first after forty days+long-boot 00000000-0000-4000-8000-00000000000a 3 1+rebooted 00000000-0000-4000-8000-00000000000c 0 1+silent 00000000-0000-4000-8000-00000000000d 4 1+check 3 today+long-boot unhealthy 3 3 reported: FAIL, verdict ok, cond 0x1555, flags 0, tamper +2, build d6d918ad+lost-baseline unhealthy 3 3 reported: FAIL, verdict ok, cond 0x1555, flags 0, tamper +2, build d6d918ad+lost-baseline-at-zero healthy 0 3 reported: pass, verdict ok, cond 0x1555, flags 0, tamper +0, build d6d918ad+rebooted healthy 0 3 reported: pass, verdict ok, cond 0x1555, flags 0, tamper +0, build d6d918ad+silent healthy 0 3 reported: pass, verdict ok, cond 0x1555, flags 0, tamper +0, build d6d918addiff --git a/tools/backend/test/retention-boot.sql b/tools/backend/test/retention-boot.sqlnew file mode 100644index 00000000..ac4f06bf--- /dev/null+++ b/tools/backend/test/retention-boot.sql@@ -0,0 +1,86 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- shirudo.boot_first drops a boot's row boot_first_retention_seconds,+-- thirty days by default, after the boot was last used, and a boot that+-- is its node's current one is used at every refresh of+-- shirudo.boot_first_keep_mv. So the baseline of a boot that has run for+-- forty days is still its first record's, and a rise since then fails+-- check 3; the same holds for a node that was silent all that time. The+-- row of a boot the node has left is gone. Should a baseline be lost all+-- the same, check 3 compares with zero, where the counters start: a+-- total above zero fails rather than passing as the new baseline.+--+-- Rows forty days old are past their TTL when this test inserts them,+-- which a refresh would have prevented in time, so TTL merges are+-- stopped until the refresh has run.++SYSTEM STOP TTL MERGES shirudo.boot_first;++-- The publication of testing/fixtures/keepalive/tree-1.1.0.json, as the+-- ingest job loads it: generation 3 with its three operations.+INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-base', 3, '1f327364233e3f2dcebcd13c0af8d84f886201531b135294bd7356a2f7ed680b', '4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942', 3, now64(3) - INTERVAL 10 MINUTE);+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-base', 1, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144', '9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6', '59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885', '13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43'),+('fleet-base', 2, 'delete', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b', 'e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55', 'f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1', '5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b'),+('fleet-base', 3, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', 'b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a', '653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97', '82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf', 'bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc');+INSERT INTO shirudo.expected_builds (version_id, note) VALUES+('d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f', 'shirudo 2026.11');++-- The bodies of testing/fixtures/keepalive/, byte for byte.+CREATE TEMPORARY TABLE fixture (name String, body String);+INSERT INTO fixture VALUES+('node-a-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1","mask":"VA==","set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1,"not_ok":0}');+++CREATE TEMPORARY TABLE record (host String, boot String, reset_count UInt64, clock UInt64, age_days UInt32, tamper UInt64);++INSERT INTO record VALUES+('long-boot', '00000000-0000-4000-8000-00000000000a', 1, 1000, 40, 3),+('rebooted', '00000000-0000-4000-8000-00000000000b', 1, 1000, 40, 1),+('rebooted', '00000000-0000-4000-8000-00000000000c', 2, 1000, 35, 0),+('silent', '00000000-0000-4000-8000-00000000000d', 1, 1000, 40, 4);++INSERT INTO shirudo.checked (received, host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT now64(3) - INTERVAL r.age_days DAY, r.host,+ replaceOne(replaceOne(f.body, '168d20a1-5011-4e1b-9924-d8b73c85aa4e', r.boot),+ '"tamper":[0,', concat('"tamper":[', toString(r.tamper), ',')),+ 1, concat('000b', r.host), 'QUtB', r.reset_count, r.clock+FROM record AS r, fixture AS f;++SYSTEM REFRESH VIEW shirudo.boot_first_keep_mv;+SYSTEM WAIT VIEW shirudo.boot_first_keep_mv;+SYSTEM START TTL MERGES shirudo.boot_first;+OPTIMIZE TABLE shirudo.boot_first FINAL;++SELECT 'boot_first after forty days';+SELECT substring(ak_name, 5), boot_id, argMinMerge(tamper_first), max(last_used) > now() - INTERVAL 1 HOUR+FROM shirudo.boot_first GROUP BY ak_name, boot_id ORDER BY ak_name, boot_id;++-- Today's records: one counter of the long boot is up by two, the silent+-- node is back with the total it had, and two nodes start a boot with a+-- total of two and of zero.+TRUNCATE TABLE record;+INSERT INTO record VALUES+('long-boot', '00000000-0000-4000-8000-00000000000a', 1, 2000, 0, 5),+('rebooted', '00000000-0000-4000-8000-00000000000c', 2, 2000, 0, 0),+('silent', '00000000-0000-4000-8000-00000000000d', 1, 2000, 0, 4),+('lost-baseline', '00000000-0000-4000-8000-00000000000e', 1, 2000, 0, 2),+('lost-baseline-at-zero', '00000000-0000-4000-8000-00000000000f', 1, 2000, 0, 0);++INSERT INTO shirudo.checked (received, host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT now64(3) - INTERVAL r.age_days DAY, r.host,+ replaceOne(replaceOne(f.body, '168d20a1-5011-4e1b-9924-d8b73c85aa4e', r.boot),+ '"tamper":[0,', concat('"tamper":[', toString(r.tamper), ',')),+ 1, concat('000b', r.host), 'QUtB', r.reset_count, r.clock+FROM record AS r, fixture AS f;++-- What an expired baseline leaves: no row for the boot.+DELETE FROM shirudo.boot_first WHERE ak_name LIKE '000blost-baseline%';++SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;++SELECT 'check 3 today';+SELECT node_id, status, failed_check, log[3] FROM shirudo.node_status ORDER BY node_id;diff --git a/tools/backend/test/retention-refused.expected b/tools/backend/test/retention-refused.expectednew file mode 100644index 00000000..39c3456c--- /dev/null+++ b/tools/backend/test/retention-refused.expected@@ -0,0 +1,12 @@+apply-retention.sh: boot_first_retention_seconds is "3600", need a number of seconds of at least 86400+keepalive 7200, boot_first 3600: status 1+boot_first TTL last_used + toIntervalSecond(2592000)+keepalive TTL toDateTime(received) + toIntervalSecond(3600)+apply-retention.sh: keepalive_retention_seconds is "0", need a number of seconds above 0+keepalive 0, boot_first 5184000: status 1+boot_first TTL last_used + toIntervalSecond(2592000)+keepalive TTL toDateTime(received) + toIntervalSecond(3600)+keepalive 7200, boot_first 86400: status 0+boot_first TTL last_used + toIntervalSecond(86400)+keepalive TTL toDateTime(received) + toIntervalSecond(7200)+7200 86400diff --git a/tools/backend/test/retention-refused.sh b/tools/backend/test/retention-refused.shnew file mode 100644index 00000000..cb5f5e5d--- /dev/null+++ b/tools/backend/test/retention-refused.sh@@ -0,0 +1,38 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# sql/apply-retention.sh refuses a retention it cannot apply safely and+# then changes neither table, not even the one whose own value was good:+# 0 for shirudo.keepalive, and less than a day for shirudo.boot_first,+# whose current baselines are written again only once an hour. A day is+# applied.++set -eu++test=$(cd "$(dirname "$0")" && pwd)++query()+{+ # shellcheck disable=SC2086 # a command with its options, to be split+ $CLICKHOUSE_CLIENT --query "$1" </dev/null+}++try()+{+ query "INSERT INTO shirudo.settings+ (stale_seconds, stuck_seconds, window, keepalive_retention_seconds,+ boot_first_retention_seconds)+ VALUES (180, 3600, 512, $1, $2)"+ status=0+ # shellcheck disable=SC2086+ "$test/../sql/apply-retention.sh" $CLICKHOUSE_CLIENT 2>&1 || status=$?+ printf 'keepalive %s, boot_first %s: status %d\n' "$1" "$2" "$status"+ query "SELECT name, extract(engine_full, 'TTL .*\\\\)') FROM system.tables+ WHERE database = 'shirudo' AND name IN ('boot_first', 'keepalive')+ ORDER BY name"+}++try 7200 3600+try 0 5184000+try 7200 86400diff --git a/tools/backend/test/retention-refused.sql b/tools/backend/test/retention-refused.sqlnew file mode 100644index 00000000..5b11611d--- /dev/null+++ b/tools/backend/test/retention-refused.sql@@ -0,0 +1,8 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- test/retention-refused.sh has shown what sql/apply-retention.sh refuses+-- and what each run left of the two TTLs. The settings keep what the+-- operator wrote last, applied or not.++SELECT keepalive_retention_seconds, boot_first_retention_seconds FROM shirudo.settings FINAL;diff --git a/tools/backend/test/retention.expected b/tools/backend/test/retention.expectednew file mode 100644index 00000000..0f431ea3--- /dev/null+++ b/tools/backend/test/retention.expected@@ -0,0 +1,10 @@+120 5184000+boot_first TTL last_used + toIntervalSecond(5184000)+keepalive TTL toDateTime(received) + toIntervalSecond(120)+keepalive+2 00000000-0000-4000-8000-000000000002+keepalive_latest+2 00000000-0000-4000-8000-000000000002+boot_first+00000000-0000-4000-8000-000000000001 5+00000000-0000-4000-8000-000000000002 0diff --git a/tools/backend/test/retention.setup.sql b/tools/backend/test/retention.setup.sqlnew file mode 100644index 00000000..dc566427--- /dev/null+++ b/tools/backend/test/retention.setup.sql@@ -0,0 +1,11 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- The settings test/retention.sql wants in place when the runner applies+-- the retention: two minutes instead of the default hour for+-- shirudo.keepalive, sixty days instead of the default thirty for+-- shirudo.boot_first.++INSERT INTO shirudo.settings (stale_seconds, stuck_seconds, window, keepalive_retention_seconds,+ boot_first_retention_seconds)+VALUES (180, 3600, 512, 120, 5184000);diff --git a/tools/backend/test/retention.sql b/tools/backend/test/retention.sqlnew file mode 100644index 00000000..1dd8f7fb--- /dev/null+++ b/tools/backend/test/retention.sql@@ -0,0 +1,33 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- sql/apply-retention.sh gives shirudo.keepalive and shirudo.boot_first+-- the retention of shirudo.settings, which test/retention.setup.sql set+-- to two minutes and to sixty days before the runner applied it. A+-- record older than two minutes leaves keepalive and stays where the+-- checks read: keepalive_latest and boot_first.++SELECT keepalive_retention_seconds, boot_first_retention_seconds FROM shirudo.settings FINAL;+SELECT name, extract(engine_full, 'TTL .*\\)') FROM system.tables+WHERE database = 'shirudo' AND name IN ('boot_first', 'keepalive')+ORDER BY name;++INSERT INTO shirudo.checked (received, host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT now64(3) - record.1, 'edge-01',+ concat('{"schema":"shirudo.keepalive/1","boot_id":"', record.2, '","tamper":[', toString(record.4), ']}'),+ 1, '000baa', 'QUtB', record.3, 1000+FROM+(+ SELECT arrayJoin([+ (600, '00000000-0000-4000-8000-000000000001', 1, 5),+ (10, '00000000-0000-4000-8000-000000000002', 2, 0)+ ]) AS record+);+OPTIMIZE TABLE shirudo.keepalive FINAL;++SELECT 'keepalive';+SELECT reset_count, boot_id FROM shirudo.keepalive FINAL ORDER BY reset_count;+SELECT 'keepalive_latest';+SELECT reset_count, boot_id FROM shirudo.keepalive_latest FINAL ORDER BY reset_count;+SELECT 'boot_first';+SELECT boot_id, argMinMerge(tamper_first) FROM shirudo.boot_first GROUP BY ak_name, boot_id ORDER BY boot_id;diff --git a/tools/backend/test/run.sh b/tools/backend/test/run.shnew file mode 100755index 00000000..233a9d22--- /dev/null+++ b/tools/backend/test/run.sh@@ -0,0 +1,177 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# test/run.sh -- run the SQL tests against a ClickHouse container of its+# own, at the image testing/vm/stack-lib.sh pins.+#+# test/run.sh [<name>...]+#+# Each test is test/<name>.sql with the output it must print in+# test/<name>.expected. Every test starts from an empty schema, loaded+# from sql/, as an installation loads it: the files in order, then+# sql/apply-retention.sh. A test of what that script applies puts the+# settings it wants in test/<name>.setup.sql, which runs between the two.+# A test that has a test/<name>.sh runs it next, with CLICKHOUSE_CLIENT+# naming the client of the test's server, as the jobs under jobs/ read+# it; what the script prints comes before the output of the SQL in+# test/<name>.expected, and a script that fails fails the test. A+# script that exits with status 77 skips the test, and the first line it+# printed says why.+# Without names, all tests run. A test named <name>-stub+# depends on the answers of test/stub-quote-check.sh and is skipped when+# SHIRUDO_QUOTE_CHECK names another checker.+#+# SHIRUDO_QUOTE_CHECK the shirudo-quote-check program to install as+# tpm_quote_check; it has to run inside the+# container. Default: test/stub-quote-check.sh.+# CONTAINER_RUNTIME docker or podman. Default: the first one found.+# CLICKHOUSE_IMAGE another image than the pinned one.++set -eu++CLICKHOUSE_IMAGE=${CLICKHOUSE_IMAGE:-docker.io/clickhouse/clickhouse-server@sha256:d426d2f612e1e189c90f9a3f8dcd85a03c6851273833817a296bb327e63aa7a7}++repo=$(cd "$(dirname "$0")/.." && pwd)+checker=${SHIRUDO_QUOTE_CHECK:-$repo/test/stub-quote-check.sh}+container=shirudo-backend-test-$$+work=++die()+{+ printf 'run.sh: %s\n' "$1" >&2+ exit 2+}++cleanup()+{+ "$runtime" rm -fv "$container" >/dev/null 2>&1 || :+ [ -z "$work" ] || rm -rf "$work"+}++client()+{+ "$runtime" exec -i "$container" clickhouse-client "$@"+}++wait_for()+{+ attempt=0+ until client --query "$1" 2>/dev/null | grep -q .; do+ attempt=$((attempt + 1))+ if [ "$attempt" -ge 150 ]; then+ "$runtime" logs "$container" >&2 || :+ die "$2"+ fi+ sleep 0.2+ done+}++load_schema()+{+ client --query 'DROP DATABASE IF EXISTS shirudo SYNC' &&+ client --query 'DROP DATABASE IF EXISTS otel SYNC' || return 1+ for file in "$repo"/sql/*.sql; do+ client <"$file" || return 1+ done+ if [ -f "$repo/test/$1.setup.sql" ]; then+ client <"$repo/test/$1.setup.sql" || return 1+ fi+ "$repo/sql/apply-retention.sh" \+ "$runtime" exec -i "$container" clickhouse-client+}++run_step()+{+ [ -f "$repo/test/$1.sh" ] || return 0+ CLICKHOUSE_CLIENT="$runtime exec -i $container clickhouse-client" \+ sh "$repo/test/$1.sh" >"$work/out" 2>>"$work/log"+}++run_test()+{+ : >"$work/out"+ step=0+ if load_schema "$1" >"$work/log" 2>&1; then+ run_step "$1" || step=$?+ else+ step=1+ fi+ if [ "$step" -eq 77 ]; then+ printf 'skip %s (%s)\n' "$1" "$(head -n 1 "$work/out")"+ return 0+ fi+ if [ "$step" -eq 0 ] &&+ client <"$repo/test/$1.sql" >>"$work/out" 2>>"$work/log" &&+ diff -u "$repo/test/$1.expected" "$work/out" >>"$work/log"; then+ printf 'ok %s\n' "$1"+ return 0+ fi+ printf 'not ok %s\n' "$1"+ sed 's/^/ /' "$work/log"+ return 1+}++if [ -n "${CONTAINER_RUNTIME:-}" ]; then+ runtime=$CONTAINER_RUNTIME+elif command -v docker >/dev/null 2>&1; then+ runtime=docker+elif command -v podman >/dev/null 2>&1; then+ runtime=podman+else+ die 'needs docker or podman'+fi+[ -f "$checker" ] || die "no quote checker at $checker"++if [ $# -eq 0 ]; then+ for file in "$repo"/test/*.sql; do+ name=${file##*/}+ case "$name" in+ *.setup.sql) continue ;;+ esac+ set -- "$@" "${name%.sql}"+ done+fi+for name in "$@"; do+ [ -f "$repo/test/$name.sql" ] || die "no test/$name.sql"+ [ -f "$repo/test/$name.expected" ] || die "no test/$name.expected"+done++trap cleanup EXIT+trap 'exit 2' HUP INT TERM+work=$(mktemp -d)++"$runtime" run -d --name "$container" -e CLICKHOUSE_SKIP_USER_SETUP=1 \+ "$CLICKHOUSE_IMAGE" >/dev/null || die "cannot start $CLICKHOUSE_IMAGE"+wait_for 'SELECT 1' 'ClickHouse did not start'++# The server picks the function up from its configuration directory and+# the program from user_scripts, where an installation puts them too.+cp "$checker" "$work/shirudo-quote-check"+chmod 0755 "$work/shirudo-quote-check"+"$runtime" exec "$container" mkdir -p /var/lib/clickhouse/user_scripts+"$runtime" cp "$work/shirudo-quote-check" \+ "$container:/var/lib/clickhouse/user_scripts/shirudo-quote-check"+"$runtime" cp "$repo/clickhouse/tpm_quote_check_function.xml" \+ "$container:/etc/clickhouse-server/tpm_quote_check_function.xml"+client --query 'SYSTEM RELOAD FUNCTIONS'+wait_for "SELECT 1 FROM system.functions WHERE name = 'tpm_quote_check'" \+ 'tpm_quote_check was not loaded'++failed=0+for name in "$@"; do+ case "$name" in+ *-stub)+ if [ -n "${SHIRUDO_QUOTE_CHECK:-}" ]; then+ printf 'skip %s (needs the stub checker)\n' "$name"+ continue+ fi ;;+ esac+ run_test "$name" || failed=$((failed + 1))+done++if [ "$failed" -ne 0 ]; then+ printf '%d of %d tests failed\n' "$failed" "$#"+ exit 1+fi+printf 'no test failed\n'diff --git a/tools/backend/test/sbom-scan-s3.expected b/tools/backend/test/sbom-scan-s3.expectednew file mode 100644index 00000000..4c49490e--- /dev/null+++ b/tools/backend/test/sbom-scan-s3.expected@@ -0,0 +1,23 @@+stub-aws: s3 cp --recursive --only-show-errors s3://fleet-images/sboms <directory> --exclude * --include */image.json --include */sbom.cdx.json+sbom-scan: fleet-os/2026.11.1/a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c: ok, components: 4, findings: 2, of kernel packages left out: 3+sbom-scan: fleet-os/2026.11.6/-: ok, components: 2, findings: 0+sbom-scan: loaded images: 2, findings: 2+rows: 2+stub-aws: s3 cp --recursive --only-show-errors s3://fleet-images/sboms <directory> --exclude * --include */image.json --include */sbom.cdx.json+sbom-scan: cannot copy s3://fleet-images/sboms, nothing loaded+copy fails: status 1+sbom-scan: the store https://registry.example.com/sboms is neither file://<directory> nor s3://<bucket>+https store: status 1+sbom-scan: the store s3:// is neither file://<directory> nor s3://<bucket>+empty s3 store: status 1+usage: sbom-scan [--store <url>] [--trivy <path>] [--cache-dir <dir>]+no store: status 2+sbom-scan: no store directory no-such-store+no directory: status 1+sbom-scan: trivy version failed, nothing loaded+no version: status 1+rows: 2+fleet-os 2026.11.1 a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c cyclonedx-json fd2407ebf451915ddb23cd4cabd3cee23db62e7f1d7a81c8c3cfb3b1c48596e4 ok 2026-11-11T06:00:00Z+fleet-os 2026.11.6 cyclonedx-json d89d4d8966a7264023fb306de62ee1b5a40e6376dfffec4b59d0774fb988f333 ok 2026-11-11T06:00:00Z+fd2407ebf451915ddb23cd4cabd3cee23db62e7f1d7a81c8c3cfb3b1c48596e4 EXAMPLE-0202 openssl+fd2407ebf451915ddb23cd4cabd3cee23db62e7f1d7a81c8c3cfb3b1c48596e4 EXAMPLE-0505 zlibdiff --git a/tools/backend/test/sbom-scan-s3.sh b/tools/backend/test/sbom-scan-s3.shnew file mode 100644index 00000000..e57aa5b0--- /dev/null+++ b/tools/backend/test/sbom-scan-s3.sh@@ -0,0 +1,59 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# jobs/sbom-scan over an s3:// store, with test/stub-aws.sh in place of+# the AWS command line: the job copies the objects it reads and scans+# them as it does a file:// store. Then what it refuses, each with a+# message and without loading anything: a copy that fails, a store of+# another kind or none, a file:// directory that is not there and a+# matcher that cannot say its version.++set -eu++test=$(cd "$(dirname "$0")" && pwd)+job=$test/../jobs/sbom-scan+root=a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c+unset SBOM_STORE TRIVY TRIVY_CACHE_DIR S3_CLIENT++work=$(mktemp -d)+trap 'rm -rf "$work"' EXIT+images=$work/s3/fleet-images/sboms/fleet-os+mkdir -p "$images/2026.11.1" "$images/2026.11.6"+cp -R "$test/sbom-store/fleet-os/2026.11.1/$root" "$images/2026.11.1/"+cp -R "$test/sbom-store/fleet-os/2026.11.6/-" "$images/2026.11.6/"+echo 'not read' >"$images/2026.11.6/-/build.log"++export STUB_S3_ROOT="$work/s3" S3_CLIENT="$test/stub-aws.sh"+"$job" --store s3://fleet-images/sboms --trivy "$test/stub-trivy.sh" 2>&1++rows()+{+ # shellcheck disable=SC2086 # a command with its options, to be split+ printf 'rows: %s\n' "$($CLICKHOUSE_CLIENT --query \+ 'SELECT count() FROM shirudo.sbom_images' </dev/null)"+}++# refused <what> <expected status> <command>...+refused()+{+ what=$1+ expected=$2+ shift 2+ status=0+ "$@" 2>&1 || status=$?+ printf '%s: status %d\n' "$what" "$status"+ [ "$status" -eq "$expected" ]+}++rows+refused 'copy fails' 1 env STUB_S3_STATUS=1 "$job" \+ --store s3://fleet-images/sboms --trivy "$test/stub-trivy.sh"+refused 'https store' 1 "$job" --store https://registry.example.com/sboms \+ --trivy "$test/stub-trivy.sh"+refused 'empty s3 store' 1 "$job" --store s3:// --trivy "$test/stub-trivy.sh"+refused 'no store' 2 "$job" --trivy "$test/stub-trivy.sh"+refused 'no directory' 1 "$job" --store file://no-such-store \+ --trivy "$test/stub-trivy.sh"+refused 'no version' 1 "$job" --store "file://$work/s3/fleet-images/sboms" --trivy false+rowsdiff --git a/tools/backend/test/sbom-scan-s3.sql b/tools/backend/test/sbom-scan-s3.sqlnew file mode 100644index 00000000..bfb925b8--- /dev/null+++ b/tools/backend/test/sbom-scan-s3.sql@@ -0,0 +1,11 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- What jobs/sbom-scan loaded from the s3:// store in+-- test/sbom-scan-s3.sh: its two images, as from a file:// store, and the+-- findings of the one that has some. The runs it refused added nothing.++SELECT image_id, image_version, image_root, sbom_format, sbom_sha256, state, db_version+FROM shirudo.sbom_images FINAL+ORDER BY image_id, image_version, image_root;+SELECT sbom_sha256, vuln_id, package FROM shirudo.sbom_vulns ORDER BY vuln_id, package;diff --git a/tools/backend/test/sbom-scan-trivy.expected b/tools/backend/test/sbom-scan-trivy.expectednew file mode 100644index 00000000..af484b96--- /dev/null+++ b/tools/backend/test/sbom-scan-trivy.expected@@ -0,0 +1,4 @@+scanned with trivy+2026.11.1 ok 1+findings of another SBOM 0+kernel findings 0diff --git a/tools/backend/test/sbom-scan-trivy.sh b/tools/backend/test/sbom-scan-trivy.shnew file mode 100644index 00000000..a849b192--- /dev/null+++ b/tools/backend/test/sbom-scan-trivy.sh@@ -0,0 +1,38 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# jobs/sbom-scan with the real Trivy as the matcher, on the first image+# of test/sbom-store. Its findings depend on the advisory database, so+# the test asserts what does not: the image is loaded ok, with the+# database's version, and no finding is of a kernel package. It needs+# trivy on the host and SBOM_TRIVY_CACHE, a Trivy cache directory that+# holds a pinned database, which the job never updates; without either+# it is skipped, as it is in CI, which caches no database.++set -eu++test=$(cd "$(dirname "$0")" && pwd)+job=$test/../jobs/sbom-scan+root=a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c+unset SBOM_STORE TRIVY TRIVY_CACHE_DIR S3_CLIENT++if ! command -v trivy >/dev/null 2>&1; then+ echo 'needs trivy on the host'+ exit 77+fi+if [ -z "${SBOM_TRIVY_CACHE:-}" ] || [ ! -d "$SBOM_TRIVY_CACHE/db" ]; then+ echo 'needs SBOM_TRIVY_CACHE, a Trivy cache with a pinned database; CI caches none'+ exit 77+fi++work=$(mktemp -d)+trap 'rm -rf "$work"' EXIT+mkdir -p "$work/store/fleet-os/2026.11.1"+cp -R "$test/sbom-store/fleet-os/2026.11.1/$root" "$work/store/fleet-os/2026.11.1/"++"$job" --store "file://$work/store" --cache-dir "$SBOM_TRIVY_CACHE" >"$work/out" 2>&1 || {+ cat "$work/out"+ exit 1+}+echo 'scanned with trivy'diff --git a/tools/backend/test/sbom-scan-trivy.sql b/tools/backend/test/sbom-scan-trivy.sqlnew file mode 100644index 00000000..579c9b21--- /dev/null+++ b/tools/backend/test/sbom-scan-trivy.sql@@ -0,0 +1,13 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- What jobs/sbom-scan loaded with the real Trivy in+-- test/sbom-scan-trivy.sh, as far as it does not depend on the advisory+-- database: the image is ok and names the database it was scanned with,+-- and every finding is of the image's SBOM and none of a kernel package.++SELECT image_version, state, db_version != '' FROM shirudo.sbom_images FINAL;+SELECT 'findings of another SBOM', countIf(sbom_sha256 != 'fd2407ebf451915ddb23cd4cabd3cee23db62e7f1d7a81c8c3cfb3b1c48596e4')+FROM shirudo.sbom_vulns;+SELECT 'kernel findings', countIf(match(package, '^(linux-image-|kernel$|kernel-core$)'))+FROM shirudo.sbom_vulns;diff --git a/tools/backend/test/sbom-scan.expected b/tools/backend/test/sbom-scan.expectednew file mode 100644index 00000000..148f1889--- /dev/null+++ b/tools/backend/test/sbom-scan.expected@@ -0,0 +1,49 @@+sbom-scan: fleet-os/2026.11.1/image.json is not <image_id>/<image_version>/<image_root or ->/image.json, left out+sbom-scan: fleet-os/2026.11.12/not-a-root/image.json is not <image_id>/<image_version>/<image_root or ->/image.json, left out+sbom-scan: fleet-os/2026.11.11/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: trivy sbom failed, not loaded:+ FATAL stub: the scan failed+sbom-scan: fleet-os/2026.11.10/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: the matcher's report is refused, not loaded: a vulnerability of the report has no PkgName+sbom-scan: fleet-os/2026.11.1/a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c: ok, components: 4, findings: 2, of kernel packages left out: 3+sbom-scan: fleet-os/2026.11.13/-: ok, components: 4, findings: 2, of kernel packages left out: 3, the SBOM of fleet-os/2026.11.1/a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c+sbom-scan: fleet-os/2026.11.2/-: missing, no sbom.cdx.json+sbom-scan: fleet-os/2026.11.3/3333333333333333333333333333333333333333333333333333333333333333: hash_mismatch, the SHA-256 of sbom.cdx.json is not sbom_sha256+sbom-scan: fleet-os/2026.11.4/4444444444444444444444444444444444444444444444444444444444444444: parse_error, bomFormat of sbom.cdx.json is not "CycloneDX"+sbom-scan: fleet-os/2026.11.5/5555555555555555555555555555555555555555555555555555555555555555: unsupported_format, sbom_format "spdx-json" has no reader+sbom-scan: fleet-os/2026.11.6/-: ok, components: 2, findings: 0+sbom-scan: fleet-os/2026.11.7/7777777777777777777777777777777777777777777777777777777777777777: parse_error, sbom.cdx.json is not a JSON value+sbom-scan: fleet-os/2026.11.8/8888888888888888888888888888888888888888888888888888888888888888: parse_error, image.json is not a JSON value+sbom-scan: fleet-os/2026.11.9/-: parse_error, image_version of image.json is not the one of its path+sbom-scan: loaded images: 10, findings: 2+first run: status 1+stub-trivy: version --format json+stub-trivy: sbom --format json --skip-db-update --quiet 1.sbom.cdx.json+stub-trivy: sbom --format json --skip-db-update --quiet 2.sbom.cdx.json+stub-trivy: sbom --format json --skip-db-update --quiet 3.sbom.cdx.json+stub-trivy: sbom --format json --skip-db-update --quiet 4.sbom.cdx.json+stub-trivy: sbom --format json --skip-db-update --quiet 9.sbom.cdx.json+sbom-scan: fleet-os/2026.11.1/a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c: ok, components: 4, findings: 2, of kernel packages left out: 3+sbom-scan: loaded images: 1, findings: 2+second run: status 0+stub-trivy: version --format json --cache-dir /var/cache/trivy-test+stub-trivy: sbom --format json --cache-dir /var/cache/trivy-test --skip-db-update --quiet 1.sbom.cdx.json+sbom_images+fleet-os 2026.11.1 a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c cyclonedx-json fd2407ebf451915ddb23cd4cabd3cee23db62e7f1d7a81c8c3cfb3b1c48596e4 ok 2026-11-02 08:00:00 2026-11-11T06:00:00Z+fleet-os 2026.11.13 cyclonedx-json fd2407ebf451915ddb23cd4cabd3cee23db62e7f1d7a81c8c3cfb3b1c48596e4 ok 2026-11-12 08:00:00 2026-11-11T06:00:00Z+fleet-os 2026.11.2 cyclonedx-json missing 2026-11-03 08:00:00+fleet-os 2026.11.3 3333333333333333333333333333333333333333333333333333333333333333 cyclonedx-json hash_mismatch 2026-11-04 08:00:00+fleet-os 2026.11.4 4444444444444444444444444444444444444444444444444444444444444444 cyclonedx-json parse_error 2026-11-05 08:00:00+fleet-os 2026.11.5 5555555555555555555555555555555555555555555555555555555555555555 spdx-json unsupported_format 2026-11-06 08:00:00+fleet-os 2026.11.6 cyclonedx-json d89d4d8966a7264023fb306de62ee1b5a40e6376dfffec4b59d0774fb988f333 ok 2026-11-07 08:00:00 2026-11-11T06:00:00Z+fleet-os 2026.11.7 7777777777777777777777777777777777777777777777777777777777777777 cyclonedx-json parse_error 2026-11-08 08:00:00+fleet-os 2026.11.8 8888888888888888888888888888888888888888888888888888888888888888 cyclonedx-json parse_error 1970-01-01 00:00:00+fleet-os 2026.11.9 cyclonedx-json parse_error 1970-01-01 00:00:00+scanned again ['2026.11.1']+scans 2+sbom_vulns+fd2407ebf451915ddb23cd4cabd3cee23db62e7f1d7a81c8c3cfb3b1c48596e4 EXAMPLE-0202 openssl 3.5.1-1 3.5.1-2 HIGH 0+fd2407ebf451915ddb23cd4cabd3cee23db62e7f1d7a81c8c3cfb3b1c48596e4 EXAMPLE-0505 zlib 1.3-1 MEDIUM 0+fd2407ebf451915ddb23cd4cabd3cee23db62e7f1d7a81c8c3cfb3b1c48596e4 EXAMPLE-0202 openssl 3.5.1-1 3.5.1-2 HIGH 1+fd2407ebf451915ddb23cd4cabd3cee23db62e7f1d7a81c8c3cfb3b1c48596e4 EXAMPLE-0505 zlib 1.3-1 MEDIUM 1+node_vulns+edge-01 2026.11.1 verified false sbom EXAMPLE-0202 openssl 3.5.1-1 3.5.1-2 HIGH exposed_no_shield+edge-01 2026.11.1 verified false sbom EXAMPLE-0505 zlib 1.3-1 MEDIUM exposed_no_shielddiff --git a/tools/backend/test/sbom-scan.sh b/tools/backend/test/sbom-scan.shnew file mode 100644index 00000000..1be5c806--- /dev/null+++ b/tools/backend/test/sbom-scan.sh@@ -0,0 +1,40 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# jobs/sbom-scan over the file:// store test/sbom-store, with+# test/stub-trivy.sh as the matcher. Every state of an image comes out+# of it: ok with findings and without, missing, hash_mismatch,+# parse_error for an SBOM that is not CycloneDX, one that is not JSON,+# an image.json that is not JSON and one that names another version,+# and unsupported_format. Two images share an SBOM, whose findings are+# loaded once. Objects out of the layout, an image whose+# matcher fails and one whose report is refused are left out with a+# message and status 1, and the rest is loaded. A second run scans the+# first image again, with a cache directory for the matcher.++set -eu++test=$(cd "$(dirname "$0")" && pwd)+job=$test/../jobs/sbom-scan+root=a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c+unset SBOM_STORE TRIVY TRIVY_CACHE_DIR S3_CLIENT++work=$(mktemp -d)+trap 'rm -rf "$work"' EXIT+export STUB_TRIVY_LOG="$work/trivy.log"++status=0+STUB_TRIVY_FAIL=67b15da716e8b47de1b70e10b04e6629f0582be47137b363211ec699d42ea537 \+ "$job" --store "file://$test/sbom-store" --trivy "$test/stub-trivy.sh" 2>&1 ||+ status=$?+printf 'first run: status %d\n' "$status"+cat "$STUB_TRIVY_LOG"++mkdir -p "$work/store/fleet-os/2026.11.1"+cp -R "$test/sbom-store/fleet-os/2026.11.1/$root" "$work/store/fleet-os/2026.11.1/"+: >"$STUB_TRIVY_LOG"+TRIVY=$test/stub-trivy.sh SBOM_STORE=file://$work/store \+ "$job" --cache-dir /var/cache/trivy-test 2>&1+echo 'second run: status 0'+cat "$STUB_TRIVY_LOG"diff --git a/tools/backend/test/sbom-scan.sql b/tools/backend/test/sbom-scan.sqlnew file mode 100644index 00000000..588fec60--- /dev/null+++ b/tools/backend/test/sbom-scan.sql@@ -0,0 +1,44 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- What jobs/sbom-scan loaded in test/sbom-scan.sh: a row for every image+-- it could read, with the state of its SBOM, and the findings of the two+-- scans of fleet-os 2026.11.1 without the kernel packages and with one+-- finding the report gave twice once; 2026.11.13, built from the same+-- SBOM, adds none. The image's row has the time of+-- the second scan, which is later than the first, and node A, which+-- booted the image's root, reads that scan's findings alone.++SELECT 'sbom_images';+SELECT image_id, image_version, image_root, sbom_format, sbom_sha256, state, toString(built_at, 'UTC'), db_version+FROM shirudo.sbom_images FINAL+ORDER BY image_id, image_version, image_root;++SELECT 'scanned again', groupArray(image_version)+FROM+(+ SELECT image_version FROM shirudo.sbom_images FINAL+ WHERE scanned_at = (SELECT max(scanned_at) FROM shirudo.sbom_images)+ ORDER BY image_version+);+SELECT 'scans', uniqExact(scanned_at) FROM shirudo.sbom_images;++SELECT 'sbom_vulns';+SELECT sbom_sha256, vuln_id, package, installed, fixed, severity,+ scanned_at = (SELECT scanned_at FROM shirudo.sbom_images FINAL WHERE image_version = '2026.11.1') AS newest+FROM shirudo.sbom_vulns+ORDER BY newest, vuln_id, package;++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock) VALUES+('edge-01', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1","mask":"VA==","set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1,"not_ok":0}',+ 1, '000b23602ab98bfb', 'QUtB', 7, 86523114);++SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SYSTEM REFRESH VIEW shirudo.node_vulns_mv;+SYSTEM WAIT VIEW shirudo.node_vulns_mv;++SELECT 'node_vulns';+SELECT node_id, image_version, binding, sbom_stale, source, vuln_id, package, installed, fixed, severity, exposure+FROM shirudo.node_vulns+ORDER BY node_id, vuln_id, package;diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.1/a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c/image.json b/tools/backend/test/sbom-store/fleet-os/2026.11.1/a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c/image.jsonnew file mode 100644index 00000000..723a2092--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.1/a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c/image.json@@ -0,0 +1,8 @@+{+ "image_id": "fleet-os",+ "image_version": "2026.11.1",+ "image_root": "a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c",+ "sbom_format": "cyclonedx-json",+ "sbom_sha256": "fd2407ebf451915ddb23cd4cabd3cee23db62e7f1d7a81c8c3cfb3b1c48596e4",+ "built_at": "2026-11-02T08:00:00Z"+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.1/a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c/sbom.cdx.json b/tools/backend/test/sbom-store/fleet-os/2026.11.1/a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c/sbom.cdx.jsonnew file mode 100644index 00000000..164b6005--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.1/a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c/sbom.cdx.json@@ -0,0 +1,53 @@+{+ "bomFormat": "CycloneDX",+ "specVersion": "1.6",+ "serialNumber": "urn:uuid:6a1c1d0e-0b1e-4c55-9a0b-2026111000001",+ "version": 1,+ "metadata": {+ "timestamp": "2026-11-02T08:00:00Z",+ "component": {+ "bom-ref": "image",+ "type": "container",+ "name": "fleet-os"+ }+ },+ "components": [+ {+ "bom-ref": "os",+ "type": "operating-system",+ "name": "debian",+ "version": "13"+ },+ {+ "bom-ref": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13",+ "type": "library",+ "name": "openssl",+ "version": "3.5.1-1",+ "purl": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ },+ {+ "bom-ref": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13",+ "type": "library",+ "name": "linux-image-7.4.2",+ "version": "7.4.2-1",+ "purl": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ },+ {+ "bom-ref": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13",+ "type": "library",+ "name": "zlib",+ "version": "1.3-1",+ "purl": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ }+ ],+ "dependencies": [+ {+ "ref": "os",+ "dependsOn": [+ "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13",+ "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13",+ "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ ]+ }+ ]+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.1/image.json b/tools/backend/test/sbom-store/fleet-os/2026.11.1/image.jsonnew file mode 100644index 00000000..900d99a6--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.1/image.json@@ -0,0 +1,4 @@+{+ "image_id": "fleet-os",+ "image_version": "2026.11.1"+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.10/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/image.json b/tools/backend/test/sbom-store/fleet-os/2026.11.10/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/image.jsonnew file mode 100644index 00000000..17bfab9f--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.10/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/image.json@@ -0,0 +1,8 @@+{+ "image_id": "fleet-os",+ "image_version": "2026.11.10",+ "image_root": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "sbom_format": "cyclonedx-json",+ "sbom_sha256": "81fc6ee4cddaf8949448930497191edc91adba67cd61ef0fa4d0857fdbf6c1ff",+ "built_at": "2026-11-11T08:00:00Z"+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.10/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/sbom.cdx.json b/tools/backend/test/sbom-store/fleet-os/2026.11.10/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/sbom.cdx.jsonnew file mode 100644index 00000000..814a6818--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.10/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/sbom.cdx.json@@ -0,0 +1,37 @@+{+ "bomFormat": "CycloneDX",+ "specVersion": "1.6",+ "serialNumber": "urn:uuid:6a1c1d0e-0b1e-4c55-9a0b-2026111000010",+ "version": 1,+ "metadata": {+ "timestamp": "2026-11-02T08:00:00Z",+ "component": {+ "bom-ref": "image",+ "type": "container",+ "name": "fleet-os"+ }+ },+ "components": [+ {+ "bom-ref": "os",+ "type": "operating-system",+ "name": "debian",+ "version": "13"+ },+ {+ "bom-ref": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13",+ "type": "library",+ "name": "openssl",+ "version": "3.5.1-1",+ "purl": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ }+ ],+ "dependencies": [+ {+ "ref": "os",+ "dependsOn": [+ "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ ]+ }+ ]+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.11/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/image.json b/tools/backend/test/sbom-store/fleet-os/2026.11.11/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/image.jsonnew file mode 100644index 00000000..509d409f--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.11/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/image.json@@ -0,0 +1,8 @@+{+ "image_id": "fleet-os",+ "image_version": "2026.11.11",+ "image_root": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",+ "sbom_format": "cyclonedx-json",+ "sbom_sha256": "67b15da716e8b47de1b70e10b04e6629f0582be47137b363211ec699d42ea537",+ "built_at": "2026-11-12T08:00:00Z"+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.11/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/sbom.cdx.json b/tools/backend/test/sbom-store/fleet-os/2026.11.11/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/sbom.cdx.jsonnew file mode 100644index 00000000..f3834461--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.11/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/sbom.cdx.json@@ -0,0 +1,37 @@+{+ "bomFormat": "CycloneDX",+ "specVersion": "1.6",+ "serialNumber": "urn:uuid:6a1c1d0e-0b1e-4c55-9a0b-2026111000011",+ "version": 1,+ "metadata": {+ "timestamp": "2026-11-02T08:00:00Z",+ "component": {+ "bom-ref": "image",+ "type": "container",+ "name": "fleet-os"+ }+ },+ "components": [+ {+ "bom-ref": "os",+ "type": "operating-system",+ "name": "debian",+ "version": "13"+ },+ {+ "bom-ref": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13",+ "type": "library",+ "name": "openssl",+ "version": "3.5.1-1",+ "purl": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ }+ ],+ "dependencies": [+ {+ "ref": "os",+ "dependsOn": [+ "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ ]+ }+ ]+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.12/not-a-root/image.json b/tools/backend/test/sbom-store/fleet-os/2026.11.12/not-a-root/image.jsonnew file mode 100644index 00000000..db3097ba--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.12/not-a-root/image.json@@ -0,0 +1,4 @@+{+ "image_id": "fleet-os",+ "image_version": "2026.11.12"+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.13/-/image.json b/tools/backend/test/sbom-store/fleet-os/2026.11.13/-/image.jsonnew file mode 100644index 00000000..77db4f2e--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.13/-/image.json@@ -0,0 +1,8 @@+{+ "image_id": "fleet-os",+ "image_version": "2026.11.13",+ "image_root": "",+ "sbom_format": "cyclonedx-json",+ "sbom_sha256": "fd2407ebf451915ddb23cd4cabd3cee23db62e7f1d7a81c8c3cfb3b1c48596e4",+ "built_at": "2026-11-12T08:00:00Z"+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.13/-/sbom.cdx.json b/tools/backend/test/sbom-store/fleet-os/2026.11.13/-/sbom.cdx.jsonnew file mode 100644index 00000000..164b6005--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.13/-/sbom.cdx.json@@ -0,0 +1,53 @@+{+ "bomFormat": "CycloneDX",+ "specVersion": "1.6",+ "serialNumber": "urn:uuid:6a1c1d0e-0b1e-4c55-9a0b-2026111000001",+ "version": 1,+ "metadata": {+ "timestamp": "2026-11-02T08:00:00Z",+ "component": {+ "bom-ref": "image",+ "type": "container",+ "name": "fleet-os"+ }+ },+ "components": [+ {+ "bom-ref": "os",+ "type": "operating-system",+ "name": "debian",+ "version": "13"+ },+ {+ "bom-ref": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13",+ "type": "library",+ "name": "openssl",+ "version": "3.5.1-1",+ "purl": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ },+ {+ "bom-ref": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13",+ "type": "library",+ "name": "linux-image-7.4.2",+ "version": "7.4.2-1",+ "purl": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ },+ {+ "bom-ref": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13",+ "type": "library",+ "name": "zlib",+ "version": "1.3-1",+ "purl": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ }+ ],+ "dependencies": [+ {+ "ref": "os",+ "dependsOn": [+ "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13",+ "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13",+ "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ ]+ }+ ]+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.2/-/image.json b/tools/backend/test/sbom-store/fleet-os/2026.11.2/-/image.jsonnew file mode 100644index 00000000..e388e6ff--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.2/-/image.json@@ -0,0 +1,8 @@+{+ "image_id": "fleet-os",+ "image_version": "2026.11.2",+ "image_root": "",+ "sbom_format": "cyclonedx-json",+ "sbom_sha256": "f4c582cd827eeea341734a51f2bec037321356ed589f2ad47893f705f5c24108",+ "built_at": "2026-11-03T08:00:00Z"+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.3/3333333333333333333333333333333333333333333333333333333333333333/image.json b/tools/backend/test/sbom-store/fleet-os/2026.11.3/3333333333333333333333333333333333333333333333333333333333333333/image.jsonnew file mode 100644index 00000000..6fb1282c--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.3/3333333333333333333333333333333333333333333333333333333333333333/image.json@@ -0,0 +1,8 @@+{+ "image_id": "fleet-os",+ "image_version": "2026.11.3",+ "image_root": "3333333333333333333333333333333333333333333333333333333333333333",+ "sbom_format": "cyclonedx-json",+ "sbom_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",+ "built_at": "2026-11-04T08:00:00Z"+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.3/3333333333333333333333333333333333333333333333333333333333333333/sbom.cdx.json b/tools/backend/test/sbom-store/fleet-os/2026.11.3/3333333333333333333333333333333333333333333333333333333333333333/sbom.cdx.jsonnew file mode 100644index 00000000..494333a6--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.3/3333333333333333333333333333333333333333333333333333333333333333/sbom.cdx.json@@ -0,0 +1,37 @@+{+ "bomFormat": "CycloneDX",+ "specVersion": "1.6",+ "serialNumber": "urn:uuid:6a1c1d0e-0b1e-4c55-9a0b-2026111000003",+ "version": 1,+ "metadata": {+ "timestamp": "2026-11-02T08:00:00Z",+ "component": {+ "bom-ref": "image",+ "type": "container",+ "name": "fleet-os"+ }+ },+ "components": [+ {+ "bom-ref": "os",+ "type": "operating-system",+ "name": "debian",+ "version": "13"+ },+ {+ "bom-ref": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13",+ "type": "library",+ "name": "openssl",+ "version": "3.5.1-1",+ "purl": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ }+ ],+ "dependencies": [+ {+ "ref": "os",+ "dependsOn": [+ "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ ]+ }+ ]+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.4/4444444444444444444444444444444444444444444444444444444444444444/image.json b/tools/backend/test/sbom-store/fleet-os/2026.11.4/4444444444444444444444444444444444444444444444444444444444444444/image.jsonnew file mode 100644index 00000000..70b6fc60--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.4/4444444444444444444444444444444444444444444444444444444444444444/image.json@@ -0,0 +1,8 @@+{+ "image_id": "fleet-os",+ "image_version": "2026.11.4",+ "image_root": "4444444444444444444444444444444444444444444444444444444444444444",+ "sbom_format": "cyclonedx-json",+ "sbom_sha256": "021624cf4995f7039b5fa7bdfda835be23fa8c40b7f9b52f1c597c1d8c056740",+ "built_at": "2026-11-05T08:00:00Z"+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.4/4444444444444444444444444444444444444444444444444444444444444444/sbom.cdx.json b/tools/backend/test/sbom-store/fleet-os/2026.11.4/4444444444444444444444444444444444444444444444444444444444444444/sbom.cdx.jsonnew file mode 100644index 00000000..03dbbb22--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.4/4444444444444444444444444444444444444444444444444444444444444444/sbom.cdx.json@@ -0,0 +1,5 @@+{+ "bomFormat": "SPDX",+ "specVersion": "1.6",+ "components": []+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.5/5555555555555555555555555555555555555555555555555555555555555555/image.json b/tools/backend/test/sbom-store/fleet-os/2026.11.5/5555555555555555555555555555555555555555555555555555555555555555/image.jsonnew file mode 100644index 00000000..635145b6--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.5/5555555555555555555555555555555555555555555555555555555555555555/image.json@@ -0,0 +1,8 @@+{+ "image_id": "fleet-os",+ "image_version": "2026.11.5",+ "image_root": "5555555555555555555555555555555555555555555555555555555555555555",+ "sbom_format": "spdx-json",+ "sbom_sha256": "d53370417fe592ad1824332c680da7beca9c192f8600d6be7e9ea23df735f07a",+ "built_at": "2026-11-06T08:00:00Z"+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.5/5555555555555555555555555555555555555555555555555555555555555555/sbom.spdx.json b/tools/backend/test/sbom-store/fleet-os/2026.11.5/5555555555555555555555555555555555555555555555555555555555555555/sbom.spdx.jsonnew file mode 100644index 00000000..cfe93b5e--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.5/5555555555555555555555555555555555555555555555555555555555555555/sbom.spdx.json@@ -0,0 +1,5 @@+{+ "spdxVersion": "SPDX-2.3",+ "SPDXID": "SPDXRef-DOCUMENT",+ "packages": []+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.6/-/image.json b/tools/backend/test/sbom-store/fleet-os/2026.11.6/-/image.jsonnew file mode 100644index 00000000..c283d2ac--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.6/-/image.json@@ -0,0 +1,7 @@+{+ "image_id": "fleet-os",+ "image_version": "2026.11.6",+ "image_root": "",+ "sbom_sha256": "d89d4d8966a7264023fb306de62ee1b5a40e6376dfffec4b59d0774fb988f333",+ "built_at": "2026-11-07T08:00:00Z"+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.6/-/sbom.cdx.json b/tools/backend/test/sbom-store/fleet-os/2026.11.6/-/sbom.cdx.jsonnew file mode 100644index 00000000..bb4a441b--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.6/-/sbom.cdx.json@@ -0,0 +1,37 @@+{+ "bomFormat": "CycloneDX",+ "specVersion": "1.6",+ "serialNumber": "urn:uuid:6a1c1d0e-0b1e-4c55-9a0b-2026111000006",+ "version": 1,+ "metadata": {+ "timestamp": "2026-11-02T08:00:00Z",+ "component": {+ "bom-ref": "image",+ "type": "container",+ "name": "fleet-os"+ }+ },+ "components": [+ {+ "bom-ref": "os",+ "type": "operating-system",+ "name": "debian",+ "version": "13"+ },+ {+ "bom-ref": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13",+ "type": "library",+ "name": "bash",+ "version": "5.2.37-2",+ "purl": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ }+ ],+ "dependencies": [+ {+ "ref": "os",+ "dependsOn": [+ "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ ]+ }+ ]+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.7/7777777777777777777777777777777777777777777777777777777777777777/image.json b/tools/backend/test/sbom-store/fleet-os/2026.11.7/7777777777777777777777777777777777777777777777777777777777777777/image.jsonnew file mode 100644index 00000000..b79d058d--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.7/7777777777777777777777777777777777777777777777777777777777777777/image.json@@ -0,0 +1,8 @@+{+ "image_id": "fleet-os",+ "image_version": "2026.11.7",+ "image_root": "7777777777777777777777777777777777777777777777777777777777777777",+ "sbom_format": "cyclonedx-json",+ "sbom_sha256": "2077e535f18f8d411c5b625258c5aa6742ec3aa203bba6341f03bdb241666a05",+ "built_at": "2026-11-08T08:00:00Z"+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.7/7777777777777777777777777777777777777777777777777777777777777777/sbom.cdx.json b/tools/backend/test/sbom-store/fleet-os/2026.11.7/7777777777777777777777777777777777777777777777777777777777777777/sbom.cdx.jsonnew file mode 100644index 00000000..5adbb383--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.7/7777777777777777777777777777777777777777777777777777777777777777/sbom.cdx.json@@ -0,0 +1 @@+{"bomFormat": "CycloneDX", "specVersion": "1.6", "components": [diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.8/8888888888888888888888888888888888888888888888888888888888888888/image.json b/tools/backend/test/sbom-store/fleet-os/2026.11.8/8888888888888888888888888888888888888888888888888888888888888888/image.jsonnew file mode 100644index 00000000..4866ef3f--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.8/8888888888888888888888888888888888888888888888888888888888888888/image.json@@ -0,0 +1 @@+{"image_id": "fleet-os", "image_version": "2026.11.8",diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.8/8888888888888888888888888888888888888888888888888888888888888888/sbom.cdx.json b/tools/backend/test/sbom-store/fleet-os/2026.11.8/8888888888888888888888888888888888888888888888888888888888888888/sbom.cdx.jsonnew file mode 100644index 00000000..bb4a441b--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.8/8888888888888888888888888888888888888888888888888888888888888888/sbom.cdx.json@@ -0,0 +1,37 @@+{+ "bomFormat": "CycloneDX",+ "specVersion": "1.6",+ "serialNumber": "urn:uuid:6a1c1d0e-0b1e-4c55-9a0b-2026111000006",+ "version": 1,+ "metadata": {+ "timestamp": "2026-11-02T08:00:00Z",+ "component": {+ "bom-ref": "image",+ "type": "container",+ "name": "fleet-os"+ }+ },+ "components": [+ {+ "bom-ref": "os",+ "type": "operating-system",+ "name": "debian",+ "version": "13"+ },+ {+ "bom-ref": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13",+ "type": "library",+ "name": "bash",+ "version": "5.2.37-2",+ "purl": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ }+ ],+ "dependencies": [+ {+ "ref": "os",+ "dependsOn": [+ "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ ]+ }+ ]+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.9/-/image.json b/tools/backend/test/sbom-store/fleet-os/2026.11.9/-/image.jsonnew file mode 100644index 00000000..0d48a21d--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.9/-/image.json@@ -0,0 +1,8 @@+{+ "image_id": "fleet-os",+ "image_version": "2026.11.8",+ "image_root": "",+ "sbom_format": "cyclonedx-json",+ "sbom_sha256": "d89d4d8966a7264023fb306de62ee1b5a40e6376dfffec4b59d0774fb988f333",+ "built_at": "2026-11-10T08:00:00Z"+}diff --git a/tools/backend/test/sbom-store/fleet-os/2026.11.9/-/sbom.cdx.json b/tools/backend/test/sbom-store/fleet-os/2026.11.9/-/sbom.cdx.jsonnew file mode 100644index 00000000..bb4a441b--- /dev/null+++ b/tools/backend/test/sbom-store/fleet-os/2026.11.9/-/sbom.cdx.json@@ -0,0 +1,37 @@+{+ "bomFormat": "CycloneDX",+ "specVersion": "1.6",+ "serialNumber": "urn:uuid:6a1c1d0e-0b1e-4c55-9a0b-2026111000006",+ "version": 1,+ "metadata": {+ "timestamp": "2026-11-02T08:00:00Z",+ "component": {+ "bom-ref": "image",+ "type": "container",+ "name": "fleet-os"+ }+ },+ "components": [+ {+ "bom-ref": "os",+ "type": "operating-system",+ "name": "debian",+ "version": "13"+ },+ {+ "bom-ref": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13",+ "type": "library",+ "name": "bash",+ "version": "5.2.37-2",+ "purl": "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ }+ ],+ "dependencies": [+ {+ "ref": "os",+ "dependsOn": [+ "pkg:deb/debian/[email protected]?arch=amd64&distro=debian-13"+ ]+ }+ ]+}diff --git a/tools/backend/test/schema.expected b/tools/backend/test/schema.expectednew file mode 100644index 00000000..ecc4cb39--- /dev/null+++ b/tools/backend/test/schema.expected@@ -0,0 +1,90 @@+otel otel_logs Null+shirudo boot_first AggregatingMergeTree ak_name, boot_id+shirudo boot_first_keep_mv MaterializedView+shirudo boot_first_mv MaterializedView+shirudo checked Null+shirudo checked_mv MaterializedView+shirudo expected_builds ReplacingMergeTree version_id+shirudo history_conflicts View+shirudo history_contradictions MergeTree ak_name, tree_id+shirudo history_contradictions_mv MaterializedView+shirudo keepalive ReplacingMergeTree ak_name, reset_count, clock+shirudo keepalive_latest ReplacingMergeTree ak_name+shirudo keepalive_latest_mv MaterializedView+shirudo keepalive_mv MaterializedView+shirudo kernel_vulns ReplacingMergeTree vuln_id, introduced+shirudo latest View+shirudo node_ops ReplacingMergeTree ak_name, tree_id, seq+shirudo node_ops_mv MaterializedView+shirudo node_sets ReplacingMergeTree ak_name, tree_id, id+shirudo node_sets_mv MaterializedView+shirudo node_status MergeTree node_id, ak_name+shirudo node_status_mv MaterializedView+shirudo node_vulns MergeTree node_id, ak_name, vuln_id, package+shirudo node_vulns_mv MaterializedView+shirudo nodes AggregatingMergeTree ak_name+shirudo nodes_mv MaterializedView+shirudo rejected MergeTree received+shirudo rejected_mv MaterializedView+shirudo sbom_images ReplacingMergeTree image_id, image_version, image_root+shirudo sbom_vulns MergeTree sbom_sha256, vuln_id, package+shirudo settings ReplacingMergeTree id+shirudo tree_ops ReplacingMergeTree tree_id, seq+shirudo tree_pubs ReplacingMergeTree tree_id, generation+shirudo upatch_fixes ReplacingMergeTree tree_id, seq, advisory, source+boot_first AggregatingMergeTree ORDER BY (ak_name, boot_id) TTL last_used + toIntervalSecond(2592000) SETTINGS index_granularity = 8192+keepalive ReplacingMergeTree ORDER BY (ak_name, reset_count, clock) TTL toDateTime(received) + toIntervalSecond(3600) SETTINGS index_granularity = 8192+keepalive_latest ReplacingMergeTree(order_key) ORDER BY ak_name SETTINGS index_granularity = 8192+node_ops ReplacingMergeTree ORDER BY (ak_name, tree_id, seq) SETTINGS deduplicate_merge_projection_mode = \'rebuild\', index_granularity = 8192+node_sets ReplacingMergeTree(last_seq) ORDER BY (ak_name, tree_id, id) SETTINGS index_granularity = 8192+rejected MergeTree ORDER BY received TTL toDateTime(received) + toIntervalDay(7) SETTINGS index_granularity = 8192+sbom_images ReplacingMergeTree(scanned_at) ORDER BY (image_id, image_version, image_root) SETTINGS index_granularity = 8192+sbom_vulns MergeTree ORDER BY (sbom_sha256, vuln_id, package) TTL scanned_at + toIntervalDay(7) SETTINGS index_granularity = 8192+ak_name String+ak_public SimpleAggregateFunction(max, String)+node_id AggregateFunction(argMin, String, DateTime64(3))+first_seen SimpleAggregateFunction(min, Nullable(DateTime64(3)))+trust SimpleAggregateFunction(max, Enum8(\'untrusted\' = 0))+node_id String+ak_name String+host_name String+status Enum8(\'healthy\' = 1, \'unhealthy\' = 2, \'stale\' = 3)+trust Enum8(\'untrusted\' = 0)+failed_check UInt8+log Array(String)+last_seen DateTime64(3)+generation Nullable(UInt64)+last_seq Nullable(UInt64)+head_seq Nullable(UInt64)+loaded UInt64+set_sha256 String+updated_at DateTime+node_id String+ak_name String+host_name String+status Enum8(\'healthy\' = 1, \'unhealthy\' = 2, \'stale\' = 3)+trust Enum8(\'untrusted\' = 0)+image_id String+image_version String+binding Enum8(\'verified\' = 1, \'declared\' = 2, \'root_mismatch\' = 3, \'no_sbom\' = 4, \'no_image\' = 5)+sbom_stale Bool+source Enum8(\'sbom\' = 1, \'kernel\' = 2, \'none\' = 3)+vuln_id String+severity LowCardinality(String)+package String+installed String+fixed String+exposure Enum8(\'shielded\' = 1, \'shield_pending\' = 2, \'shield_module_absent\' = 3, \'shield_excludes_node\' = 4, \'shield_withdrawn\' = 5, \'exposed_no_shield\' = 6, \'none\' = 7, \'unknown\' = 8)+upatch_id String+applied_seq UInt64+applied_op Enum8(\'\' = 0, \'add\' = 1, \'delete\' = 2)+next_seq UInt64+next_op Enum8(\'\' = 0, \'add\' = 1, \'delete\' = 2)+next_shields Bool+shield_link Enum8(\'none\' = 0, \'fixes\' = 1, \'manual\' = 2)+updated_at DateTime+kver+mask_code+tpm_quote_check+1 600 3600 512 3600 2592000 172800+1 3 6 4 7200 5184000 172800diff --git a/tools/backend/test/schema.sql b/tools/backend/test/schema.sqlnew file mode 100644index 00000000..5f01e1b5--- /dev/null+++ b/tools/backend/test/schema.sql@@ -0,0 +1,42 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- The schema loads: every object exists with its engine and key, the+-- functions are declared and the settings hold their defaults. A refresh+-- of node_status writes to a table with a name of its own before it+-- swaps it in, which is left out.++SELECT database, name, engine, sorting_key+FROM system.tables+WHERE database IN ('otel', 'shirudo') AND name NOT LIKE '.tmp.%'+ORDER BY database, name;++SELECT name, engine_full+FROM system.tables+WHERE database = 'shirudo' AND name IN ('boot_first', 'keepalive', 'keepalive_latest', 'node_ops', 'node_sets', 'rejected',+ 'sbom_images', 'sbom_vulns')+ORDER BY name;++SELECT name, type+FROM system.columns+WHERE database = 'shirudo' AND table = 'nodes'+ORDER BY position;++SELECT name, type+FROM system.columns+WHERE database = 'shirudo' AND table = 'node_status'+ORDER BY position;++SELECT name, type+FROM system.columns+WHERE database = 'shirudo' AND table = 'node_vulns'+ORDER BY position;++SELECT name FROM system.functions WHERE name IN ('kver', 'mask_code', 'tpm_quote_check') ORDER BY name;++SELECT * EXCEPT (updated) FROM shirudo.settings FINAL;++-- A changed setting replaces the row.+INSERT INTO shirudo.settings (stale_seconds, stuck_seconds, window, keepalive_retention_seconds, boot_first_retention_seconds)+VALUES (3, 6, 4, 7200, 5184000);+SELECT * EXCEPT (updated) FROM shirudo.settings FINAL;diff --git a/tools/backend/test/status-chain.expected b/tools/backend/test/status-chain.expectednew file mode 100644index 00000000..bd8a7e6f--- /dev/null+++ b/tools/backend/test/status-chain.expected@@ -0,0 +1,20 @@+applied healthy 0 4 chain: pass, root 15452248 6 set: pass, 1 loaded+applied-too healthy 0 4 chain: pass, root 15452248 6 set: pass, 1 loaded+module-missing healthy 0 4 chain: pass, root 15452248 6 set: pass, 0 loaded+passed-over healthy 0 4 chain: pass, root 00000000 6 set: pass, 0 loaded+no-mask unhealthy 3 4 chain: no mask 6 set: no mask+mask-not-base64 unhealthy 4 4 chain: FAIL, root 15452248 6 set: FAIL drift, 1 loaded+no-last-seq unhealthy 4 4 chain: FAIL, root 15452248 6 set: FAIL drift, 1 loaded+past-the-head unhealthy 4 4 chain: FAIL, root 15452248 6 set: pass, 1 loaded+root-not-hex unhealthy 4 4 chain: FAIL, root zzzz2248 6 set: pass, 1 loaded+root-too-long unhealthy 4 4 chain: FAIL, root 15452248 6 set: FAIL drift, 1 loaded+unreached unhealthy 4 4 chain: FAIL, root 15452248 6 set: FAIL drift, 1 loaded+wrong-mask unhealthy 4 4 chain: FAIL, root 15452248 6 set: FAIL drift, 1 loaded+wrong-root unhealthy 4 4 chain: FAIL, root a042a582 6 set: pass, 0 loaded+no-mask 1 signed: pass, untrusted, 0 rejected in the last hour+no-mask 2 fresh: pass, last record N s ago+no-mask 3 reported: FAIL, verdict ok, cond 0x1555, flags 4, tamper +0, build d6d918ad+no-mask 4 chain: no mask+no-mask 5 head: no mask+no-mask 6 set: no mask+no-mask 7 peers: no maskdiff --git a/tools/backend/test/status-chain.sql b/tools/backend/test/status-chain.sqlnew file mode 100644index 00000000..fb545633--- /dev/null+++ b/tools/backend/test/status-chain.sql@@ -0,0 +1,60 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- Check 4 folds the operations a mask marks as chained from base_root and+-- holds the result against projection_root. A mask that contradicts the+-- root, one that leaves an operation up to last_seq unreached and a record+-- whose tree keys cannot be read fail it; a mask with an operation whose+-- attach module was missing chains it and loads nothing; that node runs+-- another kernel, so it is nobody's peer here. A record without+-- a mask on a node that follows a tree fails check 3 by its flag, and+-- checks 4 to 7 say "no mask". Nodes on one path share one fold.++-- The publication of testing/fixtures/keepalive/tree-1.1.0.json, as the+-- ingest job loads it: generation 3 with its three operations.+INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-base', 3, '1f327364233e3f2dcebcd13c0af8d84f886201531b135294bd7356a2f7ed680b', '4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942', 3, now64(3) - INTERVAL 10 MINUTE);+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-base', 1, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144', '9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6', '59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885', '13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43'),+('fleet-base', 2, 'delete', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b', 'e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55', 'f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1', '5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b'),+('fleet-base', 3, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', 'b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a', '653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97', '82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf', 'bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc');+INSERT INTO shirudo.expected_builds (version_id, note) VALUES+('d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f', 'shirudo 2026.11');++-- The bodies of testing/fixtures/keepalive/, byte for byte.+CREATE TEMPORARY TABLE fixture (name String, body String);+INSERT INTO fixture VALUES+('node-a-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1","mask":"VA==","set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1,"not_ok":0}'),+('node-b-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"9a6f14ea-0cc2-45e1-8e23-7b887120cf54","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"ff2cbeff5d0e9c41a7b36f28d14ce09b73a5182e6fc40d97b5e2a1683c0f7ff8","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":null,"verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"0000000000000000000000000000000000000000000000000000000000000000","mask":"qA==","set_sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","count":0,"not_ok":0}');++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT node.1, arrayFold((body, change) -> replaceOne(body, change.1, change.2), node.3, f.body),+ 1, concat('000b', node.1), 'QUtB', 1, 1000+FROM+(+ SELECT arrayJoin([+ ('applied', 'node-a-1.1.0', [('"flags":0', '"flags":0')]),+ ('applied-too', 'node-a-1.1.0', [('"flags":0', '"flags":0')]),+ ('passed-over', 'node-b-1.1.0', [('"flags":0', '"flags":0')]),+ ('wrong-mask', 'node-a-1.1.0', [('"mask":"VA=="', '"mask":"qA=="')]),+ ('wrong-root', 'node-b-1.1.0', [('"projection_root":"0000000000000000000000000000000000000000000000000000000000000000"', '"projection_root":"a042a582b3a3d8c1b633b8ed0356e0b52f1f5aa25af85b06cc3f481562dcda93"')]),+ ('unreached', 'node-a-1.1.0', [('"mask":"VA=="', '"mask":"UA=="')]),+ ('module-missing', 'node-a-1.1.0', [('"mask":"VA=="', '"mask":"XA=="'), ('"kernel_release":"7.4.2"', '"kernel_release":"7.4.2-lean"'), ('"set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1', '"set_sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","count":0')]),+ ('no-mask', 'node-a-1.1.0', [('"flags":0', '"flags":4'), ('"base_root":"0000000000000000000000000000000000000000000000000000000000000000"', '"base_root":null'), ('"mask":"VA=="', '"mask":null')]),+ ('mask-not-base64', 'node-a-1.1.0', [('"mask":"VA=="', '"mask":"!!!!"')]),+ ('root-too-long', 'node-a-1.1.0', [('"base_root":"0000', '"base_root":"00000000')]),+ ('root-not-hex', 'node-a-1.1.0', [('"projection_root":"1545', '"projection_root":"zzzz')]),+ ('no-last-seq', 'node-a-1.1.0', [('"last_seq":3', '"last_seq":null')]),+ ('past-the-head', 'node-a-1.1.0', [('"last_seq":3', '"last_seq":9')])+ ]) AS node+) AS n+INNER JOIN fixture AS f ON f.name = node.2;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;++SELECT node_id, status, failed_check, log[4], log[6]+FROM shirudo.node_status ORDER BY failed_check, node_id;+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+WHERE node_id = 'no-mask'+ORDER BY node_id, line;diff --git a/tools/backend/test/status-cost.expected b/tools/backend/test/status-cost.expectednew file mode 100644index 00000000..d7bf43c4--- /dev/null+++ b/tools/backend/test/status-cost.expected@@ -0,0 +1,17 @@+shirudo.boot_first+shirudo.expected_builds+shirudo.history_conflicts+shirudo.history_contradictions+shirudo.keepalive_latest+shirudo.latest+shirudo.node_ops+shirudo.node_sets+shirudo.node_status_mv+shirudo.nodes+shirudo.rejected+shirudo.settings+shirudo.tree_ops+shirudo.tree_pubs+reads shirudo.keepalive 0 1+shirudo.node_ops_mv 1+shirudo.node_status_mv 1diff --git a/tools/backend/test/status-cost.sql b/tools/backend/test/status-cost.sqlnew file mode 100644index 00000000..0ab3049b--- /dev/null+++ b/tools/backend/test/status-cost.sql@@ -0,0 +1,68 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- The refresh of node_status reads the newest record of each node and the+-- first of each boot, never the records themselves: of the tables the+-- last refresh read, as system.query_log has them, none is+-- shirudo.keepalive. The table that takes the result has a name of its+-- own for every refresh and is left out. Both that refresh and the one+-- of node_ops read how far each node's history reaches through the+-- projection of node_ops, one row per node, and not its whole history,+-- of which they read only the rows the windows overlap+-- (history_conflicts); the history is refreshed twice, so that the+-- second refresh finds a part to read.++-- The publication of testing/fixtures/keepalive/tree-1.1.0.json, as the+-- ingest job loads it: generation 3 with its three operations.+INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-base', 3, '1f327364233e3f2dcebcd13c0af8d84f886201531b135294bd7356a2f7ed680b', '4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942', 3, now64(3) - INTERVAL 10 MINUTE);+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-base', 1, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144', '9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6', '59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885', '13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43'),+('fleet-base', 2, 'delete', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b', 'e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55', 'f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1', '5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b'),+('fleet-base', 3, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', 'b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a', '653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97', '82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf', 'bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc');+INSERT INTO shirudo.expected_builds (version_id, note) VALUES+('d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f', 'shirudo 2026.11');++-- The bodies of testing/fixtures/keepalive/, byte for byte.+CREATE TEMPORARY TABLE fixture (name String, body String);+INSERT INTO fixture VALUES+('node-a-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1","mask":"VA==","set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1,"not_ok":0}');++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT node.1, arrayFold((body, change) -> replaceOne(body, change.1, change.2), node.3, f.body),+ 1, concat('000b', node.1), 'QUtB', 1, 1000+FROM+(+ SELECT arrayJoin([+ ('edge-01', 'node-a-1.1.0', [('"flags":0', '"flags":0')])+ ]) AS node+) AS n+INNER JOIN fixture AS f ON f.name = node.2;+SYSTEM REFRESH VIEW shirudo.node_ops_mv;+SYSTEM WAIT VIEW shirudo.node_ops_mv;+SYSTEM REFRESH VIEW shirudo.node_ops_mv;+SYSTEM WAIT VIEW shirudo.node_ops_mv;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;++SYSTEM FLUSH LOGS;++SELECT arrayJoin(arraySort(arrayFilter(name -> name NOT LIKE '%.tmp.%', tables))) AS read+FROM system.query_log+WHERE type = 'QueryFinish' AND query_kind = 'Insert' AND has(tables, 'shirudo.node_status_mv')+ORDER BY event_time_microseconds DESC+LIMIT 1 BY read+LIMIT 20;++SELECT 'reads shirudo.keepalive', has(tables, 'shirudo.keepalive'), read_rows > 0+FROM system.query_log+WHERE type = 'QueryFinish' AND query_kind = 'Insert' AND has(tables, 'shirudo.node_status_mv')+ORDER BY event_time_microseconds DESC+LIMIT 1;++SELECT view, has(projections, 'shirudo.node_ops.reach')+FROM system.query_log+ARRAY JOIN ['shirudo.node_ops_mv', 'shirudo.node_status_mv'] AS view+WHERE type = 'QueryFinish' AND query_kind = 'Insert' AND has(tables, view)+ORDER BY view, event_time_microseconds DESC+LIMIT 1 BY view;diff --git a/tools/backend/test/status-fixtures.expected b/tools/backend/test/status-fixtures.expectednew file mode 100644index 00000000..151628bb--- /dev/null+++ b/tools/backend/test/status-fixtures.expected@@ -0,0 +1,68 @@+node-a-1.1.0 0cc0ebca20e6d16e625c7bd3b40666b5a8effd7993d0f4489583900fcb5a47bb+node-b-1.1.0 8a1815fd4bc50cac387f63bdf5def017f770ac1db208e27ff53a41569e85c8bc+Row 1:+──────+node_id: core-01+ak_name: 000b9d72e08380a1+host_name: core-01+status: healthy+trust: untrusted+failed_check: 0+generation: 3+last_seq: 3+head_seq: 3+loaded: 0+set_sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855++Row 2:+──────+node_id: edge-01+ak_name: 000b23602ab98bfb+host_name: edge-01+status: healthy+trust: untrusted+failed_check: 0+generation: 3+last_seq: 3+head_seq: 3+loaded: 1+set_sha256: 74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf++Row 3:+──────+node_id: lab-01+ak_name: 000b0c+host_name: lab-01+status: healthy+trust: untrusted+failed_check: 0+generation: ᴺᵁᴸᴸ+last_seq: ᴺᵁᴸᴸ+head_seq: ᴺᵁᴸᴸ+loaded: 0+set_sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855+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+lab-01 1 signed: pass, untrusted, 0 rejected in the last hour+lab-01 2 fresh: pass, last record N s ago+lab-01 3 reported: pass, verdict ok, cond 0x1555, flags 0, tamper +0, build d6d918ad+lab-01 4 chain: no tree+lab-01 5 head: no tree+lab-01 6 set: no tree+lab-01 7 peers: no tree+node_status is what was received 3+lab-01 lab-01 000b0c healthy+node-a edge-01 000b23602ab98bfb healthy+node-b core-01 000b9d72e08380a1 healthydiff --git a/tools/backend/test/status-fixtures.sql b/tools/backend/test/status-fixtures.sqlnew file mode 100644index 00000000..357c72df--- /dev/null+++ b/tools/backend/test/status-fixtures.sql@@ -0,0 +1,59 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- The backend page's result for node A and node B after release 1.1.0:+-- their keepalives of testing/fixtures/keepalive/ against the+-- publication of tree-1.1.0.json give healthy, untrusted, no failed+-- check and the page's log lines, with cond 0x1555 for seven conditions+-- where the page has six. A node that follows no tree keeps its row:+-- checks 1 to 3 run, checks 4 to 7 say "no tree" and pass. The first+-- SELECT shows that the bodies are the fixtures: it prints the SHA-256+-- of each file.++-- The publication of testing/fixtures/keepalive/tree-1.1.0.json, as the+-- ingest job loads it: generation 3 with its three operations.+INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-base', 3, '1f327364233e3f2dcebcd13c0af8d84f886201531b135294bd7356a2f7ed680b', '4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942', 3, now64(3) - INTERVAL 10 MINUTE);+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-base', 1, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144', '9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6', '59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885', '13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43'),+('fleet-base', 2, 'delete', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b', 'e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55', 'f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1', '5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b'),+('fleet-base', 3, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', 'b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a', '653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97', '82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf', 'bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc');+INSERT INTO shirudo.expected_builds (version_id, note) VALUES+('d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f', 'shirudo 2026.11');++-- The bodies of testing/fixtures/keepalive/, byte for byte.+CREATE TEMPORARY TABLE fixture (name String, body String);+INSERT INTO fixture VALUES+('node-a-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1","mask":"VA==","set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1,"not_ok":0}'),+('node-b-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"9a6f14ea-0cc2-45e1-8e23-7b887120cf54","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"ff2cbeff5d0e9c41a7b36f28d14ce09b73a5182e6fc40d97b5e2a1683c0f7ff8","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":null,"verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"0000000000000000000000000000000000000000000000000000000000000000","mask":"qA==","set_sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","count":0,"not_ok":0}');++SELECT name, lower(hex(SHA256(body))) FROM fixture ORDER BY name;++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT 'edge-01', body, 1, '000b23602ab98bfb', 'QUtB', 7, 86523114 FROM fixture WHERE name = 'node-a-1.1.0';+INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT 'core-01', body, 1, '000b9d72e08380a1', 'QUtC', 4, 91200408 FROM fixture WHERE name = 'node-b-1.1.0';+INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT 'lab-01', replaceOne(body, '"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"0000000000000000000000000000000000000000000000000000000000000000","mask":"qA=="', '"tree_id":null,"generation":null,"base_seq":null,"last_seq":null,"base_root":null,"projection_root":null,"mask":null'), 1, '000b0c', 'QUtD', 1, 1000 FROM fixture WHERE name = 'node-b-1.1.0';++SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;++SELECT * EXCEPT (log, last_seen, updated_at) FROM shirudo.node_status ORDER BY node_id FORMAT Vertical;+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;++SELECT 'node_status is what was received', count()+FROM shirudo.node_status AS s+INNER JOIN shirudo.keepalive_latest AS k FINAL ON k.ak_name = s.ak_name+WHERE s.last_seen = k.received;++-- An operator's label replaces the host name a key first claimed.+INSERT INTO shirudo.nodes (ak_name, node_id)+SELECT record.1, argMinState(record.2, toDateTime64(0, 3))+FROM (SELECT arrayJoin([('000b23602ab98bfb', 'node-a'), ('000b9d72e08380a1', 'node-b')]) AS record)+GROUP BY record.1;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SELECT node_id, host_name, ak_name, status FROM shirudo.node_status ORDER BY node_id;diff --git a/tools/backend/test/status-head.expected b/tools/backend/test/status-head.expectednew file mode 100644index 00000000..78a79400--- /dev/null+++ b/tools/backend/test/status-head.expected@@ -0,0 +1,39 @@+generation 3 is the newest+at-3 at-3 healthy untrusted 0 3 3 3 1+at-3 5 head: pass, seq 3 of 3, generation 3+generation 4, an hour allowed+ahead-of-ingest ahead-of-ingest healthy untrusted 0 5 5 4 1+at-1-of-generation-1 at-1-of-generation-1 unhealthy untrusted 5 1 1 4 1+at-2-of-generation-2 at-2-of-generation-2 unhealthy untrusted 5 2 2 4 0+at-3 at-3 healthy untrusted 0 3 3 4 1+at-4 at-4 healthy untrusted 0 4 4 4 2+generation-1-wrong-root generation-1-wrong-root unhealthy untrusted 4 1 1 4 1+other-tree other-tree healthy untrusted 0 3 3 \N 1+ahead-of-ingest 4 chain: publication unknown+ahead-of-ingest 5 head: publication unknown+ahead-of-ingest 6 set: publication unknown+ahead-of-ingest 7 peers: publication unknown+at-1-of-generation-1 5 head: FAIL stuck, seq 1 of 4, generation 1+at-2-of-generation-2 5 head: FAIL stuck, seq 2 of 4, generation 2+at-3 5 head: behind, seq 3 of 4, generation 3+at-4 5 head: pass, seq 4 of 4, generation 4+generation-1-wrong-root 4 chain: FAIL, root 04f93540+generation-1-wrong-root 5 head: FAIL stuck, seq 1 of 4, generation 1+generation-1-wrong-root 6 set: pass, 1 loaded+generation-1-wrong-root 7 peers: pass, 2 in group+other-tree 5 head: publication unknown+generation 4, forty minutes allowed+ahead-of-ingest ahead-of-ingest healthy untrusted 0 5 5 4 1+at-1-of-generation-1 at-1-of-generation-1 unhealthy untrusted 5 1 1 4 1+at-2-of-generation-2 at-2-of-generation-2 unhealthy untrusted 5 2 2 4 0+at-3 at-3 unhealthy untrusted 5 3 3 4 1+at-4 at-4 healthy untrusted 0 4 4 4 2+generation-1-wrong-root generation-1-wrong-root unhealthy untrusted 4 1 1 4 1+other-tree other-tree healthy untrusted 0 3 3 \N 1+ahead-of-ingest 5 head: publication unknown+at-1-of-generation-1 5 head: FAIL stuck, seq 1 of 4, generation 1+at-2-of-generation-2 5 head: FAIL stuck, seq 2 of 4, generation 2+at-3 5 head: FAIL stuck, seq 3 of 4, generation 3+at-4 5 head: pass, seq 4 of 4, generation 4+generation-1-wrong-root 5 head: FAIL stuck, seq 1 of 4, generation 1+other-tree 5 head: publication unknowndiff --git a/tools/backend/test/status-head.sql b/tools/backend/test/status-head.sqlnew file mode 100644index 00000000..1d47c21e--- /dev/null+++ b/tools/backend/test/status-head.sql@@ -0,0 +1,98 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- Check 5 holds last_seq against the head of the newest publication. A+-- node behind it is healthy and "behind" until stuck_seconds have passed+-- since the oldest publication it has not finished was loaded, then fails+-- as stuck; the threshold comes from shirudo.settings. Here generation 3+-- was loaded two hours ago and generation 4 fifty minutes ago: with an+-- hour allowed, the node at 3 is behind and those that never finished+-- generation 3 are stuck. A record naming a generation+-- newer than any in tree_pubs, or a tree with no publication there, is+-- not held against a tree the ingest job has yet to load: checks 4 to 7+-- say "publication unknown" and pass. A record naming an older generation+-- that was never loaded is checked as usual, since operations never+-- change: tree_pubs here has generations 3 and 4 only.++-- The publication of testing/fixtures/keepalive/tree-1.1.0.json, as the+-- ingest job loads it: generation 3 with its three operations.+INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-base', 3, '1f327364233e3f2dcebcd13c0af8d84f886201531b135294bd7356a2f7ed680b', '4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942', 3, now64(3) - INTERVAL 2 HOUR);+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-base', 1, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144', '9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6', '59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885', '13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43'),+('fleet-base', 2, 'delete', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b', 'e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55', 'f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1', '5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b'),+('fleet-base', 3, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', 'b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a', '653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97', '82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf', 'bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc');+INSERT INTO shirudo.expected_builds (version_id, note) VALUES+('d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f', 'shirudo 2026.11');++-- The bodies of testing/fixtures/keepalive/, byte for byte.+CREATE TEMPORARY TABLE fixture (name String, body String);+INSERT INTO fixture VALUES+('node-a-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1","mask":"VA==","set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1,"not_ok":0}'),+('node-a-1.0.0', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":1,"base_seq":0,"last_seq":1,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"04f83540c1727aefcf3c53449a99594c8fd1cc15e1466dbdbf3168cc8f9dc136","mask":"QA==","set_sha256":"6c9e113d02cd14646f617d7bba4a092b91bc3802dfdaae50e2fef7a01e0580aa","count":1,"not_ok":0}');++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT node.1, arrayFold((body, change) -> replaceOne(body, change.1, change.2), node.3, f.body),+ 1, concat('000b', node.1), 'QUtB', 1, 1000+FROM+(+ SELECT arrayJoin([+ ('at-3', 'node-a-1.1.0', [('"flags":0', '"flags":0')])+ ]) AS node+) AS n+INNER JOIN fixture AS f ON f.name = node.2;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;++SELECT 'generation 3 is the newest';+SELECT node_id, host_name, status, trust, failed_check, generation, last_seq, head_seq, loaded+FROM shirudo.node_status ORDER BY node_id;+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+WHERE line LIKE '5 %'+ORDER BY node_id, line;++-- Generation 4 was loaded 50 minutes ago.+INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-base', 4, '2396a1256ac4b1c6849c931ddb8018bdd984bb2383be21bb819a33b95d8d603f', '1f327364233e3f2dcebcd13c0af8d84f886201531b135294bd7356a2f7ed680b', 4, now64(3) - INTERVAL 50 MINUTE);+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-base', 4, 'add', 'net-guard', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', 'd6ab812e3d3e14d19f6d5b0105c130432de572417c2d1c1c2e02fb6ebe311c3f', '9f102fe3a7d618f9960701e25169aff66169d27e1d7dcf220124a9bf2047436d', '328775f7f18fd7ead422abe642a2b9cb85428593130a7d6bd230e6b8aee6b7aa', '8aa179bbf5f35a9af488b8f0e4e8d7d0c407913f70d54f5d03b746c5c955fd00');++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT node.1, arrayFold((body, change) -> replaceOne(body, change.1, change.2), node.3, f.body),+ 1, concat('000b', node.1), 'QUtB', 1, 1000+FROM+(+ SELECT arrayJoin([+ ('at-4', 'node-a-1.1.0', [('"generation":3', '"generation":4'), ('"last_seq":3', '"last_seq":4'), ('154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1', '3babcd63369daa5be22bf21c72481420e80a62e882027df3d21a8e567d622e2a'), ('"mask":"VA=="', '"mask":"VQ=="'), ('"set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1', '"set_sha256":"109355c70bab5428d322402784108238ea1f2a0aab107d81580f74dac64fe0c2","count":2')]),+ ('at-1-of-generation-1', 'node-a-1.0.0', [('"flags":0', '"flags":0')]),+ ('at-2-of-generation-2', 'node-a-1.1.0', [('"generation":3', '"generation":2'), ('"last_seq":3', '"last_seq":2'), ('154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1', 'a042a582b3a3d8c1b633b8ed0356e0b52f1f5aa25af85b06cc3f481562dcda93'), ('"mask":"VA=="', '"mask":"UA=="'), ('"set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1', '"set_sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","count":0')]),+ ('generation-1-wrong-root', 'node-a-1.0.0', [('"projection_root":"04f8', '"projection_root":"04f9')]),+ ('ahead-of-ingest', 'node-a-1.1.0', [('"generation":3', '"generation":5'), ('"last_seq":3', '"last_seq":5'), ('154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1', 'a042a582b3a3d8c1b633b8ed0356e0b52f1f5aa25af85b06cc3f481562dcda93'), ('"mask":"VA=="', '"mask":"VUA="')]),+ ('other-tree', 'node-a-1.1.0', [('"tree_id":"fleet-base"', '"tree_id":"fleet-next"')])+ ]) AS node+) AS n+INNER JOIN fixture AS f ON f.name = node.2;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;++SELECT 'generation 4, an hour allowed';+SELECT node_id, host_name, status, trust, failed_check, generation, last_seq, head_seq, loaded+FROM shirudo.node_status ORDER BY node_id;+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+WHERE line LIKE '5 %' OR node_id IN ('ahead-of-ingest', 'generation-1-wrong-root') AND line >= '4'+ORDER BY node_id, line;++INSERT INTO shirudo.settings (stale_seconds, stuck_seconds, window, keepalive_retention_seconds)+VALUES (180, 2400, 512, 3600);+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;++SELECT 'generation 4, forty minutes allowed';+SELECT node_id, host_name, status, trust, failed_check, generation, last_seq, head_seq, loaded+FROM shirudo.node_status ORDER BY node_id;+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+WHERE line LIKE '5 %'+ORDER BY node_id, line;diff --git a/tools/backend/test/status-peers.expected b/tools/backend/test/status-peers.expectednew file mode 100644index 00000000..45be45cf--- /dev/null+++ b/tools/backend/test/status-peers.expected@@ -0,0 +1,12 @@+core-01 core-01 healthy untrusted 0 3 3 3 0+edge-01 edge-01 healthy untrusted 0 3 3 3 1+edge-02 edge-02 healthy untrusted 0 3 3 3 1+edge-03 edge-03 healthy untrusted 0 3 3 3 1+edge-04 edge-04 unhealthy untrusted 7 3 3 3 0+edge-on-another-kernel edge-on-another-kernel healthy untrusted 0 3 3 3 1+core-01 7 peers: no peers, 1 in group+edge-01 7 peers: pass, 4 in group+edge-02 7 peers: pass, 4 in group+edge-03 7 peers: pass, 4 in group+edge-04 7 peers: FAIL outlier, 4 in group+edge-on-another-kernel 7 peers: no peers, 1 in groupdiff --git a/tools/backend/test/status-peers.sql b/tools/backend/test/status-peers.sqlnew file mode 100644index 00000000..188a7e43--- /dev/null+++ b/tools/backend/test/status-peers.sql@@ -0,0 +1,50 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- Check 7 groups the nodes at the same point of the same tree with the+-- same config and kernel, and fails the one whose path up to last_seq is+-- not the group's most common: of three edge nodes, the one that passed+-- every operation over. A node alone in its group has no peers and+-- passes. Peers that have seen different heads have masks of different+-- lengths for the same path, and are not outliers for that.++-- The publication of testing/fixtures/keepalive/tree-1.1.0.json, as the+-- ingest job loads it: generation 3 with its three operations.+INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-base', 3, '1f327364233e3f2dcebcd13c0af8d84f886201531b135294bd7356a2f7ed680b', '4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942', 3, now64(3) - INTERVAL 10 MINUTE);+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-base', 1, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144', '9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6', '59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885', '13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43'),+('fleet-base', 2, 'delete', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b', 'e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55', 'f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1', '5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b'),+('fleet-base', 3, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', 'b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a', '653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97', '82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf', 'bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc');+INSERT INTO shirudo.expected_builds (version_id, note) VALUES+('d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f', 'shirudo 2026.11');++-- The bodies of testing/fixtures/keepalive/, byte for byte.+CREATE TEMPORARY TABLE fixture (name String, body String);+INSERT INTO fixture VALUES+('node-a-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1","mask":"VA==","set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1,"not_ok":0}'),+('node-b-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"9a6f14ea-0cc2-45e1-8e23-7b887120cf54","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"ff2cbeff5d0e9c41a7b36f28d14ce09b73a5182e6fc40d97b5e2a1683c0f7ff8","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":null,"verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"0000000000000000000000000000000000000000000000000000000000000000","mask":"qA==","set_sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","count":0,"not_ok":0}');++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT node.1, arrayFold((body, change) -> replaceOne(body, change.1, change.2), node.3, f.body),+ 1, concat('000b', node.1), 'QUtB', 1, 1000+FROM+(+ SELECT arrayJoin([+ ('edge-01', 'node-a-1.1.0', [('"flags":0', '"flags":0')]),+ ('edge-02', 'node-a-1.1.0', [('"flags":0', '"flags":0')]),+ ('edge-03', 'node-a-1.1.0', [('"mask":"VA=="', '"mask":"VAA="')]),+ ('edge-04', 'node-b-1.1.0', [('"config_root":"ff2cbeff5d0e9c41a7b36f28d14ce09b73a5182e6fc40d97b5e2a1683c0f7ff8"', '"config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807"')]),+ ('core-01', 'node-b-1.1.0', [('"flags":0', '"flags":0')]),+ ('edge-on-another-kernel', 'node-a-1.1.0', [('"kernel_release":"7.4.2"', '"kernel_release":"7.4.3"')])+ ]) AS node+) AS n+INNER JOIN fixture AS f ON f.name = node.2;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SELECT node_id, host_name, status, trust, failed_check, generation, last_seq, head_seq, loaded+FROM shirudo.node_status ORDER BY node_id;+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+WHERE line LIKE '7 %'+ORDER BY node_id, line;diff --git a/tools/backend/test/status-reported.expected b/tools/backend/test/status-reported.expectednew file mode 100644index 00000000..473d2e17--- /dev/null+++ b/tools/backend/test/status-reported.expected@@ -0,0 +1,18 @@+busy healthy 0 3 reported: pass, verdict ok, cond 0x1555, flags 32, tamper +0, build d6d918ad+config-warn unhealthy 3 3 reported: FAIL, verdict ok, cond 0x1955, flags 0, tamper +0, build d6d918ad+degraded unhealthy 3 3 reported: FAIL, verdict degraded, cond 0x1555, flags 0, tamper +0, build d6d918ad+eighth-condition healthy 0 3 reported: pass, verdict ok, cond 0x9555, flags 0, tamper +0, build d6d918ad+no-counters unhealthy 3 3 reported: FAIL, verdict ok, cond 0x1555, flags 8, tamper +0, build d6d918ad+noisy-boot healthy 0 3 reported: pass, verdict ok, cond 0x1555, flags 0, tamper +0, build d6d918ad+other-build unhealthy 3 3 reported: FAIL, verdict ok, cond 0x1555, flags 0, tamper +0, build 0badc0de (not expected)+rebound unhealthy 3 3 reported: FAIL, verdict ok, cond 0x1555, flags 1, tamper +0, build d6d918ad+tampered-with unhealthy 3 3 reported: FAIL, verdict ok, cond 0x1555, flags 0, tamper +2, build d6d918ad+unreadable-again unhealthy 3 3 reported: FAIL, verdict ok, cond 0x1555, flags 8, tamper +0, build d6d918ad+unreadable-first healthy 0 3 reported: pass, verdict ok, cond 0x1555, flags 0, tamper +0, build d6d918ad+unreadable-then-rise unhealthy 3 3 reported: FAIL, verdict ok, cond 0x1555, flags 0, tamper +2, build d6d918ad+baselines+no-counters 0+noisy-boot 3+unreadable-again 3+unreadable-first 3+unreadable-then-rise 3diff --git a/tools/backend/test/status-reported.sql b/tools/backend/test/status-reported.sqlnew file mode 100644index 00000000..9134146b--- /dev/null+++ b/tools/backend/test/status-reported.sql@@ -0,0 +1,88 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- Check 3 fails on what the node reports about itself: a verdict other+-- than ok, a condition that is not OK, one of flags bits 0 to 3, a tamper+-- counter that rose since the first record of the boot, or a build that is+-- not in expected_builds. Flags bits 4 and 5 say the node is busy and do+-- not fail it, a condition pair this schema does not know is not read, and+-- counters a boot starts with are its baseline. The baseline is the+-- boot's first readable total: a record that could not read its counters+-- fails on its flags, sets no baseline and is compared with none.++-- The publication of testing/fixtures/keepalive/tree-1.1.0.json, as the+-- ingest job loads it: generation 3 with its three operations.+INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-base', 3, '1f327364233e3f2dcebcd13c0af8d84f886201531b135294bd7356a2f7ed680b', '4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942', 3, now64(3) - INTERVAL 10 MINUTE);+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-base', 1, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144', '9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6', '59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885', '13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43'),+('fleet-base', 2, 'delete', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b', 'e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55', 'f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1', '5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b'),+('fleet-base', 3, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', 'b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a', '653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97', '82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf', 'bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc');+INSERT INTO shirudo.expected_builds (version_id, note) VALUES+('d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f', 'shirudo 2026.11');++-- The bodies of testing/fixtures/keepalive/, byte for byte.+CREATE TEMPORARY TABLE fixture (name String, body String);+INSERT INTO fixture VALUES+('node-a-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1","mask":"VA==","set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1,"not_ok":0}');++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT node.1, arrayFold((body, change) -> replaceOne(body, change.1, change.2), node.3, f.body),+ 1, concat('000b', node.1), 'QUtB', 1, 1000+FROM+(+ SELECT arrayJoin([+ ('degraded', 'node-a-1.1.0', [('"verdict":"ok"', '"verdict":"degraded"')]),+ ('config-warn', 'node-a-1.1.0', [('"cond":5461', '"cond":6485')]),+ ('eighth-condition', 'node-a-1.1.0', [('"cond":5461', '"cond":38229')]),+ ('rebound', 'node-a-1.1.0', [('"flags":0', '"flags":1')]),+ ('no-counters', 'node-a-1.1.0', [('"flags":0', '"flags":8'), ('"tamper":[0,', '"tamper":null,"was":[0,')]),+ ('busy', 'node-a-1.1.0', [('"flags":0', '"flags":32')]),+ ('other-build', 'node-a-1.1.0', [('"version_id":"d6d918ad', '"version_id":"0badc0de')]),+ ('tampered-with', 'node-a-1.1.0', [('"flags":0', '"flags":0')]),+ ('noisy-boot', 'node-a-1.1.0', [('"tamper":[0,0,', '"tamper":[0,3,')])+ ]) AS node+) AS n+INNER JOIN fixture AS f ON f.name = node.2;++-- A later record of the same boot with one counter up by two, and a+-- later record of the boot that started with three.+INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT 'tampered-with', replaceOne(body, '"tamper":[0,0,', '"tamper":[0,2,'), 1, '000btampered-with', 'QUtB', 1, 2000+FROM fixture;+INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT 'noisy-boot', replaceOne(body, '"tamper":[0,0,', '"tamper":[0,3,'), 1, '000bnoisy-boot', 'QUtB', 1, 2000+FROM fixture;++-- Three boots whose first record could not read the counters. The first+-- then reads a total of three and keeps it: nothing rose. The second+-- reads three, then five: a rise of two. The third reads three and then+-- cannot read them again, which is not a fall to zero.+INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT record.1, arrayFold((body, change) -> replaceOne(body, change.1, change.2), record.3, f.body),+ 1, concat('000b', record.1), 'QUtB', 1, record.2+FROM+(+ SELECT arrayJoin([+ ('unreadable-first', 1000, [('"flags":0', '"flags":8'), ('"tamper":[0,', '"tamper":null,"was":[0,')]),+ ('unreadable-first', 2000, [('"tamper":[0,0,', '"tamper":[0,3,')]),+ ('unreadable-first', 3000, [('"tamper":[0,0,', '"tamper":[0,3,')]),+ ('unreadable-then-rise', 1000, [('"flags":0', '"flags":8'), ('"tamper":[0,', '"tamper":null,"was":[0,')]),+ ('unreadable-then-rise', 2000, [('"tamper":[0,0,', '"tamper":[0,3,')]),+ ('unreadable-then-rise', 3000, [('"tamper":[0,0,', '"tamper":[0,5,')]),+ ('unreadable-again', 1000, [('"flags":0', '"flags":8'), ('"tamper":[0,', '"tamper":null,"was":[0,')]),+ ('unreadable-again', 2000, [('"tamper":[0,0,', '"tamper":[0,3,')]),+ ('unreadable-again', 3000, [('"flags":0', '"flags":8'), ('"tamper":[0,', '"tamper":null,"was":[0,')])+ ]) AS record+) AS r, fixture AS f;++SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;++SELECT node_id, status, failed_check, log[3] FROM shirudo.node_status ORDER BY node_id;++SELECT 'baselines';+SELECT substring(ak_name, 5) AS node, argMinMerge(tamper_first)+FROM shirudo.boot_first+WHERE ak_name LIKE '000bunreadable%' OR ak_name IN ('000bno-counters', '000bnoisy-boot')+GROUP BY ak_name, boot_id ORDER BY node;diff --git a/tools/backend/test/status-set.expected b/tools/backend/test/status-set.expectednew file mode 100644index 00000000..4a851515--- /dev/null+++ b/tools/backend/test/status-set.expected@@ -0,0 +1,16 @@+at the head+clean healthy 0 5 head: pass, seq 3 of 3, generation 3 6 set: pass, 1 loaded+drift unhealthy 6 5 head: pass, seq 3 of 3, generation 3 6 set: FAIL drift, 1 loaded+drift-both unhealthy 6 5 head: pass, seq 3 of 3, generation 3 6 set: FAIL sync in progress at head, 1 loaded+drift-pending unhealthy 6 5 head: pass, seq 3 of 3, generation 3 6 set: FAIL sync in progress at head, 1 loaded+drift-unsettled healthy 0 5 head: pass, seq 3 of 3, generation 3 6 set: snapshot unsettled, 1 loaded+pending unhealthy 6 5 head: pass, seq 3 of 3, generation 3 6 set: FAIL sync in progress at head, 1 loaded+one operation behind+clean healthy 0 5 head: behind, seq 3 of 4, generation 3 6 set: pass, 1 loaded+drift unhealthy 6 5 head: behind, seq 3 of 4, generation 3 6 set: FAIL drift, 1 loaded+drift-both healthy 0 5 head: behind, seq 3 of 4, generation 3 6 set: sync in progress, 1 loaded+drift-pending healthy 0 5 head: behind, seq 3 of 4, generation 3 6 set: sync in progress, 1 loaded+drift-unsettled healthy 0 5 head: behind, seq 3 of 4, generation 3 6 set: snapshot unsettled, 1 loaded+pending healthy 0 5 head: behind, seq 3 of 4, generation 3 6 set: sync in progress, 1 loaded+caught up+clean healthy 0 4 chain: pass, root 3babcd63 5 head: pass, seq 4 of 4, generation 4 6 set: pass, 2 loadeddiff --git a/tools/backend/test/status-set.sql b/tools/backend/test/status-set.sqlnew file mode 100644index 00000000..296fadfe--- /dev/null+++ b/tools/backend/test/status-set.sql@@ -0,0 +1,78 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- Check 6 folds the applied operations into the set they leave loaded and+-- holds its hash against set_sha256. It is exact: the first record with+-- flags bits 4 and 5 clear whose set differs is drift. A record taken+-- while the node was busy is not evaluated and says why, and bit 4 on a+-- node at the head of its tree is a contradiction that fails at once,+-- since an operation in flight has a seq above last_seq. The nodes here+-- report the set of release 1.0.0 after applying 1.1.0, first at the head+-- and then one operation behind it.++-- The publication of testing/fixtures/keepalive/tree-1.1.0.json, as the+-- ingest job loads it: generation 3 with its three operations.+INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-base', 3, '1f327364233e3f2dcebcd13c0af8d84f886201531b135294bd7356a2f7ed680b', '4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942', 3, now64(3) - INTERVAL 10 MINUTE);+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-base', 1, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144', '9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6', '59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885', '13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43'),+('fleet-base', 2, 'delete', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b', 'e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55', 'f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1', '5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b'),+('fleet-base', 3, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', 'b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a', '653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97', '82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf', 'bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc');+INSERT INTO shirudo.expected_builds (version_id, note) VALUES+('d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f', 'shirudo 2026.11');++-- The bodies of testing/fixtures/keepalive/, byte for byte.+CREATE TEMPORARY TABLE fixture (name String, body String);+INSERT INTO fixture VALUES+('node-a-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1","mask":"VA==","set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1,"not_ok":0}');++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT node.1, arrayFold((body, change) -> replaceOne(body, change.1, change.2), node.3, f.body),+ 1, concat('000b', node.1), 'QUtB', 1, 1000+FROM+(+ SELECT arrayJoin([+ ('clean', 'node-a-1.1.0', [('"flags":0', '"flags":0')]),+ ('drift', 'node-a-1.1.0', [('74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf', '6c9e113d02cd14646f617d7bba4a092b91bc3802dfdaae50e2fef7a01e0580aa')]),+ ('drift-pending', 'node-a-1.1.0', [('74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf', '6c9e113d02cd14646f617d7bba4a092b91bc3802dfdaae50e2fef7a01e0580aa'), ('"flags":0', '"flags":16')]),+ ('drift-unsettled', 'node-a-1.1.0', [('74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf', '6c9e113d02cd14646f617d7bba4a092b91bc3802dfdaae50e2fef7a01e0580aa'), ('"flags":0', '"flags":32')]),+ ('drift-both', 'node-a-1.1.0', [('74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf', '6c9e113d02cd14646f617d7bba4a092b91bc3802dfdaae50e2fef7a01e0580aa'), ('"flags":0', '"flags":48')]),+ ('pending', 'node-a-1.1.0', [('"flags":0', '"flags":16')])+ ]) AS node+) AS n+INNER JOIN fixture AS f ON f.name = node.2;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;++SELECT 'at the head';+SELECT node_id, status, failed_check, log[5], log[6] FROM shirudo.node_status ORDER BY node_id;++-- Generation 4 adds an operation, so the same records are now of nodes+-- that have one to go, and a sync may well be in progress.+INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-base', 4, '2396a1256ac4b1c6849c931ddb8018bdd984bb2383be21bb819a33b95d8d603f', '1f327364233e3f2dcebcd13c0af8d84f886201531b135294bd7356a2f7ed680b', 4, now64(3));+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-base', 4, 'add', 'net-guard', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', 'd6ab812e3d3e14d19f6d5b0105c130432de572417c2d1c1c2e02fb6ebe311c3f', '9f102fe3a7d618f9960701e25169aff66169d27e1d7dcf220124a9bf2047436d', '328775f7f18fd7ead422abe642a2b9cb85428593130a7d6bd230e6b8aee6b7aa', '8aa179bbf5f35a9af488b8f0e4e8d7d0c407913f70d54f5d03b746c5c955fd00');+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;++SELECT 'one operation behind';+SELECT node_id, status, failed_check, log[5], log[6] FROM shirudo.node_status ORDER BY node_id;++-- At the new head with both upatches loaded.++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT node.1, arrayFold((body, change) -> replaceOne(body, change.1, change.2), node.3, f.body),+ 1, concat('000b', node.1), 'QUtB', 1, 2000+FROM+(+ SELECT arrayJoin([+ ('clean', 'node-a-1.1.0', [('"generation":3', '"generation":4'), ('"last_seq":3', '"last_seq":4'), ('154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1', '3babcd63369daa5be22bf21c72481420e80a62e882027df3d21a8e567d622e2a'), ('"mask":"VA=="', '"mask":"VQ=="'), ('"set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1', '"set_sha256":"109355c70bab5428d322402784108238ea1f2a0aab107d81580f74dac64fe0c2","count":2')])+ ]) AS node+) AS n+INNER JOIN fixture AS f ON f.name = node.2;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;++SELECT 'caught up';+SELECT node_id, status, failed_check, log[4], log[5], log[6] FROM shirudo.node_status WHERE node_id = 'clean';diff --git a/tools/backend/test/status-stale.expected b/tools/backend/test/status-stale.expectednew file mode 100644index 00000000..987504b9--- /dev/null+++ b/tools/backend/test/status-stale.expected@@ -0,0 +1,13 @@+fresh healthy 0 1 3 reported: pass, verdict ok, cond 0x1555, flags 0, tamper +0, build d6d918ad+silent stale 2 0 3 reported: pass, verdict ok, cond 0x1555, flags 0, tamper +0, build d6d918ad+silent-and-degraded stale 2 0 3 reported: FAIL, verdict degraded, cond 0x1555, flags 0, tamper +0, build d6d918ad+fresh fresh stale untrusted 2 3 3 3 1+silent silent stale untrusted 2 3 3 3 1+silent-and-degraded silent-and-degraded stale untrusted 2 3 3 3 1+fresh 1 signed: pass, untrusted, 0 rejected in the last hour+fresh 2 fresh: FAIL, last record N s ago+fresh 3 reported: pass, verdict ok, cond 0x1555, flags 0, tamper +0, build d6d918ad+fresh 4 chain: pass, root 15452248+fresh 5 head: pass, seq 3 of 3, generation 3+fresh 6 set: pass, 1 loaded+fresh 7 peers: pass, 3 in groupdiff --git a/tools/backend/test/status-stale.sql b/tools/backend/test/status-stale.sqlnew file mode 100644index 00000000..eaa40700--- /dev/null+++ b/tools/backend/test/status-stale.sql@@ -0,0 +1,66 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- A node whose newest record is older than stale_seconds is stale with+-- failed_check 2, whatever that record says, and its log still shows what+-- it said. The threshold comes from shirudo.settings, lowered here to four+-- seconds: a node turns stale while the test waits six.++-- The publication of testing/fixtures/keepalive/tree-1.1.0.json, as the+-- ingest job loads it: generation 3 with its three operations.+INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-base', 3, '1f327364233e3f2dcebcd13c0af8d84f886201531b135294bd7356a2f7ed680b', '4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942', 3, now64(3) - INTERVAL 10 MINUTE);+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-base', 1, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144', '9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6', '59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885', '13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43'),+('fleet-base', 2, 'delete', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b', 'e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55', 'f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1', '5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b'),+('fleet-base', 3, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', 'b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a', '653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97', '82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf', 'bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc');+INSERT INTO shirudo.expected_builds (version_id, note) VALUES+('d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f', 'shirudo 2026.11');++-- The bodies of testing/fixtures/keepalive/, byte for byte.+CREATE TEMPORARY TABLE fixture (name String, body String);+INSERT INTO fixture VALUES+('node-a-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1","mask":"VA==","set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1,"not_ok":0}');++INSERT INTO shirudo.settings (stale_seconds, stuck_seconds, window, keepalive_retention_seconds)+VALUES (4, 3600, 512, 3600);+++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT node.1, arrayFold((body, change) -> replaceOne(body, change.1, change.2), node.3, f.body),+ 1, concat('000b', node.1), 'QUtB', 1, 1000+FROM+(+ SELECT arrayJoin([+ ('fresh', 'node-a-1.1.0', [('"flags":0', '"flags":0')])+ ]) AS node+) AS n+INNER JOIN fixture AS f ON f.name = node.2;++INSERT INTO shirudo.checked (received, host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT now64(3) - INTERVAL 1 MINUTE, node.1, arrayFold((body, change) -> replaceOne(body, change.1, change.2), node.3, f.body),+ 1, concat('000b', node.1), 'QUtB', 1, 1000+FROM+(+ SELECT arrayJoin([+ ('silent', 'node-a-1.1.0', [('"flags":0', '"flags":0')]),+ ('silent-and-degraded', 'node-a-1.1.0', [('"verdict":"ok"', '"verdict":"degraded"')])+ ]) AS node+) AS n+INNER JOIN fixture AS f ON f.name = node.2;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;++SELECT node_id, status, failed_check, log[2] LIKE '2 fresh: pass, last record % s ago', log[3]+FROM shirudo.node_status ORDER BY node_id;++SELECT sleep(3) FORMAT Null;+SELECT sleep(3) FORMAT Null;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SELECT node_id, host_name, status, trust, failed_check, generation, last_seq, head_seq, loaded+FROM shirudo.node_status ORDER BY node_id;+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+WHERE node_id = 'fresh'+ORDER BY node_id, line;diff --git a/tools/backend/test/status-stuck.expected b/tools/backend/test/status-stuck.expectednew file mode 100644index 00000000..879d8987--- /dev/null+++ b/tools/backend/test/status-stuck.expected@@ -0,0 +1,26 @@+an hour allowed, the newest publication is 10 minutes old+at-3 unhealthy 5 3 3 6+at-4 healthy 0 4 4 6+at-5 healthy 0 6 5 6+at-6 healthy 0 7 6 6+at-3 4 chain: pass, root 15452248+at-3 5 head: FAIL stuck, seq 3 of 6, generation 3+at-3 6 set: pass, 1 loaded+at-3 7 peers: no peers, 1 in group+at-4 4 chain: pass, root 3babcd63+at-4 5 head: behind, seq 4 of 6, generation 4+at-4 6 set: pass, 2 loaded+at-4 7 peers: no peers, 1 in group+at-5 4 chain: pass, root 3babcd63+at-5 5 head: behind, seq 5 of 6, generation 6+at-5 6 set: pass, 2 loaded+at-5 7 peers: no peers, 1 in group+at-6 4 chain: pass, root 3babcd63+at-6 5 head: pass, seq 6 of 6, generation 7+at-6 6 set: pass, 2 loaded+at-6 7 peers: no peers, 1 in group+two hours allowed+at-3 healthy 0 5 head: behind, seq 3 of 6, generation 3+at-4 healthy 0 5 head: behind, seq 4 of 6, generation 4+at-5 healthy 0 5 head: behind, seq 5 of 6, generation 6+at-6 healthy 0 5 head: pass, seq 6 of 6, generation 7diff --git a/tools/backend/test/status-stuck.sql b/tools/backend/test/status-stuck.sqlnew file mode 100644index 00000000..282bcdcb--- /dev/null+++ b/tools/backend/test/status-stuck.sql@@ -0,0 +1,72 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- The stuck clock of check 5 starts at the oldest publication a node has+-- not finished, not at the newest one. An operator who publishes more+-- often than stuck_seconds, here every 30 minutes with an hour+-- allowed, still sees a node that never moves: the node at 3 has had+-- generation 4 for 70 minutes and is stuck, while the nodes at 4 and 5+-- are behind publications 40 and 10 minutes old and are given their hour.+-- A publication the timer never loaded, generation 5 here, costs nothing:+-- the clock of the node at 4 starts when the first publication beyond it+-- was loaded.++-- The publication of testing/fixtures/keepalive/tree-1.1.0.json, as the+-- ingest job loads it: generation 3 with its three operations.+INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-base', 3, '1f327364233e3f2dcebcd13c0af8d84f886201531b135294bd7356a2f7ed680b', '4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942', 3, now64(3) - INTERVAL 90 MINUTE);+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-base', 1, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144', '9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6', '59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885', '13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43'),+('fleet-base', 2, 'delete', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b', 'e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55', 'f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1', '5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b'),+('fleet-base', 3, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', 'b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a', '653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97', '82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf', 'bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc');+INSERT INTO shirudo.expected_builds (version_id, note) VALUES+('d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f', 'shirudo 2026.11');++-- The bodies of testing/fixtures/keepalive/, byte for byte.+CREATE TEMPORARY TABLE fixture (name String, body String);+INSERT INTO fixture VALUES+('node-a-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1","mask":"VA==","set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1,"not_ok":0}');+++-- Generations 4, 6 and 7, loaded 70, 40 and 10 minutes ago. Operations 5+-- and 6 select other nodes, so a node that passes them keeps its root+-- and its set.+INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-base', 4, '2396a1256ac4b1c6849c931ddb8018bdd984bb2383be21bb819a33b95d8d603f', '1f327364233e3f2dcebcd13c0af8d84f886201531b135294bd7356a2f7ed680b', 4, now64(3) - INTERVAL 70 MINUTE),+('fleet-base', 6, '5d1e0a8b7f6c4e3d2c1b0a998877665544332211ffeeddccbbaa00112233445a', '7c2f9d1e4b6a8c0e2f4a6b8d0c1e3f5a7b9d1c3e5f7a9b1d3c5e7f9a1b3d5c7e', 5, now64(3) - INTERVAL 40 MINUTE),+('fleet-base', 7, '9e8d7c6b5a493827161504f3e2d1c0bfaeddccbbaa99887766554433221100ab', '5d1e0a8b7f6c4e3d2c1b0a998877665544332211ffeeddccbbaa00112233445a', 6, now64(3) - INTERVAL 10 MINUTE);+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-base', 4, 'add', 'net-guard', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', 'd6ab812e3d3e14d19f6d5b0105c130432de572417c2d1c1c2e02fb6ebe311c3f', '9f102fe3a7d618f9960701e25169aff66169d27e1d7dcf220124a9bf2047436d', '328775f7f18fd7ead422abe642a2b9cb85428593130a7d6bd230e6b8aee6b7aa', '8aa179bbf5f35a9af488b8f0e4e8d7d0c407913f70d54f5d03b746c5c955fd00'),+('fleet-base', 5, 'add', 'core-guard', '{"labels":{"role":["core"]}}', 'oci://registry.example.com/shirudo/fleet-base', '0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0', '1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f809', '2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8091a', '3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8091a2b'),+('fleet-base', 6, 'delete', 'core-guard', '{"labels":{"role":["core"]}}', 'oci://registry.example.com/shirudo/fleet-base', '4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c', '5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d', '6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e', '708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f');++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT node.1, arrayFold((body, change) -> replaceOne(body, change.1, change.2), node.3, f.body),+ 1, concat('000b', node.1), 'QUtB', 1, 1000+FROM+(+ SELECT arrayJoin([+ ('at-3', 'node-a-1.1.0', [('"flags":0', '"flags":0')]),+ ('at-4', 'node-a-1.1.0', [('"generation":3', '"generation":4'), ('"last_seq":3', '"last_seq":4'), ('154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1', '3babcd63369daa5be22bf21c72481420e80a62e882027df3d21a8e567d622e2a'), ('"mask":"VA=="', '"mask":"VQ=="'), ('"set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1', '"set_sha256":"109355c70bab5428d322402784108238ea1f2a0aab107d81580f74dac64fe0c2","count":2')]),+ ('at-5', 'node-a-1.1.0', [('"generation":3', '"generation":6'), ('"last_seq":3', '"last_seq":5'), ('154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1', '3babcd63369daa5be22bf21c72481420e80a62e882027df3d21a8e567d622e2a'), ('"mask":"VA=="', '"mask":"VYA="'), ('"set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1', '"set_sha256":"109355c70bab5428d322402784108238ea1f2a0aab107d81580f74dac64fe0c2","count":2')]),+ ('at-6', 'node-a-1.1.0', [('"generation":3', '"generation":7'), ('"last_seq":3', '"last_seq":6'), ('154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1', '3babcd63369daa5be22bf21c72481420e80a62e882027df3d21a8e567d622e2a'), ('"mask":"VA=="', '"mask":"VaA="'), ('"set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1', '"set_sha256":"109355c70bab5428d322402784108238ea1f2a0aab107d81580f74dac64fe0c2","count":2')])+ ]) AS node+) AS n+INNER JOIN fixture AS f ON f.name = node.2;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;++SELECT 'an hour allowed, the newest publication is 10 minutes old';+SELECT node_id, status, failed_check, generation, last_seq, head_seq FROM shirudo.node_status ORDER BY node_id;+SELECT node_id, line FROM shirudo.node_status ARRAY JOIN log AS line+WHERE line >= '4' ORDER BY node_id, line;++-- With two hours allowed the node at 3 is behind again: the clock is the+-- threshold's, not a state the backend keeps.+INSERT INTO shirudo.settings (stale_seconds, stuck_seconds, window, keepalive_retention_seconds)+VALUES (180, 7200, 512, 3600);+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;++SELECT 'two hours allowed';+SELECT node_id, status, failed_check, log[5] FROM shirudo.node_status ORDER BY node_id;diff --git a/tools/backend/test/stub-aws.sh b/tools/backend/test/stub-aws.shnew file mode 100755index 00000000..6c5fb1ce--- /dev/null+++ b/tools/backend/test/stub-aws.sh@@ -0,0 +1,52 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# test/stub-aws.sh -- stand in for `aws s3 cp --recursive` in the tests+# of jobs/sbom-scan. The object s3://<bucket>/<key> is the file+# STUB_S3_ROOT/<bucket>/<key>. It names its arguments on standard error,+# the destination as <directory> since the job makes it, copies the+# files whose names the --include patterns end in and exits with+# STUB_S3_STATUS, 0 by default.++set -eu++[ "${1:-} ${2:-} ${3:-}" = 's3 cp --recursive' ] || {+ echo "stub-aws: only s3 cp --recursive, not $*" >&2+ exit 2+}+said='s3 cp --recursive'+shift 3+source=+destination=+names=+while [ $# -gt 0 ]; do+ case "$1" in+ s3://*)+ source=$STUB_S3_ROOT/${1#s3://}+ said="$said $1" ;;+ --include)+ names="$names ${2##*/}"+ said="$said $1 $2"+ shift ;;+ --exclude)+ said="$said $1 $2"+ shift ;;+ -*)+ said="$said $1" ;;+ *)+ destination=$1+ said="$said <directory>" ;;+ esac+ shift+done+printf 'stub-aws: %s\n' "$said" >&2+[ "${STUB_S3_STATUS:-0}" -eq 0 ] || exit "$STUB_S3_STATUS"++cd "$source"+for name in $names; do+ find . -type f -name "$name" | while read -r file; do+ mkdir -p "$destination/${file%/*}"+ cp "$file" "$destination/$file"+ done+donediff --git a/tools/backend/test/stub-quote-check.sh b/tools/backend/test/stub-quote-check.shnew file mode 100755index 00000000..8234bf5a--- /dev/null+++ b/tools/backend/test/stub-quote-check.sh@@ -0,0 +1,61 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# A stand-in for shirudo-quote-check that verifies nothing, so that the+# SQL tests need neither a TPM nor the shirudo tree. It reads the same+# rows and prints the same lines; a test steers the answer through the+# fields, which only have to look like base64:+#+# attest <reset_count>/<clock>/<body_sha256>+# sig "good", or anything else for bad_signature+# ak any text; ak_name is 000b and the SHA-256 of that text++set -u++tab=$(printf '\t')++answer()+{+ attest=${1%%"$tab"*}+ rest=${1#*"$tab"}+ sig=${rest%%"$tab"*}+ rest=${rest#*"$tab"}+ ak=${rest%%"$tab"*}+ body_sha256=${rest#*"$tab"}++ reset_count=${attest%%/*}+ rest=${attest#*/}+ clock=${rest%%/*}+ extra=${rest#*/}++ case "$1" in+ *"$tab"*"$tab"*"$tab"*"$tab"*) reset_count= ;;+ *"$tab"*"$tab"*"$tab"*) ;;+ *) reset_count= ;;+ esac+ case "$attest" in+ */*/*/*) reset_count= ;;+ */*/*) ;;+ *) reset_count= ;;+ esac+ case "$reset_count$clock" in+ ''|*[!0-9]*) reset_count= ;;+ esac+ if [ -z "$reset_count" ] || [ -z "$clock" ] || [ -z "$sig" ] ||+ [ -z "$ak" ]; then+ printf '{"ok":0,"reason":"malformed"}\n'+ elif [ "$sig" != good ]; then+ printf '{"ok":0,"reason":"bad_signature"}\n'+ elif [ "$extra" != "$body_sha256" ]; then+ printf '{"ok":0,"reason":"body_mismatch"}\n'+ else+ digest=$(printf '%s' "$ak" | sha256sum)+ printf '{"ok":1,"ak_name":"000b%s","ak_public":"%s","reset_count":%s,"clock":%s}\n' \+ "${digest%% *}" "$ak" "$reset_count" "$clock"+ fi+}++while IFS= read -r row; do+ answer "$row"+donediff --git a/tools/backend/test/stub-shirudo.sh b/tools/backend/test/stub-shirudo.shnew file mode 100755index 00000000..d8f4ffe4--- /dev/null+++ b/tools/backend/test/stub-shirudo.sh@@ -0,0 +1,14 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# test/stub-shirudo.sh -- stand in for `shirudo bpm tree show` in the+# tests of jobs/tree-ingest. It fetches and verifies nothing: it names+# its arguments on standard error, prints the file STUB_SHOW_OUTPUT+# names and exits with STUB_SHOW_STATUS, 0 by default.++set -eu++printf 'stub-shirudo: %s\n' "$*" >&2+cat "$STUB_SHOW_OUTPUT"+exit "${STUB_SHOW_STATUS:-0}"diff --git a/tools/backend/test/stub-trivy.sh b/tools/backend/test/stub-trivy.shnew file mode 100755index 00000000..6e7deb2a--- /dev/null+++ b/tools/backend/test/stub-trivy.sh@@ -0,0 +1,47 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# test/stub-trivy.sh -- stand in for Trivy in the tests of jobs/sbom-scan.+# It matches nothing against any database. `version` prints the version+# of a made-up database. `sbom <options> <file>` prints the report in+# test/trivy/ named by the SHA-256 of the file, or one without findings+# when there is none, and fails when STUB_TRIVY_FAIL is that SHA-256.+# Each call is appended to the file STUB_TRIVY_LOG names, with the SBOM+# by its name alone, since it lies in a directory of the job's own.++set -eu++reports=$(cd "$(dirname "$0")" && pwd)/trivy++log()+{+ [ -z "${STUB_TRIVY_LOG:-}" ] || printf 'stub-trivy: %s\n' "$*" >>"$STUB_TRIVY_LOG"+}++case "${1:-}" in+version)+ log "$@"+ printf '%s\n' '{"Version":"0.0.0-stub","VulnerabilityDB":{"Version":2,"NextUpdate":"2026-11-11T12:00:00Z","UpdatedAt":"2026-11-11T06:00:00Z","DownloadedAt":"2026-11-11T07:00:00Z"}}' ;;+sbom)+ for file; do :; done+ sha=$(sha256sum "$file" | cut -d ' ' -f 1)+ args=+ for arg; do+ [ "$arg" = "$file" ] && arg=${file##*/}+ args="$args $arg"+ done+ log "${args# }"+ if [ "$sha" = "${STUB_TRIVY_FAIL:-}" ]; then+ echo 'FATAL stub: the scan failed' >&2+ exit 1+ fi+ if [ -f "$reports/$sha.json" ]; then+ cat "$reports/$sha.json"+ else+ printf '%s\n' '{"SchemaVersion":2,"ArtifactType":"cyclonedx","Results":[]}'+ fi ;;+*)+ echo "stub-trivy: no command $*" >&2+ exit 2 ;;+esacdiff --git a/tools/backend/test/tree-ingest-refused.expected b/tools/backend/test/tree-ingest-refused.expectednew file mode 100644index 00000000..79afd2cf--- /dev/null+++ b/tools/backend/test/tree-ingest-refused.expected@@ -0,0 +1,97 @@+tree-ingest: input refused: it is not a JSON value+empty: status 1+tree-ingest: input refused: it is not a JSON value+not JSON: status 1+tree-ingest: input refused: it is not a JSON value+cut short: status 1+tree-ingest: input refused: the input is not an object+an array: status 1+tree-ingest: input refused: base.seq of segment 2 of the walk is not the seq of head of segment 1+two objects: status 1+tree-ingest: input refused: the input has no manifest_digest+a line per value: status 1+tree-ingest: input refused: the input has no manifest_digest+no manifest digest: status 1+tree-ingest: input refused: the input has no document+no document: status 1+tree-ingest: input refused: manifest_digest of the input is not "sha256:" and 64 lowercase hex digits+digest without algorithm: status 1+tree-ingest: input refused: layer_digest of artifact of the operation with seq 1 is not "sha256:" and 64 lowercase hex digits+short digest: status 1+tree-ingest: input refused: schema of the document is not 1+schema 2: status 1+tree-ingest: input refused: tree_id of the document is not 1 to 255 characters of [A-Za-z0-9._-]+tree_id: status 1+tree-ingest: input refused: generation of the document is not an unsigned 64-bit integer+generation: status 1+tree-ingest: input refused: seq of operation 2 of the document is not an unsigned 64-bit integer+negative seq: status 1+tree-ingest: input refused: seq of head is not an unsigned 64-bit integer+fractional seq: status 1+tree-ingest: input refused: seq of operation 2 of the document is used twice+seq twice: status 1+tree-ingest: input refused: op of the operation with seq 2 is neither add nor delete+op: status 1+tree-ingest: input refused: selector of the operation with seq 1 is not an object+selector: status 1+tree-ingest: input refused: the operation with seq 1 has no artifact+no artifact: status 1+tree-ingest: input refused: operations of the document is not an array+operations: status 1+tree-ingest: input refused: a key is given twice in one object+key twice: status 1+tree-ingest: input refused: base has no segment_manifest_digest+segment: status 1+tree-ingest: input refused: base has history_root but its seq is 0+base keys at seq 0: status 1+tree-ingest: input refused: seq of operation 3 of the document is not above base.seq and at most the seq of head+operation past head: status 1+tree-ingest: input refused: segment 1 of the walk has base.seq 2: the walk does not reach base.seq 0+walk from a later segment: status 1+tree-ingest: input refused: segment 1 of the walk has base.seq 4: the walk does not reach base.seq 0+segments newest first: status 1+tree-ingest: input refused: base.seq of segment 2 of the walk is not the seq of head of segment 1+a segment left out: status 1+tree-ingest: input refused: base.seq of segment 2 of the walk is not the seq of head of segment 1+base not the head before: status 1+tree-ingest: input refused: segment_manifest_digest of segment 2 of the walk is not the manifest digest of segment 1+another predecessor: status 1+tree-ingest: input refused: segment 2 of the walk: base has no segment_manifest_digest+no predecessor: status 1+tree-ingest: input refused: segment 2 of the walk: base has no history_root+no history root: status 1+tree-ingest: input refused: segment 2 of the walk: history_root of base is not 64 lowercase hex digits+history root with sha256:: status 1+tree-ingest: input refused: generation of segment 3 of the walk is not above that of segment 2+generation going back: status 1+tree-ingest: input refused: tree_id of segment 3 of the walk is not that of segment 2+another tree: status 1+tree-ingest: input refused: segment 3 of the walk: seq of operation 1 of the document is not above base.seq and at most the seq of head+operation below base: status 1+tree-ingest: input refused: segment 3 of the walk: the document has no operations but its base.seq is above 0+no operations: status 1+tree-ingest: input refused: a key is given twice in one object+key twice in a segment: status 1+rows after the refusals:+0 0 0+stub-shirudo: bpm tree show oci://registry.example.com/shirudo/fleet-base --cert /certs/operator.pem --walk+tree-ingest: bpm tree show failed, nothing loaded+failed command: status 1+0 0 0+tree-ingest: needs --cert or TREE_CERT+no certificate: status 1+usage: tree-ingest [--shirudo <path>] [--reference <ref>] [--cert <file>] [oci://<repository>]+ tree-ingest --input <file>|-+no repository: status 2+stub-shirudo: bpm tree show oci://registry.example.com/shirudo/fleet-base --reference tree --cert /certs/operator.pem --walk+tree-ingest: loaded fleet-base generation 3 (operations: 3, fixes: 2)+tree-ingest: fleet-base generation 3 is loaded with manifest 4c1d7e6b0a9f38e2d5c4b3a2918f7e6d5c4b3a29180f7e6d5c4b3a2918f7e6d5, this one is 5c1d7e6b0a9f38e2d5c4b3a2918f7e6d5c4b3a29180f7e6d5c4b3a2918f7e6d5; nothing loaded+another manifest: status 1+tree-ingest: loaded fleet-segments generation 2 (operations: 2, fixes: 1)+tree-ingest: loaded fleet-segments generation 4 (operations: 2, fixes: 1)+tree-ingest: fleet-segments generation 4 is loaded with manifest e114111ddf285a40bff312f278926be5b38f2021a417adcf83d07aca76f4f440, this one is f114111ddf285a40bff312f278926be5b38f2021a417adcf83d07aca76f4f440; nothing loaded+another manifest in a walk: status 1+fleet-base 3 4c1d7e6b0a9f38e2d5c4b3a2918f7e6d5c4b3a29180f7e6d5c4b3a2918f7e6d5 3+fleet-segments 2 2960661252c50e7232cd9781a0ccdbee045bfc40e2f081d89ba3c8fbe1c23495 2+fleet-segments 4 e114111ddf285a40bff312f278926be5b38f2021a417adcf83d07aca76f4f440 4+7 4diff --git a/tools/backend/test/tree-ingest-refused.sh b/tools/backend/test/tree-ingest-refused.shnew file mode 100644index 00000000..3f5ee063--- /dev/null+++ b/tools/backend/test/tree-ingest-refused.sh@@ -0,0 +1,115 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# jobs/tree-ingest refuses input that is not what `bpm tree show+# --walk` prints, a walk whose segments do not join up, a failed `bpm+# tree show` and another manifest for a generation it has loaded, each+# with a message and without inserting anything. The first form of the+# job, which runs the command, is shown with test/stub-shirudo.sh.++set -eu++test=$(cd "$(dirname "$0")" && pwd)+job=$test/../jobs/tree-ingest+show=$test/tree-show-1.1.0.json+walk=$test/tree-show-walk.json++query()+{+ # shellcheck disable=SC2086 # a command with its options, to be split+ $CLICKHOUSE_CLIENT --query "$1"+}++rows()+{+ query "SELECT (SELECT count() FROM shirudo.tree_pubs),+ (SELECT count() FROM shirudo.tree_ops),+ (SELECT count() FROM shirudo.upatch_fixes)"+}++# refused <what> [<sed expression>...]: the stored output, edited, must+# be refused with status 1.+refused()+{+ what=$1+ shift+ [ $# -gt 0 ] || set -- -e ''+ status=0+ sed "$@" "$input" | "$job" --input - 2>&1 || status=$?+ printf '%s: status %d\n' "$what" "$status"+ [ "$status" -eq 1 ]+}++input=$show++refused 'empty' -e d+refused 'not JSON' -e 's/^{/[/'+refused 'cut short' -e 's/"head".*//'+refused 'an array' -e 's/^/[/' -e 's/$/]/'+refused 'two objects' -e p+refused 'a line per value' -e 's/^.*"document"://' -e 's/}$//'+refused 'no manifest digest' -e 's/"manifest_digest":"sha256:4c1d[0-9a-f]*",//'+refused 'no document' -e 's/"document"/"documents"/'+refused 'digest without algorithm' -e 's/"manifest_digest":"sha256:4c1d/"manifest_digest":"4c1d/'+refused 'short digest' -e 's/"layer_digest":"sha256:9ecc/"layer_digest":"sha256:9ec/'+refused 'schema 2' -e 's/"schema":1/"schema":2/'+refused 'tree_id' -e 's/"tree_id":"fleet-base"/"tree_id":"fleet base"/'+refused 'generation' -e 's/"generation":3/"generation":"3"/'+refused 'negative seq' -e 's/"seq":2/"seq":-2/'+refused 'fractional seq' -e 's/"head":{"seq":3}/"head":{"seq":3.0}/'+refused 'seq twice' -e 's/{"seq":2/{"seq":1/'+refused 'op' -e 's/"op":"delete"/"op":"replace"/'+refused 'selector' -e 's/"selector":{"labels":{"role":\["edge"\]}}/"selector":"edge"/'+refused 'no artifact' -e 's/"artifact":/"artefact":/'+refused 'operations' -e 's/"operations":\[/"operations":{"list":[/' -e 's/\],"head"/]},"head"/'+refused 'key twice' -e 's/"generation":3/"generation":3,"generation":4/'+refused 'segment' -e 's/"base":{"seq":0}/"base":{"seq":2}/'+refused 'base keys at seq 0' \+ -e 's/"base":{"seq":0}/"base":{"seq":0,"history_root":"'"$(printf '%064d' 0)"'"}/'+refused 'operation past head' -e 's/"head":{"seq":3}/"head":{"seq":2}/'++input=$walk+seg2='"seq":2,"segment_manifest_digest":"sha256:2960661252c50e7232cd9781a0ccdbee045bfc40e2f081d89ba3c8fbe1c23495"'+refused 'walk from a later segment' -e 1d+refused 'segments newest first' -e '1!G;h;$!d'+refused 'a segment left out' -e 2d+refused 'base not the head before' -e "s/$seg2/\"seq\":1,\"segment_manifest_digest\":\"sha256:2960661252c50e7232cd9781a0ccdbee045bfc40e2f081d89ba3c8fbe1c23495\"/"+refused 'another predecessor' -e "2s/\"segment_manifest_digest\":\"sha256:2960/\"segment_manifest_digest\":\"sha256:3960/"+refused 'no predecessor' -e "2s/,\"segment_manifest_digest\":\"sha256:[0-9a-f]*\"//"+refused 'no history root' -e '2s/,"history_root":"[0-9a-f]*"//'+refused 'history root with sha256:' -e '2s/"history_root":"/"history_root":"sha256:/'+refused 'generation going back' -e '3s/"generation":5/"generation":4/'+refused 'another tree' -e '3s/"tree_id":"fleet-segments"/"tree_id":"fleet-base"/'+refused 'operation below base' -e '3s/{"seq":5,/{"seq":4,/'+refused 'no operations' -e '3s/"operations":\[.*\],"head"/"operations":[],"head"/'+refused 'key twice in a segment' -e '2s/"generation":4/"generation":4,"generation":4/'+input=$show+echo 'rows after the refusals:'+rows++status=0+STUB_SHOW_OUTPUT=$show STUB_SHOW_STATUS=1 "$job" \+ --shirudo "$test/stub-shirudo.sh" --cert /certs/operator.pem \+ oci://registry.example.com/shirudo/fleet-base 2>&1 || status=$?+printf 'failed command: status %d\n' "$status"+[ "$status" -eq 1 ]+rows++status=0+"$job" oci://registry.example.com/shirudo/fleet-base 2>&1 || status=$?+printf 'no certificate: status %d\n' "$status"+"$job" 2>&1 || status=$?+printf 'no repository: status %d\n' "$status"++STUB_SHOW_OUTPUT=$show SHIRUDO=$test/stub-shirudo.sh \+ TREE_REPOSITORY=oci://registry.example.com/shirudo/fleet-base \+ TREE_REFERENCE=tree TREE_CERT=/certs/operator.pem "$job" 2>&1++refused 'another manifest' -e 's/"manifest_digest":"sha256:4c1d/"manifest_digest":"sha256:5c1d/'++# One segment of a walk under another manifest than the loaded one+# refuses the whole walk, also the segments that are new.+head -n 2 "$walk" | "$job" --input - 2>&1+input=$walk+refused 'another manifest in a walk' -e 's/sha256:e114/sha256:f114/g'diff --git a/tools/backend/test/tree-ingest-refused.sql b/tools/backend/test/tree-ingest-refused.sqlnew file mode 100644index 00000000..ab923c62--- /dev/null+++ b/tools/backend/test/tree-ingest-refused.sql@@ -0,0 +1,11 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- After test/tree-ingest-refused.sh only the one publication that+-- `bpm tree show`, here its stub, printed is loaded, and the first two+-- segments of the walk, loaded before the walk that was refused.++SELECT tree_id, generation, manifest_digest, head_seq FROM shirudo.tree_pubs FINAL+ORDER BY tree_id, generation;+SELECT (SELECT count() FROM shirudo.tree_ops FINAL),+ (SELECT count() FROM shirudo.upatch_fixes FINAL);diff --git a/tools/backend/test/tree-ingest-variants.expected b/tools/backend/test/tree-ingest-variants.expectednew file mode 100644index 00000000..791f30a1--- /dev/null+++ b/tools/backend/test/tree-ingest-variants.expected@@ -0,0 +1,22 @@+tree-ingest: loaded no-fixes generation 3 (operations: 3, fixes: 0)+tree-ingest: operation 1: fixes is not an array of strings, loaded without fixes+tree-ingest: loaded bad-fixes generation 3 (operations: 3, fixes: 1)+tree-ingest: operation 1: fixes is not an array of strings, loaded without fixes+tree-ingest: loaded mixed-fixes generation 3 (operations: 3, fixes: 1)+tree-ingest: loaded first.tree generation 1 (operations: 1, fixes: 2)+tree_pubs+bad-fixes 3 4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942 3+first.tree 1 1+mixed-fixes 3 4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942 3+no-fixes 3 4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942 3+tree_ops+bad-fixes 3 [1,2,3]+first.tree 1 [1]+mixed-fixes 3 [1,2,3]+no-fixes 3 [1,2,3]+{"architecture":["x86_64","aarch64"],"kernel_release_prefix":["7.4."],"labels":{"role":["edge"],"site":["café \\"1\\""]}} ['café "1"']+upatch_fixes+bad-fixes 3 xfs-fix EXAMPLE-0101 fixes+first.tree 1 xfs-fix EXAMPLE-0101 fixes+first.tree 1 xfs-fix EXAMPLE-0202 fixes+mixed-fixes 3 xfs-fix EXAMPLE-0101 fixesdiff --git a/tools/backend/test/tree-ingest-variants.sh b/tools/backend/test/tree-ingest-variants.shnew file mode 100644index 00000000..2adc5bc2--- /dev/null+++ b/tools/backend/test/tree-ingest-variants.sh@@ -0,0 +1,61 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# Variants of the stored output that jobs/tree-ingest must load: a+# document without fixes, one whose first operation has a malformed+# fixes, and a first publication, without a parent, printed over many+# lines with a selector of several keys and two advisories.++set -eu++test=$(cd "$(dirname "$0")" && pwd)+job=$test/../jobs/tree-ingest+show=$test/tree-show-1.1.0.json++sed -e 's/"tree_id":"fleet-base"/"tree_id":"no-fixes"/' \+ -e 's/,"fixes":\["EXAMPLE-0101"\]//g' "$show" |+ "$job" --input - 2>&1++sed -e 's/"tree_id":"fleet-base"/"tree_id":"bad-fixes"/' \+ -e 's/"fixes":\["EXAMPLE-0101"\]/"fixes":"EXAMPLE-0101"/' "$show" |+ "$job" --input - 2>&1++sed -e 's/"tree_id":"fleet-base"/"tree_id":"mixed-fixes"/' \+ -e 's/"fixes":\["EXAMPLE-0101"\]/"fixes":["EXAMPLE-0101",101]/' "$show" |+ "$job" --input - 2>&1++"$job" --input - 2>&1 <<'END'++{+ "manifest_digest": "sha256:1111111111111111111111111111111111111111111111111111111111111111",+ "document": {+ "schema": 1,+ "tree_id": "first.tree",+ "generation": 1,+ "base": {"seq": 0},+ "operations": [+ {+ "seq": 1,+ "op": "add",+ "id": "xfs-fix",+ "selector": {+ "architecture": ["x86_64", "aarch64"],+ "kernel_release_prefix": [ "7.4." ],+ "labels": {"role": ["edge"], "site": ["café \"1\""]}+ },+ "artifact": {+ "repository": "oci://registry.example.com/shirudo/first",+ "manifest_digest": "sha256:2222222222222222222222222222222222222222222222222222222222222222",+ "layer_digest": "sha256:3333333333333333333333333333333333333333333333333333333333333333",+ "payload_sha256": "sha256:4444444444444444444444444444444444444444444444444444444444444444"+ },+ "fixes": ["EXAMPLE-0202", "EXAMPLE-0101", "EXAMPLE-0202"],+ "a_key_of_a_later_shirudo": [1, 2.5, null],+ "operation_digest": "sha256:5555555555555555555555555555555555555555555555555555555555555555"+ }+ ],+ "head": {"seq": 1}+ }+}+ENDdiff --git a/tools/backend/test/tree-ingest-variants.sql b/tools/backend/test/tree-ingest-variants.sqlnew file mode 100644index 00000000..dc5f70a3--- /dev/null+++ b/tools/backend/test/tree-ingest-variants.sql@@ -0,0 +1,22 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- What jobs/tree-ingest loaded in test/tree-ingest-variants.sh: every+-- publication and operation, a selector as compact JSON that still+-- reads as JSON, and fixes only where the list was well formed.++SELECT 'tree_pubs';+SELECT tree_id, generation, parent_manifest_digest, head_seq+FROM shirudo.tree_pubs FINAL ORDER BY tree_id;++SELECT 'tree_ops';+SELECT tree_id, count(), groupArray(seq) FROM+(+ SELECT tree_id, seq FROM shirudo.tree_ops FINAL ORDER BY tree_id, seq+)+GROUP BY tree_id ORDER BY tree_id;+SELECT selector, JSONExtract(selector, 'labels', 'site', 'Array(String)')+FROM shirudo.tree_ops FINAL WHERE tree_id = 'first.tree';++SELECT 'upatch_fixes';+SELECT * FROM shirudo.upatch_fixes FINAL ORDER BY tree_id, seq, advisory;diff --git a/tools/backend/test/tree-ingest-walk.expected b/tools/backend/test/tree-ingest-walk.expectednew file mode 100644index 00000000..55b4fbde--- /dev/null+++ b/tools/backend/test/tree-ingest-walk.expected@@ -0,0 +1,32 @@+tree-ingest: loaded fleet-segments generation 2 (operations: 2, fixes: 1)+tree-ingest: loaded fleet-segments generation 4 (operations: 2, fixes: 1)+2 4 2+stub-shirudo: bpm tree show oci://registry.example.com/shirudo/fleet-segments --cert /certs/operator.pem --walk+tree-ingest: fleet-segments: 2 segments up to generation 4 are loaded already+tree-ingest: loaded fleet-segments generation 5 (operations: 1, fixes: 2)+3 5 4+published_at of the first two segments kept+tree-ingest: fleet-segments: 3 segments up to generation 5 are loaded already+3 5 4+tree-ingest: loaded fleet-segments generation 2 (operations: 2, fixes: 1)+tree-ingest: loaded fleet-segments generation 4 (operations: 2, fixes: 1)+tree-ingest: loaded fleet-segments generation 5 (operations: 1, fixes: 2)+3 5 4+tree_pubs+fleet-segments 2 2960661252c50e7232cd9781a0ccdbee045bfc40e2f081d89ba3c8fbe1c23495 dc330b2303d82c3839502fb9f36a217525efd5a842b474fcc1d70c66a3153e55 0 2 0000000000000000000000000000000000000000000000000000000000000000+fleet-segments 4 e114111ddf285a40bff312f278926be5b38f2021a417adcf83d07aca76f4f440 2960661252c50e7232cd9781a0ccdbee045bfc40e2f081d89ba3c8fbe1c23495 2 4 2960661252c50e7232cd9781a0ccdbee045bfc40e2f081d89ba3c8fbe1c23495 889efeb27650c0111168d523c935f051addbcc049d079e440e518dd3939722f0+fleet-segments 5 6d874c2a441593d937a66d27d58cca6543b135e2acf935d266549cb05560bcf9 e114111ddf285a40bff312f278926be5b38f2021a417adcf83d07aca76f4f440 4 5 e114111ddf285a40bff312f278926be5b38f2021a417adcf83d07aca76f4f440 993c483c8123b0c057a585d6a5eacb836f16ca98f4ec647cdfb2e65a13d72079+tree_ops+fleet-segments 1 add xfs-fix 98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144 13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43+fleet-segments 2 delete xfs-fix 4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b 5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b+fleet-segments 3 add xfs-fix b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc+fleet-segments 4 delete xfs-fix 1e297eb36fb2c66fcbd60e2e4ff31631cb9a54bdf069bdbf5f7d20d3a48713f4 eea45dba39497ddd9bf2a50a9b2f76a438d94c42762297e05b2e860fabfe9cb6+fleet-segments 5 add xfs-fix 472e953ed22e9a0328b568dfc444598e2f8d0da1d89136787a55387fb54a1c7c 8370c6805f5bfd1ded51b6fc7afac60773da0d07f50ffce306f978700013b84f+upatch_fixes+fleet-segments 1 xfs-fix EXAMPLE-0101 fixes+fleet-segments 3 xfs-fix EXAMPLE-0101 fixes+fleet-segments 5 xfs-fix EXAMPLE-0101 fixes+fleet-segments 5 xfs-fix EXAMPLE-0202 fixes+chain+4 2+5 4diff --git a/tools/backend/test/tree-ingest-walk.sh b/tools/backend/test/tree-ingest-walk.shnew file mode 100644index 00000000..f228bb33--- /dev/null+++ b/tools/backend/test/tree-ingest-walk.sh@@ -0,0 +1,51 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# A stored `bpm tree show --walk` output of a tree in three segments,+# test/tree-show-walk.json, loads every segment. A walk read while the+# tree had two loads those, a later walk adds only the third, a walk+# read again adds nothing, and a walk after one that stopped before its+# last insert completes it. The stub of `bpm tree show` is given+# --walk.++set -eu++test=$(cd "$(dirname "$0")" && pwd)+job=$test/../jobs/tree-ingest+show=$test/tree-show-walk.json++query()+{+ # shellcheck disable=SC2086 # a command with its options, to be split+ $CLICKHOUSE_CLIENT --query "$1"+}++rows()+{+ query "SELECT (SELECT count() FROM shirudo.tree_pubs FINAL),+ (SELECT count() FROM shirudo.tree_ops FINAL),+ (SELECT count() FROM shirudo.upatch_fixes FINAL)"+}++head -n 2 "$show" | "$job" --input - 2>&1+rows+first=$(query 'SELECT groupArray(published_at) FROM+ (SELECT published_at FROM shirudo.tree_pubs FINAL ORDER BY generation)')++sleep 0.1+STUB_SHOW_OUTPUT=$show "$job" --shirudo "$test/stub-shirudo.sh" \+ --cert /certs/operator.pem \+ oci://registry.example.com/shirudo/fleet-segments 2>&1+rows+[ "$(query 'SELECT groupArray(published_at) FROM+ (SELECT published_at FROM shirudo.tree_pubs FINAL+ WHERE generation < 5 ORDER BY generation)')" = "$first" ]+echo 'published_at of the first two segments kept'++"$job" --input "$show" 2>&1+rows++query 'TRUNCATE TABLE shirudo.tree_pubs'+"$job" --input "$show" 2>&1+rowsdiff --git a/tools/backend/test/tree-ingest-walk.sql b/tools/backend/test/tree-ingest-walk.sqlnew file mode 100644index 00000000..73d190c3--- /dev/null+++ b/tools/backend/test/tree-ingest-walk.sql@@ -0,0 +1,30 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- What jobs/tree-ingest loaded in test/tree-ingest-walk.sh: a row in+-- tree_pubs per segment, each naming its base, the sealed segment before+-- it and the history root there, which is 64 zeros for the first and+-- shirudo's history_root over the operation digests after seq 2 and 4+-- for the others; all five operations; and their fixes.++SELECT 'tree_pubs';+SELECT tree_id, generation, manifest_digest, parent_manifest_digest,+ segment_base_seq, head_seq, segment_manifest_digest, history_root+FROM shirudo.tree_pubs FINAL ORDER BY tree_id, generation;++SELECT 'tree_ops';+SELECT tree_id, seq, op, id, manifest_digest, operation_digest+FROM shirudo.tree_ops FINAL ORDER BY tree_id, seq;++SELECT 'upatch_fixes';+SELECT * FROM shirudo.upatch_fixes FINAL ORDER BY tree_id, seq, advisory;++-- The segments join up: each one's base is the head of the one before,+-- and names its manifest.+SELECT 'chain';+SELECT s.generation, p.generation+FROM shirudo.tree_pubs AS s FINAL+INNER JOIN shirudo.tree_pubs AS p FINAL+ ON p.tree_id = s.tree_id AND p.manifest_digest = s.segment_manifest_digest+WHERE s.segment_base_seq = p.head_seq+ORDER BY s.generation;diff --git a/tools/backend/test/tree-ingest.expected b/tools/backend/test/tree-ingest.expectednew file mode 100644index 00000000..6bb24a98--- /dev/null+++ b/tools/backend/test/tree-ingest.expected@@ -0,0 +1,16 @@+tree-ingest: loaded fleet-base generation 3 (operations: 3, fixes: 2)+rows inserted, before any merge:+1 3 2+tree-ingest: fleet-base generation 3 is loaded already+1 3 2+published_at kept+tree-ingest: loaded fleet-base generation 3 (operations: 3, fixes: 2)+tree_pubs+fleet-base 3 4c1d7e6b0a9f38e2d5c4b3a2918f7e6d5c4b3a29180f7e6d5c4b3a2918f7e6d5 4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942 3 0 0000000000000000000000000000000000000000000000000000000000000000 1+tree_ops+fleet-base 1 add xfs-fix {"labels":{"role":["edge"]}} oci://registry.example.com/shirudo/fleet-base 98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144 9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6 59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885 13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43+fleet-base 2 delete xfs-fix {"labels":{"role":["edge"]}} oci://registry.example.com/shirudo/fleet-base 4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55 f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1 5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b+fleet-base 3 add xfs-fix {"labels":{"role":["edge"]}} oci://registry.example.com/shirudo/fleet-base b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a 653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97 82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc+upatch_fixes+fleet-base 1 xfs-fix EXAMPLE-0101 fixes+fleet-base 3 xfs-fix EXAMPLE-0101 fixesdiff --git a/tools/backend/test/tree-ingest.sh b/tools/backend/test/tree-ingest.shnew file mode 100644index 00000000..2e0b9b35--- /dev/null+++ b/tools/backend/test/tree-ingest.sh@@ -0,0 +1,41 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# The stored `bpm tree show` output for the generation 3 publication of+# shirudo's testing/fixtures/keepalive/tree-1.1.0.json loads once: a+# second run inserts nothing and leaves published_at alone, and a run+# after one that stopped before its last insert completes it.++set -eu++test=$(cd "$(dirname "$0")" && pwd)+job=$test/../jobs/tree-ingest+show=$test/tree-show-1.1.0.json++query()+{+ # shellcheck disable=SC2086 # a command with its options, to be split+ $CLICKHOUSE_CLIENT --query "$1"+}++rows()+{+ query "SELECT (SELECT count() FROM shirudo.tree_pubs),+ (SELECT count() FROM shirudo.tree_ops),+ (SELECT count() FROM shirudo.upatch_fixes)"+}++"$job" --input "$show"+echo 'rows inserted, before any merge:'+rows+first=$(query 'SELECT published_at FROM shirudo.tree_pubs FINAL')++sleep 0.1+"$job" --input - <"$show"+rows+[ "$(query 'SELECT published_at FROM shirudo.tree_pubs FINAL')" = "$first" ]+echo 'published_at kept'++query 'TRUNCATE TABLE shirudo.tree_pubs'+"$job" --input "$show"diff --git a/tools/backend/test/tree-ingest.sql b/tools/backend/test/tree-ingest.sqlnew file mode 100644index 00000000..3ebd04f0--- /dev/null+++ b/tools/backend/test/tree-ingest.sql@@ -0,0 +1,20 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- What jobs/tree-ingest loaded in test/tree-ingest.sh: the publication,+-- its three operations with the digests of shirudo's example, stored+-- without "sha256:", and the advisory of operations 1 and 3. A tree that+-- was never sealed is one segment: base 0, no segment before it and a+-- history root of 64 zeros.++SELECT 'tree_pubs';+SELECT tree_id, generation, manifest_digest, parent_manifest_digest, head_seq,+ segment_base_seq, segment_manifest_digest, history_root,+ published_at BETWEEN now64(3) - INTERVAL 1 HOUR AND now64(3)+FROM shirudo.tree_pubs FINAL;++SELECT 'tree_ops';+SELECT * FROM shirudo.tree_ops FINAL ORDER BY tree_id, seq;++SELECT 'upatch_fixes';+SELECT * FROM shirudo.upatch_fixes FINAL ORDER BY tree_id, seq, advisory;diff --git a/tools/backend/test/tree-show-1.1.0.json b/tools/backend/test/tree-show-1.1.0.jsonnew file mode 100644index 00000000..7691a7c0--- /dev/null+++ b/tools/backend/test/tree-show-1.1.0.json@@ -0,0 +1 @@+{"manifest_digest":"sha256:4c1d7e6b0a9f38e2d5c4b3a2918f7e6d5c4b3a29180f7e6d5c4b3a2918f7e6d5","document":{"schema":1,"tree_id":"fleet-base","generation":3,"parent_manifest_digest":"sha256:4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942","base":{"seq":0},"operations":[{"seq":1,"op":"add","id":"xfs-fix","selector":{"labels":{"role":["edge"]}},"artifact":{"repository":"oci://registry.example.com/shirudo/fleet-base","manifest_digest":"sha256:98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144","layer_digest":"sha256:9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6","payload_sha256":"sha256:59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885"},"fixes":["EXAMPLE-0101"],"operation_digest":"sha256:13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43"},{"seq":2,"op":"delete","id":"xfs-fix","selector":{"labels":{"role":["edge"]}},"artifact":{"repository":"oci://registry.example.com/shirudo/fleet-base","manifest_digest":"sha256:4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b","layer_digest":"sha256:e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55","payload_sha256":"sha256:f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1"},"operation_digest":"sha256:5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b"},{"seq":3,"op":"add","id":"xfs-fix","selector":{"labels":{"role":["edge"]}},"artifact":{"repository":"oci://registry.example.com/shirudo/fleet-base","manifest_digest":"sha256:b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a","layer_digest":"sha256:653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97","payload_sha256":"sha256:82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf"},"fixes":["EXAMPLE-0101"],"operation_digest":"sha256:bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc"}],"head":{"seq":3}}}diff --git a/tools/backend/test/tree-show-walk.json b/tools/backend/test/tree-show-walk.jsonnew file mode 100644index 00000000..87eb433e--- /dev/null+++ b/tools/backend/test/tree-show-walk.json@@ -0,0 +1,3 @@+{"manifest_digest":"sha256:2960661252c50e7232cd9781a0ccdbee045bfc40e2f081d89ba3c8fbe1c23495","document":{"schema":1,"tree_id":"fleet-segments","generation":2,"parent_manifest_digest":"sha256:dc330b2303d82c3839502fb9f36a217525efd5a842b474fcc1d70c66a3153e55","base":{"seq":0},"operations":[{"seq":1,"op":"add","id":"xfs-fix","selector":{"labels":{"role":["edge"]}},"artifact":{"repository":"oci://registry.example.com/shirudo/fleet-base","manifest_digest":"sha256:98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144","layer_digest":"sha256:9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6","payload_sha256":"sha256:59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885"},"fixes":["EXAMPLE-0101"],"operation_digest":"sha256:13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43"},{"seq":2,"op":"delete","id":"xfs-fix","selector":{"labels":{"role":["edge"]}},"artifact":{"repository":"oci://registry.example.com/shirudo/fleet-base","manifest_digest":"sha256:4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b","layer_digest":"sha256:e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55","payload_sha256":"sha256:f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1"},"operation_digest":"sha256:5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b"}],"head":{"seq":2}}}+{"manifest_digest":"sha256:e114111ddf285a40bff312f278926be5b38f2021a417adcf83d07aca76f4f440","document":{"schema":1,"tree_id":"fleet-segments","generation":4,"parent_manifest_digest":"sha256:2960661252c50e7232cd9781a0ccdbee045bfc40e2f081d89ba3c8fbe1c23495","base":{"seq":2,"segment_manifest_digest":"sha256:2960661252c50e7232cd9781a0ccdbee045bfc40e2f081d89ba3c8fbe1c23495","history_root":"889efeb27650c0111168d523c935f051addbcc049d079e440e518dd3939722f0"},"operations":[{"seq":3,"op":"add","id":"xfs-fix","selector":{"labels":{"role":["edge"]}},"artifact":{"repository":"oci://registry.example.com/shirudo/fleet-base","manifest_digest":"sha256:b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a","layer_digest":"sha256:653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97","payload_sha256":"sha256:82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf"},"fixes":["EXAMPLE-0101"],"operation_digest":"sha256:bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc"},{"seq":4,"op":"delete","id":"xfs-fix","selector":{"labels":{"role":["edge"]}},"artifact":{"repository":"oci://registry.example.com/shirudo/fleet-base","manifest_digest":"sha256:1e297eb36fb2c66fcbd60e2e4ff31631cb9a54bdf069bdbf5f7d20d3a48713f4","layer_digest":"sha256:a84bee89d33748eb6eb873ff864e676a3f112db39bde0999421d7370c7bf46c4","payload_sha256":"sha256:3676bfe3444b04804a77a9644fde2b586f54058d35813e9f622973216ebcb519"},"operation_digest":"sha256:eea45dba39497ddd9bf2a50a9b2f76a438d94c42762297e05b2e860fabfe9cb6"}],"head":{"seq":4}}}+{"manifest_digest":"sha256:6d874c2a441593d937a66d27d58cca6543b135e2acf935d266549cb05560bcf9","document":{"schema":1,"tree_id":"fleet-segments","generation":5,"parent_manifest_digest":"sha256:e114111ddf285a40bff312f278926be5b38f2021a417adcf83d07aca76f4f440","base":{"seq":4,"segment_manifest_digest":"sha256:e114111ddf285a40bff312f278926be5b38f2021a417adcf83d07aca76f4f440","history_root":"993c483c8123b0c057a585d6a5eacb836f16ca98f4ec647cdfb2e65a13d72079"},"operations":[{"seq":5,"op":"add","id":"xfs-fix","selector":{"labels":{"role":["edge"]}},"artifact":{"repository":"oci://registry.example.com/shirudo/fleet-base","manifest_digest":"sha256:472e953ed22e9a0328b568dfc444598e2f8d0da1d89136787a55387fb54a1c7c","layer_digest":"sha256:6ac2c2bf9c918e1a036f1dfacbf7e7ff7ed2e2f4d32fd90daec5f26900d234cc","payload_sha256":"sha256:e10d06097d5c9c8ff6b002cf2c654b2d4f777afc2cfa40852395308cff275740"},"fixes":["EXAMPLE-0101","EXAMPLE-0202"],"operation_digest":"sha256:8370c6805f5bfd1ded51b6fc7afac60773da0d07f50ffce306f978700013b84f"}],"head":{"seq":5}}}diff --git a/tools/backend/test/trivy/81fc6ee4cddaf8949448930497191edc91adba67cd61ef0fa4d0857fdbf6c1ff.json b/tools/backend/test/trivy/81fc6ee4cddaf8949448930497191edc91adba67cd61ef0fa4d0857fdbf6c1ff.jsonnew file mode 100644index 00000000..cf832af5--- /dev/null+++ b/tools/backend/test/trivy/81fc6ee4cddaf8949448930497191edc91adba67cd61ef0fa4d0857fdbf6c1ff.json@@ -0,0 +1,19 @@+{+ "SchemaVersion": 2,+ "ArtifactName": "10.sbom.cdx.json",+ "ArtifactType": "cyclonedx",+ "Results": [+ {+ "Target": "10.sbom.cdx.json (debian 13)",+ "Class": "os-pkgs",+ "Type": "debian",+ "Vulnerabilities": [+ {+ "VulnerabilityID": "EXAMPLE-0202",+ "InstalledVersion": "3.5.1-1",+ "Severity": "HIGH"+ }+ ]+ }+ ]+}diff --git a/tools/backend/test/trivy/fd2407ebf451915ddb23cd4cabd3cee23db62e7f1d7a81c8c3cfb3b1c48596e4.json b/tools/backend/test/trivy/fd2407ebf451915ddb23cd4cabd3cee23db62e7f1d7a81c8c3cfb3b1c48596e4.jsonnew file mode 100644index 00000000..58f04c0b--- /dev/null+++ b/tools/backend/test/trivy/fd2407ebf451915ddb23cd4cabd3cee23db62e7f1d7a81c8c3cfb3b1c48596e4.json@@ -0,0 +1,96 @@+{+ "SchemaVersion": 2,+ "CreatedAt": "2026-11-11T06:00:00.000000000Z",+ "ArtifactName": "1.sbom.cdx.json",+ "ArtifactType": "cyclonedx",+ "Metadata": {+ "OS": {+ "Family": "debian",+ "Name": "13"+ },+ "ImageConfig": {+ "architecture": "",+ "created": "0001-01-01T00:00:00Z",+ "os": "",+ "rootfs": {+ "type": "",+ "diff_ids": null+ },+ "config": {}+ }+ },+ "Results": [+ {+ "Target": "1.sbom.cdx.json (debian 13)",+ "Class": "os-pkgs",+ "Type": "debian",+ "Vulnerabilities": [+ {+ "VulnerabilityID": "EXAMPLE-0101",+ "PkgID": "[email protected]",+ "PkgName": "linux-image-7.4.2",+ "InstalledVersion": "7.4.2-1",+ "FixedVersion": "7.4.5-1",+ "Status": "fixed",+ "Severity": "CRITICAL"+ },+ {+ "VulnerabilityID": "EXAMPLE-0202",+ "PkgID": "[email protected]",+ "PkgName": "openssl",+ "InstalledVersion": "3.5.1-1",+ "FixedVersion": "3.5.1-2",+ "Status": "fixed",+ "Severity": "HIGH"+ },+ {+ "VulnerabilityID": "EXAMPLE-0505",+ "PkgID": "[email protected]",+ "PkgName": "zlib",+ "InstalledVersion": "1.3-1",+ "Status": "affected",+ "Severity": "MEDIUM"+ }+ ]+ },+ {+ "Target": "kernel",+ "Class": "os-pkgs",+ "Type": "debian",+ "Vulnerabilities": [+ {+ "VulnerabilityID": "EXAMPLE-0101",+ "PkgName": "kernel",+ "InstalledVersion": "7.4.2",+ "FixedVersion": "7.4.5",+ "Severity": "CRITICAL"+ },+ {+ "VulnerabilityID": "EXAMPLE-0101",+ "PkgName": "kernel-core",+ "InstalledVersion": "7.4.2",+ "FixedVersion": "7.4.5",+ "Severity": "CRITICAL"+ },+ {+ "VulnerabilityID": "EXAMPLE-0202",+ "PkgName": "openssl",+ "InstalledVersion": "3.5.1-1",+ "FixedVersion": "3.5.1-2",+ "Severity": "HIGH"+ }+ ]+ },+ {+ "Target": "Python",+ "Class": "lang-pkgs",+ "Type": "python-pkg",+ "Vulnerabilities": null+ },+ {+ "Target": "Java",+ "Class": "lang-pkgs",+ "Type": "jar"+ }+ ]+}diff --git a/tools/backend/test/vulns-cases.expected b/tools/backend/test/vulns-cases.expectednew file mode 100644index 00000000..03853c00--- /dev/null+++ b/tools/backend/test/vulns-cases.expected@@ -0,0 +1,75 @@+base-at-0 verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shield_pending xfs-fix 0 3 add true fixes+base-at-0 verified kernel EXAMPLE-0303 linux 7.4.2 shield_pending xfs-fix 0 3 add true manual+base-at-0 verified kernel EXAMPLE-0606 linux 7.4.2 exposed_no_shield 0 0 false none+base-at-1 verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shielded xfs-fix 1 add 3 add true fixes+base-at-1 verified kernel EXAMPLE-0303 linux 7.4.2 shield_pending xfs-fix 1 add 3 add true manual+base-at-1 verified kernel EXAMPLE-0606 linux 7.4.2 shielded xfs-fix 1 add 3 add false manual+base-at-1-excluded verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shield_excludes_node xfs-fix 1 add 3 add true fixes+base-at-1-excluded verified kernel EXAMPLE-0303 linux 7.4.2 shield_pending xfs-fix 1 add 3 add true manual+base-at-1-excluded verified kernel EXAMPLE-0606 linux 7.4.2 shield_excludes_node xfs-fix 1 add 3 add false manual+base-at-1-module-absent verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shield_module_absent xfs-fix 1 add 3 add true fixes+base-at-1-module-absent verified kernel EXAMPLE-0303 linux 7.4.2 shield_pending xfs-fix 1 add 3 add true manual+base-at-1-module-absent verified kernel EXAMPLE-0606 linux 7.4.2 shield_module_absent xfs-fix 1 add 3 add false manual+base-at-2 verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shield_withdrawn xfs-fix 2 delete 3 add true fixes+base-at-2 verified kernel EXAMPLE-0303 linux 7.4.2 shield_pending xfs-fix 2 delete 3 add true manual+base-at-2 verified kernel EXAMPLE-0606 linux 7.4.2 shield_withdrawn xfs-fix 2 delete 3 add false manual+base-at-3 verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shielded xfs-fix 3 add 3 add true fixes+base-at-3 verified kernel EXAMPLE-0303 linux 7.4.2 shielded xfs-fix 3 add 3 add true manual+base-at-3 verified kernel EXAMPLE-0606 linux 7.4.2 exposed_no_shield 0 0 false none+base-at-3-module-absent verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shield_module_absent xfs-fix 3 add 3 add true fixes+base-at-3-module-absent verified kernel EXAMPLE-0303 linux 7.4.2 shield_module_absent xfs-fix 3 add 3 add true manual+base-at-3-module-absent verified kernel EXAMPLE-0606 linux 7.4.2 exposed_no_shield 0 0 false none+binding-clean verified none none 0 0 false none+binding-no-sbom-format no_sbom none unknown 0 0 false none+binding-no-sbom-hash no_sbom none unknown 0 0 false none+binding-no-sbom-missing no_sbom kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shielded xfs-fix 3 add 3 add true fixes+binding-no-sbom-missing no_sbom kernel EXAMPLE-0303 linux 7.4.2 shielded xfs-fix 3 add 3 add true manual+binding-no-sbom-missing no_sbom kernel EXAMPLE-0606 linux 7.4.2 exposed_no_shield 0 0 false none+binding-no-sbom-no-row no_sbom none unknown 0 0 false none+binding-no-sbom-parse no_sbom none unknown 0 0 false none+binding-root-mismatch root_mismatch kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shielded xfs-fix 3 add 3 add true fixes+binding-root-mismatch root_mismatch sbom EXAMPLE-0202 openssl 3.5.1-1 3.5.1-2 exposed_no_shield 0 0 false none+binding-root-mismatch root_mismatch kernel EXAMPLE-0303 linux 7.4.2 shielded xfs-fix 3 add 3 add true manual+binding-root-mismatch root_mismatch kernel EXAMPLE-0606 linux 7.4.2 exposed_no_shield 0 0 false none+build-no-root declared sbom EXAMPLE-0808 curl 8.1-2 exposed_no_shield 0 0 false none+build-other-root root_mismatch sbom EXAMPLE-0808 curl 8.1-2 exposed_no_shield 0 0 false none+build-own-root verified sbom EXAMPLE-0707 curl 8.1-1 exposed_no_shield 0 0 false none+kernel-fixed verified kernel EXAMPLE-0303 linux 7.4.5 shielded xfs-fix 3 add 3 add true manual+kernel-fixed verified kernel EXAMPLE-0606 linux 7.4.5 exposed_no_shield 0 0 false none+kernel-unreadable verified none none 0 0 false none+mask-too-short-at-3 verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 unknown xfs-fix 3 add 3 add true fixes+mask-too-short-at-3 verified kernel EXAMPLE-0303 linux 7.4.2 unknown xfs-fix 3 add 3 add true manual+mask-too-short-at-3 verified kernel EXAMPLE-0606 linux 7.4.2 exposed_no_shield 0 0 false none+no-mask-at-0 verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shield_pending xfs-fix 0 3 add true fixes+no-mask-at-0 verified kernel EXAMPLE-0303 linux 7.4.2 shield_pending xfs-fix 0 3 add true manual+no-mask-at-0 verified kernel EXAMPLE-0606 linux 7.4.2 exposed_no_shield 0 0 false none+no-mask-at-2 verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shield_withdrawn xfs-fix 2 delete 3 add true fixes+no-mask-at-2 verified kernel EXAMPLE-0303 linux 7.4.2 shield_pending xfs-fix 2 delete 3 add true manual+no-mask-at-2 verified kernel EXAMPLE-0606 linux 7.4.2 shield_withdrawn xfs-fix 2 delete 3 add false manual+no-mask-at-3 verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 unknown xfs-fix 3 add 3 add true fixes+no-mask-at-3 verified kernel EXAMPLE-0303 linux 7.4.2 unknown xfs-fix 3 add 3 add true manual+no-mask-at-3 verified kernel EXAMPLE-0606 linux 7.4.2 exposed_no_shield 0 0 false none+old-at-0 verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shield_withdrawn old-fix 0 2 delete false fixes+old-at-0 verified kernel EXAMPLE-0303 linux 7.4.2 exposed_no_shield 0 0 false none+old-at-0 verified kernel EXAMPLE-0606 linux 7.4.2 exposed_no_shield 0 0 false none+old-at-1 verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shielded old-fix 1 add 2 delete false fixes+old-at-1 verified kernel EXAMPLE-0303 linux 7.4.2 exposed_no_shield 0 0 false none+old-at-1 verified kernel EXAMPLE-0606 linux 7.4.2 exposed_no_shield 0 0 false none+old-at-2 verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shield_withdrawn old-fix 2 delete 2 delete false fixes+old-at-2 verified kernel EXAMPLE-0303 linux 7.4.2 exposed_no_shield 0 0 false none+old-at-2 verified kernel EXAMPLE-0606 linux 7.4.2 exposed_no_shield 0 0 false none+shield-best-of-two verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shielded fix-b 2 add 2 add true fixes+shield-best-of-two verified kernel EXAMPLE-0303 linux 7.4.2 exposed_no_shield 0 0 false none+shield-best-of-two verified kernel EXAMPLE-0606 linux 7.4.2 exposed_no_shield 0 0 false none+shield-live-before-withdrawn verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shield_excludes_node fix-b 2 add 2 add true fixes+shield-live-before-withdrawn verified kernel EXAMPLE-0303 linux 7.4.2 exposed_no_shield 0 0 false none+shield-live-before-withdrawn verified kernel EXAMPLE-0606 linux 7.4.2 exposed_no_shield 0 0 false none+shield-no-tree verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 exposed_no_shield 0 0 false none+shield-no-tree verified kernel EXAMPLE-0303 linux 7.4.2 exposed_no_shield 0 0 false none+shield-no-tree verified kernel EXAMPLE-0606 linux 7.4.2 exposed_no_shield 0 0 false none+nodes 29 29+shielded now, delete coming+old-at-1 EXAMPLE-0101 old-fix 1 2+shielded now, add coming+base-at-1 EXAMPLE-0101 xfs-fix 1 3 true+base-at-1 EXAMPLE-0606 xfs-fix 1 3 falsediff --git a/tools/backend/test/vulns-cases.sql b/tools/backend/test/vulns-cases.sqlnew file mode 100644index 00000000..b0036857--- /dev/null+++ b/tools/backend/test/vulns-cases.sql@@ -0,0 +1,176 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- node_vulns case by case; a node is named for what it shows.+--+-- binding: a root other than the SBOM's is root_mismatch and keeps its+-- rows; an image whose state is not ok, or that has no row, is no_sbom,+-- which keeps the kernel rows and is unknown without any. Of two builds+-- of one version a node gets its own root's, else the newest one's.+-- A package of the kernel and the findings of an older scan are left+-- out, and an image without findings gives none.+--+-- kernel: a release at the fixed one, or one that starts with no number,+-- has no kernel finding.+--+-- shield: a row says what the node has applied, applied_seq and+-- applied_op, and what its tree ends with, next_seq and next_op. On+-- fleet-old, an add of old-fix and its delete, a node at 0 is+-- shield_withdrawn with nothing applied, a node at 1 is shielded with the+-- delete coming, and a node at 2 has applied the delete. On fleet-base,+-- xfs-fix added at 1, deleted at 2 and added again at 3, a node at 0 is+-- shield_pending, a node at 1 has what its mask says of the first add,+-- shielded, module absent or excluded, with the new add coming, a node at+-- 2 is shield_withdrawn with it coming, and a node at 3 has what its mask+-- says of the new add, where both pairs are equal. A node without a mask,+-- or with one that ends before the add it has applied, is unknown there,+-- and still pending or withdrawn where no mask is needed to say so.+--+-- links: EXAMPLE-0303 is linked by hand to the add at 3 only, so that+-- for a node at 1 or 2 the shield is still to come, whatever it has+-- loaded; EXAMPLE-0606 to the add at 1 only, which shields a node at 1,+-- is withdrawn at 2 and no longer counts once the node has applied the+-- add at 3, nor for a node at 0, whose tree ends with an add that is not+-- linked. A manual row gives shield_link manual and loses to a fixes row+-- for the same operation. Of two upatches linked to one advisory the+-- better outcome counts, and an add that is still published, even one+-- whose selector left the node out, counts before a withdrawn upatch.+-- An advisory no upatch is linked to, and any advisory for a node that+-- follows no tree, is exposed_no_shield with no upatch, seq 0, no+-- operation and shield_link none.+--+-- next_shields: a node at 1 on fleet-base is shielded against 0101 and+-- 0606 with the add at 3 coming, which carries 0101 and drops 0606, so+-- 0101 reads true and 0606 false.+--+-- Last, the nodes that are shielded now and about to lose it, and those+-- shielded now with an add coming, with whether it keeps the shield.++-- The publication of testing/fixtures/keepalive/tree-1.1.0.json, as the+-- ingest job loads it: generation 3 with its three operations.+INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-base', 3, '1f327364233e3f2dcebcd13c0af8d84f886201531b135294bd7356a2f7ed680b', '4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942', 3, now64(3) - INTERVAL 10 MINUTE);+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-base', 1, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144', '9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6', '59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885', '13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43'),+('fleet-base', 2, 'delete', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b', 'e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55', 'f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1', '5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b'),+('fleet-base', 3, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', 'b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a', '653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97', '82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf', 'bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc');+INSERT INTO shirudo.expected_builds (version_id, note) VALUES+('d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f', 'shirudo 2026.11');++-- The bodies of testing/fixtures/keepalive/, byte for byte.+CREATE TEMPORARY TABLE fixture (name String, body String);+INSERT INTO fixture VALUES+('node-a-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1","mask":"VA==","set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1,"not_ok":0}');+++INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq) VALUES+('fleet-old', 2, 'dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd', 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', 2),+('fleet-two', 2, 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', '0000000000000000000000000000000000000000000000000000000000000000', 2),+('fleet-mix', 3, '9999999999999999999999999999999999999999999999999999999999999999', '8888888888888888888888888888888888888888888888888888888888888888', 3);+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-old', 1, 'add', 'old-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-old', '1111111111111111111111111111111111111111111111111111111111111111', '5555555555555555555555555555555555555555555555555555555555555555', '9999999999999999999999999999999999999999999999999999999999999999', 'cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc'),+('fleet-old', 2, 'delete', 'old-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-old', '2222222222222222222222222222222222222222222222222222222222222222', '6666666666666666666666666666666666666666666666666666666666666666', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd'),+('fleet-two', 1, 'add', 'fix-a', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-two', '1111111111111111111111111111111111111111111111111111111111111111', '5555555555555555555555555555555555555555555555555555555555555555', '9999999999999999999999999999999999999999999999999999999999999999', 'cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc'),+('fleet-two', 2, 'add', 'fix-b', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-two', '2222222222222222222222222222222222222222222222222222222222222222', '6666666666666666666666666666666666666666666666666666666666666666', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd'),+('fleet-mix', 1, 'add', 'fix-a', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-mix', '2222222222222222222222222222222222222222222222222222222222222222', '6666666666666666666666666666666666666666666666666666666666666666', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd'),+('fleet-mix', 2, 'add', 'fix-b', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-mix', '2222222222222222222222222222222222222222222222222222222222222222', '6666666666666666666666666666666666666666666666666666666666666666', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd'),+('fleet-mix', 3, 'delete', 'fix-a', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-mix', '2222222222222222222222222222222222222222222222222222222222222222', '6666666666666666666666666666666666666666666666666666666666666666', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd');++INSERT INTO shirudo.upatch_fixes (tree_id, seq, id, advisory, source) VALUES+('fleet-base', 1, 'xfs-fix', 'EXAMPLE-0101', 'fixes'),+('fleet-base', 3, 'xfs-fix', 'EXAMPLE-0101', 'fixes'),+('fleet-base', 3, 'xfs-fix', 'EXAMPLE-0101', 'manual'),+('fleet-base', 3, 'xfs-fix', 'EXAMPLE-0303', 'manual'),+('fleet-base', 1, 'xfs-fix', 'EXAMPLE-0606', 'manual'),+('fleet-old', 1, 'old-fix', 'EXAMPLE-0101', 'fixes'),+('fleet-two', 1, 'fix-a', 'EXAMPLE-0101', 'fixes'),+('fleet-two', 2, 'fix-b', 'EXAMPLE-0101', 'fixes'),+('fleet-mix', 1, 'fix-a', 'EXAMPLE-0101', 'fixes'),+('fleet-mix', 2, 'fix-b', 'EXAMPLE-0101', 'fixes');++-- 0101 as on the page; 0303 and 0606 have no fixed release yet; 0404 was+-- fixed before 7.4.2.+INSERT INTO shirudo.kernel_vulns (vuln_id, introduced, fixed, severity) VALUES+('EXAMPLE-0101', [7, 0], [7, 4, 5], 'CRITICAL'),+('EXAMPLE-0303', [7, 4], [], 'MEDIUM'),+('EXAMPLE-0404', [7, 0], [7, 2], 'HIGH'),+('EXAMPLE-0606', [7, 0], [], 'LOW');++CREATE TEMPORARY TABLE scan AS SELECT now() - INTERVAL 1 HOUR AS at;+INSERT INTO shirudo.sbom_images (image_id, image_version, image_root, sbom_format, sbom_sha256, state, built_at, db_version, scanned_at)+SELECT 'fleet-os', '2026.11.1', 'a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c', 'cyclonedx-json', '5b0e2c8a4f6d1e3b7a9c0d2e4f6a8b1c3d5e7f9a0b2c4d6e8f1a3b5c7d9e91d4', 'ok', '2026-11-02 08:00:00', '2', at FROM scan UNION ALL+SELECT 'fleet-os', '2026.11.2', '2222222222222222222222222222222222222222222222222222222222222222', 'cyclonedx-json', '', 'missing', '2026-11-03 08:00:00', '2', at FROM scan UNION ALL+SELECT 'fleet-os', '2026.11.3', 'a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c', 'cyclonedx-json', '', 'hash_mismatch', '2026-11-04 08:00:00', '2', at FROM scan UNION ALL+SELECT 'fleet-os', '2026.11.4', 'a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c', 'cyclonedx-json', '', 'parse_error', '2026-11-05 08:00:00', '2', at FROM scan UNION ALL+SELECT 'fleet-os', '2026.11.5', 'a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c', 'spdx-json', '', 'unsupported_format', '2026-11-06 08:00:00', '2', at FROM scan UNION ALL+SELECT 'fleet-os', '2026.11.6', '6666666666666666666666666666666666666666666666666666666666666666', 'cyclonedx-json', '6666666666666666666666666666666666666666666666666666666666666666', 'ok', '2026-11-07 08:00:00', '2', at FROM scan UNION ALL+SELECT 'fleet-os', '2026.11.7', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'cyclonedx-json', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'ok', '2026-11-08 08:00:00', '2', at FROM scan UNION ALL+SELECT 'fleet-os', '2026.11.7', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', 'cyclonedx-json', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', 'ok', '2026-11-09 08:00:00', '2', at FROM scan;+INSERT INTO shirudo.sbom_vulns (sbom_sha256, vuln_id, package, installed, fixed, severity, scanned_at)+SELECT '5b0e2c8a4f6d1e3b7a9c0d2e4f6a8b1c3d5e7f9a0b2c4d6e8f1a3b5c7d9e91d4', 'EXAMPLE-0202', 'openssl', '3.5.1-1', '3.5.1-2', 'HIGH', at FROM scan UNION ALL+SELECT '5b0e2c8a4f6d1e3b7a9c0d2e4f6a8b1c3d5e7f9a0b2c4d6e8f1a3b5c7d9e91d4', 'EXAMPLE-0101', 'linux-image-7.4.2', '7.4.2-1', '7.4.5-1', 'CRITICAL', at FROM scan UNION ALL+SELECT '5b0e2c8a4f6d1e3b7a9c0d2e4f6a8b1c3d5e7f9a0b2c4d6e8f1a3b5c7d9e91d4', 'EXAMPLE-0101', 'kernel-core', '7.4.2-1', '7.4.5-1', 'CRITICAL', at FROM scan UNION ALL+SELECT '5b0e2c8a4f6d1e3b7a9c0d2e4f6a8b1c3d5e7f9a0b2c4d6e8f1a3b5c7d9e91d4', 'EXAMPLE-0909', 'zlib', '1.3-1', '1.3-2', 'LOW', at - INTERVAL 1 DAY FROM scan UNION ALL+SELECT 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'EXAMPLE-0707', 'curl', '8.1-1', '', 'MEDIUM', at FROM scan UNION ALL+SELECT 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', 'EXAMPLE-0808', 'curl', '8.1-2', '', 'MEDIUM', at FROM scan;++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT node.1, arrayFold((body, change) -> replaceOne(body, change.1, change.2), node.2, f.body),+ 1, concat('000b', node.1), 'QUtB', 1, 1000+FROM+(+ SELECT arrayJoin([+ ('binding-root-mismatch', [('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"1111111111111111111111111111111111111111111111111111111111111111"')]),+ ('binding-no-sbom-missing', [('"image_version":"2026.11.1"', '"image_version":"2026.11.2"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"2222222222222222222222222222222222222222222222222222222222222222"')]),+ ('binding-no-sbom-hash', [('"image_version":"2026.11.1"', '"image_version":"2026.11.3"'), ('"kernel_release":"7.4.2"', '"kernel_release":"6.18.9"')]),+ ('binding-no-sbom-parse', [('"image_version":"2026.11.1"', '"image_version":"2026.11.4"'), ('"kernel_release":"7.4.2"', '"kernel_release":"6.18.9"')]),+ ('binding-no-sbom-format', [('"image_version":"2026.11.1"', '"image_version":"2026.11.5"'), ('"kernel_release":"7.4.2"', '"kernel_release":"6.18.9"')]),+ ('binding-no-sbom-no-row', [('"image_version":"2026.11.1"', '"image_version":"2026.12.0"'), ('"kernel_release":"7.4.2"', '"kernel_release":"6.18.9"')]),+ ('binding-clean', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"kernel_release":"7.4.2"', '"kernel_release":"6.18.9"')]),+ ('build-own-root', [('"image_version":"2026.11.1"', '"image_version":"2026.11.7"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"'), ('"kernel_release":"7.4.2"', '"kernel_release":"6.18.9"')]),+ ('build-other-root', [('"image_version":"2026.11.1"', '"image_version":"2026.11.7"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"'), ('"kernel_release":"7.4.2"', '"kernel_release":"6.18.9"')]),+ ('build-no-root', [('"image_version":"2026.11.1"', '"image_version":"2026.11.7"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":null'), ('"kernel_release":"7.4.2"', '"kernel_release":"6.18.9"')]),+ ('kernel-fixed', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"kernel_release":"7.4.2"', '"kernel_release":"7.4.5"')]),+ ('kernel-unreadable', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"kernel_release":"7.4.2"', '"kernel_release":"next-20261111"')]),+ ('old-at-0', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"tree_id":"fleet-base"', '"tree_id":"fleet-old"'), ('"last_seq":3', '"last_seq":0'), ('"mask":"VA=="', '"mask":"AA=="')]),+ ('old-at-1', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"tree_id":"fleet-base"', '"tree_id":"fleet-old"'), ('"last_seq":3', '"last_seq":1'), ('"mask":"VA=="', '"mask":"QA=="')]),+ ('old-at-2', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"tree_id":"fleet-base"', '"tree_id":"fleet-old"'), ('"last_seq":3', '"last_seq":2'), ('"mask":"VA=="', '"mask":"UA=="')]),+ ('base-at-0', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"last_seq":3', '"last_seq":0'), ('"mask":"VA=="', '"mask":"AA=="')]),+ ('base-at-1', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"last_seq":3', '"last_seq":1'), ('"mask":"VA=="', '"mask":"QA=="')]),+ ('base-at-1-module-absent', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"last_seq":3', '"last_seq":1'), ('"mask":"VA=="', '"mask":"wA=="')]),+ ('base-at-1-excluded', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"last_seq":3', '"last_seq":1'), ('"mask":"VA=="', '"mask":"gA=="')]),+ ('base-at-2', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"last_seq":3', '"last_seq":2'), ('"mask":"VA=="', '"mask":"UA=="')]),+ ('base-at-3', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"flags":0', '"flags":0')]),+ ('base-at-3-module-absent', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"mask":"VA=="', '"mask":"XA=="')]),+ ('no-mask-at-0', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"last_seq":3', '"last_seq":0'), ('"mask":"VA=="', '"mask":null')]),+ ('no-mask-at-2', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"last_seq":3', '"last_seq":2'), ('"mask":"VA=="', '"mask":null')]),+ ('no-mask-at-3', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"mask":"VA=="', '"mask":null')]),+ ('mask-too-short-at-3', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"mask":"VA=="', '"mask":""')]),+ ('shield-best-of-two', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"tree_id":"fleet-base"', '"tree_id":"fleet-two"'), ('"last_seq":3', '"last_seq":2'), ('"mask":"VA=="', '"mask":"kA=="')]),+ ('shield-live-before-withdrawn', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"tree_id":"fleet-base"', '"tree_id":"fleet-mix"'), ('"mask":"VA=="', '"mask":"ZA=="')]),+ ('shield-no-tree', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"6666666666666666666666666666666666666666666666666666666666666666"'), ('"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3', '"tree_id":null,"generation":null,"base_seq":null,"last_seq":null'), ('"mask":"VA=="', '"mask":null')])+ ]) AS node+) AS n, fixture AS f;++SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SYSTEM REFRESH VIEW shirudo.node_vulns_mv;+SYSTEM WAIT VIEW shirudo.node_vulns_mv;++SELECT node_id, binding, source, vuln_id, package, installed, fixed, exposure, upatch_id, applied_seq, applied_op,+ next_seq, next_op, next_shields, shield_link+FROM shirudo.node_vulns ORDER BY node_id, vuln_id, package;++SELECT 'nodes', uniq(ak_name), (SELECT count() FROM shirudo.node_status) FROM shirudo.node_vulns;++SELECT 'shielded now, delete coming';+SELECT node_id, vuln_id, upatch_id, applied_seq, next_seq+FROM shirudo.node_vulns+WHERE exposure = 'shielded' AND next_seq > applied_seq AND next_op = 'delete'+ORDER BY node_id, vuln_id;++SELECT 'shielded now, add coming';+SELECT node_id, vuln_id, upatch_id, applied_seq, next_seq, next_shields+FROM shirudo.node_vulns+WHERE exposure = 'shielded' AND next_seq > applied_seq AND next_op = 'add'+ORDER BY node_id, vuln_id;diff --git a/tools/backend/test/vulns-fixtures.expected b/tools/backend/test/vulns-fixtures.expectednew file mode 100644index 00000000..a5ee9a04--- /dev/null+++ b/tools/backend/test/vulns-fixtures.expected@@ -0,0 +1,38 @@+node-a verified kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shielded xfs-fix 3 add 3 add+node-a verified sbom EXAMPLE-0202 openssl 3.5.1-1 3.5.1-2 exposed_no_shield 0 0+node-b declared kernel EXAMPLE-0101 linux 7.4.2 7.4.5 shield_excludes_node xfs-fix 3 add 3 add+node-b declared sbom EXAMPLE-0202 openssl 3.5.1-1 3.5.1-2 exposed_no_shield 0 0+node-c no_image none unknown 0 0+the other columns+node-a 000b23602ab98bfb edge-01 healthy untrusted fleet-os 2026.11.1 CRITICAL fixes 1+node-a 000b23602ab98bfb edge-01 healthy untrusted fleet-os 2026.11.1 HIGH none 1+node-b 000b9d72e08380a1 core-01 healthy untrusted fleet-os 2026.11.1 CRITICAL fixes 1+node-b 000b9d72e08380a1 core-01 healthy untrusted fleet-os 2026.11.1 HIGH none 1+node-c 000b0c lab-01 healthy untrusted none 1+fleet, worst first+EXAMPLE-0101 CRITICAL shield_excludes_node 1+EXAMPLE-0101 CRITICAL shielded 1+EXAMPLE-0202 HIGH exposed_no_shield 2+one node+EXAMPLE-0101 CRITICAL linux 7.4.2 7.4.5 shield_excludes_node xfs-fix declared healthy+EXAMPLE-0202 HIGH openssl 3.5.1-1 3.5.1-2 exposed_no_shield declared healthy+shields whose selector leaves nodes out+xfs-fix EXAMPLE-0101 ['node-b']+coverage+verified 1+declared 1+no_image 1+shielded now, delete coming+the refresh read+shirudo.keepalive_latest+shirudo.kernel_vulns+shirudo.latest+shirudo.node_ops+shirudo.node_status+shirudo.node_vulns_mv+shirudo.nodes+shirudo.sbom_images+shirudo.sbom_vulns+shirudo.settings+shirudo.tree_ops+shirudo.upatch_fixesdiff --git a/tools/backend/test/vulns-fixtures.sql b/tools/backend/test/vulns-fixtures.sqlnew file mode 100644index 00000000..26850fc9--- /dev/null+++ b/tools/backend/test/vulns-fixtures.sql@@ -0,0 +1,120 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- The vulnerability page's table for node A and node B after release+-- 1.1.0, both on image fleet-os 2026.11.1 and kernel 7.4.2. The image's+-- SBOM has one finding no upatch is linked to; the kernel has one, which+-- xfs-fix shields against. Node A booted the image's root and has xfs-fix+-- loaded: verified, shielded. Node B booted without verity and the+-- selector left it out: declared, shield_excludes_node. Node C, a host+-- installed by hand on a kernel outside every range, reports no image+-- and has its one row, unknown. Then the five queries a UI runs, and the+-- tables the refresh read, which shirudo.keepalive is not among.++-- The publication of testing/fixtures/keepalive/tree-1.1.0.json, as the+-- ingest job loads it: generation 3 with its three operations.+INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-base', 3, '1f327364233e3f2dcebcd13c0af8d84f886201531b135294bd7356a2f7ed680b', '4ee49208ad87695d862c8cc976d1c910170a3de611cfcee2ce181efd8e0a2942', 3, now64(3) - INTERVAL 10 MINUTE);+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-base', 1, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144', '9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6', '59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885', '13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43'),+('fleet-base', 2, 'delete', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', '4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b', 'e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55', 'f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1', '5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b'),+('fleet-base', 3, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-base', 'b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a', '653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97', '82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf', 'bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc');+INSERT INTO shirudo.expected_builds (version_id, note) VALUES+('d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f', 'shirudo 2026.11');++-- The bodies of testing/fixtures/keepalive/, byte for byte.+CREATE TEMPORARY TABLE fixture (name String, body String);+INSERT INTO fixture VALUES+('node-a-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1","mask":"VA==","set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1,"not_ok":0}'),+('node-b-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"9a6f14ea-0cc2-45e1-8e23-7b887120cf54","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"ff2cbeff5d0e9c41a7b36f28d14ce09b73a5182e6fc40d97b5e2a1683c0f7ff8","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":null,"verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"0000000000000000000000000000000000000000000000000000000000000000","mask":"qA==","set_sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","count":0,"not_ok":0}');+++-- What the tree ingest job takes from the fixes of operations 1 and 3.+INSERT INTO shirudo.upatch_fixes (tree_id, seq, id, advisory, source) VALUES+('fleet-base', 1, 'xfs-fix', 'EXAMPLE-0101', 'fixes'),+('fleet-base', 3, 'xfs-fix', 'EXAMPLE-0101', 'fixes');++-- What the sbom-scan job writes for the image and its one finding, in+-- place of a scan, and the kernel advisory.+CREATE TEMPORARY TABLE scan AS SELECT now() - INTERVAL 1 HOUR AS at;+INSERT INTO shirudo.sbom_images (image_id, image_version, image_root, sbom_format, sbom_sha256, state, built_at, db_version, scanned_at)+SELECT 'fleet-os', '2026.11.1', 'a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c', 'cyclonedx-json',+ '5b0e2c8a4f6d1e3b7a9c0d2e4f6a8b1c3d5e7f9a0b2c4d6e8f1a3b5c7d9e91d4', 'ok', '2026-11-02 08:00:00', '2', at+FROM scan;+INSERT INTO shirudo.sbom_vulns (sbom_sha256, vuln_id, package, installed, fixed, severity, scanned_at)+SELECT '5b0e2c8a4f6d1e3b7a9c0d2e4f6a8b1c3d5e7f9a0b2c4d6e8f1a3b5c7d9e91d4', 'EXAMPLE-0202', 'openssl', '3.5.1-1', '3.5.1-2', 'HIGH', at+FROM scan;+INSERT INTO shirudo.kernel_vulns (vuln_id, introduced, fixed, severity) VALUES+('EXAMPLE-0101', [7, 0], [7, 4, 5], 'CRITICAL');++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT 'edge-01', body, 1, '000b23602ab98bfb', 'QUtB', 7, 86523114 FROM fixture WHERE name = 'node-a-1.1.0';+INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT 'core-01', body, 1, '000b9d72e08380a1', 'QUtC', 4, 91200408 FROM fixture WHERE name = 'node-b-1.1.0';+INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT 'lab-01', replaceOne(replaceOne(replaceOne(body, '"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"0000000000000000000000000000000000000000000000000000000000000000","mask":"qA=="', '"tree_id":null,"generation":null,"base_seq":null,"last_seq":null,"base_root":null,"projection_root":null,"mask":null'),+ '"kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1"', '"kernel_release":"7.5.1","image_id":null,"image_version":null'),+ '9a6f14ea-0cc2-45e1-8e23-7b887120cf54', '5c1d7e2f-3a4b-4c5d-8e6f-7a8b9c0d1e2f'),+ 1, '000b0c', 'QUtD', 1, 1000 FROM fixture WHERE name = 'node-b-1.1.0';++-- The operator's labels, as the page has them.+INSERT INTO shirudo.nodes (ak_name, node_id)+SELECT record.1, argMinState(record.2, toDateTime64(0, 3))+FROM (SELECT arrayJoin([('000b23602ab98bfb', 'node-a'), ('000b9d72e08380a1', 'node-b'), ('000b0c', 'node-c')]) AS record)+GROUP BY record.1;++SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SYSTEM REFRESH VIEW shirudo.node_vulns_mv;+SYSTEM WAIT VIEW shirudo.node_vulns_mv;++SELECT node_id, binding, source, vuln_id, package, installed, fixed, exposure, upatch_id, applied_seq, applied_op,+ next_seq, next_op+FROM shirudo.node_vulns ORDER BY node_id, vuln_id;++SELECT 'the other columns';+SELECT node_id, ak_name, host_name, status, trust, image_id, image_version, severity, shield_link,+ updated_at > now() - INTERVAL 1 MINUTE+FROM shirudo.node_vulns ORDER BY node_id, vuln_id;++SELECT 'fleet, worst first';+SELECT vuln_id, severity, exposure, uniq(ak_name) AS nodes+FROM shirudo.node_vulns+WHERE vuln_id != ''+GROUP BY ALL+ORDER BY severity = 'CRITICAL' DESC, severity = 'HIGH' DESC, exposure DESC, nodes DESC, vuln_id;++SELECT 'one node';+SELECT vuln_id, severity, package, installed, fixed, exposure, upatch_id, binding, status+FROM shirudo.node_vulns+WHERE node_id = 'node-b'+ORDER BY vuln_id, package;++SELECT 'shields whose selector leaves nodes out';+SELECT upatch_id, vuln_id, arraySort(groupArray(node_id)) AS left_out+FROM shirudo.node_vulns+WHERE exposure = 'shield_excludes_node'+GROUP BY upatch_id, vuln_id+ORDER BY upatch_id, vuln_id;++SELECT 'coverage';+SELECT binding, uniq(ak_name) AS nodes+FROM shirudo.node_vulns+GROUP BY binding+ORDER BY binding;++SELECT 'shielded now, delete coming';+SELECT node_id, vuln_id, upatch_id, applied_seq, next_seq+FROM shirudo.node_vulns+WHERE exposure = 'shielded' AND next_seq > applied_seq AND next_op = 'delete'+ORDER BY node_id, vuln_id;++SYSTEM FLUSH LOGS;++SELECT 'the refresh read';+SELECT arrayJoin(arraySort(arrayFilter(name -> name NOT LIKE '%.tmp.%', tables))) AS read+FROM system.query_log+WHERE type = 'QueryFinish' AND query_kind = 'Insert' AND has(tables, 'shirudo.node_vulns_mv')+ORDER BY event_time_microseconds DESC+LIMIT 1 BY read+LIMIT 20;diff --git a/tools/backend/test/vulns-history.expected b/tools/backend/test/vulns-history.expectednew file mode 100644index 00000000..466dcb75--- /dev/null+++ b/tools/backend/test/vulns-history.expected@@ -0,0 +1,10 @@+in the window+core-01 EXAMPLE-0101 shield_excludes_node xfs-fix 3 add 3 add true fixes+edge-01 EXAMPLE-0101 shielded xfs-fix 3 add 3 add true fixes+below the window+core-01 EXAMPLE-0101 shield_excludes_node xfs-fix 3 add 3 add true fixes+edge-01 EXAMPLE-0101 shielded xfs-fix 3 add 3 add true fixes+edge-late EXAMPLE-0101 unknown xfs-fix 3 add 3 add true fixes+core-01 healthy 0 4 chain: pass, root 2b11a79d 6 set: pass, 0 loaded+edge-01 healthy 0 4 chain: pass, root 7abe8b4e 6 set: pass, 1 loaded+edge-late healthy 0 4 chain: pass, root 7abe8b4e, base unverified (gap) 6 set: set unverified (gap), 1 loadeddiff --git a/tools/backend/test/vulns-history.sql b/tools/backend/test/vulns-history.sqlnew file mode 100644index 00000000..6f494cb6--- /dev/null+++ b/tools/backend/test/vulns-history.sql@@ -0,0 +1,110 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- A shield older than the window: on the tree of test/history-base.sql,+-- xfs-fix, which shields against EXAMPLE-0101, is last added at seq 3.+-- From generation 4 on a node's window starts at seq 6, so its mask no+-- longer says what the add did there; node_vulns reads that from the+-- node's history instead, and edge-01 stays shielded and core-01, which+-- the selector leaves out, shield_excludes_node. edge-late is first+-- heard from at generation 4: the backend never saw what it did at seq+-- 3, and the row is unknown.++INSERT INTO shirudo.tree_pubs (tree_id, generation, manifest_digest, parent_manifest_digest, head_seq, published_at) VALUES+('fleet-long', 1, '1111111111111111111111111111111111111111111111111111111111111111', '', 2, now64(3) - INTERVAL 40 MINUTE),+('fleet-long', 2, '2222222222222222222222222222222222222222222222222222222222222222', '1111111111111111111111111111111111111111111111111111111111111111', 4, now64(3) - INTERVAL 30 MINUTE),+('fleet-long', 3, '3333333333333333333333333333333333333333333333333333333333333333', '2222222222222222222222222222222222222222222222222222222222222222', 6, now64(3) - INTERVAL 20 MINUTE),+('fleet-long', 4, '4444444444444444444444444444444444444444444444444444444444444444', '3333333333333333333333333333333333333333333333333333333333333333', 8, now64(3) - INTERVAL 10 MINUTE);+-- Operations 1 to 3 are those of+-- testing/fixtures/keepalive/tree-1.1.0.json; the digests of the others+-- are made up.+INSERT INTO shirudo.tree_ops (tree_id, seq, op, id, selector, repository, manifest_digest, layer_digest, payload_sha256, operation_digest) VALUES+('fleet-long', 1, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', '98f2c22f02ed3106f44cefae608868f529a38fada82d52a263f230cbda076144', '9ecc7c28f423abab4de35c3dbcb2af66dd44df59c0dcd52f465f7bc6338772e6', '59f8ad56dfc63ce2b91d4b2edd89218694bee7287eaafe06a8624869210cf885', '13b248d4a85d91150717e3e96dc9c2d7a8a43633e3b58f8f6168d408aed26c43'),+('fleet-long', 2, 'delete', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', '4d4f3bf9f68bf0dcbd06bffe4aa9eaf83444430e60936b9b2d11ec6229130a1b', 'e80b73d1bf9f8b4d50e5037f317e68bc4c8b15532187b1a3d73b5152a1596c55', 'f6a8fbb53b29691f47d8e9059a3796ecce2a48e693ec444da690209edef000f1', '5ce215313f29f87bfb87aa0cc65c237bf21bdc7702606e9cc29be187f950074b'),+('fleet-long', 3, 'add', 'xfs-fix', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', 'b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a', '653919e8cd88d08fc0d7d3bee8ac27323fadac7ec0a8b8eb6e9dc5a68c36bc97', '82db4a710ddb53f6e3e245e01001242cfb2d628e542e9ffefbb343b01c48a7bf', 'bd98b27dd5cfc9deeb0e4f49a7d4bd0f991762ec784be9ea838a59966d9dd0dc'),+('fleet-long', 4, 'add', 'net-guard', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', '4444444444444444444444444444444444444444444444444444444444444404', '4444444444444444444444444444444444444444444444444444444444444414', 'c1a4ce09e5b1fb14befa6c31b1686c93d65751a5f7882a70ba74ae53eff1c445', 'b5a7fd0926194d53c3c38d9a9f33191d22dbcf421eabb6a095af1b0dda854017'),+('fleet-long', 5, 'add', 'log-tap', '{"labels":{"role":["core"]}}', 'oci://registry.example.com/shirudo/fleet-long', '5555555555555555555555555555555555555555555555555555555555555505', '5555555555555555555555555555555555555555555555555555555555555515', '1c838773b1a663e05f30a70eb492a091cf7edf9e8636c0467bf4c75bc6492b60', '7e7d4e53558bdf3a32dad9b9cb76617d8c4d72df92da85bae8b80ea39dbc8de3'),+('fleet-long', 6, 'add', 'net-guard', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', '6666666666666666666666666666666666666666666666666666666666666606', '6666666666666666666666666666666666666666666666666666666666666616', '04327d1d09b5fd365976ae08b7868ce475c7e05ea06e7953298dc49f0b49a73e', '9482a7501c078b476df790ad7f3d293fc33c8fac98656b942fa9c04066fe6701'),+('fleet-long', 7, 'delete', 'log-tap', '{"labels":{"role":["core"]}}', 'oci://registry.example.com/shirudo/fleet-long', '7777777777777777777777777777777777777777777777777777777777777707', '7777777777777777777777777777777777777777777777777777777777777717', '8b0e09319c7612405a657c8adb8ddae1094224cfe816b63ee7713f982014736b', '48c8470b6db1077529650c52be2eada465d1ec6795565532a79aa0432e268152'),+('fleet-long', 8, 'delete', 'net-guard', '{"labels":{"role":["edge"]}}', 'oci://registry.example.com/shirudo/fleet-long', '8888888888888888888888888888888888888888888888888888888888888808', '8888888888888888888888888888888888888888888888888888888888888818', '45517a96247744dacfcb009e9b9a1393feb7593641b463b8bb60a8bec3a545b2', 'a7e69500fd7613e54bcbd7dccffe0d8a081145e93a59f2230114d08b9c8a81cd');+INSERT INTO shirudo.expected_builds (version_id, note) VALUES+('d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f', 'shirudo 2026.11');++-- The bodies of node A and node B of testing/fixtures/keepalive/ with+-- the tree keys left for each record to fill in.+CREATE TEMPORARY TABLE fixture (name String, body String);+INSERT INTO fixture VALUES+('a', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],@TREE@,"not_ok":0}'),+('b', '{"schema":"shirudo.keepalive/1","boot_id":"9a6f14ea-0cc2-45e1-8e23-7b887120cf54","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"ff2cbeff5d0e9c41a7b36f28d14ce09b73a5182e6fc40d97b5e2a1683c0f7ff8","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":null,"verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],@TREE@,"not_ok":0}');++-- The tree keys of each record: an edge node applies every edge+-- operation and passes the core ones over, a core node the other way+-- round. Generation g has its head at 2g and the window starts at 2g - 2.+CREATE TEMPORARY TABLE tree_keys (path String, generation UInt64, base_root String, projection_root String, mask String, set_sha256 String, count UInt64);+INSERT INTO tree_keys VALUES+('edge', 1, '0000000000000000000000000000000000000000000000000000000000000000', 'a042a582b3a3d8c1b633b8ed0356e0b52f1f5aa25af85b06cc3f481562dcda93', 'UA==', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 0),+('edge', 2, 'a042a582b3a3d8c1b633b8ed0356e0b52f1f5aa25af85b06cc3f481562dcda93', '61fc83b3a0ac0db078d815d7a1d5656d1c1b86969c33b2502a9d4553a475f75f', 'UA==', '55fe60cc8e2f809e798c3f733a1186a1a4a5d3c23bafce8278d9f6613fd24f20', 2),+('edge', 3, '61fc83b3a0ac0db078d815d7a1d5656d1c1b86969c33b2502a9d4553a475f75f', 'c7a9860aeaaa41c9b5960ea49d36bf8493829fe711d6ee041615a59e3e4a160b', 'kA==', '39cfdd2bbb3ee01e93c5f663d4f5b416ed5eac60af43d1a88d075b4d352fd352', 2),+('edge', 4, 'c7a9860aeaaa41c9b5960ea49d36bf8493829fe711d6ee041615a59e3e4a160b', '7abe8b4e5b09b24d541e029f0c21b7fddc42088b538544b28874d20820edfcd4', 'kA==', '74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf', 1),+('core', 1, '0000000000000000000000000000000000000000000000000000000000000000', '0000000000000000000000000000000000000000000000000000000000000000', 'oA==', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 0),+('core', 2, '0000000000000000000000000000000000000000000000000000000000000000', '0000000000000000000000000000000000000000000000000000000000000000', 'oA==', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 0),+('core', 3, '0000000000000000000000000000000000000000000000000000000000000000', '7eb926ee3992a1b56d01db3f58713440ca1c7378b02a9c6354e59d2e32cd577f', 'YA==', '885e4806c48d2d850267ee7f714abd8da2bd679483f6d60323fe8499fe8af7f9', 1),+('core', 4, '7eb926ee3992a1b56d01db3f58713440ca1c7378b02a9c6354e59d2e32cd577f', '2b11a79d680e7ebfe4ac646730b29f6247080ecd765d2b1d83538f21f011030a', 'YA==', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 0),+-- An edge node at generation 3 that says it applied nothing before seq 4.+('liar', 3, '0000000000000000000000000000000000000000000000000000000000000000', '78b6a625584ca000a0b7821895cb9441563e4d00f4ec0193ee1395976e16593e', 'kA==', 'fee50b592ea40c6ae2f6ecf6bed6fa2781e1a791e1b9b7a443f2f7f38c6ee650', 1);++INSERT INTO shirudo.upatch_fixes (tree_id, seq, id, advisory, source) VALUES+('fleet-long', 1, 'xfs-fix', 'EXAMPLE-0101', 'fixes'),+('fleet-long', 3, 'xfs-fix', 'EXAMPLE-0101', 'fixes');+INSERT INTO shirudo.kernel_vulns (vuln_id, introduced, fixed, severity) VALUES+('EXAMPLE-0101', [7, 0], [7, 4, 5], 'HIGH');++CREATE TEMPORARY TABLE records (round UInt64, host String, body String);+INSERT INTO records+SELECT r.1, r.2,+ replaceOne(f.body, '@TREE@',+ format('"tree_id":"fleet-long","generation":{},"base_seq":{},"last_seq":{},"base_root":"{}","projection_root":"{}","mask":"{}","set_sha256":"{}","count":{}',+ toString(t.generation), toString(2 * t.generation - 2), toString(2 * t.generation),+ t.base_root, t.projection_root, t.mask, t.set_sha256, toString(t.count)))+FROM (SELECT arrayJoin(arrayConcat(+ arrayFlatten(arrayMap(g -> [(g, 'edge-01', 'a', 'edge'), (g, 'core-01', 'b', 'core')], range(1, 5))),+ [(4, 'edge-late', 'a', 'edge')])) AS r) AS x+INNER JOIN fixture AS f ON f.name = r.3+INNER JOIN tree_keys AS t ON t.path = r.4 AND t.generation = r.1;++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT host, body, 1, concat('000b', host), 'QUtB', 1, 1000 * round FROM records WHERE round = 1;+SYSTEM REFRESH VIEW shirudo.node_ops_mv;+SYSTEM WAIT VIEW shirudo.node_ops_mv;+INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT host, body, 1, concat('000b', host), 'QUtB', 1, 1000 * round FROM records WHERE round = 2;+SYSTEM REFRESH VIEW shirudo.node_ops_mv;+SYSTEM WAIT VIEW shirudo.node_ops_mv;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SYSTEM REFRESH VIEW shirudo.node_vulns_mv;+SYSTEM WAIT VIEW shirudo.node_vulns_mv;++-- Generation 2: the add at 3 is in the window, read from the mask.+SELECT 'in the window';+SELECT node_id, vuln_id, exposure, upatch_id, applied_seq, applied_op, next_seq, next_op, next_shields, shield_link+FROM shirudo.node_vulns ORDER BY node_id, vuln_id;++INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT host, body, 1, concat('000b', host), 'QUtB', 1, 1000 * round FROM records WHERE round = 3;+SYSTEM REFRESH VIEW shirudo.node_ops_mv;+SYSTEM WAIT VIEW shirudo.node_ops_mv;+INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT host, body, 1, concat('000b', host), 'QUtB', 1, 1000 * round FROM records WHERE round = 4;+SYSTEM REFRESH VIEW shirudo.node_ops_mv;+SYSTEM WAIT VIEW shirudo.node_ops_mv;+SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SYSTEM REFRESH VIEW shirudo.node_vulns_mv;+SYSTEM WAIT VIEW shirudo.node_vulns_mv;++-- Generation 4: the add at 3 is below the window, read from the history.+SELECT 'below the window';+SELECT node_id, vuln_id, exposure, upatch_id, applied_seq, applied_op, next_seq, next_op, next_shields, shield_link+FROM shirudo.node_vulns ORDER BY node_id, vuln_id;+SELECT node_id, status, failed_check, log[4], log[6] FROM shirudo.node_status ORDER BY node_id;diff --git a/tools/backend/test/vulns-stale.expected b/tools/backend/test/vulns-stale.expectednew file mode 100644index 00000000..5c8e4c60--- /dev/null+++ b/tools/backend/test/vulns-stale.expected@@ -0,0 +1,16 @@+fresh-clean 2026.11.3 verified false none none+fresh-findings 2026.11.2 verified false sbom EXAMPLE-0707 curl exposed_no_shield+no-sbom 2026.11.4 no_sbom false none unknown+stale-expired 2026.11.6 declared true none unknown+stale-findings 2026.11.1 verified true sbom EXAMPLE-0202 openssl exposed_no_shield+stale-kernel 2026.11.6 declared true kernel EXAMPLE-0101 linux exposed_no_shield+stale images+fleet-os 2026.11.1 1+fleet-os 2026.11.6 2+sbom_stale_seconds 1800+fresh-clean 2026.11.3 verified true none unknown+fresh-findings 2026.11.2 verified true sbom EXAMPLE-0707 curl exposed_no_shield+no-sbom 2026.11.4 no_sbom false none unknown+stale-expired 2026.11.6 declared true none unknown+stale-findings 2026.11.1 verified true sbom EXAMPLE-0202 openssl exposed_no_shield+stale-kernel 2026.11.6 declared true kernel EXAMPLE-0101 linux exposed_no_shielddiff --git a/tools/backend/test/vulns-stale.sql b/tools/backend/test/vulns-stale.sqlnew file mode 100644index 00000000..9c43236c--- /dev/null+++ b/tools/backend/test/vulns-stale.sql@@ -0,0 +1,77 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- An image whose newest scan is older than sbom_stale_seconds of+-- shirudo.settings, two days by default, reads stale in node_vulns while+-- sbom_vulns still has its findings, and never clean: its findings stay,+-- with sbom_stale true on every row of its nodes, kernel rows included,+-- and a node without findings is unknown rather than none, also when+-- the findings have expired, as those of a scan eight days old have. A+-- scan an hour old is fresh, and an image whose state is not ok is+-- no_sbom and never stale. Lowering the setting to half an hour makes+-- the scans of an hour ago stale at the next refresh. The query a UI runs+-- for the stale images counts the nodes on each.++-- What the sbom-scan job writes, in place of a scan: 2026.11.1 three+-- days ago with one finding, 2026.11.6 eight days ago with none left,+-- 2026.11.2 and 2026.11.3 an hour ago, with one finding and with none,+-- and 2026.11.4 three days ago without its SBOM.+CREATE TEMPORARY TABLE scan AS SELECT now() AS at;+INSERT INTO shirudo.sbom_images (image_id, image_version, image_root, sbom_format, sbom_sha256, state, built_at, db_version, scanned_at)+SELECT 'fleet-os', '2026.11.1', 'a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c', 'cyclonedx-json', '1111111111111111111111111111111111111111111111111111111111111111', 'ok', '2026-11-02 08:00:00', '2', at - INTERVAL 3 DAY FROM scan UNION ALL+SELECT 'fleet-os', '2026.11.6', '', 'cyclonedx-json', 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', 'ok', '2026-11-07 08:00:00', '2', at - INTERVAL 8 DAY FROM scan UNION ALL+SELECT 'fleet-os', '2026.11.2', '2222222222222222222222222222222222222222222222222222222222222222', 'cyclonedx-json', 'cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', 'ok', '2026-11-03 08:00:00', '2', at - INTERVAL 1 HOUR FROM scan UNION ALL+SELECT 'fleet-os', '2026.11.3', '3333333333333333333333333333333333333333333333333333333333333333', 'cyclonedx-json', 'dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd', 'ok', '2026-11-04 08:00:00', '2', at - INTERVAL 1 HOUR FROM scan UNION ALL+SELECT 'fleet-os', '2026.11.4', '4444444444444444444444444444444444444444444444444444444444444444', 'cyclonedx-json', '', 'missing', '2026-11-05 08:00:00', '', at - INTERVAL 3 DAY FROM scan;+INSERT INTO shirudo.sbom_vulns (sbom_sha256, vuln_id, package, installed, fixed, severity, scanned_at)+SELECT '1111111111111111111111111111111111111111111111111111111111111111', 'EXAMPLE-0202', 'openssl', '3.5.1-1', '3.5.1-2', 'HIGH', at - INTERVAL 3 DAY FROM scan UNION ALL+SELECT 'cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', 'EXAMPLE-0707', 'curl', '8.1-1', '', 'MEDIUM', at - INTERVAL 1 HOUR FROM scan;+INSERT INTO shirudo.kernel_vulns (vuln_id, introduced, fixed, severity) VALUES+('EXAMPLE-0101', [7, 0], [7, 4, 5], 'CRITICAL');++-- The body of testing/fixtures/keepalive/node-a-1.1.0.json, byte for byte.+CREATE TEMPORARY TABLE fixture (name String, body String);+INSERT INTO fixture VALUES+('node-a-1.1.0', '{"schema":"shirudo.keepalive/1","boot_id":"168d20a1-5011-4e1b-9924-d8b73c85aa4e","version_id":"d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f","config_root":"1d8465c5b17838303fee92b3905420d294d2c22c576a0bdef0f69f190ed22807","kernel_release":"7.4.2","image_id":"fleet-os","image_version":"2026.11.1","image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c","verdict":"ok","cond":5461,"flags":0,"tamper":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"tree_id":"fleet-base","generation":3,"base_seq":0,"last_seq":3,"base_root":"0000000000000000000000000000000000000000000000000000000000000000","projection_root":"154522480ff8884daa95589e80f26f20248bbf9c192dfbb3cee04e03b4f136a1","mask":"VA==","set_sha256":"74e5bd2c665109f6d8f926af5476c266ad70ab07293ff13b1a13d0b89aa5c1bf","count":1,"not_ok":0}');++-- A node per case, named for it, on kernel 6.18.9, which no advisory+-- covers, unless the case is a kernel finding.+INSERT INTO shirudo.checked (host_name, body, ok, ak_name, ak_public, reset_count, clock)+SELECT node.1, arrayFold((body, change) -> replaceOne(body, change.1, change.2), node.2, f.body),+ 1, concat('000b', node.1), 'QUtB', 1, 1000+FROM+(+ SELECT arrayJoin([+ ('stale-findings', [('"kernel_release":"7.4.2"', '"kernel_release":"6.18.9"')]),+ ('stale-expired', [('"kernel_release":"7.4.2"', '"kernel_release":"6.18.9"'), ('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":null')]),+ ('stale-kernel', [('"image_version":"2026.11.1"', '"image_version":"2026.11.6"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":null')]),+ ('fresh-findings', [('"kernel_release":"7.4.2"', '"kernel_release":"6.18.9"'), ('"image_version":"2026.11.1"', '"image_version":"2026.11.2"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"2222222222222222222222222222222222222222222222222222222222222222"')]),+ ('fresh-clean', [('"kernel_release":"7.4.2"', '"kernel_release":"6.18.9"'), ('"image_version":"2026.11.1"', '"image_version":"2026.11.3"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"3333333333333333333333333333333333333333333333333333333333333333"')]),+ ('no-sbom', [('"kernel_release":"7.4.2"', '"kernel_release":"6.18.9"'), ('"image_version":"2026.11.1"', '"image_version":"2026.11.4"'), ('"image_root":"a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c"', '"image_root":"4444444444444444444444444444444444444444444444444444444444444444"')])+ ]) AS node+) AS n, fixture AS f;++SYSTEM REFRESH VIEW shirudo.node_status_mv;+SYSTEM WAIT VIEW shirudo.node_status_mv;+SYSTEM REFRESH VIEW shirudo.node_vulns_mv;+SYSTEM WAIT VIEW shirudo.node_vulns_mv;++SELECT node_id, image_version, binding, sbom_stale, source, vuln_id, package, exposure+FROM shirudo.node_vulns ORDER BY node_id, vuln_id, package;++SELECT 'stale images';+SELECT image_id, image_version, uniq(ak_name) AS nodes+FROM shirudo.node_vulns+WHERE sbom_stale+GROUP BY image_id, image_version+ORDER BY image_id, image_version;++INSERT INTO shirudo.settings (stale_seconds, stuck_seconds, window, keepalive_retention_seconds,+ boot_first_retention_seconds, sbom_stale_seconds)+VALUES (180, 3600, 512, 3600, 2592000, 1800);+SYSTEM REFRESH VIEW shirudo.node_vulns_mv;+SYSTEM WAIT VIEW shirudo.node_vulns_mv;++SELECT 'sbom_stale_seconds 1800';+SELECT node_id, image_version, binding, sbom_stale, source, vuln_id, package, exposure+FROM shirudo.node_vulns ORDER BY node_id, vuln_id, package;