From 3d993ac2417f6d81cb4c043bd202d4d3c4d29222 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Fri, 25 Sep 2026 11:29:53 +0200 Subject: [PATCH 01/29] build(debian): add the debhelper 13 source package Classic debian/ as the package conventions require (debhelper-compat 13, Rules-Requires-Root: no, 3.0 native), built by `make deb` = dpkg-buildpackage. The hermetic venv stays under /opt/linuxmuster-radius/venv (linuxmusterDEV work/plans/venv-debian-umbau.md): - packaging/build-venv.sh builds it into debian/linuxmuster-radius, without root. The pip calls, `pip check` and the freeze == lock gate are those of build-deb.sh; only the target directory is now an argument. - debian/venv-relocate (byte-identical to the hub reference, sha256 b2eb131c...cbbc) rewrites the build path in shebangs, activate scripts and pyvenv.cfg, recompiles the .pyc files as checked-hash for /opt and re-hashes the RECORD rows it touched. `--verify` runs right before dh_builddeb and fails the build on a leftover build path, a RECORD mismatch (a debhelper tool changed a pip-installed file), a stale .pyc or a failing `pip check`. - dh_strip, dh_dwz, dh_strip_nondeterminism and dh_makeshlibs stay out of the venv, dh_fixperms skips it (the wheels' .so files stay 0755), and dh_installsystemd is off: the maintainer scripts keep handling the unit. - Architecture: amd64, because the venv carries cp312 x86_64 extension modules; Depends python3 (>= 3.12), python3 (<< 3.13), since the venv runs /usr/bin/python3 and is built for 3.12; ${shlibs:Depends} adds libc6 and libgcc-s1. - lintian overrides for the venv under /opt, each with its reason. - debian/copyright notes that the bundled PyPI distributions carry their licenses in their *.dist-info directories. - The Makefile keeps untracked local state (.venv, tool caches, crabbox state, .claude/settings.local.json, keytabs, e2e test keys) out of the source tarball. Checked in lmndev-runner:24.04@sha256:6b0c8ac9 as the image's non-root user: both venv-relocate steps run (21 files rewritten, 1714 .pyc, 17 RECORD rows; --verify: 2183 RECORD hashes, 1714 .pyc), lintian --fail-on error exit 0, and against the released 7.3.3 .deb the file tree differs only by the doc/changelog, copyright and lintian override files and their directories plus the mode of ./, all 1714 .pyc are identical after the 16-byte header. --- Makefile | 30 ++-- debian/control | 27 ++++ debian/control.license | 3 + debian/copyright | 31 ++++ debian/copyright.license | 3 + debian/install | 4 + debian/links | 5 + debian/linuxmuster-radius.lintian-overrides | 16 ++ debian/rules | 45 ++++++ debian/source/format | 1 + debian/source/format.license | 3 + debian/venv-relocate | 168 ++++++++++++++++++++ packaging/build-venv.sh | 49 ++++++ 13 files changed, 375 insertions(+), 10 deletions(-) create mode 100644 debian/control create mode 100644 debian/control.license create mode 100644 debian/copyright create mode 100644 debian/copyright.license create mode 100644 debian/install create mode 100644 debian/links create mode 100644 debian/linuxmuster-radius.lintian-overrides create mode 100755 debian/rules create mode 100644 debian/source/format create mode 100644 debian/source/format.license create mode 100755 debian/venv-relocate create mode 100755 packaging/build-venv.sh diff --git a/Makefile b/Makefile index 9bf055c..0177901 100644 --- a/Makefile +++ b/Makefile @@ -2,20 +2,30 @@ # SPDX-License-Identifier: GPL-3.0-or-later # # `make deb` is the uniform build entry point of Kevin's linuxmuster.net packages -# (linuxmusterDEV/docs/paket-konventionen.md). Until the debian/ conversion it wraps -# packaging/build-deb.sh, which needs root (the venv is built at its target path -# /opt/linuxmuster-radius/venv). Build like CI does, in the same digest-pinned -# lmndev-runner container (keep the digest equal to ci.yml; Renovate bumps both): -# docker run --rm -u root -v "$PWD":/src -w /src \ +# (linuxmusterDEV/docs/paket-konventionen.md): dpkg-buildpackage, no root needed +# (Rules-Requires-Root: no; debian/rules builds the venv inside debian/linuxmuster-radius and +# relocates it to /opt/linuxmuster-radius/venv). It writes the .deb, .changes, .buildinfo, .dsc +# and the source tarball one level ABOVE this tree; -tc cleans the tree afterwards. The +# version is the top entry of debian/changelog. +# Build like CI does, in the same digest-pinned lmndev-runner container (keep the digest equal +# to ci.yml and release.yml; pins are raised by hand). Mount the checkout one level down, so +# the artefacts land in a writable parent (../out here); the image's user `build` (uid 1000) +# builds, root only installs the build dependencies: +# mkdir -p ../out && docker run --rm -u root -v "$(realpath ../out)":/b -v "$PWD":/b/src -w /b/src \ # ghcr.io/linuxmuster/lmndev-runner:24.04@sha256:6b0c8ac994cf1d2da44b0b36ebd7b3b125094886e78293e04b9db5e515b8209e \ -# bash -c 'apt-get update -qq && apt-get install -y -qq python3-venv && make deb' -# The version comes from debian/changelog (dpkg-parsechangelog); VERSION= overrides it. +# bash -c 'apt-get update -qq && apt-get build-dep -y -qq . && runuser -u build -- make deb' +# The bare -I keeps dpkg-source's default ignore list (.git, .gitignore, ...); an -I +# alone would replace it. The other patterns keep untracked local state of a working checkout +# (virtualenvs, tool caches, crabbox state, the token in .claude/settings.local.json, test +# key material) out of the source tarball; they match at any depth. +DPKG_SOURCE_IGNORE := -I -I.github -I.venv -I__pycache__ -I'*.egg-info' -I.mypy_cache \ + -I.ruff_cache -I.pytest_cache -I.crabbox -I'settings.local.json' -I'*.keytab' \ + -I'deploy/e2e/certs/out' .PHONY: deb clean deb: - bash packaging/build-deb.sh + dpkg-buildpackage -us -uc -tc $(DPKG_SOURCE_IGNORE) clean: - rm -f linuxmuster-radius_*.deb - rm -rf controlplane/build controlplane/*.egg-info + debian/rules clean diff --git a/debian/control b/debian/control new file mode 100644 index 0000000..e663f9b --- /dev/null +++ b/debian/control @@ -0,0 +1,27 @@ +Source: linuxmuster-radius +Section: admin +Priority: optional +Maintainer: Kevin Stenzel +Build-Depends: debhelper-compat (= 13), + python3 (>= 3.12), + python3 (<< 3.13), + python3-venv +Standards-Version: 4.6.2 +Rules-Requires-Root: no +Homepage: https://github.com/faircomp/linuxmuster-radius + +Package: linuxmuster-radius +Architecture: amd64 +Depends: ${misc:Depends}, + ${shlibs:Depends}, + python3 (>= 3.12), + python3 (<< 3.13), + adduser, + openssl, + git +Recommends: docker.io | docker-ce +Description: REST API + CLI managing per-school FreeRADIUS containers + Control plane that provisions and reconciles per-school FreeRADIUS (WLAN 802.1X) + Docker containers: AD-backed EAP auth, a control-plane CA issuing EAP server + certs, per-client shared secrets, and digest-pinned, health-checked, auto-rolling + updates. Ships a self-contained Python virtualenv under /opt/linuxmuster-radius. diff --git a/debian/control.license b/debian/control.license new file mode 100644 index 0000000..38fc113 --- /dev/null +++ b/debian/control.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: Kevin Stenzel + +SPDX-License-Identifier: GPL-3.0-or-later diff --git a/debian/copyright b/debian/copyright new file mode 100644 index 0000000..6d8d59c --- /dev/null +++ b/debian/copyright @@ -0,0 +1,31 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: linuxmuster-radius +Upstream-Contact: Kevin Stenzel +Source: https://github.com/faircomp/linuxmuster-radius +Comment: This file covers the source package. The binary package additionally + bundles third-party Python distributions from PyPI in the virtualenv under + /opt/linuxmuster-radius/venv, installed from the hash-pinned lockfiles + controlplane/requirements.lock and controlplane/build-requirements.lock. Each + of them carries its own license in its *.dist-info directory under + /opt/linuxmuster-radius/venv/lib/python3.12/site-packages/. + +Files: * +Copyright: 2026 Kevin Stenzel +License: GPL-3.0+ + +License: GPL-3.0+ + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + . + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + . + You should have received a copy of the GNU General Public License + along with this program. If not, see . + . + On Debian systems, the full text of the GNU General Public License + version 3 can be found in /usr/share/common-licenses/GPL-3. diff --git a/debian/copyright.license b/debian/copyright.license new file mode 100644 index 0000000..38fc113 --- /dev/null +++ b/debian/copyright.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: Kevin Stenzel + +SPDX-License-Identifier: GPL-3.0-or-later diff --git a/debian/install b/debian/install new file mode 100644 index 0000000..1705c40 --- /dev/null +++ b/debian/install @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# The unit stays in /lib/systemd/system for the 7.3 line; the maintainer scripts handle it. +packaging/systemd/linuxmuster-radius.service lib/systemd/system/ diff --git a/debian/links b/debian/links new file mode 100644 index 0000000..75a7a09 --- /dev/null +++ b/debian/links @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# The operator CLI on PATH (docs/install.md's first step after the install); a packaged +# symlink, so dpkg removes it with the package. +opt/linuxmuster-radius/venv/bin/lmnradius usr/bin/lmnradius diff --git a/debian/linuxmuster-radius.lintian-overrides b/debian/linuxmuster-radius.lintian-overrides new file mode 100644 index 0000000..c5186af --- /dev/null +++ b/debian/linuxmuster-radius.lintian-overrides @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# The hermetic venv under /opt is the design: FastAPI, pydantic v2, typer and docker-py are +# not packaged for Ubuntu 24.04 in usable versions. Its files are exactly what pip installed +# from the hash-pinned lockfiles; debian/venv-relocate --verify checks them against RECORD +# before dh_builddeb. +dir-or-file-in-opt [opt/*] +# pip compiles the bytecode; venv-relocate recompiles it as checked-hash .pyc for /opt. +package-installs-python-pycache-dir [opt/linuxmuster-radius/venv/*] +# Console scripts run the venv's own interpreter, not /usr/bin/python3. +wrong-path-for-interpreter * [opt/linuxmuster-radius/venv/*] +# Stripping would change files pip recorded in RECORD (dh_strip is overridden). +unstripped-binary-or-object [opt/linuxmuster-radius/venv/*] +# PyYAML's manylinux wheel links libyaml statically. +embedded-library libyaml [opt/linuxmuster-radius/venv/*] diff --git a/debian/rules b/debian/rules new file mode 100755 index 0000000..01442dc --- /dev/null +++ b/debian/rules @@ -0,0 +1,45 @@ +#!/usr/bin/make -f +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# The hermetic venv is built into debian/$(PKG)$(DEST) without root and relocated to +# $(DEST) (debian/venv-relocate). Every file pip installed must reach the .deb unchanged: +# debhelper tools that rewrite files (strip, dwz, strip-nondeterminism) or modes (fixperms) +# stay out of the venv, and --verify proves it against RECORD before dh_builddeb. + +include /usr/share/dpkg/pkg-info.mk + +PKG := linuxmuster-radius +DEST := /opt/$(PKG)/venv +ROOT := $(CURDIR)/debian/$(PKG) + +%: + dh $@ + +# Nothing to configure, build or test here (the fast tier tests the code); overriding also +# keeps debhelper's makefile build system from calling the top-level Makefile (recursion). +override_dh_auto_configure override_dh_auto_build override_dh_auto_test: + @: + +override_dh_auto_install: + bash packaging/build-venv.sh $(ROOT)$(DEST) + debian/venv-relocate $(ROOT) $(DEST) + +override_dh_auto_clean: + rm -rf controlplane/build controlplane/*.egg-info + +# Stripping, dwz and strip-nondeterminism would change files pip recorded in RECORD; +# dh_makeshlibs must not publish the wheels' private libraries as shlibs. +override_dh_strip override_dh_dwz override_dh_strip_nondeterminism override_dh_makeshlibs: + @: + +# The maintainer scripts handle the units by hand, unchanged since 7.3.x (the plan, §4). +override_dh_installsystemd: + @: + +# The wheels' .so files are 0755 as pip installed them; dh_fixperms would make them 0644. +override_dh_fixperms: + dh_fixperms -X$(DEST) + +execute_before_dh_builddeb: + debian/venv-relocate --verify $(ROOT) $(DEST) diff --git a/debian/source/format b/debian/source/format new file mode 100644 index 0000000..89ae9db --- /dev/null +++ b/debian/source/format @@ -0,0 +1 @@ +3.0 (native) diff --git a/debian/source/format.license b/debian/source/format.license new file mode 100644 index 0000000..38fc113 --- /dev/null +++ b/debian/source/format.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: Kevin Stenzel + +SPDX-License-Identifier: GPL-3.0-or-later diff --git a/debian/venv-relocate b/debian/venv-relocate new file mode 100755 index 0000000..89863db --- /dev/null +++ b/debian/venv-relocate @@ -0,0 +1,168 @@ +#!/usr/bin/python3 +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Make a venv built inside the package tree correct for its installed path, or prove it. + + debian/venv-relocate (override_dh_auto_install) + debian/venv-relocate --verify (execute_before_dh_builddeb) + + is debian/, the installed venv path, e.g. /opt/linuxmuster-squid/venv. +The venv is built at without root. pip writes that build path into the +console-script shebangs, bin/activate*, pyvenv.cfg and the co_filename of every .pyc. +Relocating rewrites the text files, recompiles the .pyc files (checked-hash, reproducible, +independent of mtimes) and re-hashes the RECORD rows of the files it rewrote. +--verify fails the build if any file in the package still carries the build path, if any +RECORD row does not match its file (so no debhelper tool changed a pip-installed file), if +any .pyc would be stale on the target, or if `pip check` fails. +""" + +import base64 +import csv +import glob +import hashlib +import importlib.util +import io +import marshal +import os +import py_compile +import re +import subprocess +import sys + +# distlib writes this /bin/sh trampoline instead of a plain shebang when the interpreter path +# is longer than 127 bytes (deep build directories). Normalised to the plain form. +TRAMPOLINE = re.compile(rb"\A#!/bin/sh\n'''exec' (?:\"([^\"]+)\"|(\S+)) \"\$0\" \"\$@\"\n' '''\n") + + +def walk(top): + for d, _dirs, names in os.walk(top): + for n in names: + p = os.path.join(d, n) + if not os.path.islink(p): + yield p + + +def read(path): + with open(path, "rb") as f: + return f.read() + + +def record_hash(data): + return "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode() + + +def records(venv): + return sorted(glob.glob(venv + "/lib/python3*/site-packages/*.dist-info/RECORD")) + + +def read_record(path): + raw = read(path) + nl = "\r\n" if b"\r\n" in raw else "\n" + return list(csv.reader(io.StringIO(raw.decode(), newline=""))), nl + + +def relocate(root, dest): + venv = root + dest + old, new = venv.encode(), dest.encode() + changed, pycs = set(), [] + for p in walk(venv): + if p.endswith(".pyc"): + pycs.append(p) + continue + data = read(p) + if old not in data: + continue + m = TRAMPOLINE.match(data) + if m: + data = b"#!" + (m.group(1) or m.group(2)) + b"\n" + data[m.end() :] + with open(p, "r+b") as f: # same inode, same mode + f.write(data.replace(old, new)) + f.truncate() + changed.add(os.path.realpath(p)) + for pyc in pycs: + src = importlib.util.source_from_cache(pyc) + py_compile.compile( + src, + cfile=pyc, + dfile=dest + src[len(venv) :], + doraise=True, + invalidation_mode=py_compile.PycInvalidationMode.CHECKED_HASH, + ) + fixed = 0 + for rec in records(venv): + rows, nl = read_record(rec) + base = os.path.dirname(os.path.dirname(rec)) + for row in rows: + p = os.path.realpath(os.path.join(base, row[0])) + if row[1] and p in changed: + data = read(p) + row[1], row[2] = record_hash(data), str(len(data)) + fixed += 1 + out = io.StringIO(newline="") + csv.writer(out, lineterminator=nl).writerows(rows) + with open(rec, "w", newline="") as f: + f.write(out.getvalue()) + print( + f"venv-relocate: {len(changed)} files rewritten, {len(pycs)} .pyc recompiled, " + f"{fixed} RECORD rows re-hashed" + ) + + +def verify(root, dest): + venv = root + dest + errors = [] + marker = (root + dest).encode() + for p in walk(root): + if marker in read(p): + errors.append(f"build path left in {p}") + for d, dirs, names in os.walk(root): + for n in dirs + names: + p = os.path.join(d, n) + if os.path.islink(p) and os.readlink(p).startswith(root): + errors.append(f"symlink into the build tree: {p}") + rows_ok = 0 + for rec in records(venv): + rows, _ = read_record(rec) + base = os.path.dirname(os.path.dirname(rec)) + for row in rows: + p = os.path.join(base, row[0]) + if not os.path.lexists(p): + errors.append(f"{rec}: {row[0]} missing") + elif row[1]: + data = read(p) + if row[1] != record_hash(data) or row[2] != str(len(data)): + errors.append(f"{rec}: {row[0]} differs from its RECORD row") + else: + rows_ok += 1 + pyc_ok = 0 + for pyc in (p for p in walk(venv) if p.endswith(".pyc")): + data = read(pyc) + src = importlib.util.source_from_cache(pyc) + want = importlib.util.source_hash(read(src)) + if int.from_bytes(data[4:8], "little") != 3 or data[8:16] != want: + errors.append(f"stale or unchecked .pyc: {pyc}") + elif not marshal.loads(data[16:]).co_filename.startswith(dest + "/"): + errors.append(f"co_filename outside {dest}: {pyc}") + else: + pyc_ok += 1 + env = dict( + os.environ, PYTHONDONTWRITEBYTECODE="1", PIP_NO_INPUT="1", PIP_DISABLE_PIP_VERSION_CHECK="1" + ) + r = subprocess.run([venv + "/bin/python", "-B", "-m", "pip", "check"], env=env) + if r.returncode: + errors.append("pip check failed") + for e in errors[:50]: + print("venv-relocate --verify:", e, file=sys.stderr) + if errors: + sys.exit(f"venv-relocate --verify: {len(errors)} problem(s)") + print( + f"venv-relocate --verify: no build path, {rows_ok} RECORD hashes match, " + f"{pyc_ok} .pyc valid, pip check ok" + ) + + +if __name__ == "__main__": + if sys.argv[1:2] == ["--verify"]: + verify(*sys.argv[2:4]) + else: + relocate(*sys.argv[1:3]) diff --git a/packaging/build-venv.sh b/packaging/build-venv.sh new file mode 100755 index 0000000..7566014 --- /dev/null +++ b/packaging/build-venv.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Builds the hermetic Python venv of linuxmuster-radius into $1. debian/rules passes +# debian/linuxmuster-radius/opt/linuxmuster-radius/venv (no root needed) and then runs +# debian/venv-relocate, which makes the shebangs, activate scripts, pyvenv.cfg and .pyc files +# correct for /opt/linuxmuster-radius/venv. The version of the control plane is the top entry +# of debian/changelog (controlplane/setup.py reads it). +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +VENV="${1:?usage: build-venv.sh }" +WHEELS="$(mktemp -d)" +trap 'rm -rf "$WHEELS"' EXIT + +echo "== venv @ $VENV ==" +rm -rf "$VENV" +mkdir -p "$(dirname "$VENV")" +python3 -m venv "$VENV" +# Supply chain: every distribution in the venv comes from a lockfile that pins its +# version AND sha256 (controlplane/*.lock, `uv pip compile --generate-hashes`, bumped by +# Renovate PRs, checked by scripts/check-lockfiles.sh). --require-hashes: pip installs a +# file only if its hash is in the lock. --only-binary :all:: wheels only, so no sdist is +# built with unhashed build dependencies. --no-deps: the lock is the whole closure, pip +# resolves nothing on its own (pip check below proves it is complete). +LOCKED=("$VENV/bin/pip" install --quiet --require-hashes --only-binary :all: --no-deps) +# pip itself (replaces what ensurepip bootstrapped) and setuptools, the build backend. +"${LOCKED[@]}" -r "$ROOT/controlplane/build-requirements.lock" +# The runtime closure; cryptography (P3) arrives as a manylinux wheel -> no extra apt Depends. +"${LOCKED[@]}" -r "$ROOT/controlplane/requirements.lock" +# The control plane itself: built offline with the locked setuptools, then installed by name +# from that wheel (a path install would record the build directory in direct_url.json). +"$VENV/bin/pip" wheel --quiet --no-index --no-build-isolation --no-deps -w "$WHEELS" "$ROOT/controlplane" +"$VENV/bin/pip" install --quiet --no-index --only-binary :all: --no-deps --find-links "$WHEELS" lmnradius +"$VENV/bin/pip" check +# setuptools was only needed to build the control plane; nothing imports it at runtime. +"$VENV/bin/pip" uninstall --quiet --yes setuptools +# The venv holds exactly the lockfiles, nothing else (names PEP 503-normalised on both sides). +norm() { + "$VENV/bin/python" -c 'import re, sys +for line in sys.stdin: + name, version = line.split()[0].split("==") + print(re.sub(r"[-_.]+", "-", name).lower() + "==" + version)' | LC_ALL=C sort +} +diff -u <(grep -hE '^[A-Za-z0-9]' "$ROOT/controlplane/requirements.lock" \ + "$ROOT/controlplane/build-requirements.lock" | grep -v '^setuptools==' | norm) \ + <("$VENV/bin/pip" freeze --all --exclude lmnradius | norm) + From eae8038ab9707783378fee594d0b10c183177823 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Fri, 25 Sep 2026 11:31:50 +0200 Subject: [PATCH 02/29] build(debian): move the maintainer scripts packaging/debian/{postinst,prerm,postrm} move to debian/ unchanged, plus one #DEBHELPER# line right before the final `exit 0` (never inside a comment: debhelper replaces every occurrence of the token). No debhelper tool adds a snippet here (no dh_installsystemd, no dh_python3, no conffiles), so the built DEBIAN/postinst, prerm and postrm equal those of the released 7.3.3 .deb plus one empty line each, which compare-release.sh confirms. --- {packaging/debian => debian}/postinst | 1 + {packaging/debian => debian}/postrm | 1 + {packaging/debian => debian}/prerm | 1 + 3 files changed, 3 insertions(+) rename {packaging/debian => debian}/postinst (99%) rename {packaging/debian => debian}/postrm (97%) rename {packaging/debian => debian}/prerm (97%) diff --git a/packaging/debian/postinst b/debian/postinst similarity index 99% rename from packaging/debian/postinst rename to debian/postinst index bc52141..33b0960 100644 --- a/packaging/debian/postinst +++ b/debian/postinst @@ -101,4 +101,5 @@ if [ -d /run/systemd/system ]; then fi fi +#DEBHELPER# exit 0 diff --git a/packaging/debian/postrm b/debian/postrm similarity index 97% rename from packaging/debian/postrm rename to debian/postrm index 2cef08e..7f703c5 100644 --- a/packaging/debian/postrm +++ b/debian/postrm @@ -10,4 +10,5 @@ if [ "$1" = "purge" ]; then rm -rf /opt/linuxmuster-radius rm -rf /etc/linuxmuster-radius /var/lib/linuxmuster-radius fi +#DEBHELPER# exit 0 diff --git a/packaging/debian/prerm b/debian/prerm similarity index 97% rename from packaging/debian/prerm rename to debian/prerm index 8dfb5f9..b4449c4 100644 --- a/packaging/debian/prerm +++ b/debian/prerm @@ -8,4 +8,5 @@ set -e if [ "$1" = remove ] && [ -d /run/systemd/system ]; then systemctl disable --now linuxmuster-radius.service || true fi +#DEBHELPER# exit 0 From fc7f394d759752b06dd5c949e1e16dcad990df27 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Fri, 25 Sep 2026 11:32:05 +0200 Subject: [PATCH 03/29] build(packaging): remove build-deb.sh and packaging/debian debian/rules and packaging/build-venv.sh replace the hand-rolled dpkg-deb build, debian/control replaces packaging/debian/control (the maintainer scripts moved in the previous commit). packaging/systemd/ stays: debian/install takes the unit from there. .gitignore also ignores debhelper's build stamp. --- .gitignore | 3 ++ packaging/build-deb.sh | 92 -------------------------------- packaging/debian/control | 13 ----- packaging/debian/control.license | 3 -- 4 files changed, 3 insertions(+), 108 deletions(-) delete mode 100755 packaging/build-deb.sh delete mode 100644 packaging/debian/control delete mode 100644 packaging/debian/control.license diff --git a/.gitignore b/.gitignore index af25514..3d20993 100644 --- a/.gitignore +++ b/.gitignore @@ -23,9 +23,12 @@ dist/ build/ # --- Debian packaging build artifacts --- +# debhelper's working files; `make deb` (dpkg-buildpackage -tc) removes them again, and +# writes the .deb, .changes, .buildinfo, .dsc and source tarball one level above the tree. debian/.debhelper/ debian/files debian/*.substvars +debian/debhelper-build-stamp debian/linuxmuster-radius/ *.deb *.buildinfo diff --git a/packaging/build-deb.sh b/packaging/build-deb.sh deleted file mode 100755 index 7004cd5..0000000 --- a/packaging/build-deb.sh +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env bash -# SPDX-FileCopyrightText: Kevin Stenzel -# SPDX-License-Identifier: GPL-3.0-or-later -# -# Builds the linuxmuster-radius .deb with a hermetic Python venv under -# /opt/linuxmuster-radius/venv (built at the target path so the shebangs are correct) -# + systemd unit + maintainer scripts. RUN AS ROOT (or `make deb` in the lmndev-runner -# container). The version is the top entry of debian/changelog, the single version -# source; VERSION= in the environment overrides only the .deb metadata (the venv's -# Python package always carries the changelog version via controlplane/setup.py). -set -euo pipefail - -ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -VERSION="${VERSION:-$(dpkg-parsechangelog -l "$ROOT/debian/changelog" -S Version)}" -case "$VERSION" in - ""|*[!0-9A-Za-z.+~-]*) echo "invalid VERSION: '$VERSION'" >&2; exit 1 ;; -esac -VENV=/opt/linuxmuster-radius/venv -STAGE="$(mktemp -d)" -WHEELS="$(mktemp -d)" -trap 'rm -rf "$STAGE" "$WHEELS"' EXIT - -echo "== venv @ $VENV ==" -rm -rf "$VENV" -mkdir -p /opt/linuxmuster-radius -python3 -m venv "$VENV" -# Supply chain: every distribution in the venv comes from a lockfile that pins its -# version AND sha256 (controlplane/*.lock, `uv pip compile --generate-hashes`, bumped by -# Renovate PRs, checked by scripts/check-lockfiles.sh). --require-hashes: pip installs a -# file only if its hash is in the lock. --only-binary :all:: wheels only, so no sdist is -# built with unhashed build dependencies. --no-deps: the lock is the whole closure, pip -# resolves nothing on its own (pip check below proves it is complete). -LOCKED=("$VENV/bin/pip" install --quiet --require-hashes --only-binary :all: --no-deps) -# pip itself (replaces what ensurepip bootstrapped) and setuptools, the build backend. -"${LOCKED[@]}" -r "$ROOT/controlplane/build-requirements.lock" -# The runtime closure; cryptography (P3) arrives as a manylinux wheel -> no extra apt Depends. -"${LOCKED[@]}" -r "$ROOT/controlplane/requirements.lock" -# The control plane itself: built offline with the locked setuptools, then installed by name -# from that wheel (a path install would record the build directory in direct_url.json). -"$VENV/bin/pip" wheel --quiet --no-index --no-build-isolation --no-deps -w "$WHEELS" "$ROOT/controlplane" -"$VENV/bin/pip" install --quiet --no-index --only-binary :all: --no-deps --find-links "$WHEELS" lmnradius -"$VENV/bin/pip" check -# setuptools was only needed to build the control plane; nothing imports it at runtime. -"$VENV/bin/pip" uninstall --quiet --yes setuptools -# The venv holds exactly the lockfiles, nothing else (names PEP 503-normalised on both sides). -norm() { - "$VENV/bin/python" -c 'import re, sys -for line in sys.stdin: - name, version = line.split()[0].split("==") - print(re.sub(r"[-_.]+", "-", name).lower() + "==" + version)' | LC_ALL=C sort -} -diff -u <(grep -hE '^[A-Za-z0-9]' "$ROOT/controlplane/requirements.lock" \ - "$ROOT/controlplane/build-requirements.lock" | grep -v '^setuptools==' | norm) \ - <("$VENV/bin/pip" freeze --all --exclude lmnradius | norm) - -echo "== staging tree ==" -mkdir -p "$STAGE/opt/linuxmuster-radius" "$STAGE/lib/systemd/system" "$STAGE/DEBIAN" \ - "$STAGE/usr/bin" -cp -a "$VENV" "$STAGE/opt/linuxmuster-radius/venv" -# Operator CLI onto PATH. The venv keeps the hermetic interpreter, but without this -# packaged symlink `lmnradius` is "command not found" for the admin — the docs' very -# first post-install step. (Found on a real install, 2026-08-04: postinst masked it by -# calling the full venv path itself.) Packaged symlink => dpkg removes it on purge. -ln -s /opt/linuxmuster-radius/venv/bin/lmnradius "$STAGE/usr/bin/lmnradius" -cp "$ROOT/packaging/systemd/linuxmuster-radius.service" \ - "$STAGE/lib/systemd/system/linuxmuster-radius.service" -sed "s/@VERSION@/$VERSION/" "$ROOT/packaging/debian/control" > "$STAGE/DEBIAN/control" -for f in postinst prerm postrm; do - cp "$ROOT/packaging/debian/$f" "$STAGE/DEBIAN/$f" - chmod 0755 "$STAGE/DEBIAN/$f" -done - -# DEBIAN/md5sums (what dh_md5sums would generate): every shipped regular file, path -# without the leading "./", DEBIAN/ itself excluded. Without it the .deb carries no -# integrity data -- lintian: no-md5sums-control-file, and `dpkg --verify` only sees the -# sums dpkg computed itself at unpack time (found in the 2026-09-22 campaign). -echo "== md5sums ==" -( cd "$STAGE" && find . -type f -not -path './DEBIAN/*' -printf '%P\n' | LC_ALL=C sort \ - | xargs -r -d '\n' md5sum > DEBIAN/md5sums ) -chmod 0644 "$STAGE/DEBIAN/md5sums" -echo " $(wc -l < "$STAGE/DEBIAN/md5sums") files" - -OUT="$ROOT/linuxmuster-radius_${VERSION}_all.deb" -echo "== dpkg-deb -> $OUT ==" -dpkg-deb --build --root-owner-group "$STAGE" "$OUT" -echo "== built $OUT ==" - -# Signing (production): apt does NOT verify individual .deb signatures, but rather the -# signed repo `Release` (InRelease / Release.gpg). So add the .deb into the lmn73 **reprepro** -# repo (deb.linuxmuster.net); reprepro signs the `Release` with the linuxmuster -# GPG key (reprepro `SignWith`). NO `dpkg-sig` per package. Requires the real key + repo access -# (human gate). Verified against wiki.debian.org/DebianRepository/SetupWithReprepro + deb.linuxmuster.net. diff --git a/packaging/debian/control b/packaging/debian/control deleted file mode 100644 index 668441c..0000000 --- a/packaging/debian/control +++ /dev/null @@ -1,13 +0,0 @@ -Package: linuxmuster-radius -Version: @VERSION@ -Architecture: all -Maintainer: Kevin Stenzel -Section: admin -Priority: optional -Depends: python3 (>= 3.12), adduser, openssl, git -Recommends: docker.io | docker-ce -Description: REST API + CLI managing per-school FreeRADIUS containers - Control plane that provisions and reconciles per-school FreeRADIUS (WLAN 802.1X) - Docker containers: AD-backed EAP auth, a control-plane CA issuing EAP server - certs, per-client shared secrets, and digest-pinned, health-checked, auto-rolling - updates. Ships a self-contained Python virtualenv under /opt/linuxmuster-radius. diff --git a/packaging/debian/control.license b/packaging/debian/control.license deleted file mode 100644 index 38fc113..0000000 --- a/packaging/debian/control.license +++ /dev/null @@ -1,3 +0,0 @@ -SPDX-FileCopyrightText: Kevin Stenzel - -SPDX-License-Identifier: GPL-3.0-or-later From b0a9848a27fdb2d71bb1f46a66c00d916139c8f3 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Fri, 25 Sep 2026 11:32:50 +0200 Subject: [PATCH 04/29] docs: the build is dpkg-buildpackage now CLAUDE.md and README describe the debhelper package: `make deb` = dpkg-buildpackage without root, packaging/build-venv.sh builds the venv into the package tree, debian/venv-relocate makes it correct for /opt and proves with --verify that no debhelper tool changed a pip-installed file, and the artefacts land next to the checkout. The download and install examples in install.md and operations.md name the _amd64.deb, the comments in build-requirements.in, check-lockfiles.sh and renovate.json and ADR-016 name build-venv.sh, and the threat model no longer names the removed script. --- CLAUDE.md | 18 ++++++++++++------ README.md | 2 +- controlplane/build-requirements.in | 2 +- docs/decisions.md | 2 +- docs/install.md | 2 +- docs/operations.md | 4 ++-- docs/threat-model.md | 2 +- renovate.json | 2 +- scripts/check-lockfiles.sh | 4 ++-- 9 files changed, 22 insertions(+), 16 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 9a1e29b..9e7f683 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -27,7 +27,7 @@ assumptions in [`docs/threat-model.md`](docs/threat-model.md), the decisions in | CLI | `controlplane/lmnradius/cli.py` | Python · Typer · httpx (thin client of the REST API, **no direct Docker**) | | EAP-CA / Cert manager | `controlplane/lmnradius/ca.py` | Private single-purpose EAP-CA (`ca init` / `cert issue` / `ca export`) | | E2E / Deploy | `deploy/` | docker-compose (Samba AD DC + joined FreeRADIUS + `eapol_test`), instance YAML, client GPO/MDM templates | -| Packaging | `packaging/` (`make deb`), `debian/changelog` | `.deb` via `packaging/build-deb.sh` (hermetic venv under `/opt`, only from the hash-pinned lockfiles `controlplane/*.lock`), hardened systemd service (lmn73 layout) | +| Packaging | `debian/` (`make deb` = `dpkg-buildpackage`), `packaging/` | debhelper 13 package; `packaging/build-venv.sh` builds the hermetic venv (only from the hash-pinned lockfiles `controlplane/*.lock`) into the package tree, `debian/venv-relocate` makes it correct for `/opt/linuxmuster-radius/venv`; hardened systemd service (lmn73 layout) | | Tests | `scripts/tests/` | `run.sh` aggregator; heavy tier on **crabbox** (`eapol_test` E2E) | > **The stack is deliberately Python** (linuxmuster-api7/webui7 are likewise FastAPI/ @@ -40,17 +40,23 @@ This is one of Kevin's own linuxmuster.net packages. The development hub is conventions are `../../docs/paket-konventionen.md` there. The rules that bite here: - **Version:** the top entry of `debian/changelog` is the only hand-edited version - (`7.3.N`, distribution `lmn73`, no `-0` revision). `packaging/build-deb.sh` - (`dpkg-parsechangelog`), `controlplane/setup.py` (`pyproject.toml` is `dynamic`) and + (`7.3.N`, distribution `lmn73`, no `-0` revision). `dpkg-buildpackage` (the .deb), + `controlplane/setup.py` (`pyproject.toml` is `dynamic`) and `GET /v1/version` (`importlib.metadata`) derive from it — never write a version anywhere else (not in `docs/install.md` either). Never bump it outside a release: Kevin sets it and tags `v7.3.N`; `release.yml` refuses a tag that does not match the changelog. - **Changelog:** one bullet in the top block of `debian/changelog` per user-visible change, in the same PR, written for admins in English. There is no `CHANGELOG.md`. -- **Build:** `make deb` (wraps `packaging/build-deb.sh`; needs root, so run it in - `ghcr.io/linuxmuster/lmndev-runner:24.04` like CI does, pinned by digest — the command is - in the `Makefile`; never reference the image by tag alone). +- **Build:** `make deb` = `dpkg-buildpackage` (debhelper 13, `Rules-Requires-Root: no`). It + writes `../linuxmuster-radius__amd64.deb` plus `.changes`, `.buildinfo`, `.dsc` and + the source tarball **next to** the checkout. Build it in + `ghcr.io/linuxmuster/lmndev-runner:24.04` like CI does, pinned by digest — the command is in + the `Makefile`; never reference the image by tag alone. `debian/rules` keeps debhelper's + file-changing tools (strip, dwz, fixperms, ...) out of the venv, and + `debian/venv-relocate --verify` fails the build if any pip-installed file changed. + `debian/venv-relocate` is shared byte-for-byte with linuxmuster-squid and + linuxmuster-readonlydc (the hub keeps the reference); change it there, not here alone. - **Python dependencies** are locked with hashes (ADR-016): `controlplane/requirements.lock` (from `pyproject.toml`) and `controlplane/build-requirements.lock` (pip + setuptools). After changing dependencies, re-run the command in the lockfile's header inside diff --git a/README.md b/README.md index b2c6f80..077be76 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ git-versioniert verwaltet über **REST-API + Typer-CLI**. | Control Plane (REST-API) | `controlplane/lmnradius/` | Python 3.11+ · FastAPI · uvicorn · **docker-py** (Container-Lifecycle) · pydantic v2 | | CLI | `controlplane/lmnradius/cli.py` | Python · Typer · httpx (Thin Client der REST-API) | | E2E / Deploy | `deploy/` | docker-compose (Samba AD DC + gejointer FreeRADIUS + `eapol_test`), Instanz-Definitionen | -| Packaging | `packaging/` (`make deb`), `debian/changelog` | `.deb` via `packaging/build-deb.sh` (hermetisches venv unter `/opt`, nur aus Hash-gepinnten Lockfiles `controlplane/*.lock`), gehärteter systemd-Dienst | +| Packaging | `debian/` (`make deb` = `dpkg-buildpackage`), `packaging/` | debhelper-13-Paket; `packaging/build-venv.sh` baut das hermetische venv (nur aus Hash-gepinnten Lockfiles `controlplane/*.lock`) in den Paketbaum, `debian/venv-relocate` macht es passend für `/opt/linuxmuster-radius/venv`; gehärteter systemd-Dienst | | Tests | `scripts/tests/` | `run.sh`-Aggregator; Heavy-Tier auf **crabbox** | Details: [`docs/architecture.md`](docs/architecture.md). diff --git a/controlplane/build-requirements.in b/controlplane/build-requirements.in index 5c3a34f..57c70f8 100644 --- a/controlplane/build-requirements.in +++ b/controlplane/build-requirements.in @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Kevin Stenzel # SPDX-License-Identifier: GPL-3.0-or-later # -# The tooling packaging/build-deb.sh installs into the venv before the runtime +# The tooling packaging/build-venv.sh installs into the venv before the runtime # dependencies: pip itself (replacing the one ensurepip bootstrapped) and the build # backend of the control plane, so `pip install ./controlplane` runs without build # isolation and fetches nothing unhashed. Locked in build-requirements.lock. diff --git a/docs/decisions.md b/docs/decisions.md index 5b20477..8a6cd24 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -254,7 +254,7 @@ radius-and-ad.md § 3 und threat-model.md). **Quelle:** FreeRADIUS-Wiki „Rlm_l --python-version=3.12 --exclude-newer=P7D` erzeugt (nur Fassungen, die mindestens eine Woche auf PyPI liegen; in diesem Fenster fallen kompromittierte Uploads meist auf): `controlplane/requirements.lock` (Laufzeit, aus `pyproject.toml`) und `controlplane/build-requirements.lock` (pip selbst und setuptools, -aus `build-requirements.in`). `build-deb.sh` installiert sie mit `--require-hashes +aus `build-requirements.in`). `packaging/build-venv.sh` installiert sie mit `--require-hashes --only-binary :all: --no-deps`, baut das eigene Paket offline zum Wheel (`--no-index --no-build-isolation`) und installiert es per Namen (kein Build-Pfad in `direct_url.json`), prüft mit `pip check`, entfernt setuptools wieder und bricht ab, wenn `pip freeze --all` diff --git a/docs/install.md b/docs/install.md index 6c29d1f..3962bde 100644 --- a/docs/install.md +++ b/docs/install.md @@ -45,7 +45,7 @@ VER=$(curl -fsSL https://api.github.com/repos/faircomp/linuxmuster-radius/releas | sed -n 's/.*"tag_name": *"v\([^"]*\)".*/\1/p') : "${VER:?konnte die neueste Version nicht von der GitHub-API lesen - VER=7.3.N von Hand setzen}" curl -fsSLo lmnradius.deb \ - https://github.com/faircomp/linuxmuster-radius/releases/download/v${VER}/linuxmuster-radius_${VER}_all.deb + https://github.com/faircomp/linuxmuster-radius/releases/download/v${VER}/linuxmuster-radius_${VER}_amd64.deb sudo apt install -y ./lmnradius.deb lmnradius health # {"status":"ok"} ``` diff --git a/docs/operations.md b/docs/operations.md index 6564f55..f4bebfd 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -18,7 +18,7 @@ Alle `lmnradius`-Befehle sind ein dünner Client der REST-API (FastAPI, gebunden ## Installation (Control-Plane-Tooling) ``` -apt install ./linuxmuster-radius__all.deb # oder aus dem lmn73-apt-Repo +apt install ./linuxmuster-radius__amd64.deb # oder aus dem lmn73-apt-Repo systemctl status linuxmuster-radius # sollte "active" sein ``` @@ -296,7 +296,7 @@ Zu sichern: Frischer Host → laufende Instanzen: ``` -apt install ./linuxmuster-radius__all.deb # Dienst kommt hoch +apt install ./linuxmuster-radius__amd64.deb # Dienst kommt hoch # API-Token behalten: config.yml zurückspielen ODER das neue Token akzeptieren cp -a /secrets/* /etc/linuxmuster-radius/secrets/ # Betriebs-Secrets cp -a /certs/* /etc/linuxmuster-radius/certs/ # EAP-CA + Server-Keys diff --git a/docs/threat-model.md b/docs/threat-model.md index a0d5120..95967a2 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -55,7 +55,7 @@ SPDX-License-Identifier: GPL-3.0-or-later die Domäne (Konto + Record gelöscht) und entfernt das Volume. - **Manipulierte Build-Eingaben (Lieferkette)** — das `.deb` wird auf Schulservern als root installiert; was in den Build-Job gelangt, landet im Paket. Bis 7.3.2 holte - `build-deb.sh` die Python-Abhängigkeiten ungepinnt und ohne Prüfsumme von PyPI: eine + der Paketbau die Python-Abhängigkeiten ungepinnt und ohne Prüfsumme von PyPI: eine kompromittierte oder brechende Fassung wäre ohne Codeänderung ausgeliefert worden, zwei Bauten desselben Tags konnten sich unterscheiden. **Gegenmaßnahme (7.3.3):** das venv entsteht nur aus `controlplane/requirements.lock` und `build-requirements.lock` (Version diff --git a/renovate.json b/renovate.json index 2839df5..f48a385 100644 --- a/renovate.json +++ b/renovate.json @@ -6,7 +6,7 @@ "semanticCommits": "enabled", "docker-compose": { "enabled": true }, "pip-compile": { - "description": "The hash-pinned lockfiles build-deb.sh installs with --require-hashes. Renovate re-runs the command in each header (uv pip compile ... --generate-hashes) inside controlplane/; scripts/check-lockfiles.sh (CI job `lockfile`) proves the result.", + "description": "The hash-pinned lockfiles packaging/build-venv.sh installs with --require-hashes. Renovate re-runs the command in each header (uv pip compile ... --generate-hashes) inside controlplane/; scripts/check-lockfiles.sh (CI job `lockfile`) proves the result.", "managerFilePatterns": ["/^controlplane/(build-)?requirements\\.lock$/"], "lockFileMaintenance": { "description": "The only way the Python lockfiles move: the dependencies in pyproject.toml carry no version (Renovate skips them as unspecified-version) and the transitive ones are indirect (disabled by default). On every run (the workflow runs weekly) Renovate deletes each lockfile and re-runs its header command, i.e. a fresh resolution with fresh hashes, as ONE reviewable PR. The header's --exclude-newer=P7D keeps releases younger than a week out (minimumReleaseAge cannot: lock maintenance has no package timestamps). The schedule lives in the workflow cron only; the default (before 4am on monday) would never match it.", diff --git a/scripts/check-lockfiles.sh b/scripts/check-lockfiles.sh index c15bdc1..b1d8622 100755 --- a/scripts/check-lockfiles.sh +++ b/scripts/check-lockfiles.sh @@ -3,7 +3,7 @@ # SPDX-License-Identifier: GPL-3.0-or-later # # Proves that the hash-pinned lockfiles under controlplane/ still match their sources and -# the target platform. packaging/build-deb.sh installs them with --no-deps, so nothing +# the target platform. packaging/build-venv.sh installs them with --no-deps, so nothing # else would notice a dependency added to pyproject.toml without re-locking. # 1. The header records the canonical command (the one Renovate re-runs on a bump). # --exclude-newer=P7D: only releases that have been on PyPI for at least a week, the @@ -11,7 +11,7 @@ # 2. Re-resolving with that command, preferring the locked versions, yields the same pins # (so a pin younger than seven days fails here). # 3. Resolving strictly for the target -- CPython 3.12 on Ubuntu 24.04 (glibc 2.39, -# x86_64), wheels only, as build-deb.sh installs -- yields the same pins, so every +# x86_64), wheels only, as build-venv.sh installs -- yields the same pins, so every # locked version has a wheel the build can use. (Renovate refuses --python-platform # and --only-binary in the header, hence this second resolution.) # 4. Every hash in a lockfile is one PyPI publishes for that exact version. This needs a From b15a2005e82df06bc9fa3f489ff7aee25c750ead Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Fri, 25 Sep 2026 11:46:15 +0200 Subject: [PATCH 05/29] fix(packaging): read the lockfiles the way pip does, fail the build on any venv drift The cold verification of stage A (linuxmusterDEV work/verification/cold-stage-a.md, F2) built a .deb with a foreign package in its venv: an indented `zzzevil @ file:///...whl#sha256=...` line in controlplane/requirements.lock passed scripts/check-lockfiles.sh, whose pins()/hashes() only read lines starting in column 1, while pip strips the indentation and installs the URL requirement (its #sha256= fragment satisfies --require-hashes). The freeze == lock comparison of the build then crashed with ValueError inside a process substitution, which `set -e` never sees, and diff compared two equally truncated lists. The check was also green for an --extra-index-url line and for a pin whose hashes were removed. scripts/lockfile_gate.py (stdlib only) now does the reading for both: - lint: every byte is printable ASCII or \n (pip splits lines with str.splitlines(), so a CR, form feed or U+2028 inside a comment would start a line pip reads), and every line is empty, a comment, a pin `name==version \` as uv writes it, or a ` --hash=sha256:<64 hex>` line continuing that pin. Everything else fails: indented lines, URL requirements, -i/--index-url, --extra-index-url, -f/--find-links, -e, -r, -c and any other option, markers, a pin without hash, a pin twice. check-lockfiles.sh runs it first and stops there (no uv run on a file that fails it); `check-lockfiles.sh --lint` runs only this step. - pypi: every hash is one PyPI publishes for exactly that version. pip compares only the hash of the file it downloads, so a replaced hash of the sdist or of another platform's wheel would have passed the build. - freeze: `pip freeze --all` (written to a file, its exit status checked) equals the lock pins minus setuptools plus lmnradius, every line a plain name==version pin, compared pin by pin. - closure: every distribution in the venv is required, directly or through others, by lmnradius or pip (markers and extras evaluated in the venv), so an extra pin that carries PyPI's genuine hashes fails too. build-venv.sh runs lint and pypi before pip reads a lockfile and freeze and closure after the install, each with an explicit status check; no pipeline or process substitution is left in the gate. ADR-016 and the threat model describe the hardened gates. --- docs/decisions.md | 13 ++ docs/threat-model.md | 8 +- packaging/build-venv.sh | 33 ++-- scripts/check-lockfiles.sh | 22 +++ scripts/lockfile_gate.py | 310 +++++++++++++++++++++++++++++++++++++ 5 files changed, 374 insertions(+), 12 deletions(-) create mode 100755 scripts/lockfile_gate.py diff --git a/docs/decisions.md b/docs/decisions.md index 8a6cd24..df57516 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -259,6 +259,19 @@ aus `build-requirements.in`). `packaging/build-venv.sh` installiert sie mit `--r --no-build-isolation`) und installiert es per Namen (kein Build-Pfad in `direct_url.json`), prüft mit `pip check`, entfernt setuptools wieder und bricht ab, wenn `pip freeze --all` nicht exakt den Lockfiles entspricht. +Seit 7.3.4 (kalte Prüfung von Stufe A, Befund F2) liest der Bau die Lockfiles nicht mehr +ungeprüft: `scripts/lockfile_gate.py` lässt vor pip nur Zeilen zu, die uv schreibt (leer, +Kommentar, `name==version \`, ` --hash=sha256:<64 hex>`, nur druckbares ASCII) — pip liest +auch eingerückte Zeilen, URL-Anforderungen (`name @ url#sha256=…` erfüllt `--require-hashes`) +und Optionszeilen wie `--extra-index-url`, und `str.splitlines()` trennt auch an CR/FF/U+2028; +eine eingerückte URL-Zeile hatte die alte Prüfung (nur Spalte 1) passiert und landete im +`.deb`. Jede Prüfsumme muss eine sein, die PyPI für genau diese Fassung veröffentlicht (pip +prüft nur die der geladenen Datei). Nach der Installation vergleicht der Bau `pip freeze +--all` Zeile für Zeile mit den Lockfiles (jede Zeile ein schlichtes `name==version`, jeder +Fehler bricht ab, keine Prozess-Substitution mehr, die eine Ausnahme verschluckt) und +verlangt, dass jede installierte Distribution von `lmnradius` oder pip gebraucht wird (ein +zusätzlicher Pin mit echten Hashes fiele sonst durch). `scripts/tests/lock_gates.sh` +(Fast-Tier) hält die Fälle dauerhaft fest. `scripts/check-lockfiles.sh` (CI-Job `lockfile`) beweist, dass die Lockfiles zu ihren Quellen passen (eine Fassung jünger als sieben Tage fällt dabei durch), jede Prüfsumme eine von PyPI für genau diese Fassung ist und jede Fassung ein Wheel für die Zielplattform hat diff --git a/docs/threat-model.md b/docs/threat-model.md index 95967a2..a8bf92b 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -61,7 +61,13 @@ SPDX-License-Identifier: GPL-3.0-or-later entsteht nur aus `controlplane/requirements.lock` und `build-requirements.lock` (Version und sha256 je Datei, nur Fassungen, die mindestens eine Woche auf PyPI liegen, `--require-hashes --only-binary :all: --no-deps`, eigenes Paket offline), danach `pip check`, und der Bau bricht ab, wenn das venv nicht exakt den - Lockfiles entspricht; der CI-Job `lockfile` prüft die Lockfiles gegen + Lockfiles entspricht. **Nachgehärtet (7.3.4):** bis 7.3.3 passierte eine eingerückte + `name @ file:///…whl#sha256=…`-Zeile die Lockfile-Prüfung, und der venv-Abgleich stürzte in + einer Prozess-Substitution ab, ohne den Bau anzuhalten — das fremde Paket lag im `.deb` + (kalte Prüfung Stufe A, F2). Jetzt lassen Prüfung und Bau nur Zeilen zu, die uv schreibt, + der Bau prüft jede Prüfsumme gegen PyPI, vergleicht `pip freeze` fehlerfest und verlangt, + dass jede Distribution im venv gebraucht wird; `scripts/tests/lock_gates.sh` hält die Fälle + fest; der CI-Job `lockfile` prüft die Lockfiles gegen `pyproject.toml`, PyPI und die Zielplattform; neue Fassungen nur per Renovate-PR, den ein Mensch merged (ADR-016). Das Build-Image (`lmndev-runner`, fremde Org, wöchentlich neu gebaut, Build als root) steht per Digest, jede Action per Commit-SHA; das Release diff --git a/packaging/build-venv.sh b/packaging/build-venv.sh index 7566014..84c3083 100755 --- a/packaging/build-venv.sh +++ b/packaging/build-venv.sh @@ -11,8 +11,20 @@ set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" VENV="${1:?usage: build-venv.sh }" +GATE="$ROOT/scripts/lockfile_gate.py" +LOCKS=("$ROOT/controlplane/build-requirements.lock" "$ROOT/controlplane/requirements.lock") WHEELS="$(mktemp -d)" trap 'rm -rf "$WHEELS"' EXIT +die() { echo "build-venv.sh: $*" >&2; exit 1; } + +# Before pip reads a lockfile. (1) Every line is one uv writes: pip would also honour an +# indented URL requirement, an --extra-index-url line and every other option line, and a +# check that reads only some lines lets them through. (2) Every hash is one PyPI publishes +# for that exact version: pip compares only the hash of the file it downloads, so a +# replaced hash of any other file (the sdist, another platform's wheel) would pass pip. +echo "== lockfiles ==" +python3 -I -B "$GATE" lint "${LOCKS[@]}" || die "a lockfile holds a line uv does not write" +python3 -I -B "$GATE" pypi "${LOCKS[@]}" || die "a lockfile hash is not a file PyPI publishes" echo "== venv @ $VENV ==" rm -rf "$VENV" @@ -36,14 +48,13 @@ LOCKED=("$VENV/bin/pip" install --quiet --require-hashes --only-binary :all: --n "$VENV/bin/pip" check # setuptools was only needed to build the control plane; nothing imports it at runtime. "$VENV/bin/pip" uninstall --quiet --yes setuptools -# The venv holds exactly the lockfiles, nothing else (names PEP 503-normalised on both sides). -norm() { - "$VENV/bin/python" -c 'import re, sys -for line in sys.stdin: - name, version = line.split()[0].split("==") - print(re.sub(r"[-_.]+", "-", name).lower() + "==" + version)' | LC_ALL=C sort -} -diff -u <(grep -hE '^[A-Za-z0-9]' "$ROOT/controlplane/requirements.lock" \ - "$ROOT/controlplane/build-requirements.lock" | grep -v '^setuptools==' | norm) \ - <("$VENV/bin/pip" freeze --all --exclude lmnradius | norm) - +# The venv holds exactly the lockfiles plus the control plane, nothing else, and every +# distribution in it is needed by the control plane or pip. Every step writes a file or +# returns its own status, checked right here: no pipeline, no process substitution, so an +# error anywhere (a crash included) fails the build. +FREEZE="$WHEELS/freeze.txt" +"$VENV/bin/pip" freeze --all > "$FREEZE" || die "pip freeze failed" +python3 -I -B "$GATE" freeze --own lmnradius --drop setuptools "$FREEZE" "${LOCKS[@]}" \ + || die "the venv differs from the lockfiles" +"$VENV/bin/python" -I -B "$GATE" closure --root lmnradius --root pip \ + || die "the venv holds a distribution that nothing requires" diff --git a/scripts/check-lockfiles.sh b/scripts/check-lockfiles.sh index b1d8622..3be004b 100755 --- a/scripts/check-lockfiles.sh +++ b/scripts/check-lockfiles.sh @@ -5,6 +5,14 @@ # Proves that the hash-pinned lockfiles under controlplane/ still match their sources and # the target platform. packaging/build-venv.sh installs them with --no-deps, so nothing # else would notice a dependency added to pyproject.toml without re-locking. +# 0. Every line is one pip reads exactly the way uv wrote it: empty, a comment, a +# `name==version \` pin or a ` --hash=sha256:<64 hex>` line continuing it, in +# printable ASCII (scripts/lockfile_gate.py lint). pip also reads indented lines, URL +# requirements and option lines such as --extra-index-url; an indented +# `name @ file:///...whl#sha256=...` passed the column-1 greps this script used up to +# 7.3.3. Nothing else is checked (and no uv runs on the file) until this passes. +# `check-lockfiles.sh --lint [LOCK...]` runs only this step, without uv or network; +# build-venv.sh runs it before pip reads a lockfile. # 1. The header records the canonical command (the one Renovate re-runs on a bump). # --exclude-newer=P7D: only releases that have been on PyPI for at least a week, the # window in which a compromised upload is usually noticed and yanked. @@ -24,9 +32,23 @@ set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +GATE="$ROOT/scripts/lockfile_gate.py" +LOCKS=("$ROOT/controlplane/requirements.lock" "$ROOT/controlplane/build-requirements.lock") + +if [ "${1:-}" = --lint ]; then + shift + [ "$#" -gt 0 ] || set -- "${LOCKS[@]}" + exec python3 -I -B "$GATE" lint "$@" +fi +if ! python3 -I -B "$GATE" lint "${LOCKS[@]}"; then + echo "FAIL lockfile grammar (above); nothing else is checked until it is fixed" + exit 1 +fi + TMP="$(mktemp -d)" trap 'rm -rf "$TMP"' EXIT +# Exact after step 0: a pin starts in column 1, its hashes follow on indented lines. pins() { grep -E '^[A-Za-z0-9]' "$1" | cut -d' ' -f1 | sort; } hashes() { awk '/^[A-Za-z0-9]/ { pin = $1 } /--hash=/ { print pin, $1 }' "$1" | sort; } diff --git a/scripts/lockfile_gate.py b/scripts/lockfile_gate.py new file mode 100755 index 0000000..0ccb59f --- /dev/null +++ b/scripts/lockfile_gate.py @@ -0,0 +1,310 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The gates between controlplane/*.lock and the venv that packaging/build-venv.sh builds. + + lockfile_gate.py lint LOCK... + Every line is one pip reads exactly the way uv wrote it (see below). + lockfile_gate.py pypi LOCK... + Every hash is one PyPI publishes for that exact version, including the hashes of + files pip never downloads (an sdist, another platform's wheel). + lockfile_gate.py freeze [--own NAME] [--drop NAME] FREEZE LOCK... + FREEZE (the output of `pip freeze --all`) holds exactly the pins of the LOCKs, minus + --drop, plus --own; every line is a plain name==version pin. + lockfile_gate.py closure --root NAME... [--path DIR] + Run with the venv's python: every installed distribution is required, directly or + through others (markers and extras evaluated here), by one of the roots. An extra + pin that carries PyPI's genuine hashes passes lint, pypi and freeze, but not this. + +Why lint is a whitelist: pip splits a requirements file with str.splitlines(), which also +breaks lines at \\r, \\v, \\f, \\x1c-\\x1e, \\x85, \\u2028 and \\u2029, ignores leading +whitespace, joins backslash continuations, and honours option lines (--index-url, +--extra-index-url, -f/--find-links, -e, -r, -c, ...) as well as URL requirements +(`name @ url#sha256=...`, whose fragment satisfies --require-hashes). A check that reads only +some lines misses lines pip does read: an indented `name @ file:///...whl#sha256=...` passed +the old check and was installed into the venv (linuxmusterDEV +work/verification/cold-stage-a.md, F2). So every byte must be printable ASCII or \\n, and every +line must be empty, a comment (`#` after optional spaces), a pin `name==version \\` as uv +writes it, or a ` --hash=sha256:<64 hex>` line continuing the pin above it. Anything else +fails. +""" + +from __future__ import annotations + +import argparse +import json +import re +import sys +import time +import urllib.error +import urllib.request +from dataclasses import dataclass, field +from pathlib import Path + +PIN = re.compile(r"([a-z0-9](?:[a-z0-9-]*[a-z0-9])?)==([0-9][0-9A-Za-z.+!]*) \\") +HASH = re.compile(r" --hash=sha256:([0-9a-f]{64})( \\)?") +COMMENT = re.compile(r" *#.*") +FREEZE_PIN = re.compile(r"([A-Za-z0-9][A-Za-z0-9._-]*)==([0-9][0-9A-Za-z.+!]*)") + + +@dataclass +class Pin: + name: str + version: str + line: int + hashes: list[str] = field(default_factory=list) + + def __str__(self) -> str: + return f"{self.name}=={self.version}" + + +def canonical(name: str) -> str: + """PEP 503 normalised project name.""" + return re.sub(r"[-_.]+", "-", name).lower() + + +def ascii_lines(path: str, errors: list[str]) -> list[tuple[int, str | None]]: + """The file split at \\n, as pip would see it only if every byte is printable ASCII. + + A line with any other byte comes back as None after an error was recorded. + """ + data = Path(path).read_bytes() + lines = data.split(b"\n") + if lines[-1] == b"": + lines.pop() + out: list[tuple[int, str | None]] = [] + for n, raw in enumerate(lines, 1): + bad = sorted({b for b in raw if not 0x20 <= b <= 0x7E}) + if bad: + codes = ", ".join(f"0x{b:02x}" for b in bad) + errors.append( + f"{path}:{n}: byte(s) {codes} outside printable ASCII; pip may split or " + f"decode this line differently than it looks: {raw!r}" + ) + out.append((n, None)) + else: + out.append((n, raw.decode("ascii"))) + return out + + +def parse(path: str) -> tuple[list[Pin], list[str]]: + """The pins of a lockfile, and every line that is not one uv writes.""" + errors: list[str] = [] + pins: list[Pin] = [] + seen: dict[str, int] = {} + cont: Pin | None = None # the pin whose next line must be a hash line + for n, line in ascii_lines(path, errors): + if line is None: + cont = None + continue + if cont is not None: + m = HASH.fullmatch(line) + if m is None: + errors.append( + f"{path}:{n}: expected a ' --hash=sha256:<64 hex>' line continuing " + f"{cont.name}=={cont.version} (line {cont.line}): {line!r}" + ) + cont = None + continue + cont.hashes.append(m[1]) + if m[2] is None: + cont = None + continue + if line == "" or COMMENT.fullmatch(line): + continue + m = PIN.fullmatch(line) + if m is None: + errors.append( + f"{path}:{n}: not an empty line, a comment, a 'name==version \\' pin or its " + f"hash line: {line!r}" + ) + continue + if m[1] in seen: + errors.append( + f"{path}:{n}: {m[1]} is pinned twice (first on line {seen[m[1]]})" + ) + seen[m[1]] = n + cont = Pin(m[1], m[2], n) + pins.append(cont) + if cont is not None: + errors.append(f"{path}: ends inside the pin {cont.name}=={cont.version}") + return pins, errors + + +def report(errors: list[str], ok: str) -> int: + for e in errors: + print(f"FAIL {e}", file=sys.stderr) + if errors: + return 1 + print(ok) + return 0 + + +def cmd_lint(args: argparse.Namespace) -> int: + errors: list[str] = [] + counts = [] + for path in args.locks: + pins, errs = parse(path) + errors += errs + counts.append( + f"{path}: {len(pins)} pins, {sum(len(p.hashes) for p in pins)} hashes" + ) + return report(errors, "lint ok: " + "; ".join(counts)) + + +def fetch_json(url: str) -> dict: + """GET a JSON document; transient errors are retried, a 404 is final.""" + for attempt in (1, 2, 3): + try: + with urllib.request.urlopen(url, timeout=30) as resp: + return json.load(resp) + except urllib.error.HTTPError as e: + if e.code == 404 or attempt == 3: + raise + except (urllib.error.URLError, TimeoutError): + if attempt == 3: + raise + time.sleep(attempt * 5) + raise AssertionError("unreachable") + + +def published(pin: Pin) -> set[str]: + """sha256 of every file PyPI lists for exactly this release (yanked ones included).""" + data = fetch_json(f"https://pypi.org/pypi/{pin.name}/{pin.version}/json") + if data["info"]["version"] != pin.version: + raise ValueError(f"PyPI answered for version {data['info']['version']}") + return {u["digests"]["sha256"] for u in data["urls"]} + + +def cmd_pypi(args: argparse.Namespace) -> int: + errors: list[str] = [] + checked = 0 + for path in args.locks: + pins, errs = parse(path) + if errs: + errors += errs + continue + for pin in pins: + # Any answer but the release's file list fails closed. + try: + known = published(pin) + except Exception as e: + errors.append(f"{path}: {pin}: cannot read PyPI: {e}") + continue + for h in pin.hashes: + if h in known: + checked += 1 + else: + errors.append( + f"{path}:{pin.line}: {pin.name}=={pin.version}: sha256:{h} is not a " + "file PyPI publishes for this version" + ) + return report(errors, f"pypi ok: {checked} hashes are files PyPI publishes") + + +def cmd_freeze(args: argparse.Namespace) -> int: + errors: list[str] = [] + want: dict[str, str] = {} + for path in args.locks: + pins, errs = parse(path) + errors += errs + for pin in pins: + if pin.name in want: + errors.append(f"{path}: {pin.name} is pinned in more than one lockfile") + want[pin.name] = pin.version + for name in map(canonical, args.drop): + if want.pop(name, None) is None: + errors.append(f"--drop {name}: not pinned in any lockfile") + have: dict[str, str] = {} + for n, line in ascii_lines(args.freeze, errors): + if line is None: + continue + m = FREEZE_PIN.fullmatch(line) + if m is None: + errors.append( + f"{args.freeze}:{n}: not a plain name==version pin (installed from a URL, a " + f"path or editable?): {line!r}" + ) + continue + name = canonical(m[1]) + if name in have: + errors.append(f"{args.freeze}:{n}: {name} appears twice") + have[name] = m[2] + for name in map(canonical, args.own): + if have.pop(name, None) is None: + errors.append(f"{name} is not installed in the venv") + for name in sorted(set(have) - set(want)): + errors.append(f"in the venv, not in the lockfiles: {name}=={have[name]}") + for name in sorted(set(want) - set(have)): + errors.append(f"in the lockfiles, not in the venv: {name}=={want[name]}") + for name in sorted(n for n in set(want) & set(have) if want[n] != have[n]): + errors.append( + f"{name}: the venv has {have[name]}, the lockfiles pin {want[name]}" + ) + return report( + errors, f"freeze ok: the venv holds exactly the {len(want)} locked pins" + ) + + +def cmd_closure(args: argparse.Namespace) -> int: + from importlib import metadata + + # pip is in every venv this runs in (it is locked in build-requirements.lock). + from pip._vendor.packaging.requirements import Requirement + + errors: list[str] = [] + dists: dict[str, metadata.Distribution] = {} + for d in metadata.distributions(path=args.path or sys.path): + name = canonical(d.metadata["Name"]) + if name in dists: + errors.append(f"{name} is installed twice") + dists[name] = d + seen: set[tuple[str, str]] = set() + todo = [(canonical(r), "") for r in args.root] + while todo: + name, extra = todo.pop() + if (name, extra) in seen: + continue + seen.add((name, extra)) + if name not in dists: + errors.append(f"{name} is required but not installed") + continue + for spec in dists[name].requires or []: + req = Requirement(spec) + if req.marker is None or req.marker.evaluate({"extra": extra}): + dep = canonical(req.name) + todo += [(dep, "")] + [(dep, canonical(e)) for e in req.extras] + reached = {name for name, _ in seen} + for name in sorted(set(dists) - reached): + errors.append( + f"{name}=={dists[name].version} is installed but required by nothing " + f"(roots: {', '.join(args.root)}); an extra pin in a lockfile?" + ) + return report(errors, f"closure ok: all {len(dists)} distributions are required") + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0]) + sub = ap.add_subparsers(dest="cmd", required=True) + p = sub.add_parser("lint") + p.add_argument("locks", nargs="+") + p.set_defaults(func=cmd_lint) + p = sub.add_parser("pypi") + p.add_argument("locks", nargs="+") + p.set_defaults(func=cmd_pypi) + p = sub.add_parser("freeze") + p.add_argument("--own", action="append", default=[]) + p.add_argument("--drop", action="append", default=[]) + p.add_argument("freeze") + p.add_argument("locks", nargs="+") + p.set_defaults(func=cmd_freeze) + p = sub.add_parser("closure") + p.add_argument("--root", action="append", required=True) + p.add_argument("--path", action="append", help="search here instead of sys.path") + p.set_defaults(func=cmd_closure) + args = ap.parse_args() + return int(args.func(args)) + + +if __name__ == "__main__": + sys.exit(main()) From 0ed8b579cb5e9217fc5ddf2d34150de213dc627e Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Fri, 25 Sep 2026 11:46:40 +0200 Subject: [PATCH 06/29] test(packaging): keep the tampered-lockfile cases as a fast-tier regression test scripts/tests/lock_gates.sh runs in the fast job (uv pinned there as in the lockfile job) and in `run.sh quick` when uv is installed. Each case of the cold verification's F2 matrix edits controlplane/requirements.lock in a copy of the tree, and both scripts/check-lockfiles.sh and packaging/build-venv.sh must refuse it for the expected reason, not just exit non-zero: indented ` zzzevil @ file:///...whl#sha256=...` lint (check and build) `--extra-index-url https://evil.example/simple` lint (check and build) every hash of the first pin removed lint (check and build) last hash of the first pin changed (the sdist of check: hashes PyPI does not annotated-doc, a file pip never downloads) publish; build: pypi gate six 1.16.0 added with PyPI's genuine hashes check: pins differ from a fresh resolution; build: closure gate `six==1.16.0` without hash lint (check and build) Plus the gates of scripts/lockfile_gate.py one by one: lint against URL requirements in column 1, -i/--index-url, -f/--find-links, -e, -r, -c, --trusted-host, indented options, ${VAR}, requirements hidden behind CR, form feed or U+2028 in a comment, tab, NUL, uppercase names, markers, malformed hashes, orphan hashes, duplicate pins (and that empty lines and comments stay allowed); pypi against a changed first hash and an unknown version; freeze against URL and editable installs, extra, missing and different pins, a leftover setuptools, a missing lmnradius and a CR; closure against an extra distribution, one needed only by an unrequested extra and a missing one. The script never skips; a missing uv fails it. LOCK_GATES_DEB=1, run in the build image, also runs the whole `make deb` on each tampered tree and requires it to fail without leaving a .deb. --- .github/workflows/ci.yml | 6 + docs/test-strategy.md | 9 ++ scripts/tests/lock_gates.sh | 259 ++++++++++++++++++++++++++++++++++++ scripts/tests/run.sh | 3 + 4 files changed, 277 insertions(+) create mode 100755 scripts/tests/lock_gates.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d0fa1cc..12d65c0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,6 +62,7 @@ jobs: reuse==6.2.0 \ pytest==9.1.1 \ types-PyYAML==6.0.12.20260906 \ + uv==0.12.18 \ pytest-asyncio pip install --require-hashes --only-binary :all: --no-deps -r controlplane/requirements.lock pip install --no-deps ./controlplane @@ -74,6 +75,11 @@ jobs: run: mypy --config-file controlplane/pyproject.toml controlplane/lmnradius - name: pytest run: pytest -q controlplane/tests + # Tampered lockfiles (an indented URL requirement, --extra-index-url, removed or changed + # hashes, an extra pin, a pin without hash, ...) must fail scripts/check-lockfiles.sh AND + # packaging/build-venv.sh, for the expected reason. Needs uv and PyPI; never skips. + - name: Lockfile gates refuse tampered lockfiles + run: bash scripts/tests/lock_gates.sh - name: shellcheck run: | sudo apt-get update -qq && sudo apt-get install -y -qq shellcheck diff --git a/docs/test-strategy.md b/docs/test-strategy.md index c2f97e0..8164436 100644 --- a/docs/test-strategy.md +++ b/docs/test-strategy.md @@ -17,6 +17,15 @@ SPDX-License-Identifier: GPL-3.0-or-later Pins passen zu `pyproject.toml`/`build-requirements.in`, jede Prüfsumme stammt von PyPI, jede Fassung hat ein Wheel für CPython 3.12/glibc 2.39/x86_64. `pytest` und `mypy` laufen in CI gegen die gelockten Fassungen. +- Lock-Tore: `bash scripts/tests/lock_gates.sh` (CI-Job `fast`; braucht `uv` und PyPI, überspringt + nie) — manipulierte Lockfiles müssen **sowohl** `check-lockfiles.sh` **als auch** + `packaging/build-venv.sh` (also den Paketbau) mit dem erwarteten Grund scheitern lassen: + eingerückte URL-Zeile (` zzzevil @ file:///…#sha256=…`), `--extra-index-url`, entfernte + Hashes eines Pins, geänderter Hash (auch der eines nie geladenen sdist), zusätzlicher Pin mit + echten PyPI-Hashes, Pin ohne Hash; dazu je Tor (`scripts/lockfile_gate.py lint|pypi|freeze| + closure`) die Varianten, die pip anders liest als sie aussehen (`-i/-f/-e/-r/-c`, CR/FF/U+2028 + in Kommentaren, Tab, NUL, Marker, Großschreibung, …). Mit `LOCK_GATES_DEB=1` im Build-Image + zusätzlich der ganze `make deb` je Fall (muss ohne `.deb` scheitern). ## Heavy-Tier (crabbox, Docker) diff --git a/scripts/tests/lock_gates.sh b/scripts/tests/lock_gates.sh new file mode 100755 index 0000000..49d4788 --- /dev/null +++ b/scripts/tests/lock_gates.sh @@ -0,0 +1,259 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Regression test for the gates in front of the shipped venv (linuxmusterDEV +# work/verification/cold-stage-a.md, finding F2). Up to 7.3.3 an indented +# zzzevil @ file:///...whl#sha256=... +# line in controlplane/requirements.lock passed scripts/check-lockfiles.sh (it read only +# lines starting in column 1, pip reads indented ones too), and the freeze == lock check of +# the build crashed inside a process substitution that `set -e` never saw: `make deb` +# shipped the foreign package. Now every tampered lockfile of the matrix below must be +# refused, for the expected reason, by BOTH +# check scripts/check-lockfiles.sh (the CI job `lockfile`), and +# build packaging/build-venv.sh, which debian/rules runs: its failure fails `make deb`. +# Plus cases for each gate of scripts/lockfile_gate.py on its own (lint, pypi, freeze, +# closure), including the variants pip reads that the old check did not. +# Needs uv (the version pinned in ci.yml), python3 >= 3.12 with venv and pip, and PyPI. It +# never skips: a missing tool fails. LOCK_GATES_VERBOSE=1 prints every refusal's reason. +# LOCK_GATES_DEB=1 also runs the whole `make deb` (dpkg-buildpackage) on each tampered tree +# and requires it to fail without a .deb; run that inside the build image, as a user who +# may write the checkout, after `apt-get build-dep .` (the command is in the Makefile). +set -uo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +GATE="$ROOT/scripts/lockfile_gate.py" +LOCK="$ROOT/controlplane/requirements.lock" +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT +PASS=0 +FAIL=0 +H64="$(printf 'e%.0s' $(seq 64))" +EVIL_URL="file:///tmp/evil/zzzevil-1.0-py3-none-any.whl#sha256=$H64" + +for tool in uv python3; do + command -v "$tool" > /dev/null || { echo "lock_gates.sh: $tool is required"; exit 1; } +done +python3 -c 'import sys, venv, pip; sys.exit(sys.version_info < (3, 12))' \ + || { echo "lock_gates.sh: python3 >= 3.12 with venv and pip is required"; exit 1; } + +# expect