eBPF-based security platform
backend: share what the jobs copy from each other
John Fastabendde864a49df02
diff --git a/Documentation/operate/backend/index.rst b/Documentation/operate/backend/index.rstindex 3e764ea2..207c0967 100644--- a/Documentation/operate/backend/index.rst+++ b/Documentation/operate/backend/index.rst@@ -96,6 +96,9 @@ Files* - :src:`tools/backend/jobs/sbom-scan`- Scans the SBOM of every image in the SBOM store and loads theoutcome into ``sbom_images`` and ``sbom_vulns``.+ * - :src:`tools/backend/jobs/job.sh`, :src:`tools/backend/jobs/common.py`+ - What the jobs share and read from their own directory: a job is+ installed with both and with its ``*-rows.py``.* - :src:`tools/backend/test/`- The SQL tests and their runner, ``test/run.sh``(:ref:`testing-backend`).diff --git a/tools/backend/jobs/common.py b/tools/backend/jobs/common.pynew file mode 100644index 00000000..42e5b908--- /dev/null+++ b/tools/backend/jobs/common.py@@ -0,0 +1,57 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# jobs/common.py -- what the *-rows.py scripts of the jobs share: JSON+# read strictly, text made safe for a message, and rows written in+# ClickHouse's JSONEachRow format.++import json+++class Refused(Exception):+ pass+++def printable(text):+ return "".join(c if c.isprintable() else "?" for c in str(text))+++def unique_keys(pairs):+ seen = {}+ for key, value in pairs:+ if key in seen:+ raise Refused('the key "%s" is given twice in one object'+ % printable(key))+ seen[key] = value+ return seen+++def not_a_number(name):+ raise Refused("%s is not a JSON number" % name)+++def utf8_text(data, what):+ try:+ return data.decode("utf-8")+ except UnicodeDecodeError:+ raise Refused("%s is not UTF-8" % what)+++def strict_decoder():+ """A decoder that refuses a key given twice, NaN and Infinity."""+ return json.JSONDecoder(object_pairs_hook=unique_keys,+ parse_constant=not_a_number)+++def parse_json(data, what):+ text = utf8_text(data, what)+ try:+ return strict_decoder().decode(text)+ except (ValueError, RecursionError):+ raise Refused("%s is not a JSON value" % what)+++def write_rows(path, table):+ with open(path, "w", encoding="ascii") as out:+ for row in table:+ out.write(json.dumps(row, separators=(",", ":")) + "\n")diff --git a/tools/backend/jobs/enroll-put b/tools/backend/jobs/enroll-putindex 62d606fa..18b190df 100755--- a/tools/backend/jobs/enroll-put+++ b/tools/backend/jobs/enroll-put@@ -27,33 +27,18 @@set -euhere=$(cd "$(dirname "$0")" && pwd)+prog=enroll-put+# shellcheck source=tools/backend/jobs/job.sh+. "$here/job.sh"check=0-work=columns='ak_name String, ek_name String, node_id String, source String, new UInt8'-die()-{- printf 'enroll-put: %s\n' "$1" >&2- exit 1-}-usage(){printf '%s\n' 'usage: enroll-put [--check] <bindings.json>|-' >&2exit 2}-cleanup()-{- [ -z "$work" ] || rm -rf "$work"-}--client()-{- # shellcheck disable=SC2086 # a command with its options, to be split- ${CLICKHOUSE_CLIENT:-clickhouse-client} "$@"-}-[ "${1:-}" = --check ] && { check=1; shift; }[ $# -eq 1 ] || usagecase "$1" in@@ -61,9 +46,7 @@ case "$1" in-*) usage ;;esac-trap cleanup EXIT-trap 'exit 1' HUP INT TERM-work=$(mktemp -d)+make_workif [ "$1" = - ]; thencat >"$work/bindings.json"elsediff --git a/tools/backend/jobs/enroll-rows.py b/tools/backend/jobs/enroll-rows.pyindex 8da2b27b..9a29a781 100644--- a/tools/backend/jobs/enroll-rows.py+++ b/tools/backend/jobs/enroll-rows.py@@ -23,6 +23,8 @@ import jsonimport reimport sys+from common import Refused, parse_json, printable+PROG = "enroll-put"# 000b, TPM_ALG_SHA256, and the SHA-256 of the public area, as# shirudo attest and shirudo-quote-check write a name.@@ -31,41 +33,6 @@ TEXT = re.compile(r"[^\x00-\x1f\x7f]{1,255}")KEYS = {"ak_name", "ek_name", "node_id"}-class Refused(Exception):- pass---def unique_keys(pairs):- seen = {}- for key, value in pairs:- if key in seen:- raise Refused('the key "%s" is given twice in one object'- % printable(key))- seen[key] = value- return seen---def not_a_number(name):- raise Refused("%s is not a JSON number" % name)---def printable(text):- return "".join(c if c.isprintable() else "?" for c in text)---def parse(data):- try:- text = data.decode("utf-8")- except UnicodeDecodeError:- raise Refused("the file is not UTF-8")- decoder = json.JSONDecoder(object_pairs_hook=unique_keys,- parse_constant=not_a_number)- try:- return decoder.decode(text)- except (ValueError, RecursionError):- raise Refused("the file is not a JSON value")--def name_of(where, entry, key):"""The binding's TPM name under key, "" for an ek_name left out."""name = entry.get(key, "")@@ -154,7 +121,7 @@ def main():path, enrolled_path, rows = sys.argv[1:]try:with open(path, "rb") as f:- source, bindings = bindings_of(parse(f.read()))+ source, bindings = bindings_of(parse_json(f.read(), "the file"))new = check_against(bindings, enrolled_of(enrolled_path))except Refused as reason:print("%s: %s, nothing loaded" % (PROG, reason), file=sys.stderr)diff --git a/tools/backend/jobs/job.sh b/tools/backend/jobs/job.shnew file mode 100644index 00000000..fc6d915d--- /dev/null+++ b/tools/backend/jobs/job.sh@@ -0,0 +1,47 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# jobs/job.sh -- what the jobs share, read by each with its name in+# prog: its messages, its scratch directory and the commands it runs.++work=++die()+{+ printf '%s: %s\n' "$prog" "$1" >&2+ exit 1+}++cleanup()+{+ [ -z "$work" ] || rm -rf "$work"+}++# make_work: a scratch directory in work that leaves with the job.+make_work()+{+ trap cleanup EXIT+ trap 'exit 1' HUP INT TERM+ work=$(mktemp -d)+}++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 <table> <rows.jsonl>: load the rows, none when the file is empty.+insert()+{+ [ -s "$2" ] || return 0+ client --query "INSERT INTO shirudo.$1 FORMAT JSONEachRow" <"$2" ||+ die "cannot insert into shirudo.$1"+}diff --git a/tools/backend/jobs/labels-put b/tools/backend/jobs/labels-putindex 7526496b..2d211309 100755--- a/tools/backend/jobs/labels-put+++ b/tools/backend/jobs/labels-put@@ -29,14 +29,10 @@set -euhere=$(cd "$(dirname "$0")" && pwd)+prog=labels-put+# shellcheck source=tools/backend/jobs/job.sh+. "$here/job.sh"check=0-work=--die()-{- printf 'labels-put: %s\n' "$1" >&2- exit 1-}usage(){@@ -44,17 +40,6 @@ usage()exit 2}-cleanup()-{- [ -z "$work" ] || rm -rf "$work"-}--client()-{- # shellcheck disable=SC2086 # a command with its options, to be split- ${CLICKHOUSE_CLIENT:-clickhouse-client} "$@"-}-[ "${1:-}" = --check ] && { check=1; shift; }[ $# -eq 1 ] || usagecase "$1" in@@ -62,9 +47,7 @@ case "$1" in-*) usage ;;esac-trap cleanup EXIT-trap 'exit 1' HUP INT TERM-work=$(mktemp -d)+make_workif [ "$1" = - ]; thencat >"$work/sets.json"elsediff --git a/tools/backend/jobs/labels-rows.py b/tools/backend/jobs/labels-rows.pyindex 8cfbf4d6..49ff22b6 100644--- a/tools/backend/jobs/labels-rows.py+++ b/tools/backend/jobs/labels-rows.py@@ -23,6 +23,8 @@ import jsonimport reimport sys+from common import Refused, parse_json, printable+PROG = "labels-put"# As TREE_MAX_LABELS and TREE_STRING_MAX of util/bpm_tree.h.MAX_LABELS = 64@@ -38,41 +40,6 @@ NAMES = {CONTROL = re.compile(r"[\x00-\x1f\x7f]")-class Refused(Exception):- pass---def unique_keys(pairs):- seen = {}- for key, value in pairs:- if key in seen:- raise Refused('the key "%s" is given twice in one object'- % printable(key))- seen[key] = value- return seen---def not_a_number(name):- raise Refused("%s is not a JSON number" % name)---def printable(text):- return "".join(c if c.isprintable() else "?" for c in text)---def parse(data):- try:- text = data.decode("utf-8")- except UnicodeDecodeError:- raise Refused("the file is not UTF-8")- decoder = json.JSONDecoder(object_pairs_hook=unique_keys,- parse_constant=not_a_number)- try:- return decoder.decode(text)- except (ValueError, RecursionError):- raise Refused("the file is not a JSON value")--def text_ok(text):"""What a node.labels line keeps of a key or value: no blank at eitherend, no control character, at most MAX_TEXT bytes."""@@ -153,7 +120,7 @@ def main():path, rows, put_at = sys.argv[1], sys.argv[2], int(sys.argv[3])try:with open(path, "rb") as f:- sets = sets_of(parse(f.read()))+ sets = sets_of(parse_json(f.read(), "the file"))except Refused as reason:print("%s: %s, nothing loaded" % (PROG, reason), file=sys.stderr)return 1diff --git a/tools/backend/jobs/sbom-put b/tools/backend/jobs/sbom-putindex fc58140e..4c5c724b 100755--- a/tools/backend/jobs/sbom-put+++ b/tools/backend/jobs/sbom-put@@ -31,19 +31,15 @@set -euhere=$(cd "$(dirname "$0")" && pwd)+prog=sbom-put+# shellcheck source=tools/backend/jobs/job.sh+. "$here/job.sh"store=${SBOM_STORE:-}image_id=image_version=image_root=-built_at=scan=0-work=--die()-{- printf 'sbom-put: %s\n' "$1" >&2- exit 1-}usage(){@@ -54,17 +50,6 @@ usage()exit 2}-cleanup()-{- [ -z "$work" ] || rm -rf "$work"-}--s3()-{- # shellcheck disable=SC2086 # a command with its options, to be split- ${S3_CLIENT:-aws} "$@"-}-while [ $# -gt 0 ]; docase "$1" in--store|--image-id|--image-version|--image-root|--built-at)@@ -93,9 +78,7 @@ sbom=$1[ -n "$image_root" ] || image_root=-[ -n "$built_at" ] || built_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)-trap cleanup EXIT-trap 'exit 1' HUP INT TERM-work=$(mktemp -d)+make_workmkdir "$work/new" "$work/old"python3 "$here/sbom-rows.py" put "$work/new" "$image_id" "$image_version" \diff --git a/tools/backend/jobs/sbom-rows.py b/tools/backend/jobs/sbom-rows.pyindex 0786eb6d..5f413107 100755--- a/tools/backend/jobs/sbom-rows.py+++ b/tools/backend/jobs/sbom-rows.py@@ -50,6 +50,8 @@ import osimport reimport sys+from common import Refused, parse_json, printable, write_rows+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}")@@ -59,40 +61,6 @@ UINT32_MAX = 2**32 - 1LEFT_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)@@ -335,12 +303,6 @@ def db_version(work):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)diff --git a/tools/backend/jobs/sbom-scan b/tools/backend/jobs/sbom-scanindex 738e14f7..9ce01510 100755--- a/tools/backend/jobs/sbom-scan+++ b/tools/backend/jobs/sbom-scan@@ -30,17 +30,13 @@set -euhere=$(cd "$(dirname "$0")" && pwd)+prog=sbom-scan+# shellcheck source=tools/backend/jobs/job.sh+. "$here/job.sh"store=${SBOM_STORE:-}trivy=${TRIVY:-trivy}cache=${TRIVY_CACHE_DIR:-}incomplete=0-work=--die()-{- printf 'sbom-scan: %s\n' "$1" >&2- exit 1-}usage(){@@ -49,30 +45,6 @@ usage()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()@@ -115,9 +87,7 @@ while [ $# -gt 0 ]; dodone[ -n "$store" ] || usage-trap cleanup EXIT-trap 'exit 1' HUP INT TERM-work=$(mktemp -d)+make_workcase "$store" infile://?*)@@ -167,7 +137,7 @@ 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+insert sbom_vulns "$work/sbom_vulns.jsonl"+insert sbom_images "$work/sbom_images.jsonl"cat "$work/summary"exit "$incomplete"diff --git a/tools/backend/jobs/shields-put b/tools/backend/jobs/shields-putindex 99f9488b..037170b6 100755--- a/tools/backend/jobs/shields-put+++ b/tools/backend/jobs/shields-put@@ -27,14 +27,10 @@set -euhere=$(cd "$(dirname "$0")" && pwd)+prog=shields-put+# shellcheck source=tools/backend/jobs/job.sh+. "$here/job.sh"check=0-work=--die()-{- printf 'shields-put: %s\n' "$1" >&2- exit 1-}usage(){@@ -42,17 +38,6 @@ usage()exit 2}-cleanup()-{- [ -z "$work" ] || rm -rf "$work"-}--client()-{- # shellcheck disable=SC2086 # a command with its options, to be split- ${CLICKHOUSE_CLIENT:-clickhouse-client} "$@"-}-[ "${1:-}" = --check ] && { check=1; shift; }[ $# -eq 1 ] || usagecase "$1" in@@ -60,9 +45,7 @@ case "$1" in-*) usage ;;esac-trap cleanup EXIT-trap 'exit 1' HUP INT TERM-work=$(mktemp -d)+make_workif [ "$1" = - ]; thencat >"$work/catalog.json"elsediff --git a/tools/backend/jobs/shields-rows.py b/tools/backend/jobs/shields-rows.pyindex b11a306f..361294c5 100644--- a/tools/backend/jobs/shields-rows.py+++ b/tools/backend/jobs/shields-rows.py@@ -24,6 +24,8 @@ import jsonimport reimport sys+from common import Refused, parse_json, printable+PROG = "shields-put"# As BPM_BUILD_MAX_FIXES, TREE_STRING_MAX and BPM_FIX_ID_CHARS of# tools/shirudo-build/bpm.h, and the name rules of bpm-formats.rst.@@ -42,41 +44,6 @@ KEYS = {"id", "package", "version", "reference", "manifest_digest", "fixes","selector", "description"}-class Refused(Exception):- pass---def unique_keys(pairs):- seen = {}- for key, value in pairs:- if key in seen:- raise Refused('the key "%s" is given twice in one object'- % printable(key))- seen[key] = value- return seen---def not_a_number(name):- raise Refused("%s is not a JSON number" % name)---def printable(text):- return "".join(c if c.isprintable() else "?" for c in str(text))---def parse(data):- try:- text = data.decode("utf-8")- except UnicodeDecodeError:- raise Refused("the file is not UTF-8")- decoder = json.JSONDecoder(object_pairs_hook=unique_keys,- parse_constant=not_a_number)- try:- return decoder.decode(text)- except (ValueError, RecursionError):- raise Refused("the file is not a JSON value")--def string(n, entry, key, pattern, form):value = entry.get(key)if type(value) is not str or not pattern.fullmatch(value):@@ -168,7 +135,7 @@ def main():path, rows, put_at = sys.argv[1], sys.argv[2], int(sys.argv[3])try:with open(path, "rb") as f:- shields = shields_of(parse(f.read()))+ shields = shields_of(parse_json(f.read(), "the file"))except Refused as reason:print("%s: %s, nothing loaded" % (PROG, reason), file=sys.stderr)return 1diff --git a/tools/backend/jobs/tree-ingest b/tools/backend/jobs/tree-ingestindex 79bf5342..c77286fc 100755--- a/tools/backend/jobs/tree-ingest+++ b/tools/backend/jobs/tree-ingest@@ -31,18 +31,14 @@set -euhere=$(cd "$(dirname "$0")" && pwd)+prog=tree-ingest+# shellcheck source=tools/backend/jobs/job.sh+. "$here/job.sh"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(){@@ -52,24 +48,6 @@ usage()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 ]; docase "$1" in--shirudo|--reference|--cert|--input)@@ -89,9 +67,7 @@ while [ $# -gt 0 ]; doesacdone-trap cleanup EXIT-trap 'exit 1' HUP INT TERM-work=$(mktemp -d)+make_workif [ "$input" = - ]; thencat >"$work/show"@@ -152,9 +128,9 @@ 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+insert tree_ops "$work/new.ops.jsonl"+insert upatch_fixes "$work/new.fixes.jsonl"+insert tree_pubs "$work/new.pub.jsonl"while IFS=' ' read -r generation ops fixes; doprintf 'tree-ingest: loaded %s generation %s (operations: %d, fixes: %d)\n' \"$tree_id" "$generation" "$ops" "$fixes"diff --git a/tools/backend/jobs/tree-rows.py b/tools/backend/jobs/tree-rows.pyindex 52f1722f..25a90eb4 100755--- a/tools/backend/jobs/tree-rows.py+++ b/tools/backend/jobs/tree-rows.py@@ -21,6 +21,8 @@ import osimport reimport sys+from common import Refused, strict_decoder, utf8_text, write_rows+PROG = "tree-ingest"DIGEST = re.compile(r"sha256:([0-9a-f]{64})")ROOT = re.compile(r"[0-9a-f]{64}")@@ -29,23 +31,6 @@ ZERO_ROOT = "0" * 64UINT64_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))@@ -225,12 +210,8 @@ def walk(shows):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)+ text = utf8_text(data, "it")+ decoder = strict_decoder()shows = []end = 0while True:@@ -244,12 +225,6 @@ def parse(data):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)diff --git a/tools/backend/test/tree-ingest-refused.expected b/tools/backend/test/tree-ingest-refused.expectedindex 79afd2cf..8616e8fd 100644--- a/tools/backend/test/tree-ingest-refused.expected+++ b/tools/backend/test/tree-ingest-refused.expected@@ -38,7 +38,7 @@ tree-ingest: input refused: the operation with seq 1 has no artifactno artifact: status 1tree-ingest: input refused: operations of the document is not an arrayoperations: status 1-tree-ingest: input refused: a key is given twice in one object+tree-ingest: input refused: the key "generation" is given twice in one objectkey twice: status 1tree-ingest: input refused: base has no segment_manifest_digestsegment: status 1@@ -70,7 +70,7 @@ tree-ingest: input refused: segment 3 of the walk: seq of operation 1 of the docoperation below base: status 1tree-ingest: input refused: segment 3 of the walk: the document has no operations but its base.seq is above 0no operations: status 1-tree-ingest: input refused: a key is given twice in one object+tree-ingest: input refused: the key "generation" is given twice in one objectkey twice in a segment: status 1rows after the refusals:0 0 0