ci: снимок конфигурации, runtime-drift и вычисление всех хостов

config-fingerprint.sh: снимок поведенчески значимых частей конфигурации
всех хостов (юниты и их unitConfig, порты и vhost'ы nginx, зона DNS,
пакеты, монтирования, контейнеры) — чтобы «функционал не изменился»
было измеримым, а не обещанием. Значения секретов в снимок не попадают.

runtime-drift.sh: сверка декларации с работающим хостом — nginx -T против
/etc/nginx/nginx.conf, podman inspect против -p в systemd-юните, и
наличие ConditionPathIsMountPoint у охраняемых юнитов. Ловит класс
«в nix всё правильно, в проде — нет» (инвариант 8, ADR-0003/0004).

evaluate-all-hosts.yml: workflow вручную вычисляет все семь конфигураций.
Раньше CI проверял только sapphira (раннер — сам сапфир), и поломки в
mobile.nix были невидимы.
This commit is contained in:
oqyude committed 2026-11-15 06:34:11 +03:00
1 parent 86b58fc576
commit 53df473609
3 files changed
+353

No files matched your search

+150
View File
@@ -0,0 +1,150 @@
#!/usr/bin/env bash
# Config fingerprint — behavioural snapshot of every host configuration.
#
# Why: a refactor that "does not change behaviour" is a claim, not a fact.
# This script turns the claim into a diff. It evaluates each host config and
# dumps the parts that carry behaviour — systemd unit names, firewall ports,
# nginx vhosts and their upstreams, CoreDNS zone contents, package sets,
# mounts, container images/ports — as JSON. Two revisions can then be
# compared byte for byte.
#
# Deliberately NOT included: secret values. `sops.secrets.*.path` is captured
# (names only), never the decrypted content, so the snapshot is safe to keep
# in a work directory and to diff on a laptop.
#
# Usage:
# .ci/verify/config-fingerprint.sh [out-dir] [hosts...]
#
# out-dir where to write <host>.json (default: ./fingerprint-<utc-ts>)
# hosts subset of host names (default: all NixOS configurations)
#
# Example:
# .ci/verify/config-fingerprint.sh /tmp/before
# # ... change something ...
# .ci/verify/config-fingerprint.sh /tmp/after
# diff -r /tmp/before /tmp/after && echo "no behavioural change"
#
# Exit code: 0 when every requested host evaluated, 1 otherwise.
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
cd "$REPO_ROOT"
OUT_DIR="${1:-./fingerprint-$(date -u +%Y%m%dT%H%M%SZ)}"
shift || true
if [ "$#" -gt 0 ]; then
HOSTS="$*"
else
# Attribute names of `nixosConfigurations` — `default` included: it is a real
# configuration (the minimal template), and a change there is a change to the
# template every new host starts from.
HOSTS=$(nix --extra-experimental-features "nix-command flakes" eval \
--raw '.#nixosConfigurations' --apply 'c: builtins.concatStringsSep " " (builtins.attrNames c)')
fi
mkdir -p "$OUT_DIR"
# The expression applied to `config`. Kept in one place so the snapshot shape
# cannot drift between hosts.
FINGERPRINT_EXPR='c: let
# Package sets come in two shapes: `home.packages` is an attribute set
# (home-manager), `users.users.<u>.packages` is a list (NixOS). Both are
# normalised to a sorted list of names. A derivation is named by its
# `name` attribute on purpose: `toString` would yield the store path, which
# differs between revisions even when the package set is identical.
pkgNames = v:
if builtins.isAttrs v then
builtins.attrNames v
else
map (x: if builtins.isAttrs x then (x.name or x.pname or "?") else toString x) v;
in {
hostname = c.networking.hostName;
systemdServices = builtins.attrNames c.systemd.services;
# Unit-level conditions of every service. This is where the storage guard
# lives (AGENTS.md invariant 2: `ConditionPathIsMountPoint` must land in
# the [Unit] section) and where a phantom unit would show up
# (ADR-0004: the attribute name must match the real unit).
systemdUnitConfig = builtins.mapAttrs (_: s: s.unitConfig or {}) c.systemd.services;
services = builtins.attrNames c.services;
sopsSecrets = builtins.attrNames c.sops.secrets;
firewall = {
allowedTCPPorts = c.networking.firewall.allowedTCPPorts;
allowedUDPPorts = c.networking.firewall.allowedUDPPorts;
interfaces = builtins.mapAttrs (_: v: {
allowedTCPPorts = v.allowedTCPPorts;
allowedUDPPorts = v.allowedUDPPorts;
}) c.networking.firewall.interfaces;
};
nginx = builtins.mapAttrs (_: v: {
listen = v.listen or [];
forceSSL = v.forceSSL or null;
enableACME = v.enableACME or null;
locations = builtins.mapAttrs (_: l: {
proxyPass = l.proxyPass or null;
proxyWebsockets = l.proxyWebsockets or null;
extraConfig = l.extraConfig or null;
}) v.locations;
}) c.services.nginx.virtualHosts;
coredns = c.services.coredns.config;
users = builtins.mapAttrs (_: u: {
packages = pkgNames (u.packages or {});
extraGroups = u.extraGroups or [];
}) c.users.users;
homeUsers = builtins.mapAttrs (_: u: {
packages = pkgNames (u.home.packages or {});
programs = builtins.attrNames (u.home.programs or {});
files = builtins.attrNames (u.home.file or {});
services = builtins.attrNames (u.home.services or {});
sessionVariables = builtins.attrNames (u.home.sessionVariables or {});
# systemd user units: ExecStart and Environment are the contract between
# the unit and the server behind it (ports, CORS, proxy settings).
systemdUserServices = builtins.mapAttrs (_: s: {
ExecStart = s.ExecStart or null;
Environment = s.Environment or null;
description = s.description or null;
}) ((u.systemd.user.services or {}) // {});
}) c.home-manager.users;
systemPackages = pkgNames c.environment.systemPackages;
nextcloudSettings = c.services.nextcloud.settings or null;
samba = {
enable = c.services.samba.enable;
workgroup = c.services.samba.workgroup or null;
domain = c.services.samba.domain or null;
};
fileSystems = builtins.mapAttrs (_: v: {
device = v.device;
fsType = v.fsType;
options = v.options or [];
}) c.fileSystems;
containers = builtins.mapAttrs (_: v: {
image = v.image;
ports = v.ports or [];
volumes = v.volumes or [];
environment = if (v.environment or null) == null then [] else if builtins.isAttrs v.environment then builtins.attrNames v.environment else v.environment;
}) c.virtualisation.oci-containers.containers;
sessionVariables = builtins.attrNames c.environment.sessionVariables;
boot = {
kernel = c.boot.kernelPackages.kernel.version;
};
}'
FAILED=0
for host in $HOSTS; do
echo "fingerprint: evaluating ${host} ..."
if nix --extra-experimental-features "nix-command flakes" eval \
--json ".#nixosConfigurations.${host}.config" \
--apply "$FINGERPRINT_EXPR" > "${OUT_DIR}/${host}.json" 2>"${OUT_DIR}/${host}.err"; then
echo " ok: ${OUT_DIR}/${host}.json"
else
echo " FAIL: ${host}" >&2
sed 's/^/ /' "${OUT_DIR}/${host}.err" >&2
FAILED=1
fi
done
if [ "$FAILED" -ne 0 ]; then
echo "fingerprint: some hosts failed to evaluate" >&2
exit 1
fi
echo "fingerprint: written to ${OUT_DIR}"
+151
View File
@@ -0,0 +1,151 @@
#!/usr/bin/env bash
# Runtime drift: what Nix declares vs what the host actually runs.
#
# The repo knows this failure mode well (AGENTS.md invariant 8, ADR-0003):
# a Nix change is a *declaration*. It changes the running system only after
# `nixos-rebuild switch` — and for containers it changes nothing at all until
# the container is recreated. A config that is correct on disk and wrong in
# production produces no error anywhere: the panel answers, the port is wrong,
# the logs are silent.
#
# This script closes that gap for a live host. It compares three pairs:
#
# 1. nginx — the rendered config (/etc/nginx/nginx.conf) vs the config
# nginx actually loaded (`nginx -T`). A vhost present in the
# file but absent from the running config means the rebuild
# happened and the reload did not.
# 2. podman — the ports declared in the rendered systemd unit vs the ports
# the running container actually publishes. This is the case
# that never recovers on its own (invariant 8).
# 3. systemd — every unit that the repo guards with
# `ConditionPathIsMountPoint` must actually carry that
# condition at runtime. A unit without it is a guard that
# silently does nothing (ADR-0004: the attribute name must
# match the real unit, or a phantom without ExecStart wins).
#
# Usage (on the host, as root):
# bash .ci/verify/runtime-drift.sh [--nginx] [--podman] [--systemd]
#
# Exit code: 0 when nothing drifted, 1 when at least one drift was found.
#
# This script is NOT part of CI: it needs a live host with the services
# running. Run it after a rebuild, or from cron on the production hosts.
set -uo pipefail
NGINX_CONF="${NGINX_CONF:-/etc/nginx/nginx.conf}"
GUARDED_UNITS=(
samba-smbd
phpfpm-nextcloud
immich-server
podman-3xui_app
podman-taperotation-backend
podman-taperotation-frontend
)
DO_NGINX=0
DO_PODMAN=0
DO_SYSTEMD=0
if [ "$#" -eq 0 ]; then
DO_NGINX=1
DO_PODMAN=1
DO_SYSTEMD=1
else
for arg in "$@"; do
case "$arg" in
--nginx) DO_NGINX=1 ;;
--podman) DO_PODMAN=1 ;;
--systemd) DO_SYSTEMD=1 ;;
*) echo "Unknown arg: $arg" >&2; exit 2 ;;
esac
done
fi
DRIFT=0
# --- nginx: rendered file vs loaded config ---------------------------------
if [ "$DO_NGINX" -eq 1 ]; then
echo "=== nginx: rendered config vs loaded config ==="
if ! command -v nginx >/dev/null 2>&1; then
echo " SKIP: nginx not in PATH"
elif [ ! -f "$NGINX_CONF" ]; then
echo " SKIP: $NGINX_CONF not found"
else
rendered=$(mktemp)
loaded=$(mktemp)
grep -hoE '^[[:space:]]*server_name[[:space:]]+[^;]+;' "$NGINX_CONF" \
| sed -E 's/.*server_name[[:space:]]+//; s/;//' | tr ' ' '\n' | sort -u > "$rendered"
nginx -T 2>/dev/null \
| grep -hoE '^[[:space:]]*server_name[[:space:]]+[^;]+;' \
| sed -E 's/.*server_name[[:space:]]+//; s/;//' | tr ' ' '\n' | sort -u > "$loaded"
if diff -u "$rendered" "$loaded" >/dev/null 2>&1; then
echo " OK: nginx serves the same server_name set as the rendered config"
else
echo " DRIFT: nginx has NOT reloaded the current config" >&2
diff -u "$rendered" "$loaded" | sed 's/^/ /' >&2
DRIFT=1
fi
rm -f "$rendered" "$loaded"
fi
echo
fi
# --- podman: declared ports vs published ports -----------------------------
if [ "$DO_PODMAN" -eq 1 ]; then
echo "=== podman: declared ports vs published ports ==="
if ! command -v podman >/dev/null 2>&1; then
echo " SKIP: podman not in PATH"
else
for unit in $(systemctl list-units --type=service --all --no-legend 2>/dev/null \
| awk '$1 ~ /^podman-/ {print $1}'); do
unit_file="/etc/systemd/system/${unit}.service"
[ -f "$unit_file" ] || continue
container=$(sed -nE 's/.*--name[= ]"?([^" ]+)"?.*/\1/p' "$unit_file" | head -1)
[ -n "$container" ] || continue
if ! podman inspect "$container" >/dev/null 2>&1; then
echo " DRIFT: ${unit}: container '${container}' does not exist (never created?)" >&2
DRIFT=1
continue
fi
declared=$(sed -nE 's/.*(-p|--publish)[= ]"?([^" ]+)"?.*/\2/p' "$unit_file" \
| tr ',' '\n' | sed 's/^[[:space:]]*//' | sort -u)
published=$(podman inspect "$container" --format '{{json .NetworkSettings.Ports}}' 2>/dev/null)
for entry in $declared; do
host_port="${entry%%:*}"
if ! printf '%s' "$published" | grep -q "\"${host_port}/tcp\""; then
echo " DRIFT: ${unit}: declares -p ${entry} but the running container does not publish ${host_port}/tcp" >&2
echo " declared: ${declared}" >&2
echo " published: ${published}" >&2
echo " fix: podman rm ${container} && systemctl restart ${unit}" >&2
DRIFT=1
fi
done
done
[ "$DRIFT" -eq 0 ] && echo " OK: every container publishes the ports its unit declares"
fi
echo
fi
# --- systemd: storage guard actually landed in the unit ---------------------
if [ "$DO_SYSTEMD" -eq 1 ]; then
echo "=== systemd: storage guard present in the unit ==="
for unit in "${GUARDED_UNITS[@]}"; do
if ! systemctl show "$unit" >/dev/null 2>&1; then
echo " SKIP: ${unit} is not installed on this host"
continue
fi
condition=$(systemctl show "$unit" -p ConditionPathIsMountPoint --value 2>/dev/null)
if [ -z "$condition" ]; then
echo " DRIFT: ${unit} carries no ConditionPathIsMountPoint — the storage guard is dead" >&2
DRIFT=1
else
echo " OK: ${unit} guarded by ${condition}"
fi
done
echo
fi
if [ "$DRIFT" -ne 0 ]; then
echo "runtime-drift: DRIFT DETECTED" >&2
exit 1
fi
echo "runtime-drift: OK (declaration and runtime agree)"
+52
View File
@@ -0,0 +1,52 @@
name: evaluate all hosts
# The everyday workflow (.gitea/workflows/nix-checks.yml) evaluates ONE host —
# sapphira — because the runner *is* sapphira: evaluating all seven
# configurations there took 40+ minutes and pushed the production host into
# swap. That left the other six hosts unevaluated by CI, and it was not a
# theoretical gap: `configurations/mobile.nix:12` once imported a
# non-existent `lib/xlib.nix` and epral silently stopped building
# (AGENTS.md invariant 1).
#
# This workflow closes that gap. It is MANUAL on purpose: on the self-hosted
# runner it is a heavy, slow sweep, so it runs when someone asks for it, not
# on every push.
#
# What it does: evaluates every configuration (no build). Evaluation is
# enough to catch the class of breakage above — a broken import, a missing
# attribute, a type error — and it needs no store write access, which the
# runner user does not have (see the sapphira workflow for that constraint).
#
# To run it: push → Actions → "evaluate all hosts" → Run workflow.
on:
workflow_dispatch:
jobs:
evaluate-all:
runs-on: native
# Seven configurations on a 2-core / 5.6 GiB host. Generous: the point is
# to finish, not to be fast.
timeout-minutes: 120
steps:
- uses: actions/checkout@v4
- name: toolchain probe
run: |
nix --version
git --version
- name: evaluate every NixOS configuration
run: |
set -euo pipefail
for host in atoridu rydiwo otreca sapphira wsl default; do
echo "== ${host} =="
nix --extra-experimental-features "nix-command flakes" eval --raw \
".#nixosConfigurations.${host}.config.system.build.toplevel.drvPath"
echo
done
- name: evaluate the nix-on-droid configuration
run: |
nix --extra-experimental-features "nix-command flakes" eval --raw \
'.#nixOnDroidConfigurations.epral.config.system.build.toplevel.drvPath'