diff --git a/.claude/skills/test/SKILL.md b/.claude/skills/test/SKILL.md index 93f9c31..3e416b3 100644 --- a/.claude/skills/test/SKILL.md +++ b/.claude/skills/test/SKILL.md @@ -30,7 +30,7 @@ config). The `CRABBOX_PROXMOX_TOKEN_SECRET` lives **only** in the gitignored from `deploy/e2e/dc` and `deploy/e2e/client` by compose, not pulled): `crabbox run --id -- 'bash scripts/tests/crabbox_bootstrap.sh'` 3. **Run** the aggregator — one command, dependency-gated: - - `crabbox run --id -- 'bash scripts/tests/run.sh quick'` (ruff + mypy + pytest + shellcheck + reuse) + - `crabbox run --id -- 'bash scripts/tests/run.sh quick'` (lock gate first, stops if it fails; then ruff + mypy + pytest + shellcheck + reuse + lock regression test) - `crabbox run --id -- 'LMNRADIUS_ALLOW_REAL=1 bash scripts/tests/run.sh e2e'` (docker-compose winbind/EAP E2E) - `crabbox run --id -- 'LMNRADIUS_ALLOW_REAL=1 bash scripts/tests/run.sh all'` (quick + e2e) 4. **Inspect** on failure: `crabbox ssh --id ` (live), or read the newest diff --git a/.github/workflows/build-image.yml b/.github/workflows/build-image.yml index 42b84d1..1441e30 100644 --- a/.github/workflows/build-image.yml +++ b/.github/workflows/build-image.yml @@ -1,8 +1,9 @@ # SPDX-FileCopyrightText: Kevin Stenzel # SPDX-License-Identifier: GPL-3.0-or-later # Build the data-plane FreeRADIUS image and push it to GHCR by tag + immutable digest. -# Renovate then pins that digest in the deployment; a human merges the bump. -# Every action is pinned by full commit SHA (`# vN` names the tag); Renovate bumps both. +# Pin that digest as DEFAULT_IMAGE (controlplane/lmnradius/models.py) in a reviewed PR; while +# Renovate is disabled (Kevin, 2026-09-25) that is done by hand. +# Every action is pinned by full commit SHA (`# vN` names the tag); raised by hand as well. name: build-image on: @@ -49,4 +50,4 @@ jobs: run: | echo "Published ghcr.io/${{ github.repository_owner }}/linuxmuster-radius" echo "Digest: ${{ steps.build.outputs.digest }}" - echo "Pin this digest via Renovate (docker:pinDigests)." + echo "Pin this digest as DEFAULT_IMAGE in controlplane/lmnradius/models.py (by hand while Renovate is disabled)." diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d0fa1cc..7711a7b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,11 +1,13 @@ # SPDX-FileCopyrightText: Kevin Stenzel # SPDX-License-Identifier: GPL-3.0-or-later # -# From linuxmusterDEV/templates/ci.yml. Three stages on every push/PR: the fast tier -# (lint/type/unit + shell + license compliance), the package build in the same -# container upstream CI uses (proves it builds on the target Ubuntu/Python), and an -# install smoke on ubuntu-24.04. The heavy winbind/EAP FreeRADIUS E2E runs on crabbox, -# not in GitHub CI. +# From linuxmusterDEV/templates/ci.yml. On every push to main and every PR: the fast tier +# (lint/type/unit, the lockfile gate regression test, shell, license compliance), the +# lockfile check, the package build with dpkg-buildpackage in the same container upstream CI +# uses (proves it builds on the target Ubuntu/Python) plus lintian, the file-tree gate against +# the newest release, an install smoke and an upgrade smoke on ubuntu-24.04. release.yml runs +# the same gates on a tag. The heavy winbind/EAP FreeRADIUS E2E runs on crabbox, not in +# GitHub CI. # # Supply chain (stage A, linuxmusterDEV work/plans/paketarchiv.md §2): every input of the # build is pinned to an immutable reference, because a released .deb vouches for everything @@ -13,10 +15,13 @@ # * Python dependencies from hash-pinned lockfiles (controlplane/*.lock, job `lockfile`). # * Build image by digest. ghcr.io/linuxmuster/lmndev-runner: is a mutable tag of # another org, rebuilt every week, and the build runs as root in it; `:@sha256:` -# pulls exactly that image (the digest wins, the tag only tells Renovate which tag's digest -# to follow). ci.yml, release.yml and the Makefile carry the SAME digests, or CI proves a +# pulls exactly that image (the digest wins, the tag only names the line whose digest is +# pinned). ci.yml, release.yml and the Makefile carry the SAME digests, or CI proves a # different build than the one that is released. # * Every action by full commit SHA with a `# vN` comment: a tag can be moved, a SHA cannot. +# Pins and locks are raised by hand: the Renovate workflow is disabled (Kevin, 2026-09-25) +# until Renovate is re-enabled with a GitHub App (renovate.json and renovate.yml stay for that +# day). Raise a digest in ci.yml, release.yml and the Makefile in the same commit. name: ci on: @@ -45,16 +50,27 @@ jobs: - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 with: python-version: "3.12" # = Ubuntu 24.04 / lmn73 + # K1/R2: the lock gate is the first step, before anything from a lockfile is installed. + # It verifies all three lockfiles (grammar, uv lock == the published uv of + # uv-requirements.in, every hash published by PyPI, pins == closure of the declared + # inputs) with /usr/bin/python3 -I and a uv it installs itself from the verified uv lock + # into an isolated venv; it ignores PATH (setup-python's bin/ is first on it), VIRTUAL_ENV, + # PYTHON*, UV_* and PIP_*. A planted package in any lock stops the job here, so it is + # never installed into the interpreter below whose bin/ is on PATH. + # scripts/tests/lock_gates.sh (R2) replays this step and the next word for word. + - name: Lock gate (every lockfile, before anything from one is installed) + run: bash scripts/check-lockfiles.sh # The gate tools are PINNED on purpose: an unpinned `pip install ruff` picks up # whatever released last, and a linter that widens its default rule set turns the # pipeline red without a single line of our code changing (exactly what happened - # on 2026-08-04). Pinned == the developer's local result == CI's result. Renovate - # proposes bumps as PRs, so upgrading stays a deliberate, reviewed step. + # on 2026-08-04). Pinned == the developer's local result == CI's result. The pins are + # raised by hand in a reviewed PR, so upgrading stays a deliberate step. # The runtime dependencies come from the hash-pinned lockfile the .deb is built from, - # installed AFTER the tools so no tool can move them: pytest and mypy see exactly - # the versions that ship (and the ones a Renovate lockfile bump proposes), not - # whatever PyPI serves today. pip check: the tools still fit the locked versions. - - name: Install control-plane (locked dependencies) + tools + # verified by the step above, installed AFTER the tools so no tool can move them: + # pytest and mypy see exactly the versions that ship (and the ones a lockfile bump + # proposes), not whatever PyPI serves today. pip check: the tools still fit the locked + # versions. uv is not installed here: the gate brings its own. + - name: Install tools + control plane (locked dependencies) run: | pip install \ ruff==0.15.21 \ @@ -74,30 +90,43 @@ 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, a planted package in any lock, ...) must fail + # scripts/check-lockfiles.sh AND packaging/build-venv.sh, for the expected reason, without + # running any of the planted code, also under a poisoned caller environment (R1) and + # through the lock steps of ci.yml/release.yml (R2). Needs PyPI; never skips. + - name: Lockfile gates refuse tampered lockfiles + run: bash scripts/tests/lock_gates.sh + # debian/venv-relocate has no .py extension, so `ruff check .` does not see it. + - name: ruff (debian/venv-relocate) + run: | + ruff check --line-length 100 debian/venv-relocate + ruff format --check --line-length 100 debian/venv-relocate - name: shellcheck run: | sudo apt-get update -qq && sudo apt-get install -y -qq shellcheck shellcheck --severity=warning \ - image/*.sh scripts/*.sh packaging/*.sh \ - packaging/debian/postinst packaging/debian/prerm packaging/debian/postrm + image/*.sh scripts/*.sh scripts/tests/*.sh packaging/*.sh \ + debian/postinst debian/prerm debian/postrm - name: reuse (license compliance) run: reuse lint - # build-deb.sh installs the lockfiles with --no-deps, so only this job notices a - # dependency added to pyproject.toml without re-locking, a hand-edited pin or hash, or a - # locked version without a wheel for the target (CPython 3.12, glibc 2.39, x86_64). + # The lock gate on its own: it notices a malformed lockfile, a uv lock that is not exactly + # the published uv of uv-requirements.in, a lock that no longer matches pyproject.toml or + # build-requirements.in (an extra or missing pin), a pin younger than seven days, a hash PyPI + # does not publish, or a locked version without a wheel for the target (CPython 3.12, + # glibc 2.39, x86_64). The fast tier and the build (packaging/build-venv.sh) run the same + # gate first; release.yml carries this job character for character. lockfile: runs-on: ubuntu-24.04 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 - with: - python-version: "3.12" + # Nothing is installed before or around it (R2): the gate verifies the uv lock with the + # stdlib, installs uv from it into an isolated venv of its own and calls it by absolute + # path, with /usr/bin/python3 -I (the runner's Python 3.12), a fixed PATH and no + # UV_*/PIP_* variables. - name: Lockfiles match their sources, PyPI and the target platform - run: | - pip install \ - uv==0.12.18 - bash scripts/check-lockfiles.sh + run: bash scripts/check-lockfiles.sh resolve: runs-on: ubuntu-latest @@ -109,7 +138,8 @@ jobs: - id: image run: | DIST=$(dpkg-parsechangelog -S Distribution); NUM="${DIST#lmn}" - # By digest, never by tag alone (see the header); Renovate proposes the bumps. + # By digest, never by tag alone (see the header); raise both lines here and in + # release.yml together. if [ "${NUM:-0}" -ge 74 ] 2>/dev/null; then IMG=ghcr.io/linuxmuster/lmndev-runner:latest@sha256:d735e6ccc6fd9df71b2552b06ac6f5cb4bf2d03f40e14bafe47213325b7b801b else @@ -126,19 +156,187 @@ jobs: options: --user root steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - - name: Build package (make deb wraps packaging/build-deb.sh) + - name: Build package (make deb = dpkg-buildpackage; build deps via build-dep) run: | - # No debian/control at the root yet (that is the debian/ conversion PR), so - # install what build-deb.sh needs by hand instead of `apt-get build-dep`. - apt-get update -qq && apt-get install -y -qq python3-venv + apt-get update -qq && apt-get build-dep -y -qq . + # make-deb.sh keeps git's ownership guard on. The runner created the workspace + # directory, the container builds as root: trust exactly this checkout (its + # .git/config was written by actions/checkout, not by the pull request), never '*'. + git config --global --add safe.directory "$GITHUB_WORKSPACE" make deb - mkdir -p output && mv ./linuxmuster-radius_*.deb output/ + # dpkg-buildpackage writes one level above the source tree. The .dsc and the + # source tarball go along because the .changes lists them with their checksums. + mkdir -p output && mv ../*.deb ../*.changes ../*.buildinfo ../*.dsc ../*.tar.xz output/ + dpkg-deb -I output/*.deb + # DEBIAN/md5sums must cover every shipped file, or `dpkg --verify` is a no-op. + dpkg-deb --ctrl-tarfile output/*.deb | tar -tf - | grep -qx './md5sums' + test "$(dpkg-deb -c output/*.deb | grep -c '^-')" = "$(dpkg-deb --ctrl-tarfile output/*.deb | tar -xOf - ./md5sums | wc -l)" + echo "md5sums: $(dpkg-deb --ctrl-tarfile output/*.deb | tar -xOf - ./md5sums | wc -l) files" + - name: Lintian (the .deb only) + run: | + # Never lint the .changes: `lmn73` is not a distribution lintian knows, so it would + # fail every build with E: bad-distribution-in-changes-file. + lintian --fail-on error output/*.deb - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: packages path: output/ if-no-files-found: error + # The lock gates through a real `make deb` in the pinned image, as the build user. Proves K1 + # end to end: a wheel pinned in the build lock, the runtime lock, both, or the uv lock, whose + # distribution ships executable bin/ scripts and a marker-writing .pth -- with a real name + # and hash, its "publication" simulated only in the throwaway copy -- is rejected BEFORE + # anything from a lock is installed, so `make deb` fails, ships no .deb, and none of its code + # runs (the marker stays absent), also under a poisoned caller environment (R1). The fast tier + # runs the same script without LOCK_GATES_DEB. Then scripts/tests/make_deb_checks.sh: a + # complete `make deb` of a dirty git checkout under the same poisoned environment (R1, R3, + # R4): it builds, warns about every uncommitted difference, packs exactly the tracked files + # with fixed modes and symlinks, runs nothing configured in .git, and refuses a worktree + # whose repository git cannot reach. + lock-gates-build: + needs: resolve + runs-on: ubuntu-latest + container: + image: ${{ needs.resolve.outputs.image }} + options: --user root + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + # The lock gate first (cold verification r3, F1): the tests below copy the committed + # lockfiles into their cases, so they run only if these pass. build-dep installs + # python3-venv from the Ubuntu archive (nothing from a lockfile); the gate installs its + # own uv from the verified uv lock. + - name: Lock gate (every lockfile, before anything from one is installed) + run: | + apt-get update -qq && apt-get build-dep -y -qq . + chown -R build:build . + runuser -u build -- env HOME=/home/build bash scripts/check-lockfiles.sh + - name: Every manipulated lock stops make deb, and no lock wheel runs first + run: | + runuser -u build -- env HOME=/home/build \ + LOCK_GATES_DEB=1 LOCK_GATES_VERBOSE=1 bash scripts/tests/lock_gates.sh + - name: make deb of a dirty checkout under a poisoned environment (R1, R3, R4) + run: | + # As root in a checkout that belongs to `build`: git's ownership guard refuses it and + # nothing its .git configures runs as root (R3). Then the dirty build as `build`. + bash scripts/tests/make_deb_checks.sh guard build + runuser -u build -- env HOME=/home/build bash scripts/tests/make_deb_checks.sh + + # The one failure mode of a packaging change that no other job would notice: a module of + # the control plane, the unit or the CLI link quietly falls out of the package, or a mode + # changes (dh_fixperms would make the wheels' .so files 0644), because debian/rules places + # things differently than the old hand-rolled dpkg-deb build. It would only show up on a + # school server. So every build is compared, path by path, against the newest published + # release: a path that disappears or changes mode/owner fails the build. Two venv rules: + # the own lmnradius-.dist-info is compared under a fixed name, and a third-party + # path under site-packages that disappears (a lock bump) is reported, not failed -- the + # completeness of those is proven by `debian/venv-relocate --verify` (RECORD) and the + # freeze == lock gates of the build. This gate is permanent, and release.yml carries the + # same job (the run blocks are character-identical). + file-tree: + needs: package + runs-on: ubuntu-latest # GitHub-hosted: gh is installed here, not in the container + permissions: + contents: read + steps: + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: packages + path: packages/ + - name: Fetch the newest published release + id: prev + env: + GH_TOKEN: ${{ github.token }} + run: | + set -eu + mkdir -p previous + # Prefer the newest real release, fall back to the newest prerelease. Skipping is + # only legitimate when the repo has NO release at all: this gate stands between a + # silently shrunk package and a school server. + tag=$(gh release list --repo "$GITHUB_REPOSITORY" --limit 30 \ + --json tagName,isDraft,isPrerelease \ + --jq '[.[] | select(.isDraft == false and .isPrerelease == false)][0].tagName // ""') + if [ -z "$tag" ]; then + tag=$(gh release list --repo "$GITHUB_REPOSITORY" --limit 30 \ + --json tagName,isDraft --jq '[.[] | select(.isDraft == false)][0].tagName // ""') + [ -n "$tag" ] && echo "::warning::no full release yet, comparing against prerelease $tag" + fi + if [ -z "$tag" ]; then + if [ "$(gh release list --repo "$GITHUB_REPOSITORY" --limit 1 --json tagName --jq 'length')" != "0" ]; then + echo "::error::releases exist but none could be selected - refusing to skip"; exit 1 + fi + echo "skip=1" >> "$GITHUB_OUTPUT" + echo "::notice::first release of this package, nothing to compare against" + exit 0 + fi + for i in 1 2 3; do + gh release download "$tag" --repo "$GITHUB_REPOSITORY" --pattern '*.deb' --dir previous && break + echo "download attempt $i failed, retrying"; sleep 10 + done + test -n "$(ls previous/*.deb 2>/dev/null)" + echo "tag=$tag" >> "$GITHUB_OUTPUT" + - name: Compare the file tree with the released package + if: steps.prev.outputs.skip != '1' + env: + PREV_TAG: ${{ steps.prev.outputs.tag }} + run: | + set -euo pipefail # without pipefail `tee` would swallow the exit code + # mode owner path, sorted. Directories are compared too, so an emptied or lost + # directory cannot go unnoticed. A symlink prints "path -> target"; the target is + # carried along, so a retargeted link (/usr/bin/lmnradius, the venv's python and + # lib64 links) is drift too. + norm() { dpkg-deb -c "$1" | awk '{t = ($7 == "->" ? " " $7 " " $8 : ""); print $1, $2, $6 t}' | LC_ALL=C sort; } + norm previous/*.deb > old.txt + norm packages/*.deb > new.txt + python3 - old.txt new.txt linuxmuster-radius lmnradius "$PREV_TAG" <<'PY' | tee -a "$GITHUB_STEP_SUMMARY" + import re + import sys + + old_f, new_f, PKG, OWN, TAG = sys.argv[1:6] + SP = rf"opt/{PKG}/venv/lib/python3\.12/site-packages/" + # 1. the own dist-info carries the version: compare it under a fixed name. + DIST = re.compile(rf"^({SP}{OWN})-[^/]+\.dist-info") + # 2. third-party distributions come and go with every lock bump; their completeness + # is proven by `debian/venv-relocate --verify` (RECORD) and the freeze == lock + # gates of the build, so a path of theirs that disappears is reported, not failed. + # Mode/owner is checked everywhere. + THIRD = re.compile(rf"^{SP}(?!{OWN}[/-])") + # Paths that may legitimately disappear. Add one ONLY together with the changelog + # sentence that explains it to admins. + ALLOW_GONE = set() + + + def read(name): + rows = {} + for line in open(name): + mode, owner, path = line.rstrip("\n").split(" ", 2) + if path == "./": # the package root: dpkg never applies its mode + continue + rows[DIST.sub(r"\1-VERSION.dist-info", path.removeprefix("./"))] = (mode, owner) + return rows + + + old, new = read(old_f), read(new_f) + gone = sorted(set(old) - set(new)) + added = sorted(set(new) - set(old)) + changed = sorted(p for p in set(old) & set(new) if old[p] != new[p]) + strict_gone = [p for p in gone if not THIRD.match(p) and p not in ALLOW_GONE] + print(f"## File tree vs {TAG}\n") + print(f"- released: {len(old)} entries, built: {len(new)} entries") + print(f"- third-party venv paths: {sum(1 for p in gone if THIRD.match(p))} gone, " + f"{sum(1 for p in added if THIRD.match(p))} added (lock changes, see RECORD check)") + for p in added: + if not THIRD.match(p): + print(f"- added: `{p}`") + for p in strict_gone: + print(f"::error::file lost from the package: {p}") + for p in changed: + print(f"::error::mode or owner changed: {p}: {old[p]} -> {new[p]}") + if strict_gone or changed: + sys.exit(1) + print("\nfile tree: nothing lost, no mode or owner change") + PY + install-smoke: needs: package runs-on: ubuntu-24.04 # the target OS; the venv python must match @@ -353,8 +551,14 @@ jobs: # thing that restarts it is `systemctl try-restart` inside the postinst's # `if [ -n "${2:-}" ]` branch, which exists only when dpkg passes an old version. grep -qE 'Unpacking linuxmuster-radius \([^)]+\) over \([^)]+\)' upgrade.log - # dpkg's own record of the action, independent of apt's wording. - grep -q ' upgrade linuxmuster-radius:' /var/log/dpkg.log + # dpkg's own record of the action, independent of apt's wording: exactly this + # step, from the released version to the built one (a reinstall of an equal version + # is logged as an upgrade too), and never a downgrade (--allow-downgrades above + # would let one through, and dpkg logs it as "upgrade" as well). + old_ver="$(dpkg-deb -f previous/*.deb Version)" + new_ver="$(dpkg-deb -f packages/*.deb Version)" + dpkg --compare-versions "$new_ver" ge "$old_ver" + grep -E " upgrade linuxmuster-radius:(all|amd64) ${old_ver//./\\.} ${new_ver//./\\.}\$" /var/log/dpkg.log after_pid="$(systemctl show -p MainPID --value linuxmuster-radius.service)" echo "postinst upgrade branch ran: MainPID $before_pid -> $after_pid" test "$before_pid" != "$after_pid" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 87aae7a..2b4e7eb 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,8 +12,8 @@ # * Python dependencies from hash-pinned lockfiles (controlplane/*.lock, checked by ci.yml). # * Build image by digest. ghcr.io/linuxmuster/lmndev-runner: is a mutable tag of # another org, rebuilt every week, and the build runs as root in it; `:@sha256:` -# pulls exactly that image (the digest wins, the tag only tells Renovate which tag's digest -# to follow). ci.yml, release.yml and the Makefile carry the SAME digests, or CI proves a +# pulls exactly that image (the digest wins, the tag only names the line whose digest is +# pinned). ci.yml, release.yml and the Makefile carry the SAME digests, or CI proves a # different build than the one that is released. # * Every action by full commit SHA with a `# vN` comment: a tag can be moved, a SHA cannot. # * No third-party release action next to `contents: write`: the release job uses the gh CLI @@ -24,6 +24,17 @@ # release that is published first cannot receive its assets afterwards # (https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/immutable-releases). # A failed run leaves only a draft, which a re-run of the job completes. +# * Immutable or not at all: after publishing, the job re-reads the release and fails unless +# `immutable` is true (readable with GITHUB_TOKEN). The setting only acts on releases published +# after it was switched on, so without this check a release can come out mutable while the run +# is green. Checking the setting itself before publishing needs the Administration permission, +# which no GITHUB_TOKEN can hold (HTTP 403 even with `permissions: write-all`). With the +# OPTIONAL secret IMMUTABLE_CHECK_TOKEN (a fine-grained token for this repo with only +# "Administration: Read-only") the job also refuses to publish while the setting is off; +# without it, it says so in a notice and relies on the check after publishing. +# Pins and locks are raised by hand: the Renovate workflow is disabled (Kevin, 2026-09-25) +# until Renovate is re-enabled with a GitHub App. Raise a digest here, in ci.yml and in the +# Makefile in the same commit. name: release on: @@ -51,7 +62,8 @@ jobs: TAGVER="${GITHUB_REF_NAME#v}"; TAGVER="${TAGVER//-rc/~rc}" # v7.3.1-rc1 -> 7.3.1~rc1 if [ "$GITHUB_REF_TYPE" = tag ] && [ "$TAGVER" != "$VERSION" ]; then echo "::error::tag $GITHUB_REF_NAME does not match debian/changelog version $VERSION"; exit 1; fi - # By digest, never by tag alone (see the header); Renovate proposes the bumps. + # By digest, never by tag alone (see the header); raise both lines here and in + # ci.yml together. if [ "${NUM:-0}" -ge 74 ] 2>/dev/null; then IMG=ghcr.io/linuxmuster/lmndev-runner:latest@sha256:d735e6ccc6fd9df71b2552b06ac6f5cb4bf2d03f40e14bafe47213325b7b801b else @@ -59,6 +71,21 @@ jobs: fi echo "image=$IMG" >> "$GITHUB_OUTPUT"; echo "version=$VERSION" >> "$GITHUB_OUTPUT" + # The lock gate (scripts/check-lockfiles.sh) as a release gate of its own (release needs it), + # character for character the `lockfile` job of ci.yml: a tag cannot be published while a + # lock drifted from its inputs (cold verification of the debian umbau, finding 5). The build + # runs the same gate first (packaging/build-venv.sh); nothing is installed around it (R2). + lockfile: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + # Nothing is installed before or around it (R2): the gate verifies the uv lock with the + # stdlib, installs uv from it into an isolated venv of its own and calls it by absolute + # path, with /usr/bin/python3 -I (the runner's Python 3.12), a fixed PATH and no + # UV_*/PIP_* variables. + - name: Lockfiles match their sources, PyPI and the target platform + run: bash scripts/check-lockfiles.sh + build: needs: gate runs-on: ubuntu-latest @@ -67,19 +94,148 @@ jobs: options: --user root steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - - name: Build package (make deb wraps packaging/build-deb.sh) + - name: Build package (make deb = dpkg-buildpackage; build deps via build-dep) run: | - # No debian/control at the root yet (that is the debian/ conversion PR), so - # install what build-deb.sh needs by hand instead of `apt-get build-dep`. - apt-get update -qq && apt-get install -y -qq python3-venv + apt-get update -qq && apt-get build-dep -y -qq . + # make-deb.sh keeps git's ownership guard on. The runner created the workspace + # directory, the container builds as root: trust exactly this checkout (its + # .git/config was written by actions/checkout, not by the pull request), never '*'. + git config --global --add safe.directory "$GITHUB_WORKSPACE" make deb - mkdir -p output && mv ./linuxmuster-radius_*.deb output/ + # dpkg-buildpackage writes one level above the source tree. The .dsc and the + # source tarball go along because the .changes lists them with their checksums. + mkdir -p output && mv ../*.deb ../*.changes ../*.buildinfo ../*.dsc ../*.tar.xz output/ + dpkg-deb -I output/*.deb + # DEBIAN/md5sums must cover every shipped file, or `dpkg --verify` is a no-op. + dpkg-deb --ctrl-tarfile output/*.deb | tar -tf - | grep -qx './md5sums' + test "$(dpkg-deb -c output/*.deb | grep -c '^-')" = "$(dpkg-deb --ctrl-tarfile output/*.deb | tar -xOf - ./md5sums | wc -l)" + echo "md5sums: $(dpkg-deb --ctrl-tarfile output/*.deb | tar -xOf - ./md5sums | wc -l) files" + - name: Lintian (the .deb only) + run: | + # Never lint the .changes: `lmn73` is not a distribution lintian knows, so it would + # fail every build with E: bad-distribution-in-changes-file. + lintian --fail-on error output/*.deb - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: packages path: output/ if-no-files-found: error + # The one failure mode of a packaging change that no other job would notice: a module of + # the control plane, the unit or the CLI link quietly falls out of the package, or a mode + # changes (dh_fixperms would make the wheels' .so files 0644), because debian/rules places + # things differently than the old hand-rolled dpkg-deb build. It would only show up on a + # school server. So every build is compared, path by path, against the newest published + # release: a path that disappears or changes mode/owner fails the build. Two venv rules: + # the own lmnradius-.dist-info is compared under a fixed name, and a third-party + # path under site-packages that disappears (a lock bump) is reported, not failed -- the + # completeness of those is proven by `debian/venv-relocate --verify` (RECORD) and the + # freeze == lock gates of the build. This gate is permanent, and release.yml carries the + # same job (the run blocks are character-identical). + file-tree: + needs: build + runs-on: ubuntu-latest # GitHub-hosted: gh is installed here, not in the container + permissions: + contents: read + steps: + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: packages + path: packages/ + - name: Fetch the newest published release + id: prev + env: + GH_TOKEN: ${{ github.token }} + run: | + set -eu + mkdir -p previous + # Prefer the newest real release, fall back to the newest prerelease. Skipping is + # only legitimate when the repo has NO release at all: this gate stands between a + # silently shrunk package and a school server. + tag=$(gh release list --repo "$GITHUB_REPOSITORY" --limit 30 \ + --json tagName,isDraft,isPrerelease \ + --jq '[.[] | select(.isDraft == false and .isPrerelease == false)][0].tagName // ""') + if [ -z "$tag" ]; then + tag=$(gh release list --repo "$GITHUB_REPOSITORY" --limit 30 \ + --json tagName,isDraft --jq '[.[] | select(.isDraft == false)][0].tagName // ""') + [ -n "$tag" ] && echo "::warning::no full release yet, comparing against prerelease $tag" + fi + if [ -z "$tag" ]; then + if [ "$(gh release list --repo "$GITHUB_REPOSITORY" --limit 1 --json tagName --jq 'length')" != "0" ]; then + echo "::error::releases exist but none could be selected - refusing to skip"; exit 1 + fi + echo "skip=1" >> "$GITHUB_OUTPUT" + echo "::notice::first release of this package, nothing to compare against" + exit 0 + fi + for i in 1 2 3; do + gh release download "$tag" --repo "$GITHUB_REPOSITORY" --pattern '*.deb' --dir previous && break + echo "download attempt $i failed, retrying"; sleep 10 + done + test -n "$(ls previous/*.deb 2>/dev/null)" + echo "tag=$tag" >> "$GITHUB_OUTPUT" + - name: Compare the file tree with the released package + if: steps.prev.outputs.skip != '1' + env: + PREV_TAG: ${{ steps.prev.outputs.tag }} + run: | + set -euo pipefail # without pipefail `tee` would swallow the exit code + # mode owner path, sorted. Directories are compared too, so an emptied or lost + # directory cannot go unnoticed. A symlink prints "path -> target"; the target is + # carried along, so a retargeted link (/usr/bin/lmnradius, the venv's python and + # lib64 links) is drift too. + norm() { dpkg-deb -c "$1" | awk '{t = ($7 == "->" ? " " $7 " " $8 : ""); print $1, $2, $6 t}' | LC_ALL=C sort; } + norm previous/*.deb > old.txt + norm packages/*.deb > new.txt + python3 - old.txt new.txt linuxmuster-radius lmnradius "$PREV_TAG" <<'PY' | tee -a "$GITHUB_STEP_SUMMARY" + import re + import sys + + old_f, new_f, PKG, OWN, TAG = sys.argv[1:6] + SP = rf"opt/{PKG}/venv/lib/python3\.12/site-packages/" + # 1. the own dist-info carries the version: compare it under a fixed name. + DIST = re.compile(rf"^({SP}{OWN})-[^/]+\.dist-info") + # 2. third-party distributions come and go with every lock bump; their completeness + # is proven by `debian/venv-relocate --verify` (RECORD) and the freeze == lock + # gates of the build, so a path of theirs that disappears is reported, not failed. + # Mode/owner is checked everywhere. + THIRD = re.compile(rf"^{SP}(?!{OWN}[/-])") + # Paths that may legitimately disappear. Add one ONLY together with the changelog + # sentence that explains it to admins. + ALLOW_GONE = set() + + + def read(name): + rows = {} + for line in open(name): + mode, owner, path = line.rstrip("\n").split(" ", 2) + if path == "./": # the package root: dpkg never applies its mode + continue + rows[DIST.sub(r"\1-VERSION.dist-info", path.removeprefix("./"))] = (mode, owner) + return rows + + + old, new = read(old_f), read(new_f) + gone = sorted(set(old) - set(new)) + added = sorted(set(new) - set(old)) + changed = sorted(p for p in set(old) & set(new) if old[p] != new[p]) + strict_gone = [p for p in gone if not THIRD.match(p) and p not in ALLOW_GONE] + print(f"## File tree vs {TAG}\n") + print(f"- released: {len(old)} entries, built: {len(new)} entries") + print(f"- third-party venv paths: {sum(1 for p in gone if THIRD.match(p))} gone, " + f"{sum(1 for p in added if THIRD.match(p))} added (lock changes, see RECORD check)") + for p in added: + if not THIRD.match(p): + print(f"- added: `{p}`") + for p in strict_gone: + print(f"::error::file lost from the package: {p}") + for p in changed: + print(f"::error::mode or owner changed: {p}: {old[p]} -> {new[p]}") + if strict_gone or changed: + sys.exit(1) + print("\nfile tree: nothing lost, no mode or owner change") + PY + install-smoke: needs: build runs-on: ubuntu-24.04 @@ -290,8 +446,14 @@ jobs: # thing that restarts it is `systemctl try-restart` inside the postinst's # `if [ -n "${2:-}" ]` branch, which exists only when dpkg passes an old version. grep -qE 'Unpacking linuxmuster-radius \([^)]+\) over \([^)]+\)' upgrade.log - # dpkg's own record of the action, independent of apt's wording. - grep -q ' upgrade linuxmuster-radius:' /var/log/dpkg.log + # dpkg's own record of the action, independent of apt's wording: exactly this + # step, from the released version to the built one (a reinstall of an equal version + # is logged as an upgrade too), and never a downgrade (--allow-downgrades above + # would let one through, and dpkg logs it as "upgrade" as well). + old_ver="$(dpkg-deb -f previous/*.deb Version)" + new_ver="$(dpkg-deb -f packages/*.deb Version)" + dpkg --compare-versions "$new_ver" ge "$old_ver" + grep -E " upgrade linuxmuster-radius:(all|amd64) ${old_ver//./\\.} ${new_ver//./\\.}\$" /var/log/dpkg.log after_pid="$(systemctl show -p MainPID --value linuxmuster-radius.service)" echo "postinst upgrade branch ran: MainPID $before_pid -> $after_pid" test "$before_pid" != "$after_pid" @@ -363,7 +525,7 @@ jobs: run: sudo journalctl -u linuxmuster-radius.service --no-pager | tail -60 || true release: - needs: [gate, build, install-smoke, upgrade-smoke] + needs: [gate, lockfile, build, file-tree, install-smoke, upgrade-smoke] if: github.ref_type == 'tag' runs-on: ubuntu-latest permissions: @@ -384,12 +546,16 @@ jobs: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} TAG: ${{ github.ref_name }} # through env, never interpolated into the script + # Optional read-only token for the immutable-releases setting (see the header), used for + # that one call only; empty when the secret does not exist. + IMMUTABLE_CHECK_TOKEN: ${{ secrets.IMMUTABLE_CHECK_TOKEN }} run: | set -euo pipefail shopt -s nullglob - # .changes/.buildinfo join the assets with the debian/ conversion (dpkg-buildpackage). - assets=(packages/*.deb) - [ "${#assets[@]}" -gt 0 ] || { echo "::error::no .deb to publish"; exit 1; } + # The .deb and the source package: the .changes lists the .dsc, the source tarball and + # the .buildinfo with their checksums, so all of them go along. + assets=(packages/*.deb packages/*.changes packages/*.buildinfo packages/*.dsc packages/*.tar.*) + compgen -G 'packages/*.deb' > /dev/null || { echo "::error::no .deb to publish"; exit 1; } # GitHub renames special characters in asset names (`~` becomes `.`, `+` stays), so # names are compared in this normalised form, in which no two assets may collide. norm() { local n=${1##*/}; printf '%s\n' "${n//[^A-Za-z0-9._-]/.}"; } @@ -462,6 +628,31 @@ jobs: | while read -r d n; do printf '%s %s\n' "$d" "$(norm "$n")"; done | sort > uploaded.sha256 diff built.sha256 uploaded.sha256 \ || { echo "::error::assets on the draft differ from the build, not publishing"; exit 1; } + # Immutable or not at all (why: see the header). In advance, at the last moment the release + # is still a draft, but only with the optional token: GITHUB_TOKEN cannot read the setting. + # A repo with the setting off answers {"enabled":false}; the docs also name 404. With the + # token, anything but enabled == true stops here and leaves the draft unpublished. + if [ -z "${IMMUTABLE_CHECK_TOKEN:-}" ]; then + echo "::notice::immutable releases could not be checked before publishing: secret IMMUTABLE_CHECK_TOKEN is not set and GITHUB_TOKEN cannot read the setting. Publishing anyway; the check after publishing fails this job if $TAG does not come out immutable." + else + if ! enabled=$(GH_TOKEN=$IMMUTABLE_CHECK_TOKEN gh api "repos/$GH_REPO/immutable-releases" --jq '.enabled'); then + echo "::error::cannot read the immutable-releases setting of $GH_REPO (${enabled//$'\n'/ }); draft $rid stays unpublished"; exit 1 + fi + [ "$enabled" = true ] || { + echo "::error::immutable releases are not enabled for $GH_REPO (enabled=$enabled); draft $rid stays unpublished"; exit 1; } + fi gh api -X PATCH "repos/$GH_REPO/releases/$rid" -F draft=false --jq '"published \(.html_url)"' - immutable=$(gh api "repos/$GH_REPO/releases/$rid" --jq '.immutable' || true) - [ "$immutable" = true ] || echo "::warning::$TAG is published but not immutable (immutable=$immutable)" + # Re-read by id: the published release must be immutable. This check always runs (the + # release is readable with GITHUB_TOKEN) and is the one that guarantees a mutable release + # is noticed. An error, never a warning, or the run ends green with assets that can still + # be replaced. The retry only covers a read that lags behind the publish. + immutable= + for i in 1 2 3; do + immutable=$(gh api "repos/$GH_REPO/releases/$rid" --jq '.immutable') && [ "$immutable" = true ] && break + [ "$i" = 3 ] || sleep $((i * 5)) + done + if [ "$immutable" != true ]; then + echo "::error::$TAG is published but NOT immutable (immutable=${immutable:-unreadable}), its assets can still be replaced: delete release $rid (the tag stays), turn immutable releases on, re-run this job" + exit 1 + fi + echo "$TAG is published and immutable" diff --git a/.github/workflows/renovate.yml b/.github/workflows/renovate.yml index b331e76..f74df16 100644 --- a/.github/workflows/renovate.yml +++ b/.github/workflows/renovate.yml @@ -2,6 +2,10 @@ # # SPDX-License-Identifier: GPL-3.0-or-later +# DISABLED (Kevin, 2026-09-25): this workflow is turned off in the repository settings until +# Renovate is re-enabled with a GitHub App; until then no Renovate PRs are opened and pins and +# locks are raised by hand. The rest of this header describes the workflow once re-enabled. +# # Self-hosted Renovate — so digest bumps work without depending on the org-level # Renovate/Mend GitHub App. Runs weekly and on demand. It opens PRs that bump the # @sha256 pins (the data-plane image DEFAULT_IMAGE, every Dockerfile / docker-compose 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/CLAUDE.md b/CLAUDE.md index 9a1e29b..284770f 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,22 +40,57 @@ 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` (it mounts the repository's common git directory too, so it works in a git + worktree); never reference the image by tag alone. `packaging/make-deb.sh` builds an export + of the **git-tracked files as they are in the working tree**: uncommitted edits and staged + new files ARE built, untracked files are NOT (`git add` a new module first), and every + difference from HEAD is printed as a WARNING before and after the build — the .deb still + carries the changelog's version, so never hand such a build around as the release. A `.git` + that git cannot use (a worktree without its repository, a checkout owned by someone else) + stops the build; nothing configured in `.git` runs (no fsmonitor, hooks or filters). + `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 - `controlplane/` (needs `uv`) and check with `bash scripts/check-lockfiles.sh`. Never - hand-edit a lockfile; Renovate bumps them by PR. + `controlplane/uv-requirements.lock` pins the resolver `uv` (exactly the `uv==` of + `uv-requirements.in`, all PyPI hashes). After changing dependencies, re-run the command in + the lockfile's header inside `controlplane/` (needs `uv`) and check with + `bash scripts/check-lockfiles.sh`. Never hand-edit a lockfile. + `scripts/check-lockfiles.sh` is **the lock gate**, and every consumer runs it before + anything from a lockfile is installed: the CI fast tier and the CI job `lock-gates-build` + (first step each), the `lockfile` job of ci.yml and release.yml (nothing else in it), + `packaging/build-venv.sh` (so `make deb`, CI `package`, the release build) and + `scripts/tests/run.sh` (first; run.sh stops if it fails). `scripts/tests/lock_gates.sh` + stops if the committed locks fail it, and its counter-probes (install paths without the + gate) install fixture locks that pin only the test wheel, never the checkout's. It verifies + all three locks — grammar, every hash on PyPI, pin set == closure of the declared inputs + (uv re-resolves `pyproject.toml`/`build-requirements.in`) — and installs the uv it needs + itself, from the verified uv lock into an isolated venv, called by absolute path. The + gates run `/usr/bin/python3 -I`, set a fixed PATH and drop `VIRTUAL_ENV`, `PYTHON*`, + `UV_*` and `PIP_*` (and pip/uv config files), so an activated venv or a `.venv` in the + checkout takes no part. Not neutralized, a stated limit: `BASH_ENV`, exported shell + functions and proxy/CA variables (`HTTPS_PROXY`, `SSL_CERT_FILE`, `REQUESTS_CA_BUNDLE`, …) + — whoever sets those already runs code as the caller, or decides whom the gate trusts as PyPI. + Limit: pins are compared with the closure by name; another real release of a pinned + package (older or newer, a week old, genuine hashes) that satisfies the declared + requirements passes every gate — only the review of the lockfile diff catches it. + Renovate is disabled (Kevin, 2026-09-25), so locks, digests, action + SHAs and CI tool pins are raised by hand in a reviewed PR. - **Maintainer string** everywhere: `Kevin Stenzel `. **Security pitfalls (from the threat model — do not violate):** @@ -215,8 +250,10 @@ with **Docker**. **crabbox** leases an ephemeral Proxmox VM for this (provider i `.claude/settings.json`, token only in the gitignored `.claude/settings.local.json`; `crabbox doctor`). Rules/details: the `/test` skill (`.claude/skills/test/SKILL.md`). -- **One aggregate runner:** `bash scripts/tests/run.sh [lint|unit|quick|e2e|all]` - (created in P0/P1). `quick` (default) = lint + unit; `e2e`/`all` run the +- **One aggregate runner:** `bash scripts/tests/run.sh [gate|lint|unit|quick|locks|e2e|all]` + (created in P0/P1). Every mode but `e2e` runs the lock gate first (network needed); if it + fails, run.sh stops there and runs nothing else. `quick` (default) = gate + lint + unit + + the lock regression test; `e2e`/`all` run the Docker suites and **refuse without `LMNRADIUS_ALLOW_REAL=1`**. Summary: `N passed, M failed, K skipped` (exit ≠ 0 on failure); steps dep-gated. - **Box lifecycle:** `crabbox warmup` → `crabbox run --id -- 'bash scripts/tests/crabbox_bootstrap.sh'` diff --git a/Makefile b/Makefile index 9bf055c..4692687 100644 --- a/Makefile +++ b/Makefile @@ -2,20 +2,31 @@ # 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). packaging/make-deb.sh builds from an export of +# the git-tracked files as they are in the working tree: uncommitted edits and staged new files +# ARE built, untracked files are NOT (git add them), and every such difference from HEAD is +# printed as a WARNING -- the .deb still carries the changelog's version. An untracked or +# .gitignored file (a venv, caches, deploy/secrets, .env, a token under .claude/) never +# reaches the source tarball (K3). A .git that git cannot use stops the build. It writes the +# .deb, .changes, .buildinfo, .dsc and the source tarball one level ABOVE this tree. +# Build like CI does, in the same digest-pinned lmndev-runner container (keep the digest equal +# to ci.yml and release.yml; raised by hand while Renovate is disabled). Mount the checkout +# one level down, so the artefacts land in a writable parent (../out here), and the +# repository's common git directory at its own path, so git works in a git worktree too (in a +# plain clone that is the checkout's .git, mounted twice); the image's user `build` +# (uid 1000) builds, root only installs the build dependencies: +# C="$(git rev-parse --path-format=absolute --git-common-dir)" +# mkdir -p ../out && docker run --rm -u root -v "$(realpath ../out)":/b -v "$PWD":/b/src \ +# -v "$C":"$C" -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' +# git's ownership guard stays on: the checkout must belong to uid 1000 (the image's `build`). .PHONY: deb clean deb: - bash packaging/build-deb.sh + /bin/bash packaging/make-deb.sh clean: - rm -f linuxmuster-radius_*.deb - rm -rf controlplane/build controlplane/*.egg-info + debian/rules clean 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/controlplane/lmnradius/models.py b/controlplane/lmnradius/models.py index 8b18eea..4585d16 100644 --- a/controlplane/lmnradius/models.py +++ b/controlplane/lmnradius/models.py @@ -86,8 +86,8 @@ def is_ldaps(url: str) -> bool: # Default data-plane image for new/updated instances, so callers need not pass # --image. Pinned to an immutable ``@sha256:`` — the data-plane image built and # published to GHCR by the build-image workflow (verified end-to-end against a real DC); -# Renovate keeps it current (same rationale as linuxmuster-squid). The image validator -# requires an explicit :tag or @sha256 and rejects a bare repo either way. +# raised by hand in a reviewed PR while Renovate is disabled (Kevin, 2026-09-25). The +# image validator requires an explicit :tag or @sha256 and rejects a bare repo either way. DEFAULT_IMAGE = "ghcr.io/faircomp/linuxmuster-radius@sha256:7385d3a64c3d98afa33577473c6b065f2a6a2ef88fa7ff70117ab6262118a77a" diff --git a/controlplane/tests/test_packaging.py b/controlplane/tests/test_packaging.py index eac5fa2..334438f 100644 --- a/controlplane/tests/test_packaging.py +++ b/controlplane/tests/test_packaging.py @@ -2,15 +2,46 @@ # SPDX-License-Identifier: GPL-3.0-or-later """Repo-level contracts that have no other test: the Renovate regex manager must see every pinned CI gate tool in ci.yml (a four-component version like -types-PyYAML==6.0.12.20260906 slipped through the old three-component pattern).""" +types-PyYAML==6.0.12.20260906 slipped through the old three-component pattern), the +resolver uv is pinned by hash in its own lockfile, not as a bare ci.yml `uv==` line (K1), and +no workflow step installs anything from a lockfile before the lock gate ran in that job (R2). +scripts/tests/lock_gates.sh replays those steps with a planted package; these tests keep the +order from being edited away.""" from __future__ import annotations +import importlib.util import json import re +import sys from pathlib import Path +from types import ModuleType +from typing import Any + +import yaml ROOT = Path(__file__).resolve().parents[2] +WORKFLOWS = ROOT / ".github" / "workflows" +GATE_STEP = "bash scripts/check-lockfiles.sh" +# A command that installs from a lockfile or the control plane (whose build needs the locks). +LOCK_INSTALL = re.compile(r"pip\S* install[^\n]*(-r\s+\S*\.lock|controlplane)") + + +def _lockfile_gate() -> ModuleType: + spec = importlib.util.spec_from_file_location( + "lockfile_gate", ROOT / "scripts" / "lockfile_gate.py" + ) + assert spec and spec.loader + mod = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = mod # dataclasses resolve the module's annotations through it + spec.loader.exec_module(mod) + return mod + + +def _jobs(name: str) -> dict[str, Any]: + doc = yaml.safe_load((WORKFLOWS / name).read_text(encoding="utf-8")) + jobs: dict[str, Any] = doc["jobs"] + return jobs def _renovate_ci_pattern() -> re.Pattern[str]: @@ -25,7 +56,79 @@ def _renovate_ci_pattern() -> re.Pattern[str]: def test_renovate_matches_every_pinned_ci_tool() -> None: ci = (ROOT / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8") pinned = dict(re.findall(r"^\s+([A-Za-z0-9_.-]+)==([0-9][0-9.]*)", ci, re.MULTILINE)) - assert {"ruff", "mypy", "reuse", "pytest", "types-PyYAML", "uv"} <= set(pinned) + # uv is no longer a bare ci.yml pin: it is installed hash-pinned from its own lockfile + # (K1), so it must NOT appear here (it would be an unhashed `pip install uv==...`). + assert {"ruff", "mypy", "reuse", "pytest", "types-PyYAML"} <= set(pinned) + assert "uv" not in pinned found = {m["depName"]: m["currentValue"] for m in _renovate_ci_pattern().finditer(ci)} assert found == pinned assert found["types-PyYAML"].count(".") == 3 # the four-part version is captured whole + + +def test_uv_is_pinned_by_hash_in_its_own_lockfile() -> None: + # Parsed the way the gate parses it (every line, not only column 1): exactly uv, with + # hashes, at the version uv-requirements.in pins. + gate = _lockfile_gate() + pins, errors = gate.parse(str(ROOT / "controlplane" / "uv-requirements.lock")) + assert errors == [] + assert [p.name for p in pins] == ["uv"], "the uv lock must hold exactly uv" + assert pins[0].hashes, "uv pin needs hashes" + wanted = (ROOT / "controlplane" / "uv-requirements.in").read_text(encoding="ascii") + assert f"uv=={pins[0].version}" in wanted.splitlines() + + +def test_no_workflow_installs_from_a_lockfile_before_the_lock_gate() -> None: + for wf in ("ci.yml", "release.yml"): + for job, spec in _jobs(wf).items(): + gated = False + for step in spec.get("steps", []): + run = step.get("run", "") + if run.strip() == GATE_STEP: + gated = True + assert not (LOCK_INSTALL.search(run) and not gated), ( + f"{wf}/{job}: step {step.get('name')!r} installs from a lockfile " + f"before a `{GATE_STEP}` step" + ) + # the gate brings its own uv; nothing installs the uv lock around it + assert "uv-requirements.lock" not in run, f"{wf}/{job}: installs the uv lock" + + +def test_every_job_that_runs_the_lock_tests_passes_the_gate_first() -> None: + # lock_gates.sh and make_deb_checks.sh copy the committed lockfiles into their cases; a job + # runs them only after a step that ran the gate on those files (cold verification r3, F1). + for wf in ("ci.yml", "release.yml"): + for job, spec in _jobs(wf).items(): + gated = False + for step in spec.get("steps", []): + run = step.get("run", "") + if ( + "scripts/tests/lock_gates.sh" in run + or "scripts/tests/make_deb_checks.sh" in run + ): + assert gated, f"{wf}/{job}: {step.get('name')!r} runs before the lock gate" + if re.search(r"(^|\s)bash scripts/check-lockfiles\.sh\s*$", run, re.MULTILINE): + gated = True + + +def test_fast_tier_runs_the_gate_first_and_lockfile_jobs_are_only_the_gate() -> None: + fast = _jobs("ci.yml")["fast"]["steps"] + runs = [s["run"] for s in fast if "run" in s] + assert runs[0].strip() == GATE_STEP, "the lock gate is the first run step of the fast tier" + for wf in ("ci.yml", "release.yml"): + steps = _jobs(wf)["lockfile"]["steps"] + assert [s["run"].strip() for s in steps if "run" in s] == [GATE_STEP] + assert not any("setup-python" in s.get("uses", "") for s in steps) + assert _jobs("ci.yml")["lockfile"] == _jobs("release.yml")["lockfile"] + # the release waits for it + assert "lockfile" in _jobs("release.yml")["release"]["needs"] + + +def test_make_deb_never_waives_the_git_ownership_guard_wholesale() -> None: + script = (ROOT / "packaging" / "make-deb.sh").read_text(encoding="utf-8") + assert not re.search(r"safe\.directory\s*=\s*['\"]?\*", script) + for wf in ("ci.yml", "release.yml"): + text = (WORKFLOWS / wf).read_text(encoding="utf-8") + for line in re.findall(r".*safe\.directory.*", text): + if line.lstrip().startswith("#"): + continue + assert line.strip() == 'git config --global --add safe.directory "$GITHUB_WORKSPACE"' diff --git a/controlplane/uv-requirements.in b/controlplane/uv-requirements.in new file mode 100644 index 0000000..0e1b969 --- /dev/null +++ b/controlplane/uv-requirements.in @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# The resolver of the lock gate (scripts/check-lockfiles.sh). uv-requirements.lock must pin +# exactly this version (the gate checks it). Regenerate the lock from the PyPI file list of +# this exact version; the gate installs it hash-pinned and in isolation. +uv==0.12.18 diff --git a/controlplane/uv-requirements.lock b/controlplane/uv-requirements.lock new file mode 100644 index 0000000..fb71d35 --- /dev/null +++ b/controlplane/uv-requirements.lock @@ -0,0 +1,27 @@ +# This file was autogenerated from the PyPI file list of uv 0.12.18 (all published +# sha256, every platform). uv is the resolver of the lock gate (scripts/check-lockfiles.sh), +# which verifies this file first -- lint, exactly one pin equal to the uv== of +# uv-requirements.in, every hash published by PyPI -- and only then installs it into an +# isolated venv and calls it by absolute path, before anything else from a lockfile is +# installed (linuxmusterDEV work/tasks/nachbesserung-kalte-pruefung-umbau.md, K1, R2). +# Never re-resolved (a fresh tool would need itself). +uv==0.12.18 \ + --hash=sha256:03da66a73d0ac01fb7a95d096aebf5993b51ec65df620d57f415e111e6789c88 \ + --hash=sha256:0a3c4e415515bd4c24c7516523d9042a2957ce716423e193f8b2be9fb8773340 \ + --hash=sha256:0a8fa0c6408c1bedf8a19219b471d6c14ae98695940b20269fcb7514a136cfa4 \ + --hash=sha256:145f17e2b7f165da9bd4dd14c4c2525d5b1647cb8daadb684106babedbc502ff \ + --hash=sha256:328abf19b5992b4846f96d1d4440cdd9e0b7d20c0f00b0644e68ca8cfb561c26 \ + --hash=sha256:4f9769cf34558a026ff9b8e04cdf9d25c16fe3d61f35956daf6548f2b0379ff0 \ + --hash=sha256:53a035e48cbe94ca47ee304b293060b690d0ac03140a64ff3ff4713eabcede99 \ + --hash=sha256:77b71bc25d274a04594d32167b0f766fb5b6805980c3aed02872c468e1905e7e \ + --hash=sha256:799dcef1ef97ab6491b34f5827e2da8dd9153d65be056c779b60a2d4d3d6c45b \ + --hash=sha256:98a8a4786db518b4d708eacc96aadfc0626072d5873c708bcab8239e6453176d \ + --hash=sha256:99c64f9f3eea3eb3fd496c29da47462824da0e47775b3b39d444d9832c815549 \ + --hash=sha256:9aa0ef69c7cb2aff485a0e9ce46feeb7b6dbeef3d796ffd04b944cf355ba8334 \ + --hash=sha256:9c237410b6b193e691c7c37752fd7f3cfebd9b5d5331c53e748f004c6397334f \ + --hash=sha256:9c77a4de02c2b7737f6d4eb5fcd359bc0f0948f2a4133f8095c527addb84fc56 \ + --hash=sha256:b656468f973ac363ac96b0b6b9bf9c5f5836cd84b664d0ca67b67bb8e35f9bcf \ + --hash=sha256:cbbfcca37cf678b5135f61f722631a2a85e2eddc459ba64692054011f160f6c2 \ + --hash=sha256:d5037ec17654c756fc9841270f413c5fc9ecef89108b443f5dd34600a3ccdb19 \ + --hash=sha256:e7ab1387b222ab640dbd057b95548a199e4c621aa35e9f6a32c0516c76e7637d \ + --hash=sha256:fbe0489871e74ebfb70379a32526c62b9fb615acf13576b9f19bc09a142f62b0 diff --git a/packaging/debian/control.license b/controlplane/uv-requirements.lock.license similarity index 100% rename from packaging/debian/control.license rename to controlplane/uv-requirements.lock.license diff --git a/debian/changelog b/debian/changelog index ae86cba..c96312a 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,52 @@ +linuxmuster-radius (7.3.4) lmn73; urgency=medium + + * The package is now built with debhelper (dpkg-buildpackage) instead of a + hand-written script. It installs the same files with the same + permissions as 7.3.3; the service, the CLI, the configuration and the + upgrade path behave exactly as before. New are only the files + /usr/share/doc/linuxmuster-radius/changelog.gz and copyright and the + package's lintian overrides. + * Architecture is now amd64 instead of all: the bundled Python environment + contains compiled x86_64 libraries, so the package never worked on other + architectures. apt upgrades an installed 7.3.x (all) to 7.3.4 (amd64) + like any other version. + * Depends on python3 (>= 3.12) and python3 (<< 3.13) instead of + python3 (>= 3.12): the environment under /opt/linuxmuster-radius/venv is + built for the Python 3.12 of Ubuntu 24.04. A plain "apt upgrade" then + keeps the newer Python back (python3 stays at 3.12) instead of leaving a + broken service; a full distribution upgrade ("apt full-upgrade", + do-release-upgrade) removes this package instead, leaving its + configuration and state in place, so it can be reinstalled once a + matching build exists. The compiled libraries add libc6 and libgcc-s1. + * Hardened dependency checks. The lockfile check and the build now read + every line of the lockfiles the way pip does and refuse anything but + pinned versions with their SHA-256 hashes; an indented or URL + requirement and option lines such as --extra-index-url used to pass the + check. Before anything from a lockfile is installed, in the build and in + every CI job, every hash is verified against PyPI and the pins must be + exactly the resolved closure of the declared dependencies: an extra + package slipped into a lockfile, even with a genuine hash, is refused + before its code can run. The resolver for that check, uv, is pinned by + hash and verified first. The checks no longer take their programs or + package sources from the PATH, an activated virtualenv or the Python, + pip and uv variables of whoever runs them. The build re-checks the + finished environment against the lockfiles. Not caught: a pin moved to + another genuine release, older or newer, that still satisfies the + declared dependencies; only the review of the lockfile change shows it. + * The post-installation script turns off git's background maintenance in + the instance change log (/var/lib/linuxmuster-radius/instances) and no + longer lets git look into /root/.config when XDG_CONFIG_HOME is + inherited from the installing admin. A precaution taken over from + linuxmuster-squid 7.3.4, whose configuration failed on such a + maintenance process. + * After publishing, the release job checks that GitHub marks the release + immutable and fails otherwise, so the files of a release cannot be + replaced unnoticed. A release also carries the source package (.dsc, + source tarball with the files tracked in git except the CI workflows + and developer tool settings, .changes, .buildinfo). + + -- Kevin Stenzel Fri, 25 Sep 2026 11:55:45 +0200 + linuxmuster-radius (7.3.3) lmn73; urgency=medium * Reproducible builds with verified dependencies: the Python environment diff --git a/packaging/debian/control b/debian/control similarity index 54% rename from packaging/debian/control rename to debian/control index 668441c..e663f9b 100644 --- a/packaging/debian/control +++ b/debian/control @@ -1,10 +1,24 @@ -Package: linuxmuster-radius -Version: @VERSION@ -Architecture: all -Maintainer: Kevin Stenzel +Source: linuxmuster-radius Section: admin Priority: optional -Depends: python3 (>= 3.12), adduser, openssl, git +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) 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/packaging/debian/postinst b/debian/postinst similarity index 83% rename from packaging/debian/postinst rename to debian/postinst index bc52141..330e60a 100644 --- a/packaging/debian/postinst +++ b/debian/postinst @@ -49,14 +49,25 @@ chmod 700 /etc/linuxmuster-radius/secrets /etc/linuxmuster-radius/certs # directory"), the identity was never set and every commit died with "empty ident # name" -- the change log stayed empty (found on real installs, 2026-09-22). # Idempotent: repairs an existing 7.3.0 repo (identity, pending records) on upgrade. +# Background maintenance is off in the repository config, set before its first commit: git +# 2.47 and later start auto-maintenance after a commit as a DETACHED process that creates +# and removes files under .git (objects/maintenance.lock) while the `chown -R` above walks +# the tree on the next configure; linuxmuster-squid 7.3.1-7.3.3 failed its configure on +# exactly that race. The service's own commits read the same repository config, so they +# spawn none either. A change log of a few commits needs no gc. INST_DIR=/var/lib/linuxmuster-radius/instances if command -v git >/dev/null 2>&1; then - as_lmnradius() { runuser -u lmnradius -- "$@"; } + # runuser resets HOME, not XDG_CONFIG_HOME: an admin environment pointing it into /root + # (GitHub runners, `sudo -E`) would make every git call warn "unable to access + # '/root/.config/git/...': Permission denied". + as_lmnradius() { runuser -u lmnradius -- env -u XDG_CONFIG_HOME "$@"; } if [ ! -d "$INST_DIR/.git" ]; then as_lmnradius git -C "$INST_DIR" -c init.defaultBranch=main init -q fi as_lmnradius git -C "$INST_DIR" config user.name "linuxmuster-radius" as_lmnradius git -C "$INST_DIR" config user.email "lmnradius@localhost" + as_lmnradius git -C "$INST_DIR" config maintenance.auto false + as_lmnradius git -C "$INST_DIR" config gc.auto 0 # Records written while the change log was broken (staged but never committed, or # never added) become one import commit, so `git log` is complete after the upgrade. for f in "$INST_DIR"/*.yaml; do @@ -101,4 +112,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 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/deploy/docker-socket-proxy.yml b/deploy/docker-socket-proxy.yml index 9f88083..af7069d 100644 --- a/deploy/docker-socket-proxy.yml +++ b/deploy/docker-socket-proxy.yml @@ -8,7 +8,7 @@ # and restart the service. (ADR-012.) services: docker-socket-proxy: - image: tecnativa/docker-socket-proxy:v0.4.2 # fixed version instead of :latest (Renovate pins the @sha256 digest) + image: tecnativa/docker-socket-proxy:v0.4.2 # fixed version instead of :latest environment: CONTAINERS: "1" # create/inspect/start/stop/remove/logs IMAGES: "1" # pull the digest-pinned data-plane image diff --git a/deploy/instances/README.md b/deploy/instances/README.md index 32a3380..98a861a 100644 --- a/deploy/instances/README.md +++ b/deploy/instances/README.md @@ -39,7 +39,7 @@ or config-injection sink), so the examples double as the validation contract. | `ldap_bind_secret` | **Filename** of the LDAP bind password secret. | | `radius_secret` | **Filename** of the per-subnet RADIUS shared secret. | | `ldap_ca` | **Filename** (under `certs_dir//`) of the PEM bundle the DC's LDAPS certificate is verified against (`ldap-ca.pem`, written by the API from `--ldap-ca`/`--ldap-ca-tofu`). Mandatory for `ldaps://` on create; `null` marks a pre-7.3.1 record whose LDAPS link is unverified. | -| `image` | Data-plane image; carries an explicit `:tag` or `@sha256:` — **digest-pinned** in production (Renovate, P5). A bare repo is rejected. | +| `image` | Data-plane image; carries an explicit `:tag` or `@sha256:` — **digest-pinned** in production (P5). A bare repo is rejected. | The three `*_secret` fields are **secret file names**, never the secret values — the values live in `/etc/linuxmuster-radius/secrets/` (0700) and are mounted into diff --git a/deploy/instances/default-school.yaml b/deploy/instances/default-school.yaml index 4b79460..5f85be6 100644 --- a/deploy/instances/default-school.yaml +++ b/deploy/instances/default-school.yaml @@ -31,5 +31,5 @@ radius_secret: default-school.radius # create --ldap-ca` / `set-ldap-ca`). Mandatory for ldaps:// since 7.3.1; null only # on records created earlier (then listed as "LDAPS unverified"). ldap_ca: ldap-ca.pem -# Digest-pinned in production (Renovate, P5). The 64-hex digest below is illustrative. +# Digest-pinned in production (P5). The 64-hex digest below is illustrative. image: ghcr.io/faircomp/linuxmuster-radius@sha256:7385d3a64c3d98afa33577473c6b065f2a6a2ef88fa7ff70117ab6262118a77a diff --git a/docs/architecture.md b/docs/architecture.md index 2dff9a4..2baec78 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -112,8 +112,8 @@ die Entscheidungen mit Begründung und verworfenen Alternativen: `docs/decisions `crash_looping`, nicht „running"). `rm` verlässt die Domäne (Image-Aktion `leave`) und entfernt Container, Volume, Config und Datensatz. - **Updater:** Pull-by-**Digest** (`image@sha256:`), **health-gated**, **Auto-Rollback** - auf den letzten Known-Good; Renovate (`docker:pinDigests`, `automerge:false`) + - CI-Publish. Kein Watchtower. + auf den letzten Known-Good; neue Digests per geprüftem PR (Renovate ist seit 2026-09-25 + abgeschaltet, bis dahin von Hand) + CI-Publish. Kein Watchtower. - **EAP-CA / Cert-Manager:** dedizierte, single-purpose EAP-CA (`lmnradius ca init` / `cert issue` / `ca export`) — siehe §7. - **CLI (`lmnradius`, Typer/httpx):** ausschließlich über die REST-API — **ein** diff --git a/docs/decisions.md b/docs/decisions.md index 5b20477..224270f 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -181,7 +181,9 @@ dannyda (HowTos: Subnetz statt Controller-IP in clients.conf). apt-Installation ist das menschliche Go/No-Go), jeweils mit Health-Auto-Rollback. **Begründung:** deterministische, auditierbare Updates. **Verworfene Alternative:** Watchtower — archiviert (2025-12-17), **kein** Rollback, wendet Breaking Changes blind -an, braucht einen Root-Socket. **Quelle:** Watchtower-Repo (archiviert 2025-12-17); +an, braucht einen Root-Socket. **Stand 2026-09-25:** Renovate ist abgeschaltet (Kevin), bis +es mit einer GitHub-App wieder läuft; bis dahin hebt ein Mensch Digests, Locks und Pins per +PR an. **Quelle:** Watchtower-Repo (archiviert 2025-12-17); linuxmuster-squid ADR-010. ### ADR-011 — Packaging via dh-virtualenv @@ -211,7 +213,7 @@ Fläche, kein Endpoint-Filter). **Quelle:** tecnativa/docker-socket-proxy; Docke ### ADR-013 — Image-Registry: GHCR (Default) **Status:** Accepted (Default 2026-07-10; jederzeit änderbar). **Entscheidung:** Das Data-Plane-Image wird nach **GHCR (`ghcr.io/faircomp/linuxmuster-radius`)** publiziert; -Renovate pinnt den Digest. **Begründung:** kostenlos, integriert sauber mit GitHub-CI + +der Digest wird per PR gepinnt (von Hand, solange Renovate abgeschaltet ist). **Begründung:** kostenlos, integriert sauber mit GitHub-CI + Renovate-Digest-Pinning. **Verworfene Alternative:** Docker Hub (Pull-Rate-Limits) oder eine selbstgehostete/linuxmuster-Registry (mehr Infrastruktur). **Quelle:** GitHub Container Registry (Docs); linuxmuster-squid ADR-013. @@ -254,16 +256,58 @@ 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` nicht exakt den Lockfiles entspricht. -`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 -(CPython 3.12, glibc 2.39, x86_64). Renovate hebt die -Fassungen per PR, ohne Automerge. **Begründung:** ohne Pins zog jeder Release-Bau die +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. +Weiter nachgehärtet (7.3.4, Nachbesserung K1 und Runde 3): ein Wheel aus einer Sperrdatei +kann `bin/`-Skripte und eine `.pth` mitbringen; würde es vor der Mengen-/Hüllen-Prüfung +installiert, liefe sein Code (die `.pth` beim Bau des eigenen Wheels, im CI-Fast-Tier seine +`bin/`-Werkzeuge im PATH). Darum ist `scripts/check-lockfiles.sh` **das** Lock-Tor, und jeder +Verbraucher ruft es auf, bevor irgendetwas aus einer Sperrdatei installiert wird: der +Fast-Tier und der CI-Job `lock-gates-build` (je erster Schritt), der Job `lockfile` in ci.yml +und release.yml (nur das Tor), `packaging/build-venv.sh` (also `make deb`, CI `package`, +Release-`build`) und `scripts/tests/run.sh` (zuerst; scheitert es, bricht run.sh ab). +`scripts/tests/lock_gates.sh` bricht ab, wenn die committeten Sperrdateien das Tor nicht +bestehen, und seine Gegenproben (Installationswege ohne Tor) installieren nur Fixture- +Sperrdateien mit dem Test-Wheel, nie die des Checkouts (kalte Prüfung r3, F1). Es prüft alle drei Sperrdateien: Grammatik; die uv-Sperrdatei hält +genau das `uv==` aus `uv-requirements.in` mit von PyPI veröffentlichten Hashes (nur stdlib); +erst dann installiert es dieses uv in ein eigenes, isoliertes venv und ruft es per absolutem +Pfad auf; uv löst `pyproject.toml`/`build-requirements.in` neu auf, die Pins müssen genau +diese Hülle sein, und jeder Hash muss von PyPI für genau diese Fassung stammen. Aus der +Umgebung des Aufrufers nehmen die Tore weder Programme noch Paketquellen: fester PATH ohne +venv-`bin/`, `/usr/bin/python3 -I`, `VIRTUAL_ENV`/`PYTHON*`/`UV_*`/`PIP_*` entfernt (auch +`PIP_REQUIREMENT`/`PIP_CONSTRAINT`), keine pip-/uv-Konfigurationsdateien, uv mit `--python +/usr/bin/python3 --no-config` (kein Projekt-venv, keine umgelenkte Paketquelle). **Grenze:** +nicht neutralisiert sind `BASH_ENV` (bash führt es vor der ersten Skriptzeile aus), +exportierte Shell-Funktionen und Proxy-/CA-Variablen (`HTTPS_PROXY`, `SSL_CERT_FILE`, +`REQUESTS_CA_BUNDLE`, …), die bestimmen, wem das Tor als PyPI vertraut; wer die Umgebung des +Aufrufers so setzt, führt ohnehin Code als dieser aus. Ein +zusätzlicher Pin mit echten Hashes wird so abgewiesen, bevor sein Code läuft (nachgewiesen: +die K1-, R1- und R2-Fälle in `scripts/tests/lock_gates.sh`, die Marker entstehen nie; die +Gegenproben ohne Tor erzeugen sie). +`scripts/check-lockfiles.sh` beweist außerdem, dass die Lockfiles zu ihren +Quellen passen (eine Fassung jünger als sieben Tage fällt dabei durch) und jede Fassung ein +Wheel für die Zielplattform hat (CPython 3.12, glibc 2.39, x86_64). **Grenze:** Die Pins +werden nach Namen mit der Hülle verglichen, die Auflösung bevorzugt die gepinnten Fassungen. +Eine andere echte Fassung eines gepinnten Pakets (älter **oder neuer**, mindestens eine Woche +alt, mit ihren echten Hashes), die die deklarierten Anforderungen erfüllt, besteht darum jedes +Tor; nur die Review des Sperrdatei-Diffs fängt sie. Neue Fassungen kommen per PR, ohne +Automerge (von Hand, solange Renovate abgeschaltet ist). **Begründung:** ohne Pins zog jeder Release-Bau die neueste PyPI-Fassung ohne Prüfsumme; Bauten waren nicht reproduzierbar und eine kompromittierte Fassung wäre unbemerkt in ein root-installiertes Paket gelangt. **Verworfene Alternativen:** Pins ohne Hashes (schützen nicht gegen eine ausgetauschte @@ -276,8 +320,9 @@ Auflösung). **Quelle:** pip-Doku „Secure installs" (hash-checking mode); Reno ### ADR-017 — Build-Eingaben unveränderlich referenziert, Release erst als Entwurf **Status:** Accepted (Stufe A „Lieferkette", 2026-09-23). **Entscheidung:** Das Build-Image steht überall als `ghcr.io/linuxmuster/lmndev-runner:@sha256:` (ci.yml, -release.yml und der Build-Befehl im Makefile, derselbe Digest). Renovate schlägt neue -Digests als PR vor, ein Mensch merged; den Tag ändert Renovate nie (`24.04 → 26.04` wäre +release.yml und der Build-Befehl im Makefile, derselbe Digest). Neue Digests kommen per +PR, ein Mensch merged (von Hand, solange Renovate abgeschaltet ist); den Tag ändert ein +Bump nie (`24.04 → 26.04` wäre eine neue linuxmuster-Linie, kein Update). Jede GitHub Action steht per vollständigem Commit-SHA mit `# vN`-Kommentar (`helpers:pinGitHubActionDigests`). Das Release legt die `gh`-CLI des Runners an (keine Dritt-Action neben `contents: write`): erst als Entwurf, dann diff --git a/docs/install.md b/docs/install.md index 6c29d1f..d3cf1bc 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"} ``` @@ -253,9 +253,6 @@ sudo apt upgrade # neues .deb -> postinst: try-res > Docker-Bridge-Adresse) und die Instanz-Historie (`git log` im State-Verzeichnis) > repariert. `update-all` hebt **jede Instanz auf das im `.deb` gepinnte Image**, pro Instanz mit Health-Check und -**automatischem Rollback**. Neue Images kommen via **Renovate**: ein neues GHCR-Image → Renovate -öffnet einen **Digest-Bump-PR** (`DEFAULT_IMAGE`), ein Mensch merged → neuer `v*`-Tag → neues `.deb` -→ `apt upgrade`. *(Für das Repo: das Secret `RENOVATE_TOKEN`, ein fine-grained PAT nur für dieses Repo -mit Contents, Pull requests, Issues und Workflows: read and write, ist Pflicht. Mit dem `GITHUB_TOKEN` -starten Renovate-PRs keine CI, und Änderungen unter `.github/workflows/` (Action-SHAs, Build-Image- -Digest) darf er gar nicht pushen.)* +**automatischem Rollback**. Neue Images kommen per **Digest-Bump-PR** (`DEFAULT_IMAGE`): ein neues +GHCR-Image → PR, ein Mensch merged → neuer `v*`-Tag → neues `.deb` → `apt upgrade`. Renovate ist seit +2026-09-25 abgeschaltet (Kevin); bis es mit einer GitHub-App wieder läuft, entsteht der PR von Hand. diff --git a/docs/operations.md b/docs/operations.md index 6564f55..8862328 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 ``` @@ -29,7 +29,8 @@ den Dienst — gebunden an **`127.0.0.1:8080`**. Verzeichnisse: `secrets_dir` `0700`), `instances_dir` (`/var/lib/linuxmuster-radius/instances`, als Git-Repo = Change-Log: jedes `create`/`set-ldap-ca`/`rm` ist ein Commit, `sudo -u lmnradius git -C /var/lib/linuxmuster-radius/instances log` zeigt die Historie; die `postinst` legt Repo -und Identität als `lmnradius` an und holt beim Upgrade liegengebliebene Datensätze nach). +und Identität als `lmnradius` an, schaltet git-Hintergrundwartung im Repo ab +(`maintenance.auto false`, `gc.auto 0`) und holt beim Upgrade liegengebliebene Datensätze nach). ## Erstinbetriebnahme (einmalig) @@ -164,7 +165,7 @@ lmnradius rollback default-school # auf das letzte bekannt-gute I Das Update zieht den neuen Digest, ersetzt den Container, wartet auf `healthy` (winbind- Trust **und** radiusd erreichbar) und **rollt bei Fehler automatisch zurück** — die Schule bleibt online. Welcher Digest in Produktion gehört, entscheidet ein **gemergter -Renovate-PR** (nie Auto-Merge). Bei einem **`.deb`-Upgrade** ruft die `postinst` +Digest-Bump-PR** (nie Auto-Merge; von Hand, solange Renovate abgeschaltet ist). Bei einem **`.deb`-Upgrade** ruft die `postinst` automatisch `update-all` auf (best-effort; Instanzen auf dem Default werden übersprungen, die apt-Transaktion scheitert daran nie). @@ -296,7 +297,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/test-strategy.md b/docs/test-strategy.md index c2f97e0..0fbcfb8 100644 --- a/docs/test-strategy.md +++ b/docs/test-strategy.md @@ -12,11 +12,63 @@ SPDX-License-Identifier: GPL-3.0-or-later ## Fast-Tier (lokal / CI) - `ruff check` · `ruff format --check` · `mypy` · `pytest` · `shellcheck` · `reuse lint` -- Aggregat: `bash scripts/tests/run.sh quick` (entsteht in P1/P2). -- Lockfiles: `bash scripts/check-lockfiles.sh` (CI-Job `lockfile`; braucht `uv` und PyPI) — - 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. +- Aggregat: `bash scripts/tests/run.sh quick` = Lock-Tor zuerst, dann lint, unit und der + Lock-Regressionstest; scheitert das Tor, bricht run.sh ab und nichts weiter läuft (lint, unit + und der Lock-Test könnten Code aus einer Sperrdatei ausführen). `run.sh gate` ist nur das Tor. +- Lock-Tor: `bash scripts/check-lockfiles.sh` — **das** Tor vor allem, was aus einer + Sperrdatei installiert wird (CI-Fast-Tier und CI-Job `lock-gates-build` als erster Schritt, + Job `lockfile` in ci.yml und release.yml, `packaging/build-venv.sh`, `run.sh`). Prüft alle drei Sperrdateien: Grammatik, + uv-Sperrdatei = genau das uv aus `uv-requirements.in` mit PyPI-Hashes, dann uv aus ihr in + ein isoliertes venv (absoluter Pfad), Pins = Hülle von `pyproject.toml`/ + `build-requirements.in`, jede Prüfsumme von PyPI, jede Fassung hat ein Wheel für CPython + 3.12/glibc 2.39/x86_64. Braucht `/usr/bin/python3` mit venv (python3-venv) und PyPI, kein uv + vorab. Unabhängig von PATH, venv und `PYTHON*`/`UV_*`/`PIP_*` des Aufrufers; nicht + neutralisiert (Grenze): `BASH_ENV`, exportierte Shell-Funktionen, Proxy-/CA-Variablen. Ohne Netz + scheitert es nach Sekunden (kurze PyPI-Timeouts, Abbruch beim ersten unlesbaren Pin). + **Grenze:** eine andere echte Fassung (älter oder neuer, echte Hashes), die die deklarierten + Anforderungen erfüllt, besteht das Tor; nur die Review fängt sie. `pytest` und `mypy` laufen + in CI gegen die gelockten Fassungen, installiert erst nach dem Tor. +- Lock-Tore: `bash scripts/tests/lock_gates.sh` (CI-Job `fast`; braucht PyPI, überspringt + nie; bricht sofort ab, wenn die committeten Sperrdateien das Tor nicht bestehen, denn jeder + Fall arbeitet auf Kopien davon) — 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, …). Dazu: + - **K1:** das Wheel aus `scripts/tests/k1_wheel.py` (ausführbare `bin/`-Skripte `diff`, + `comm`, `sort`, `awk`, `grep`, `cut`, `cp`, `python3`, `python`, `pip`, `uv`, `bash`, … und + eine `.pth`, alle schreiben eine Markerdatei), als echter Pin (Name und Hash echt, + Veröffentlichung nur in der Wegwerfkopie simuliert) in der Build-, der Laufzeit-, in beiden + oder in der uv-Sperrdatei: Tor und `build-venv.sh` weisen es ab, der Marker entsteht nie. + - **R6:** das Wheel ist scharf — ohne Tor installiert, sind seine `bin/`-Skripte ausführbare + Dateien und schreiben den Marker, ebenso die `.pth`; Gegenprobe: `build-venv.sh` ohne den + Tor-Aufruf erzeugt den Marker aus einem `bin/`-Skript. Die Gegenproben (hier und bei R2) + installieren nur Fixture-Sperrdateien, die allein das Test-Wheel pinnen, nie die + Sperrdateien des Checkouts (kalte Prüfung r3, F1). + - **R1:** unter vergifteter Umgebung (aktiviertes venv mit dem Wheel vorn im PATH, + `VIRTUAL_ENV`, `PYTHONPATH` mit Marker-`sitecustomize`, `PYTHONHOME`, `UV_*`/`PIP_*` samt + Konfigurationsdateien, die Paketquelle und Interpreter umlenken, `.venv` im Checkout) gleiche + Urteile und kein Marker: `check-lockfiles.sh`, `build-venv.sh`, `run.sh gate`/`lint`. + - **R2:** die Lock-Schritte von ci.yml (`fast`, `lockfile`) und release.yml (`lockfile`), + per `scripts/tests/ci_step.py` wörtlich ausgelesen und wie in Actions nachgefahren, bleiben + mit einem gepflanzten Paket in jeder Sperrdatei am Tor stehen; nichts wird installiert, kein + Marker. Gegenprobe: die Sperrdatei-Zeilen des Install-Schritts ohne Tor-Schritt davor + installieren es, der Marker entsteht aus einem `bin/`-Skript. `controlplane/tests/ + test_packaging.py` hält die Reihenfolge der Workflow-Schritte zusätzlich statisch fest. + Mit `LOCK_GATES_DEB=1` im Build-Image zusätzlich der ganze `make deb` je Fall (CI-Job + `lock-gates-build`): muss ohne `.deb` und ohne Marker scheitern, auch unter der vergifteten + Umgebung. +- `make deb` selbst: `bash scripts/tests/make_deb_checks.sh` (CI-Job `lock-gates-build`, im + Build-Image): ein vollständiger Bau eines schmutzigen git-Checkouts (geänderte, gelöschte, + gestagte, nicht hinzugefügte Datei, Modus 0600 und umask 002, versionierter Symlink, + ignorierte Geheimnisse) unter der vergifteten Umgebung und mit fsmonitor, Filter und Hooks in + `.git`: baut, warnt vor und nach dem Bau über jede Abweichung von HEAD (und dass die Version + die des Changelogs bleibt), packt genau die versionierten Dateien mit 0644/0755 und den + Symlink, führt nichts aus `.git` oder der Umgebung aus. Ein Worktree ohne erreichbares + Repository bricht ab, ohne etwas zu packen; `make_deb_checks.sh guard build` als root: ein + Checkout eines anderen Nutzers wird von git's Eigentümerschutz abgewiesen, nichts läuft. ## Heavy-Tier (crabbox, Docker) diff --git a/docs/threat-model.md b/docs/threat-model.md index a0d5120..e3b04f3 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -55,20 +55,41 @@ 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 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 - `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 + 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. **Nachgehärtet (7.3.4, K1, Runden 3/4):** + nichts aus den Paket-Sperrdateien (`requirements.lock`, `build-requirements.lock`) wird + installiert und kein Programm aus einem venv daraus läuft, bevor alle drei Sperrdateien + voll geprüft sind (Grammatik, Hashes von PyPI, Pins = Hülle der Eingaben); uv kommt aus der + uv-Sperrdatei erst, nachdem diese geprüft ist (genau das uv aus `uv-requirements.in`, Hashes + von PyPI). Das gilt im Bau, im CI-Fast-Tier, in den CI-Jobs `lockfile` (ci.yml und Release) + und `lock-gates-build` und lokal in `run.sh` (bricht nach rotem Tor ab); die Gegenproben der + Lock-Tests installieren nur Fixture-Sperrdateien. Das eine Tor ist + `scripts/check-lockfiles.sh`, mit eigenem, isoliertem uv. PATH, aktiviertes venv, `.venv` + im Checkout und `PYTHON*`/`UV_*`/`PIP_*` des Aufrufers steuern die Tore nicht; nicht + neutralisiert (Grenze) sind `BASH_ENV`, exportierte Shell-Funktionen und Proxy-/CA-Variablen + — wer sie setzt, führt ohnehin Code als der Aufrufer aus. + `make deb` baut nur versionierte Dateien, führt nichts aus der `.git`-Konfiguration des + Checkouts aus (kein fsmonitor, keine Hooks, keine Filter) und verzichtet nicht auf git's + Eigentümerschutz. `scripts/tests/lock_gates.sh` und `make_deb_checks.sh` halten die Fälle + fest (mit Gegenproben ohne Tor); neue Fassungen nur per PR, den ein Mensch + merged (ADR-016; von Hand, solange Renovate abgeschaltet ist). Das Build-Image (`lmndev-runner`, fremde Org, wöchentlich neu gebaut, Build als root) steht per Digest, jede Action per Commit-SHA; das Release entsteht als Entwurf und wird erst nach dem sha256-Abgleich der Assets veröffentlicht (ADR-017). **Restlücke:** wer einen Bump-PR merged, vertraut der neuen Fassung — die Prüfsumme belegt nur, dass genau diese Datei gebaut wird, nicht, dass sie - gutartig ist. **Verifikation:** zwei Bauten ergeben dieselbe Paketliste, `pip freeze` + gutartig ist. Und: eine andere echte Fassung eines gepinnten Pakets (älter oder neuer, mit + echten Hashes), die die deklarierten Anforderungen erfüllt, besteht alle Tore — nur die + Review des Sperrdatei-Diffs fängt sie. **Verifikation:** zwei Bauten ergeben dieselbe Paketliste, `pip freeze` im venv = Lockfile; Negativtests des Lockfile-Checks (`work/campaign/stufe-a-radius.md` im Hub). diff --git a/image/Dockerfile b/image/Dockerfile index 3c4fc04..2b967b3 100644 --- a/image/Dockerfile +++ b/image/Dockerfile @@ -20,7 +20,8 @@ # under /etc/freeradius/3.0/ (owned by the freeradius-config dependency); loadable # modules are /usr/lib/freeradius/rlm_*.so. # The base by digest: the tag is rebuilt upstream, the digest names exactly one image. -# Renovate proposes new 24.04 digests as PRs (never 26.04: a new linuxmuster line). +# New 24.04 digests are raised by hand while Renovate is disabled (never 26.04: a new +# linuxmuster line). FROM ubuntu:24.04@sha256:008173c23f95b170204355c12626cb5a965d779a7e1283b09e9cffbb1bf33ca3 ENV DEBIAN_FRONTEND=noninteractive 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/build-venv.sh b/packaging/build-venv.sh new file mode 100755 index 0000000..52710e6 --- /dev/null +++ b/packaging/build-venv.sh @@ -0,0 +1,97 @@ +#!/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 + +# Which programs run is not left to the PATH, venv or Python/pip/uv settings of the caller (R1): a +# fixed PATH without any venv bin/ (an activated venv, a checkout's .venv), no VIRTUAL_ENV, no +# PYTHON*, UV_* or PIP_* variables and no pip configuration file. debian/rules calls this script +# with a bare `bash`, and dpkg-buildpackage may be started by hand, so it cleans up itself. Not +# neutralized, and named as the limit: BASH_ENV (bash runs it before a script's first line), +# exported shell functions, and the proxy/CA variables (HTTPS_PROXY, SSL_CERT_FILE, +# REQUESTS_CA_BUNDLE, ...) that decide whom pip and the gate trust as PyPI. Whoever sets those in +# the caller's environment already runs code as the caller. +export PATH=/usr/sbin:/usr/bin:/sbin:/bin +unset VIRTUAL_ENV CONDA_PREFIX +for v in $(compgen -e); do + case "$v" in PYTHON* | UV_* | PIP_*) unset "$v" ;; esac +done +export PIP_CONFIG_FILE=/dev/null PIP_DISABLE_PIP_VERSION_CHECK=1 + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)" +VENV="${1:?usage: build-venv.sh }" +GATE="$ROOT/scripts/lockfile_gate.py" +CP="$ROOT/controlplane" +LOCKS=("$CP/build-requirements.lock" "$CP/requirements.lock") +WHEELS="$(mktemp -d)" +trap 'rm -rf "$WHEELS"' EXIT +die() { echo "build-venv.sh: $*" >&2; exit 1; } +# The system interpreter, isolated (-I: no PYTHON* variables, no user site, neither the script's +# directory nor the working directory on sys.path) -- never one from a venv this script +# populates from a lockfile. +PY=/usr/bin/python3 + +# K1 (linuxmusterDEV work/tasks/nachbesserung-kalte-pruefung-umbau.md): no program or +# interpreter from a venv populated by requirements.lock / build-requirements.lock runs, and +# no such bin/ is on PATH, until ALL locks are fully verified -- grammar, every hash published +# by PyPI, and the pin set equal to the closure of the declared inputs. A wheel from the build +# lock ships bin/ scripts and a .pth; installing it before the set/closure check would run +# that .pth while lmnradius's own wheel is built (a lock-only build-lock pin ran a .pth 18 +# times on the pre-K1 head, though the extra pin was caught afterwards). So the venv below is +# created only after step 3. +echo "== lockfiles: grammar and published hashes ==" +# 1. Grammar (stdlib only): every line is one uv writes. pip would also honour an indented +# URL requirement, an --extra-index-url line and every other option line. +"$PY" -I -B "$GATE" lint "${LOCKS[@]}" || die "a lockfile holds a line uv does not write" +# 2. Every hash is one PyPI publishes for that exact version (pip only checks the file it +# downloads, so a replaced sdist or other-platform-wheel hash would pass pip). +"$PY" -I -B "$GATE" pypi "${LOCKS[@]}" || die "a lockfile hash is not a file PyPI publishes" + +echo "== lockfiles: the uv lock, uv, and pin set == closure of the declared inputs ==" +# 3. scripts/check-lockfiles.sh, the one lock gate: the grammar of all three locks, the uv +# lock is exactly the published uv of uv-requirements.in, uv from it into an isolated venv +# (called by absolute path, never put on PATH), and uv re-resolves pyproject.toml / +# build-requirements.in: the committed pins must be exactly that closure -- an extra pin +# (even with real PyPI hashes and a shipped wheel) is rejected HERE, before any lock wheel +# is unpacked. +bash "$ROOT/scripts/check-lockfiles.sh" \ + || die "a lockfile is not the closure of its declared inputs (extra/other pins)" + +echo "== venv @ $VENV ==" +rm -rf "$VENV" +mkdir -p "$(dirname "$VENV")" +"$PY" -I -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`, raised in +# reviewed 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 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" +"$PY" -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/packaging/make-deb.sh b/packaging/make-deb.sh new file mode 100755 index 0000000..82c9983 --- /dev/null +++ b/packaging/make-deb.sh @@ -0,0 +1,194 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# `make deb` calls this. It runs dpkg-buildpackage on an export of exactly the files git +# tracks, as they are in the working tree -- never an untracked or .gitignored file a working +# checkout carries (a venv, a cache, deploy/secrets/krb5.conf, deploy/**/ssl_db/, .env, a token +# under .claude/; linuxmusterDEV work/tasks/nachbesserung-kalte-pruefung-umbau.md, K3, R3). +# The .deb, .changes, .buildinfo, .dsc and source tarball land one level ABOVE the checkout. +# +# What is built, and what is said about it (R4): +# * the tracked files (the git index) with their working-tree content: uncommitted edits +# and staged new files ARE built, a tracked file deleted in the working tree is left out; +# * untracked files are NOT built, even if they are not ignored (git add them first); +# * whenever that differs from HEAD, a WARNING lists every difference before and after the +# build: the package still carries the version of debian/changelog, so such a .deb is not +# the release of that version; +# * modes as git records them (0644/0755, directories 0755), whatever the umask of the +# checkout or of this build; mtimes = the changelog date; tracked symlinks stay symlinks. +# Deliberate exclusions from the published source: .github (workflows) and .claude +# (developer tooling with internal endpoints/token ids); dpkg-source drops .gitignore files. +# +# git only reads here, and nothing configured in the checkout runs: git's ownership guard stays +# on (no safe.directory waiver -- a checkout owned by another user is refused, as git refuses +# it; CI marks its own workspace safe by its exact path), core.fsmonitor and hooks are switched +# off, and the files are copied from the working tree instead of through a git command that +# would run a clean/smudge filter (stash, archive, status). A .git that git cannot use -- a +# worktree whose repository is not mounted into the container, a refused owner -- stops the +# build: packing the tree as it is would pack everything in it. Only without any .git (an +# unpacked source package) is the tree built in place. +set -euo pipefail + +# Which programs run is not left to the PATH, venv, Python/pip/uv or git variables of the caller +# (R1). Not neutralized, and named as the limit: BASH_ENV (bash runs it before a script's first +# line), exported shell functions, and the proxy/CA variables (HTTPS_PROXY, SSL_CERT_FILE, +# REQUESTS_CA_BUNDLE, ...) that decide whom the build trusts as PyPI. Whoever sets those in the +# caller's environment already runs code as the caller. +export PATH=/usr/sbin:/usr/bin:/sbin:/bin +unset VIRTUAL_ENV CONDA_PREFIX +for v in $(compgen -e); do + case "$v" in PYTHON* | UV_* | PIP_* | GIT_*) unset "$v" ;; esac +done + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)" +PKG=linuxmuster-radius +cd "$ROOT" +# -tc cleans the build tree afterwards; -I keeps dpkg-source's default ignore list (.git, +# editor backups, ...); the two -I patterns drop the deliberate exclusions. +DPKG_ARGS=(-us -uc -tc -I -I.github -I.claude) +say() { echo "make-deb.sh: $*"; } +die() { echo "make-deb.sh: $*" >&2; exit 1; } +git_() { git --no-pager -c core.fsmonitor=false -c core.hooksPath=/dev/null -C "$ROOT" "$@"; } + +if [ ! -e "$ROOT/.git" ] && [ ! -L "$ROOT/.git" ]; then + say "no .git here (an unpacked source package), building in place" + exec dpkg-buildpackage "${DPKG_ARGS[@]}" +fi + +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +if ! top="$(git_ rev-parse --show-toplevel 2> "$work/git.err")"; then + sed 's/^/ git: /' "$work/git.err" >&2 + die "$ROOT/.git exists, but git cannot use it. Not building: without git the source" \ + "package would pack every file in the tree. A git worktree needs its repository's" \ + "common .git directory at the same path (docker: add -v \"\$C\":\"\$C\" with" \ + "C=\$(git rev-parse --path-format=absolute --git-common-dir), see the Makefile); a" \ + "checkout owned by another user is refused by git's ownership guard -- build as its" \ + "owner, or mark exactly this path safe (git config --global --add safe.directory PATH)" \ + "if you trust its .git/config." +fi +[ "$top" = "$ROOT" ] || die "git's top level is $top, not $ROOT" +head="$(git_ rev-parse --verify --short HEAD)" || die "no commit to build from" +VERSION="$(dpkg-parsechangelog -S Version)" +STAMP="@$(dpkg-parsechangelog -S Timestamp)" + +# ------------------------------------------------------------------ what is built +# The index: " \t", NUL-separated. +git_ ls-files -s -z > "$work/index" +: > "$work/files" # paths to copy, NUL-separated +: > "$work/modes" # " ", NUL-separated +: > "$work/check" # " " of present regular files, compared below +declare -a changes=() +while IFS= read -r -d '' entry; do + meta="${entry%%$'\t'*}" path="${entry#*$'\t'}" + read -r mode obj stage <<< "$meta" + [ "$stage" = 0 ] || die "unmerged path (resolve the conflict first): $path" + case "$path" in *$'\n'*) die "a tracked path contains a newline: ${path@Q}" ;; esac + if [ ! -e "$path" ] && [ ! -L "$path" ]; then + changes+=("D $path (deleted in the working tree: left out)") + continue + fi + case "$mode" in + 100644 | 100755) + [ -f "$path" ] && [ ! -L "$path" ] \ + || die "tracked as a file, but not a regular file in the working tree: $path" + if [ "$mode" = 100755 ] && [ ! -x "$path" ]; then + changes+=("M $path (not executable in the working tree; built 0755 as git records)") + elif [ "$mode" = 100644 ] && [ -x "$path" ]; then + changes+=("M $path (executable in the working tree; built 0644 as git records)") + fi + printf '%s %s\n' "$obj" "$path" >> "$work/check" + ;; + 120000) + [ -L "$path" ] || die "tracked as a symlink, but not one in the working tree: $path" + [ "$(printf '%s' "$(readlink "$path")" | git_ hash-object --stdin)" = "$obj" ] \ + || changes+=("M $path (symlink target changed)") + ;; + *) die "unsupported tracked entry (mode $mode, a submodule?): $path" ;; + esac + printf '%s\0' "$path" >> "$work/files" + printf '%s %s\0' "$mode" "$path" >> "$work/modes" +done < "$work/index" +# Working-tree content vs index, raw bytes (--no-filters: no clean filter runs). +if [ -s "$work/check" ]; then + cut -d' ' -f2- "$work/check" | git_ hash-object --no-filters --stdin-paths > "$work/wt" + while IFS=' ' read -r obj path <&3 && read -r now <&4; do + [ "$obj" = "$now" ] || changes+=("M $path (changed in the working tree)") + done 3< "$work/check" 4< "$work/wt" +fi +# Index vs HEAD (staged, not committed; no working tree involved). +git_ diff-index --cached --no-renames --name-status -z HEAD > "$work/staged" +while IFS= read -r -d '' st && IFS= read -r -d '' path; do + case "$st" in + A) changes+=("A $path (staged, not committed)") ;; + D) changes+=("D $path (removed from the index, not committed)") ;; + *) changes+=("$st $path (staged, not committed)") ;; + esac +done < "$work/staged" +git_ ls-files --others --exclude-standard -z > "$work/untracked" + +warn() { + local u + if [ "${#changes[@]}" -gt 0 ]; then + say "WARNING: this build is NOT commit $head, it carries uncommitted changes:" + printf 'make-deb.sh: %s\n' "${changes[@]}" + fi + if [ -s "$work/untracked" ]; then + say "WARNING: untracked files are NOT in this build (git add them to build them):" + while IFS= read -r -d '' u; do say " ?? $u"; done < "$work/untracked" + fi + if [ "${#changes[@]}" -gt 0 ] || [ -s "$work/untracked" ]; then + say "WARNING: the package version stays $VERSION (debian/changelog): do not take this" \ + ".deb for the release $VERSION." + fi +} +warn + +# ------------------------------------------------------------------ the export +src="$work/$PKG-$VERSION" # canonical dir name -> stable tarball top level +mkdir -m 0755 "$src" +tar -C "$ROOT" --null --no-recursion -T "$work/files" -cf - | tar -C "$src" --no-same-owner -xf - +find "$src" -type d -exec chmod 0755 {} + +while IFS= read -r -d '' entry; do + mode="${entry%% *}" path="${entry#* }" + case "$mode" in + 100755) chmod 0755 "$src/$path" ;; + 100644) chmod 0644 "$src/$path" ;; + esac +done < "$work/modes" +find "$src" -exec touch -h -d "$STAMP" {} + +tr '\0' '\n' < "$work/files" | LC_ALL=C sort > "$work/tracked" +say "building $(wc -l < "$work/tracked") tracked files (HEAD $head) in $src" +( cd "$src" && dpkg-buildpackage "${DPKG_ARGS[@]}" ) + +# The source tarball must hold exactly the exported files minus the deliberate exclusions: +# never an untracked or ignored file, and prove it here rather than trust the export. +tar="$work/${PKG}_${VERSION}.tar.xz" +[ -f "$tar" ] || die "no source tarball at $tar" +# Members that are not directories (files and symlinks; directory entries end in '/'); strip +# the canonical top-level dir. Expected = exported minus .github, .claude and every .gitignore +# (dpkg-source drops those by its default ignore list; a documented tool exclusion). +grep -vE '^(\.github|\.claude)(/|$)' "$work/tracked" | grep -vE '(^|/)\.gitignore$' \ + | LC_ALL=C sort -u > "$work/expected" +tar -tJf "$tar" | grep -v '/$' | sed -e 's|^\./||' -e "s|^$PKG-$VERSION/||" \ + | grep -v '^$' | LC_ALL=C sort -u > "$work/intar" +leaked="$(comm -13 "$work/expected" "$work/intar")" +missing="$(comm -23 "$work/expected" "$work/intar")" +if [ -n "$leaked" ]; then + printf ' %s\n' "$leaked" >&2 + die "in the source tarball but not an exported tracked file (above)" +fi +if [ -n "$missing" ]; then + printf ' %s\n' "$missing" >&2 + die "tracked but missing from the source tarball (dpkg-source default ignores?) (above)" +fi +bad_modes="$(tar -tvJf "$tar" | awk '$1 !~ /^(-rw-r--r--|-rwxr-xr-x|drwxr-xr-x|lrwxrwxrwx)$/')" +[ -z "$bad_modes" ] || { printf ' %s\n' "$bad_modes" >&2; die "unexpected modes in the source tarball"; } +say "source tarball holds exactly the tracked files minus .github/.claude ($(wc -l < "$work/expected")), modes 0644/0755" + +# dpkg-buildpackage wrote the artefacts one level above the build tree (in $work); move them +# next to the checkout, where CI and the developer expect them. +mv "$work/${PKG}_"* "$ROOT/.." +say "artefacts in $(cd "$ROOT/.." && pwd)" +warn 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..685c124 100755 --- a/scripts/check-lockfiles.sh +++ b/scripts/check-lockfiles.sh @@ -2,31 +2,100 @@ # SPDX-FileCopyrightText: Kevin Stenzel # 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 -# 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). +# THE lock gate. It proves that the hash-pinned lockfiles under controlplane/ are exactly what +# they claim to be, and it is the first thing every consumer runs, before anything from a lockfile +# is installed: the CI fast tier and the CI job lock-gates-build (first step each), the CI and +# release `lockfile` jobs, packaging/build-venv.sh (so `make deb`, the CI `package` job and the +# release build) and scripts/tests/run.sh, which stops when it fails. The lock regression tests +# run only after it passed on the committed files, and their counter-probes (install paths without +# the gate) install fixture locks, never these files (linuxmusterDEV +# work/tasks/nachbesserung-kalte-pruefung-umbau.md, K1, R1, R2, S1). packaging/build-venv.sh +# installs the locks with --no-deps, so nothing else would notice a dependency added to +# pyproject.toml without re-locking. +# 0. Every line of all three lockfiles (requirements, build-requirements, uv-requirements) +# 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 until +# this passes. `check-lockfiles.sh --lint [LOCK...]` runs only this step (no network). +# 1. The resolver's own lock, uv-requirements.lock, holds exactly `uv==` and every hash in it is a file PyPI publishes for that version +# (stdlib only). Only then is uv installed from it, --require-hashes, into an isolated +# venv of its own (the stdlib/ensurepip pip of /usr/bin/python3), and called by absolute +# path. No other uv ever runs here, whatever the caller has on PATH. +# 2. The header records the canonical command (the one that regenerates the lockfile). # --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. -# 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 +# 3. Re-resolving with that command, preferring the locked versions, yields the same pins: +# the pin set is the closure of pyproject.toml / build-requirements.in, nothing more and +# nothing less (so an extra pin, even one with PyPI's genuine hashes, fails here, and so +# does a pin younger than seven days). +# 4. Resolving strictly for the target -- CPython 3.12 on Ubuntu 24.04 (glibc 2.39, +# 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 +# 5. Every hash in a lockfile is one PyPI publishes for that exact version. This needs a # resolution WITHOUT the lockfile in place: uv carries the hashes of kept pins over # from an existing output file instead of fetching them again. Hashes PyPI gained # since (a wheel added to an existing release) are fine: that file is not in the # lock, so pip would refuse it. -# Needs uv and access to PyPI. To regenerate a lockfile, run the command in its header -# inside controlplane/. +# Limit: the pins are compared by NAME with the closure; the resolution prefers the locked +# versions. So another real release of a pinned package (older or newer, at least a week old, +# with its genuine hashes) that still satisfies the declared requirements passes every gate; +# only the review of the lockfile diff catches it. +# +# What it takes from the caller's environment (R1, S4): not the PATH (fixed, no venv bin/), not +# VIRTUAL_ENV or any PYTHON*, UV_* or PIP_* variable (all dropped, PIP_REQUIREMENT and +# PIP_CONSTRAINT included), no pip/uv configuration file; Python is /usr/bin/python3 -I, uv gets +# that interpreter explicitly (--python) and reads no uv.toml (--no-config), so it neither +# discovers a project venv nor a redirected index. HOME stays (pip/uv caches; every file is +# hash-checked). Not neutralized, and named as the limit: BASH_ENV (bash runs it before a script's +# first line), exported shell functions, and the proxy/CA variables (HTTPS_PROXY, SSL_CERT_FILE, +# REQUESTS_CA_BUNDLE, ...) that decide whom the gate trusts as PyPI. Whoever sets those in the +# caller's environment already runs code as the caller. +# Needs /usr/bin/python3 with venv/ensurepip (python3-venv) and access to PyPI. To regenerate +# a lockfile, run the command in its header inside controlplane/. set -euo pipefail -ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +export PATH=/usr/sbin:/usr/bin:/sbin:/bin +unset VIRTUAL_ENV CONDA_PREFIX +for v in $(compgen -e); do + case "$v" in PYTHON* | UV_* | PIP_*) unset "$v" ;; esac +done +export PIP_CONFIG_FILE=/dev/null PIP_DISABLE_PIP_VERSION_CHECK=1 + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)" +GATE="$ROOT/scripts/lockfile_gate.py" +PY=(/usr/bin/python3 -I -B) +LOCKS=("$ROOT/controlplane/requirements.lock" "$ROOT/controlplane/build-requirements.lock") +UVLOCK="$ROOT/controlplane/uv-requirements.lock" + +if [ "${1:-}" = --lint ]; then + shift + [ "$#" -gt 0 ] || set -- "${LOCKS[@]}" "$UVLOCK" + exec "${PY[@]}" "$GATE" lint "$@" +fi +if ! "${PY[@]}" "$GATE" lint "${LOCKS[@]}" "$UVLOCK"; 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 +# 1. uv, verified before it is installed, installed before anything else from a lock. +if ! "${PY[@]}" "$GATE" only uv "$UVLOCK" --input "$ROOT/controlplane/uv-requirements.in" \ + || ! "${PY[@]}" "$GATE" pypi "$UVLOCK"; then + echo "FAIL uv-requirements.lock is not exactly the published uv of uv-requirements.in" + exit 1 +fi +/usr/bin/python3 -I -m venv "$TMP/uv" +"$TMP/uv/bin/python" -I -m pip install --quiet --require-hashes --only-binary :all: --no-deps \ + -r "$UVLOCK" +UV=("$TMP/uv/bin/uv" pip compile --quiet --no-config --python /usr/bin/python3) + +# 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; } @@ -52,8 +121,7 @@ for pair in pyproject.toml:requirements.lock build-requirements.in:build-require if [ "$mode" = target ]; then extra=(--python-platform=x86_64-manylinux_2_39 --only-binary=:all:) fi - (cd "$dir" && uv pip compile --quiet "${LOCK_ARGS[@]}" "${extra[@]}" \ - --output-file="$lock" "$src") + (cd "$dir" && "${UV[@]}" "${LOCK_ARGS[@]}" "${extra[@]}" --output-file="$lock" "$src") if ! diff -u <(pins "$committed") <(pins "$dir/$lock") > "$TMP/pins.diff"; then fail "$lock: pins differ from a fresh $mode resolution" cat "$TMP/pins.diff" @@ -62,7 +130,7 @@ for pair in pyproject.toml:requirements.lock build-requirements.in:build-require mkdir -p "$TMP/fresh" pins "$committed" > "$TMP/fresh/$lock.in" - (cd "$TMP/fresh" && uv pip compile --quiet --generate-hashes --python-version=3.12 \ + (cd "$TMP/fresh" && "${UV[@]}" --generate-hashes --python-version=3.12 \ --no-deps --output-file="$lock" "$lock.in") unknown="$(comm -23 <(hashes "$committed") <(hashes "$TMP/fresh/$lock"))" if [ -n "$unknown" ]; then @@ -73,4 +141,5 @@ for pair in pyproject.toml:requirements.lock build-requirements.in:build-require echo "ok $lock: $(pins "$committed" | wc -l) pins, $(hashes "$committed" | wc -l) hashes" fi done +[ "$rc" = 0 ] && echo "ok the lockfiles are verified: grammar, uv, published hashes, closure" exit "$rc" diff --git a/scripts/lockfile_gate.py b/scripts/lockfile_gate.py new file mode 100755 index 0000000..14add66 --- /dev/null +++ b/scripts/lockfile_gate.py @@ -0,0 +1,357 @@ +#!/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 only NAME LOCK [--input IN] + LOCK holds exactly one pin, NAME (the tool lock of the resolver uv); with --input, its + version is the one IN (e.g. uv-requirements.in) pins with ==. + 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 briefly, a 404 is final. + + Short on purpose: without network the build must fail within about a minute, not after + retrying every pin for minutes (cold verification r2, F9). cmd_pypi stops at the first + pin it cannot read. + """ + for attempt in (1, 2, 3): + try: + with urllib.request.urlopen(url, timeout=10) 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 * 2) + 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, and at once: an unreachable + # PyPI would only fail every further pin after the same retries. + try: + known = published(pin) + except Exception as e: + errors.append(f"{path}: {pin}: cannot read PyPI: {e}") + return report(errors, "") + 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 cmd_only(args: argparse.Namespace) -> int: + """Fail unless LOCK holds exactly one pin, named NAME (the tool lock, e.g. uv). + + With --input, the pin's version must be the one the input file pins (NAME==VERSION, its + only requirement): the closure of a single ==-pinned tool without dependencies is that pin. + """ + errors: list[str] = [] + pins, errs = parse(args.lock) + errors += errs + names = [p.name for p in pins] + if names != [canonical(args.name)]: + errors.append( + f"{args.lock}: expected exactly the one pin {args.name}, found {names or 'none'}" + ) + if args.input and len(pins) == 1: + reqs = [ + line.split("#", 1)[0].strip() + for line in Path(args.input).read_text(encoding="ascii").splitlines() + ] + reqs = [r for r in reqs if r] + want = f"{canonical(args.name)}=={pins[0].version}" + if reqs != [want]: + errors.append( + f"{args.lock}: pins {pins[0]}, but {args.input} asks for {reqs or 'nothing'}" + ) + return report( + errors, + f"only ok: {args.lock} holds exactly {args.name}=={pins[0].version if pins else '?'}", + ) + + +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("only") + p.add_argument("name") + p.add_argument("lock") + p.add_argument( + "--input", help="the .in file whose one NAME==VERSION the pin must equal" + ) + p.set_defaults(func=cmd_only) + 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()) diff --git a/scripts/tests/ci_step.py b/scripts/tests/ci_step.py new file mode 100755 index 0000000..70cb881 --- /dev/null +++ b/scripts/tests/ci_step.py @@ -0,0 +1,67 @@ +#!/usr/bin/python3 +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Print the `run:` script of one step of a GitHub workflow job (stdlib only, no PyYAML). + + ci_step.py WORKFLOW JOB STEP-NAME + +For scripts/tests/lock_gates.sh, which replays the lock-related steps of ci.yml and +release.yml word for word with a planted lockfile package (R2): the test runs what CI runs, +not a copy that could drift. Reads the layout these workflows use -- `jobs:` at column 0, a +job at 2, `- name:` of a step, `run: |` block or one-line `run:` -- and fails loudly on +anything else, so a reformatted workflow breaks the test instead of silently testing nothing. +""" + +from __future__ import annotations + +import re +import sys + + +def indent(line: str) -> int: + return len(line) - len(line.lstrip(" ")) + + +def main() -> int: + path, job, name = sys.argv[1:4] + lines = open(path, encoding="utf-8").read().split("\n") + try: + start = lines.index(f" {job}:", lines.index("jobs:")) + except ValueError: + sys.exit(f"{path}: no job {job!r}") + end = next( + (n for n in range(start + 1, len(lines)) if re.match(r"^ \S", lines[n])), + len(lines), + ) + for n in range(start + 1, end): + m = re.match(r"^( *)- name: (.*)$", lines[n]) + if not m or m[2].strip().strip("'\"") != name: + continue + dash, keys = len(m[1]), len(m[1]) + 2 + k = n + 1 + while k < end and (not lines[k].strip() or indent(lines[k]) > dash): + line = lines[k] + if indent(line) == keys and re.fullmatch(r" *run: \|", line): + block = [] + k += 1 + while k < end and (not lines[k].strip() or indent(lines[k]) > keys): + block.append(lines[k]) + k += 1 + while block and not block[-1].strip(): + block.pop() + if not block: + sys.exit(f"{path}: {job}/{name}: empty run block") + cut = indent(block[0]) + print("\n".join(b[cut:] if b.strip() else "" for b in block)) + return 0 + one = re.fullmatch(r" *run: (\S.*)", line) + if indent(line) == keys and one: + print(one[1]) + return 0 + k += 1 + sys.exit(f"{path}: {job}/{name}: no run") + sys.exit(f"{path}: no step {name!r} in job {job!r}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/tests/k1_wheel.py b/scripts/tests/k1_wheel.py new file mode 100755 index 0000000..01c8fa7 --- /dev/null +++ b/scripts/tests/k1_wheel.py @@ -0,0 +1,76 @@ +#!/usr/bin/python3 +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Build the attack wheel of the lock-gate regression tests (stdlib only). + + k1_wheel.py OUTDIR MARKER -> prints the path of OUTDIR/zzzk1-1.0-py3-none-any.whl + +The wheel of the cold verifications (linuxmusterDEV work/tasks/nachbesserung-kalte-pruefung- +umbau.md, K1, R6): a `.pth` that appends a line to MARKER in every interpreter of the venv it +is installed into, and executable scripts under bin/ -- the tools the gates use (diff, comm, +sort, awk, grep, cut, cp, python3, uv, ...) plus python and pip, the entry points a venv's own +programs go through -- each appending "bin/ ran: " to MARKER and exiting 0. Any +line in MARKER proves that code of a lockfile package ran. + +The scripts are *.data/scripts/ entries with S_IFREG|0755 in the zip: pip marks an installed +script executable only for a regular-file mode with an x bit (a bare 0o755 << 16, as the first +version of this test had, installs them 0644 and the bin/ half of the test could never fire; +cold verification r2 of radius, F8). +""" + +from __future__ import annotations + +import base64 +import hashlib +import stat +import sys +import zipfile + +TOOLS = ( + "diff comm sort awk grep cut cp python3 python pip uv sed tar git mktemp find env xargs " + "head tail wc tr cat rm mv chmod touch readlink bash" +).split() + + +def main() -> int: + out, marker = sys.argv[1:3] + pth = ( + "import os; open(%r, 'a').write('pth ran in pid %%d\\n' %% os.getpid())\n" + % marker + ) + files = { + "zzzk1/__init__.py": "", + "zzzk1.pth": pth, + "zzzk1-1.0.dist-info/METADATA": "Metadata-Version: 2.1\nName: zzzk1\nVersion: 1.0\n", + "zzzk1-1.0.dist-info/WHEEL": ( + "Wheel-Version: 1.0\nGenerator: t\nRoot-Is-Purelib: true\nTag: py3-none-any\n" + ), + } + for tool in TOOLS: + files[f"zzzk1-1.0.data/scripts/{tool}"] = ( + f'#!/bin/sh\necho "bin/{tool} ran: $*" >> {marker}\nexit 0\n' + ) + record = [] + for name, text in files.items(): + data = text.encode() + digest = ( + base64.urlsafe_b64encode(hashlib.sha256(data).digest()) + .rstrip(b"=") + .decode() + ) + record.append(f"{name},sha256={digest},{len(data)}") + record.append("zzzk1-1.0.dist-info/RECORD,,") + files["zzzk1-1.0.dist-info/RECORD"] = "\n".join(record) + "\n" + path = f"{out}/zzzk1-1.0-py3-none-any.whl" + with zipfile.ZipFile(path, "w") as whl: + for name, text in files.items(): + info = zipfile.ZipInfo(name, (2026, 1, 1, 0, 0, 0)) + mode = 0o755 if "/scripts/" in name else 0o644 + info.external_attr = (stat.S_IFREG | mode) << 16 + whl.writestr(info, text) + print(path) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/tests/lock_gates.sh b/scripts/tests/lock_gates.sh new file mode 100755 index 0000000..59c99de --- /dev/null +++ b/scripts/tests/lock_gates.sh @@ -0,0 +1,609 @@ +#!/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 and in front of every CI step +# that installs from a lockfile (linuxmusterDEV work/verification/cold-stage-a.md F2, +# work/tasks/nachbesserung-kalte-pruefung-umbau.md K1 and "Runde 3" R1, R2, R6). +# 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 lock gate: CI fast tier and `lockfile` jobs), 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, and: +# K1 a published-looking wheel (scripts/tests/k1_wheel.py: a marker-writing .pth and +# marker-writing bin/ tools) pinned in the build lock, the runtime lock, both, or the uv +# lock is refused before any of its code runs (no marker); +# R6 that wheel is sharp: installed without a gate, its bin/ scripts are executable and +# write the marker, and so does its .pth; +# R1 the gates are not steered by these parts of the caller's environment: an activated +# venv (bin/ first on PATH, VIRTUAL_ENV), a .venv in the checkout, PYTHONPATH/PYTHONHOME, +# UV_*/PIP_* variables and config files that redirect the index or the interpreter -- no +# marker, same verdicts; +# R2 the lock-related steps of ci.yml and release.yml (extracted word for word by +# scripts/tests/ci_step.py) stop at the gate with a planted package, before anything is +# installed; the counter-probe without the gate step installs it and the marker appears. +# The counter-probes (R6, R2) run install paths WITHOUT the gate, so they install fixture +# locks that pin only the test wheel, never the checkout's lockfiles; and nothing after the +# first cases runs unless the committed lockfiles pass the gate (cold verification r3, F1). +# Needs /usr/bin/python3 >= 3.12 with venv/ensurepip (python3-venv) and PyPI; no uv (the gate +# installs its own). 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 and without a marker; 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). The harness drops the same PATH/PYTHON*/UV_*/PIP_*/GIT_* parts of +# its environment as the gates. +set -uo pipefail + +export PATH=/usr/sbin:/usr/bin:/sbin:/bin +unset VIRTUAL_ENV CONDA_PREFIX +for v in $(compgen -e); do + case "$v" in PYTHON* | UV_* | PIP_* | GIT_*) unset "$v" ;; esac +done +export PIP_CONFIG_FILE=/dev/null PIP_DISABLE_PIP_VERSION_CHECK=1 + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)" +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" + +/usr/bin/python3 -I -c 'import sys, venv, ensurepip; sys.exit(sys.version_info < (3, 12))' \ + || { echo "lock_gates.sh: /usr/bin/python3 >= 3.12 with venv/ensurepip is required"; exit 1; } + +# expect