eBPF-based security platform
testing: assert the OTLP export settings and payload exactly
Daniel Borkmann5bc643b74cdd
diff --git a/Documentation/developer-guide.rst b/Documentation/developer-guide.rstindex f726f2c3..ca4cbd6a 100644--- a/Documentation/developer-guide.rst+++ b/Documentation/developer-guide.rst@@ -222,10 +222,4 @@ software TPM on the host for development without a VM.8) Open work-------------The export path has room for more exact assertions: endpoint, CA,-client-certificate and header precedence across the command line, the-signal-specific and generic environment, the config and the defaults;-every resource, scope and metric attribute of the OTLP payload; export-failure and drain across timer intervals; S3 with ``AWS_CA_BUNDLE``; and-the bounds of transport timeouts, response buffers and compression.``upatch get`` is checked for the loaded source, not its JSON form.diff --git a/testing/functional/otel/t8001-otel-map.sh b/testing/functional/otel/t8001-otel-map.shindex 9753aad0..1769d49c 100644--- a/testing/functional/otel/t8001-otel-map.sh+++ b/testing/functional/otel/t8001-otel-map.sh@@ -13,33 +13,32 @@ trap 'rm -rf "$W"' EXITcd "$W" || exit 1test_expect_success 'OTLP CLI options reject invalid combinations early' '- ! "$S" upatch map --otel-retries=11 >/dev/null 2>&1 &&- ! "$S" upatch map --otel-insecure >/dev/null 2>&1 &&- ! "$S" upatch map --otel=log --metric-kind=gauge >/dev/null 2>&1 &&- ! "$S" upatch map --otel=s3 --metric-kind=gauge >/dev/null 2>&1 &&- ! "$S" upatch map --otel=s3 >/dev/null 2>&1 &&- ! "$S" upatch map --otel=log --s3-uri=s3://bucket >/dev/null 2>&1 &&- ! "$S" upatch map --all unexpected >/dev/null 2>&1 &&- ! "$S" upatch map --all --otel --metric-name=shared \- >/dev/null 2>&1 &&- ! "$S" upatch map --tenant-id=tenant-uuid-1234 \- >/dev/null 2>&1 &&- ! "$S" upatch map --otel=log --tenant-id="bad tenant" \- >/dev/null 2>&1 &&- ! "$S" upatch map --otel=log --tenant-id=one --tenant-id=two \- >/dev/null 2>&1 &&- ! "$S" upatch map --emit=otel >/dev/null 2>&1+ for args in "--otel-retries=11" "--otel --otel-retries=" \+ "--otel-insecure" "--tenant-id=tenant-uuid-1234" \+ "--s3-uri=s3://bucket" "--otel-endpoint=http://127.0.0.1:1" \+ "--otel" "--otel --otel" "--otel --otel-endpoint=" \+ "--otel --tenant-id=bad/tenant" \+ "--otel --tenant-id=one --tenant-id=two" \+ "--otel=s3" "--all unexpected"; do+ rc=0+ "$S" upatch map $args >/dev/null 2>&1 || rc=$?+ [ "$rc" = 2 ] || {+ echo "upatch map $args: exit $rc"+ return 1+ }+ done'-test_expect_success 'explicit OTEL modes and JSON combination reach map read' '- "$S" upatch map missing values \- --json=combined.ndjson --otel=log \+test_expect_success 'a map that cannot be read fails before any export or JSON line' '+ rc=0+ "$S" upatch map missing values --json=combined.ndjson --otel \--tenant-id=tenant-uuid-1234 \- --otel-endpoint=http://127.0.0.1:4318 >/dev/null 2>&1;- test $? -eq 1 && test ! -e combined.ndjson &&- "$S" upatch map missing values --otel=s3 \- --s3-uri=s3://test-bucket/prefix >/dev/null 2>&1;- test $? -eq 1+ --otel-endpoint=http://127.0.0.1:1 >/dev/null 2>&1 || rc=$?+ [ "$rc" = 1 ] && [ ! -e combined.ndjson ] || return 1+ rc=0+ "$S" upatch map missing values --otel \+ --s3-uri=s3://test-bucket/prefix >/dev/null 2>&1 || rc=$?+ [ "$rc" = 1 ]'test_expect_success 'automatic OTLP signal classification is structural' '@@ -64,25 +63,35 @@ assert entry["sum"] == "12"test_expect_success 'structured OTLP log preserves aligned per-CPU values' '"$H" log | python3 -c '\''-import json,sys+import json,socket,sysd=json.load(sys.stdin)assert set(d) == {"resourceLogs"}rl=d["resourceLogs"][0]assert set(rl) == {"resource", "scopeLogs"}resource={x["key"]:x["value"] for x in rl["resource"]["attributes"]}-assert set(resource) == {"service.name", "service.version", "host.name"}-assert resource["service.name"]["stringValue"] == "shirudo"+assert resource == {"service.name": {"stringValue": "shirudo"},+ "service.version": {"stringValue": "test-1"},+ "host.name": {"stringValue": socket.gethostname()}}, resourcesl=rl["scopeLogs"][0]assert set(sl) == {"scope", "logRecords"}-assert sl["scope"]["name"] == "shirudo.upatch.maps"-assert set(sl["scope"]) == {"name", "version"}+assert sl["scope"] == {"name": "shirudo.upatch.maps", "version": "test-1"}r=sl["logRecords"][0]assert set(r) == {"timeUnixNano", "observedTimeUnixNano", "severityNumber", "severityText", "eventName", "body", "attributes"}assert r["timeUnixNano"].isdigit() and r["observedTimeUnixNano"].isdigit()assert r["severityNumber"] == 9 and r["severityText"] == "INFO"assert r["eventName"] == "shirudo.bpf.map.snapshot"attrs={x["key"]:x["value"] for x in r["attributes"]}-assert set(attrs) == {"shirudo.upatch.name", "shirudo.upatch.location", "shirudo.map.name", "shirudo.map.type", "shirudo.map.max_entries", "shirudo.map.n_entries", "shirudo.map.n_cpus", "shirudo.map.serialized", "shirudo.map.truncated"}+assert attrs == {+ "shirudo.upatch.name": {"stringValue": "test-upatch"},+ "shirudo.upatch.location": {"stringValue": "fentry/test_hook"},+ "shirudo.map.name": {"stringValue": "hits_total"},+ "shirudo.map.type": {"stringValue": "percpu_array"},+ "shirudo.map.max_entries": {"intValue": "1"},+ "shirudo.map.n_entries": {"intValue": "1"},+ "shirudo.map.n_cpus": {"intValue": "2"},+ "shirudo.map.serialized": {"boolValue": False},+ "shirudo.map.truncated": {"boolValue": False},+}, attrsvals=r["body"]["kvlistValue"]["values"]root={x["key"]:x["value"] for x in vals}data={x["key"]:x["value"] for x in root["data"]["kvlistValue"]["values"]}@@ -90,10 +99,6 @@ entry=data["entries"]["arrayValue"]["values"][0]["kvlistValue"]["values"]entry={x["key"]:x["value"] for x in entry}assert [x["stringValue"] for x in entry["values_per_cpu"]["arrayValue"]["values"]] == ["5", "7"]assert entry["sum"]["stringValue"] == "12"-attrs={x["key"]:x["value"] for x in r["attributes"]}-assert attrs["shirudo.upatch.name"]["stringValue"] == "test-upatch"-assert attrs["shirudo.upatch.location"]["stringValue"] == "fentry/test_hook"-assert attrs["shirudo.map.name"]["stringValue"] == "hits_total"'\'''@@ -109,9 +114,21 @@ assert attrs["shirudo.upatch.location"]["stringValue"] == ""test_expect_success 'OTLP metric emits one aggregated gauge point' '"$H" metric | python3 -c '\''-import json,sys+import json,socket,sysd=json.load(sys.stdin)-m=d["resourceMetrics"][0]["scopeMetrics"][0]["metrics"][0]+assert set(d) == {"resourceMetrics"}+rm=d["resourceMetrics"][0]+assert set(rm) == {"resource", "scopeMetrics"}+resource={x["key"]:x["value"] for x in rm["resource"]["attributes"]}+assert resource == {"service.name": {"stringValue": "shirudo"},+ "service.version": {"stringValue": "test-1"},+ "host.name": {"stringValue": socket.gethostname()}}, resource+sm=rm["scopeMetrics"][0]+assert set(sm) == {"scope", "metrics"}+assert sm["scope"] == {"name": "shirudo.upatch.maps", "version": "test-1"}+assert len(sm["metrics"]) == 1+m=sm["metrics"][0]+assert m["unit"] == "1"assert m["name"] == "shirudo.test.hits"p=m["gauge"]["dataPoints"][0]assert p["asInt"] == "12"@@ -401,12 +418,27 @@ record=log["resourceLogs"][0]["scopeLogs"][0]["logRecords"][0]assert record["eventName"] == "shirudo.bpf.map.snapshot.reference"assert set(record["body"]) == {"stringValue"}attrs={x["key"]:x["value"] for x in record["attributes"]}-assert attrs["shirudo.upatch.name"]["stringValue"] == "test-upatch"-assert attrs["shirudo.upatch.location"]["stringValue"] == "fentry/test_hook"-assert attrs["shirudo.map.name"]["stringValue"] == "hits_total"-uri=attrs["shirudo.map.snapshot.uri"]["stringValue"]+uri=attrs.pop("shirudo.map.snapshot.uri")["stringValue"]assert uri.startswith("s3://test-bucket/prefix/") and uri.endswith(digest+".json.gz")-assert attrs["shirudo.map.snapshot.sha256"]["stringValue"] == digest+assert record["body"]["stringValue"] == "BPF map snapshot stored in S3: " + uri+assert attrs == {+ "shirudo.upatch.name": {"stringValue": "test-upatch"},+ "shirudo.upatch.location": {"stringValue": "fentry/test_hook"},+ "shirudo.map.name": {"stringValue": "hits_total"},+ "shirudo.map.type": {"stringValue": "percpu_array"},+ "shirudo.map.max_entries": {"intValue": "1"},+ "shirudo.map.n_entries": {"intValue": "1"},+ "shirudo.map.n_cpus": {"intValue": "2"},+ "shirudo.map.serialized": {"boolValue": False},+ "shirudo.map.truncated": {"boolValue": False},+ "shirudo.map.snapshot.format": {"stringValue": "shirudo.map.v1+json"},+ "shirudo.map.snapshot.content_type": {"stringValue": "application/json"},+ "shirudo.map.snapshot.content_encoding": {"stringValue": "gzip"},+ "shirudo.map.snapshot.size_bytes": {"intValue": str(len(raw))},+ "shirudo.map.snapshot.uncompressed_size_bytes":+ {"intValue": str(len(gzip.decompress(raw)))},+ "shirudo.map.snapshot.sha256": {"stringValue": digest},+}, attrsassert len(open("s3.log","rb").read()) < 16384'\'''diff --git a/testing/functional/otel/t8004-status-otel.sh b/testing/functional/otel/t8004-status-otel.shindex 9279e055..4dc4fbc7 100644--- a/testing/functional/otel/t8004-status-otel.sh+++ b/testing/functional/otel/t8004-status-otel.sh@@ -72,9 +72,16 @@ test_expect_success 'keepalive status severities and structured body are determi"$H" send-status "http://127.0.0.1:$port" "$status" &&wait "$server" &&python3 - "$status" "$work/body" <<'\''PY'\'' || return 1-import json, sys+import json, socket, sysstatus = sys.argv[1]-record = json.load(open(sys.argv[2]))["resourceLogs"][0]["scopeLogs"][0]["logRecords"][0]+rl = json.load(open(sys.argv[2]))["resourceLogs"][0]+resource = {item["key"]: item["value"] for item in rl["resource"]["attributes"]}+assert resource == {"service.name": {"stringValue": "shirudo"},+ "service.version": {"stringValue": "test-1"},+ "host.name": {"stringValue": socket.gethostname()}}, resource+assert rl["scopeLogs"][0]["scope"] == {"name": "shirudo.keepalive",+ "version": "test-1"}+record = rl["scopeLogs"][0]["logRecords"][0]expected = {"ok": (9, "INFO"), "degraded": (13, "WARN"),"init-pending": (13, "WARN"), "reboot-pending": (13, "WARN"),"lsm-off": (17, "ERROR"),@@ -85,8 +92,9 @@ body = {item["key"]: item["value"] for item in record["body"]["kvlistValue"]["vaassert body["status"]["stringValue"] == statusassert body["schema"]["intValue"] == "1"attrs = {item["key"]: item["value"] for item in record["attributes"]}-assert attrs["shirudo.status"]["stringValue"] == status-assert attrs["shirudo.tamper_attempts"]["intValue"] == "2"+assert attrs == {"shirudo.status": {"stringValue": status},+ "shirudo.version_id": {"stringValue": "test-version"},+ "shirudo.tamper_attempts": {"intValue": "2"}}, attrsPYrm -f "$work/port" "$work/body" "$work/meta" || return 1donediff --git a/testing/functional/otel/t8006-otel-transport.sh b/testing/functional/otel/t8006-otel-transport.shnew file mode 100644index 00000000..3a536e88--- /dev/null+++ b/testing/functional/otel/t8006-otel-transport.sh@@ -0,0 +1,199 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# t8006 -- where an OTLP export goes and how, as the environment says: the+# endpoint, header, protocol, compression and timeout variables, a+# signal-specific one over the generic one, an empty one as unset, and the+# default; what is refused before any request is sent; and the bound on a+# collector's response. TLS material is t8105's, on the target, where a+# collector can offer the hybrid ML-KEM groups.++cd "$(dirname "$0")/../.."+. ./test-lib.sh++H=$PWD/helper/test-otel-map+M=$PWD/helper+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"+[ -x "$H" ] || test_skip_all "test-otel-map helper not built"+for v in $(env | sed -n 's/^\(OTEL_EXPORTER_OTLP_[A-Z_]*\)=.*/\1/p'); do+ unset "$v"+done+W=$(mktemp -d) || exit 1+trap 'rm -rf "$W"' EXIT+cd "$W" || exit 1++# Start the OTLP mock in mode $1; it listens on $port as $server.+mock() {+ rm -f otel.port otel.body otel.meta+ python3 "$M/otel-mock.py" "$1" otel.port otel.body otel.meta &+ server=$!+ i=0+ while [ ! -s otel.port ] && [ "$i" -lt 100 ]; do+ i=$((i + 1))+ sleep .02+ done+ port=$(cat otel.port)+}++# The field $1 of the request the mock saw, headers.<name> for a header.+meta() {+ python3 -c '+import json, sys+value = json.load(open("otel.meta"))+for part in sys.argv[1].split(".", 1):+ value = value.get(part, "") if isinstance(value, dict) else ""+print(value)' "$1"+}++# A log export with the environment assignments $@ fails, and the mock+# it would have reached saw no request.+refused() {+ mock success+ rc=0+ env OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:$port" "$@" \+ "$H" send-log-env 0 2>/dev/null || rc=$?+ kill "$server" 2>/dev/null || true+ wait "$server" 2>/dev/null || true+ [ "$rc" != 0 ] && [ ! -e otel.meta ] || {+ echo "not refused: $*"+ return 1+ }+}++test_expect_success 'the generic endpoint gets the signal path, a signal one is used as given' '+ mock success &&+ OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:$port/base?fleet=eu" \+ "$H" send-log-env 0 && wait "$server" &&+ [ "$(meta path)" = "/base/v1/logs?fleet=eu" ] &&+ mock success &&+ OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:$port/base/" \+ "$H" send-metric-env && wait "$server" &&+ [ "$(meta path)" = /base/v1/metrics ] &&+ mock success &&+ OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:1/generic \+ OTEL_EXPORTER_OTLP_LOGS_ENDPOINT="http://127.0.0.1:$port/ingest" \+ "$H" send-log-env 0 && wait "$server" &&+ [ "$(meta path)" = /ingest ] &&+ mock success &&+ OTEL_EXPORTER_OTLP_METRICS_ENDPOINT="http://127.0.0.1:$port/ingest/m" \+ "$H" send-metric-env && wait "$server" &&+ [ "$(meta path)" = /ingest/m ]+'++test_expect_success 'an empty variable is unset, and one signal leaves the other alone' '+ mock success &&+ OTEL_EXPORTER_OTLP_LOGS_ENDPOINT= \+ OTEL_EXPORTER_OTLP_LOGS_HEADERS= OTEL_EXPORTER_OTLP_HEADERS=X-Fleet=eu \+ OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:$port" \+ "$H" send-log-env 0 && wait "$server" &&+ [ "$(meta path)" = /v1/logs ] && [ "$(meta headers.x-fleet)" = eu ] &&+ mock success &&+ OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=http://127.0.0.1:1/v1/logs \+ OTEL_EXPORTER_OTLP_LOGS_HEADERS=X-Logs=1 \+ OTEL_EXPORTER_OTLP_LOGS_COMPRESSION=gzip \+ OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:$port" \+ "$H" send-metric-env && wait "$server" &&+ [ "$(meta path)" = /v1/metrics ] &&+ [ -z "$(meta headers.x-logs)" ] && [ -z "$(meta content_encoding)" ]+'++if python3 -c 'import socket; socket.socket().bind(("127.0.0.1", 4318))' 2>/dev/null; then+ test_expect_success 'without any endpoint the export goes to localhost:4318' '+ export SHIRUDO_TEST_OTEL_PORT=4318 &&+ mock success &&+ "$H" send-log-env 0 && wait "$server" &&+ [ "$(meta path)" = /v1/logs ] &&+ [ "$(meta headers.host)" = localhost:4318 ]+ '+else+ echo "# SKIP port 4318 is taken, the default endpoint is not tried"+fi++test_expect_success 'signal headers replace the generic ones, trimmed and decoded' '+ mock success &&+ OTEL_EXPORTER_OTLP_HEADERS="X-Generic=1,Authorization=Bearer%20generic" \+ OTEL_EXPORTER_OTLP_LOGS_HEADERS=" X-Signal = a%2Cb,Authorization=Bearer%20specific" \+ OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:$port" \+ "$H" send-log-env 0 && wait "$server" &&+ [ "$(meta headers.x-signal)" = "a,b" ] &&+ [ "$(meta headers.authorization)" = "Bearer specific" ] &&+ [ -z "$(meta headers.x-generic)" ] &&+ [ "$(meta headers.content-type)" = application/json ] &&+ [ "$(meta headers.user-agent)" = "Shirudo OTel-OTLP-Exporter-C/1" ]+'++test_expect_success 'malformed, reserved and oversized headers are refused before any request' '+ for h in X-No-Value =value X:Colon=v X-Bad=%zz X-Bad=%4 X-Bad=a%0Db \+ Content-Type=text/plain Content-Encoding=br Content-Length=1 \+ Host=collector User-Agent=other; do+ refused OTEL_EXPORTER_OTLP_LOGS_HEADERS="$h" || return 1+ done &&+ pad=$(python3 -c "print(\"x\" * (16384 - len(\"X-Big=\")))") &&+ refused OTEL_EXPORTER_OTLP_HEADERS="X-Big=${pad}x" &&+ mock success &&+ OTEL_EXPORTER_OTLP_HEADERS="X-Big=$pad" \+ OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:$port" \+ "$H" send-log-env 0 && wait "$server" &&+ [ "$(meta headers.x-big)" = "$pad" ]+'++test_expect_success 'only http/json is spoken' '+ refused OTEL_EXPORTER_OTLP_PROTOCOL=grpc &&+ refused OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf &&+ refused OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=grpc \+ OTEL_EXPORTER_OTLP_PROTOCOL=http/json &&+ mock success &&+ OTEL_EXPORTER_OTLP_PROTOCOL=http/json \+ OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:$port" \+ "$H" send-log-env 0 && wait "$server"+'++test_expect_success 'compression is gzip or none, the signal one first' '+ refused OTEL_EXPORTER_OTLP_COMPRESSION=br &&+ refused OTEL_EXPORTER_OTLP_LOGS_COMPRESSION=deflate &&+ mock success &&+ OTEL_EXPORTER_OTLP_COMPRESSION=gzip \+ OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:$port" \+ "$H" send-log-env 0 && wait "$server" &&+ [ "$(meta content_encoding)" = gzip ] &&+ mock success &&+ OTEL_EXPORTER_OTLP_COMPRESSION=gzip OTEL_EXPORTER_OTLP_LOGS_COMPRESSION=none \+ OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:$port" \+ "$H" send-log-env 0 && wait "$server" &&+ [ -z "$(meta content_encoding)" ]+'++test_expect_success 'an attempt timeout is 1 to 120000 ms, the signal one first' '+ for t in 0 120001 -1 10s " 5"; do+ refused OTEL_EXPORTER_OTLP_TIMEOUT="$t" || return 1+ done &&+ refused OTEL_EXPORTER_OTLP_LOGS_TIMEOUT=0 OTEL_EXPORTER_OTLP_TIMEOUT=5000 &&+ mock success &&+ OTEL_EXPORTER_OTLP_TIMEOUT=120000 \+ OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:$port" \+ "$H" send-log-env 0 && wait "$server" &&+ mock timeout &&+ OTEL_EXPORTER_OTLP_TIMEOUT=100 OTEL_EXPORTER_OTLP_LOGS_TIMEOUT=5000 \+ OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:$port" \+ "$H" send-log-env 0 && wait "$server" &&+ mock timeout &&+ ! OTEL_EXPORTER_OTLP_TIMEOUT=5000 OTEL_EXPORTER_OTLP_LOGS_TIMEOUT=100 \+ OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:$port" \+ "$H" send-log-env 0 2>/dev/null && wait "$server"+'++test_expect_success 'a client certificate needs its key, and the key its certificate' '+ refused OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE=client.pem &&+ refused OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY=client.key+'++test_expect_success 'a collector response is read up to 64 KiB less one byte' '+ mock big-ok &&+ "$H" send-log "http://127.0.0.1:$port" 2 && wait "$server" &&+ mock big-over &&+ ! "$H" send-log "http://127.0.0.1:$port" 2 2>/dev/null && wait "$server" &&+ [ "$(meta attempts)" = 1 ]+'++test_donediff --git a/testing/functional/otel/t8104-export-config.sh b/testing/functional/otel/t8104-export-config.shnew file mode 100644index 00000000..cb70e49b--- /dev/null+++ b/testing/functional/otel/t8104-export-config.sh@@ -0,0 +1,172 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# t8104 -- what the signed config sets for `upatch map --all` and what+# overrides it: map_export.otel_endpoint and map_export.tenant_id win+# over the OTEL_EXPORTER_OTLP_* variables, and --otel-endpoint and+# --tenant-id over them. An export that fails, the collector down, fails+# that run of the map-export service, the timer runs it again, and the+# interval the failed run drained is not sent again: the next one holds+# only what was collected since. The serialized-metric fixture counts 10+# packets once after a load.++cd "$(dirname "$0")/../.."+. ./integration-lib.sh+target_guard+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"+command -v systemctl >/dev/null 2>&1 || test_skip_all "no systemctl"+FIXTURES=${SHIRUDO_TEST_FIXTURES_DIR:?target fixture directory is not set}+NAME=shirudo-test-serialized-metric+LOAD="$FIXTURES/$NAME.upatch"+UNLOAD="$FIXTURES/$NAME.unload.upatch"+PIN="/run/shirudo/bpffs/upatches/$NAME"+CONFIG_PORT=5444+W=$(mktemp -d)+[ -s "$LOAD" ] && [ -s "$UNLOAD" ] || test_skip_all "missing serialized metric fixture"+[ ! -e "$PIN" ] || test_skip_all "$NAME is loaded"+systemctl cat shirudo-map-export.timer >/dev/null 2>&1 ||+ test_skip_all "map-export timer is not installed"+"$SHIRUDO_BIN" image update "$SHIRUDO_TEST_KEY_FIXTURES/config-otel" \+ >/dev/null 2>&1 || test_skip_all "cannot activate the config-otel image"++# The sinks, started in the subshells the test bodies run in, by their+# pid files.+stop_sinks() {+ for p in "$W"/*.pid; do+ [ -e "$p" ] || continue+ kill "$(cat "$p")" 2>/dev/null || true+ rm -f "$p"+ done+}++# Under the library's errexit a failing step would end the cleanup.+cleanup() {+ systemctl stop shirudo-map-export.timer >/dev/null 2>&1 || true+ systemctl stop shirudo-map-export.service >/dev/null 2>&1 || true+ systemctl reset-failed shirudo-map-export.service >/dev/null 2>&1 || true+ stop_sinks+ if [ -e "$PIN" ]; then+ "$SHIRUDO_BIN" upatch unload "$UNLOAD" --no-precheck \+ >/dev/null 2>&1 || true+ fi+ if [ "$TIMER_WAS_ACTIVE" = 1 ]; then+ systemctl start shirudo-map-export.timer >/dev/null 2>&1 || true+ fi+ rm -rf "$W"+}+TIMER_WAS_ACTIVE=0+systemctl is-active --quiet shirudo-map-export.timer && TIMER_WAS_ACTIVE=1+trap cleanup EXIT+systemctl stop shirudo-map-export.timer >/dev/null 2>&1 || true+systemctl stop shirudo-map-export.service >/dev/null 2>&1 || true++cat >"$W/sink.py" <<'PY'+import http.server, json, pathlib, sys+port, port_file, out = int(sys.argv[1]), *map(pathlib.Path, sys.argv[2:4])+requests = []+class Handler(http.server.BaseHTTPRequestHandler):+ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))+ requests.append({"path": self.path,+ "tenant": self.headers.get("X-Tenant-ID", ""),+ "body": body})+ out.write_text(json.dumps(requests))+ payload = b"{}"+ self.send_response(200)+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+ def log_message(self, *args): pass+server = http.server.HTTPServer(("127.0.0.1", port), Handler)+port_file.write_text(str(server.server_port))+server.serve_forever()+PY++# Start a sink on port $1 (0 for any) recording into $W/$2.json; the port+# it got is in $W/$2.port.+sink() {+ rm -f "$W/$2.port" "$W/$2.json"+ python3 "$W/sink.py" "$1" "$W/$2.port" "$W/$2.json" &+ echo "$!" >"$W/$2.pid"+ i=0+ while [ ! -s "$W/$2.port" ] && [ "$i" -lt 100 ]; do+ i=$((i + 1))+ sleep .05+ done+ [ -s "$W/$2.port" ]+}++# The requests sink $1 recorded: their paths and tenants, and the packet+# counts of the serialized metric they carry, one line per request.+seen() {+ python3 - "$W/$1.json" <<'PY'+import json, os, sys+if not os.path.exists(sys.argv[1]):+ sys.exit(0)+for r in json.load(open(sys.argv[1])):+ packets = ""+ for rm in r["body"].get("resourceMetrics", []):+ for sm in rm["scopeMetrics"]:+ for m in sm["metrics"]:+ if m["name"] == "shirudo.serialized.packets":+ packets = m["sum"]["dataPoints"][0]["asInt"]+ print(r["path"], r["tenant"], packets)+PY+}++test_expect_success 'the config names the endpoint and tenant, over the environment' '+ sink "$CONFIG_PORT" config && sink 0 env &&+ env_url="http://127.0.0.1:$(cat "$W/env.port")" &&+ "$SHIRUDO_BIN" upatch load "$LOAD" --no-precheck >/dev/null 2>&1 &&+ OTEL_EXPORTER_OTLP_ENDPOINT="$env_url" \+ OTEL_EXPORTER_OTLP_LOGS_ENDPOINT="$env_url/v1/logs" \+ OTEL_EXPORTER_OTLP_METRICS_ENDPOINT="$env_url/v1/metrics" \+ OTEL_EXPORTER_OTLP_HEADERS=X-Tenant-ID=tenant-env-1111 \+ "$SHIRUDO_BIN" upatch map --all >/dev/null &&+ seen config >"$W/config.seen" && seen env >"$W/env.seen" &&+ grep -qx "/v1/metrics tenant-config-0000 10" "$W/config.seen" &&+ grep -q "^/v1/logs tenant-config-0000" "$W/config.seen" &&+ [ "$(grep -vc " tenant-config-0000" "$W/config.seen")" = 0 ] &&+ [ ! -s "$W/env.seen" ]+'++test_expect_success 'the command line wins over the config' '+ sink 0 cli &&+ cli_url="http://127.0.0.1:$(cat "$W/cli.port")" &&+ "$SHIRUDO_BIN" upatch map --all --otel-endpoint="$cli_url" \+ --tenant-id=tenant-cli-2222 >/dev/null &&+ seen cli >"$W/cli.seen" && seen config >"$W/config.seen2" &&+ grep -qx "/v1/metrics tenant-cli-2222 0" "$W/cli.seen" &&+ grep -q "^/v1/logs tenant-cli-2222" "$W/cli.seen" &&+ [ "$(grep -vc " tenant-cli-2222" "$W/cli.seen")" = 0 ] &&+ cmp -s "$W/config.seen" "$W/config.seen2"+'++stop_sinks++test_expect_success 'with the collector down, a run of the service fails' '+ "$SHIRUDO_BIN" upatch unload "$UNLOAD" --no-precheck >/dev/null 2>&1 &&+ "$SHIRUDO_BIN" upatch load "$LOAD" --no-precheck >/dev/null 2>&1 &&+ ! systemctl start shirudo-map-export.service 2>/dev/null &&+ [ "$(systemctl show -p Result --value shirudo-map-export.service)" = exit-code ]+'++test_expect_success 'the timer runs it again, without the interval the failed run drained' '+ sink "$CONFIG_PORT" timer &&+ systemctl start shirudo-map-export.timer &&+ i=0 &&+ until grep -q "^/v1/metrics " "$W/timer.seen" 2>/dev/null; do+ i=$((i + 1))+ [ "$i" -lt 60 ] || return 1+ sleep .5+ seen timer >"$W/timer.seen"+ done &&+ systemctl stop shirudo-map-export.timer &&+ grep -qx "/v1/metrics tenant-config-0000 0" "$W/timer.seen" || {+ cat "$W/timer.seen"+ false+ }+'++test_donediff --git a/testing/functional/otel/t8105-export-tls.sh b/testing/functional/otel/t8105-export-tls.shnew file mode 100644index 00000000..6069ea39--- /dev/null+++ b/testing/functional/otel/t8105-export-tls.sh@@ -0,0 +1,184 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# t8105 -- the TLS material of an export: the CA bundle a collector is+# verified with and the client certificate it gets, each the signal+# variable over the generic one, and S3 trusting AWS_CA_BUNDLE, never the+# collector's CA, nor the collector AWS_CA_BUNDLE. The collectors are the+# mocks behind a throwaway CA on the target, whose Python offers the+# hybrid ML-KEM groups the exporter requires; the exporter is+# test-otel-map's.++cd "$(dirname "$0")/../.."+. ./integration-lib.sh+target_guard+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"+command -v openssl >/dev/null 2>&1 || test_skip_all "no openssl"+python3 -c 'import ssl, sys; sys.exit(ssl.OPENSSL_VERSION_INFO < (3, 5))' ||+ test_skip_all "python3 cannot offer a hybrid ML-KEM group"+H=$PWD/helper/test-otel-map+M=$PWD/helper+[ -x "$H" ] || test_skip_all "test-otel-map helper not built"+for v in $(env | sed -n 's/^\(OTEL_EXPORTER_OTLP_[A-Z_]*\|AWS_[A-Z_0-9]*\)=.*/\1/p'); do+ unset "$v"+done+W=$(mktemp -d)+# A mock a failed test body left running, by its pid file.+cleanup() {+ [ ! -s "$W/m.pid" ] || kill "$(cat "$W/m.pid")" 2>/dev/null || true+ rm -rf "$W"+}+trap cleanup EXIT+cd "$W"++# A CA, the collector's certificate and two client certificates it+# issued, and a second CA that issued nothing here.+ca() {+ openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \+ -keyout "$1.key" -out "$1.pem" -days 1 -subj "/CN=$1" 2>/dev/null+}+issue() {+ openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \+ -keyout "$1.key" -out "$1.csr" -subj "/CN=$1" 2>/dev/null &&+ printf '%s\n' "$2" >"$1.ext" &&+ openssl x509 -req -in "$1.csr" -CA ca.pem -CAkey ca.key \+ -CAcreateserial -out "$1.pem" -days 1 -extfile "$1.ext" 2>/dev/null+}+ca ca && ca other &&+ issue collector 'subjectAltName=IP:127.0.0.1' &&+ issue client-a 'extendedKeyUsage=clientAuth' &&+ issue client-b 'extendedKeyUsage=clientAuth' ||+ test_skip_all "openssl could not make the test certificates"++# Start mock $1 (otel or s3) in mode $2 with the TLS arguments to follow;+# it listens on $port.+mock() {+ kind=$1 mode=$2+ shift 2+ rm -f m.port m.body m.meta m.snapshot m.log+ if [ "$kind" = s3 ]; then+ python3 "$M/otel-s3-mock.py" "$mode" m.port m.snapshot m.log \+ m.meta "$@" &+ else+ python3 "$M/otel-mock.py" "$mode" m.port m.body m.meta "$@" &+ fi+ SERVER=$!+ echo "$SERVER" >m.pid+ i=0+ while [ ! -s m.port ] && [ "$i" -lt 100 ]; do+ i=$((i + 1))+ sleep .05+ done+ port=$(cat m.port)+}++# Wait for the mock to finish its exchange.+finished() {+ rc=0+ wait "$SERVER" || rc=$?+ rm -f m.pid+ return "$rc"+}++# Stop the mock, which must have seen no request when $1 is "none".+stop() {+ kill "$SERVER" 2>/dev/null || true+ wait "$SERVER" 2>/dev/null || true+ rm -f m.pid+ [ "${1:-}" != none ] || [ ! -e m.meta ]+}++field() {+ python3 -c '+import json, sys+print(json.load(open("m.meta")).get(sys.argv[1], ""))' "$1"+}++# A log export to the mock on $port, with the assignments $@.+send() {+ env OTEL_EXPORTER_OTLP_ENDPOINT="https://127.0.0.1:$port" "$@" \+ "$H" send-log-env 0 2>/dev/null+}++test_expect_success 'the signal CA wins over the generic one' '+ mock otel success collector.pem collector.key &&+ send OTEL_EXPORTER_OTLP_CERTIFICATE="$W/other.pem" \+ OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE="$W/ca.pem" &&+ finished &&+ mock otel success collector.pem collector.key &&+ ! send OTEL_EXPORTER_OTLP_CERTIFICATE="$W/ca.pem" \+ OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE="$W/other.pem" &&+ stop none+'++test_expect_success 'the generic CA serves without a signal one, the system store without either' '+ mock otel success collector.pem collector.key &&+ send OTEL_EXPORTER_OTLP_CERTIFICATE="$W/ca.pem" &&+ finished &&+ mock otel success collector.pem collector.key &&+ ! send &&+ stop none+'++test_expect_success 'a collector that asks for a client certificate gets the signal one' '+ mock otel success collector.pem collector.key ca.pem &&+ send OTEL_EXPORTER_OTLP_CERTIFICATE="$W/ca.pem" \+ OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE="$W/client-b.pem" \+ OTEL_EXPORTER_OTLP_CLIENT_KEY="$W/client-b.key" \+ OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE="$W/client-a.pem" \+ OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY="$W/client-a.key" &&+ finished &&+ [ "$(field client)" = client-a ] &&+ mock otel success collector.pem collector.key ca.pem &&+ send OTEL_EXPORTER_OTLP_CERTIFICATE="$W/ca.pem" \+ OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE="$W/client-b.pem" \+ OTEL_EXPORTER_OTLP_CLIENT_KEY="$W/client-b.key" &&+ finished &&+ [ "$(field client)" = client-b ]+'++test_expect_success 'and without one gets nothing through' '+ mock otel success collector.pem collector.key ca.pem &&+ ! send OTEL_EXPORTER_OTLP_CERTIFICATE="$W/ca.pem" &&+ stop none+'++# An S3 export to the mock on $port, the collector at the same place,+# with the assignments $@.+s3() {+ env AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=secret \+ AWS_REGION=us-east-1 \+ OTEL_EXPORTER_OTLP_LOGS_ENDPOINT="https://127.0.0.1:$port/v1/logs" \+ "$@" "$H" send-s3 "https://127.0.0.1:$port" 0 2>/dev/null+}++methods() {+ python3 -c '+import json, os+if os.path.exists("m.meta"):+ print(" ".join(r["method"] for r in json.load(open("m.meta"))["requests"]))'+}++test_expect_success 'S3 is verified with AWS_CA_BUNDLE, the collector with its own CA' '+ mock s3 success collector.pem collector.key &&+ s3 AWS_CA_BUNDLE="$W/ca.pem" \+ OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE="$W/ca.pem" &&+ finished &&+ [ "$(methods)" = "PUT POST" ] && [ -s m.snapshot ] && [ -s m.log ]+'++test_expect_success 'the collector CA does not verify S3' '+ mock s3 success collector.pem collector.key &&+ ! s3 OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE="$W/ca.pem" &&+ stop none+'++test_expect_success 'nor AWS_CA_BUNDLE the collector' '+ mock s3 success collector.pem collector.key &&+ ! s3 AWS_CA_BUNDLE="$W/ca.pem" &&+ stop &&+ [ "$(methods)" = PUT ] && [ -s m.snapshot ] && [ ! -e m.log ]+'++test_donediff --git a/testing/helper/otel-mock.py b/testing/helper/otel-mock.pyindex a59197f5..49fac8e1 100644--- a/testing/helper/otel-mock.py+++ b/testing/helper/otel-mock.py@@ -3,8 +3,8 @@# Copyright (c) 2026 Authors of shirudo"""OTLP/HTTP sink for the exporter tests.-usage: otel-mock.py <success|retry|partial> <port-file> <body-file>- <meta-file> [<cert.pem> <key.pem>]+usage: otel-mock.py <success|retry|partial|...> <port-file> <body-file>+ <meta-file> [<cert.pem> <key.pem> [<client-ca.pem>]]Listens on an ephemeral loopback port (written to <port-file> oncebound), serves until the exchange the mode describes is complete, then@@ -14,11 +14,15 @@ exits 0 so a test can `wait` for it:retry the first two requests fail with 503, the third succeedspartial the first request gets 200 with a partialSuccess body, whichthe exporter must treat as a non-retryable failure+ big-ok the first request gets 200 with a 65535-byte JSON body+ big-over the first request gets 200 with a 65536-byte JSON bodyThe last request body (gzip-decoded when announced) is written as JSON-to <body-file>; <meta-file> records the attempt count, the request path-and, when sent, the Authorization and Content-Encoding headers. With a-certificate and key the sink speaks HTTPS.+to <body-file>; <meta-file> records the attempt count, the request path,+every request header and, when sent, the Authorization and+Content-Encoding headers. With a certificate and key the sink speaks+HTTPS; with a client CA too it requires a client certificate that CA+issued and records its common name."""import gzip@@ -32,7 +36,7 @@ import timemode, port_file, body_file, meta_file = sys.argv[1:5]-tls = sys.argv[5:7]+tls = sys.argv[5:8]attempts = 0meta = {}request_times = []@@ -65,7 +69,12 @@ class Handler(http.server.BaseHTTPRequestHandler):if self.headers.get("Content-Encoding", "").lower() == "gzip":raw = gzip.decompress(raw)meta = {"attempts": attempts, "path": self.path,- "raw_bytes": len(raw)}+ "raw_bytes": len(raw),+ "headers": {k.lower(): v for k, v in self.headers.items()}}+ if len(tls) == 3:+ subject = dict(item[0] for item in+ self.connection.getpeercert()["subject"])+ meta["client"] = subject.get("commonName", "")if len(request_times) > 1:meta["interval_ms"] = round((request_times[-1] - request_times[-2]) * 1000)@@ -115,6 +124,10 @@ class Handler(http.server.BaseHTTPRequestHandler):self.reply(200, {"partialSuccess": {"rejectedLogRecords": "0"}})elif mode == "malformed":self.reply(200, b"not-json")+ elif mode in {"big-ok", "big-over"}:+ size = 65535 if mode == "big-ok" else 65536+ pad = size - len(b'{"pad":""}')+ self.reply(200, b'{"pad":"' + b"x" * pad + b'"}')elif mode == "partial":self.reply(200, {"partialSuccess": {"rejectedLogRecords": 1,"errorMessage": "rejected by mock"}})@@ -128,6 +141,9 @@ server.done = Falseif tls:context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)context.load_cert_chain(tls[0], tls[1])+ if len(tls) == 3:+ context.verify_mode = ssl.CERT_REQUIRED+ context.load_verify_locations(tls[2])server.socket = context.wrap_socket(server.socket, server_side=True)pathlib.Path(port_file).write_text(f"{server.server_address[1]}\n")server.timeout = 0.25diff --git a/testing/helper/otel-s3-mock.py b/testing/helper/otel-s3-mock.pyindex 24e54838..ad326b54 100644--- a/testing/helper/otel-s3-mock.py+++ b/testing/helper/otel-s3-mock.py@@ -1,7 +1,13 @@#!/usr/bin/env python3# SPDX-License-Identifier: BSD-2-Clause# Copyright (c) 2026 Authors of shirudo-"""Combined S3 PUT and OTLP log sink used by t8001."""+"""Combined S3 PUT and OTLP log sink used by t8001 and t8105.++usage: otel-s3-mock.py <mode> <port-file> <snapshot-file> <log-file>+ <meta-file> [<cert.pem> <key.pem>]++With a certificate and key both sinks speak HTTPS.+"""import gzipimport hashlib@@ -9,11 +15,13 @@ import hmacimport http.serverimport jsonimport pathlib+import sslimport sysimport timemode, port_file, snapshot_file, log_file, meta_file = sys.argv[1:6]+tls = sys.argv[6:8]requests = []put_attempts = 0@@ -146,6 +154,10 @@ class Handler(http.server.BaseHTTPRequestHandler):server = http.server.HTTPServer(("127.0.0.1", 0), Handler)+if tls:+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)+ context.load_cert_chain(tls[0], tls[1])+ server.socket = context.wrap_socket(server.socket, server_side=True)server.timeout = 5server.done = Falsepathlib.Path(port_file).write_text(str(server.server_port))