diff --git a/.claude/settings.json b/.claude/settings.json index 66bedef..3054a83 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -1,14 +1,4 @@ { - "env": { - "CRABBOX_PROVIDER": "proxmox", - "CRABBOX_PROXMOX_API_URL": "https://192.168.250.2:8006", - "CRABBOX_PROXMOX_TOKEN_ID": "crabbox@pve!ci", - "CRABBOX_PROXMOX_NODE": "babo", - "CRABBOX_PROXMOX_TEMPLATE_ID": "9400", - "CRABBOX_PROXMOX_STORAGE": "raid5", - "CRABBOX_PROXMOX_BRIDGE": "vmbr1", - "CRABBOX_PROXMOX_INSECURE_TLS": "1" - }, "permissions": { "allow": [ "Bash(crabbox run:*)", diff --git a/.claude/skills/test/SKILL.md b/.claude/skills/test/SKILL.md index 3e416b3..e5d2419 100644 --- a/.claude/skills/test/SKILL.md +++ b/.claude/skills/test/SKILL.md @@ -18,9 +18,15 @@ which the sandboxed dev box lacks. This suite is **authored here, run by the operator**: crabbox leases an ephemeral Proxmox VM, rsyncs the working tree, runs the suite, and tears down. -Provider env (proxmox) comes from `.claude/settings.json` (the **non-secret** provider -config). The `CRABBOX_PROXMOX_TOKEN_SECRET` lives **only** in the gitignored -`.claude/settings.local.json` — never commit it. Confirm with `crabbox doctor`. +The provider settings (`CRABBOX_PROVIDER`, `CRABBOX_PROXMOX_*`: API URL, token id and +secret, node, template, storage, bridge) live **only** in the gitignored +`.claude/settings.local.json` (`env` block) — never in the versioned `.claude/settings.json`, +which holds only the crabbox permissions: they are internal details of Kevin's lab and this +repository is public. Confirm with `crabbox doctor`. + +> **State (2026-09-27): crabbox cannot lease boxes right now** — its Proxmox user was +> removed. Until Kevin sets it up again, the heavy tier does not run; say so in every +> report instead of claiming the E2E. ## Single-box flow (warm once → reuse the slug → stop) @@ -37,7 +43,9 @@ config). The `CRABBOX_PROXMOX_TOKEN_SECRET` lives **only** in the gitignored `.crabbox/captures/*.tar.gz` (logs, timings, ready-made stop command). 5. **Stop** when done: `crabbox stop --id `. -`run.sh` prints `N passed, M failed, K skipped` and exits non-zero on any failure. +`run.sh` prints `N passed, M failed, K skipped` plus every step that was not checked, and +exits 0 only if every step ran and passed: 1 on a failure, 77 if a step was skipped (a missing +tool, e2e without `LMNRADIUS_ALLOW_REAL=1`). `LMNRADIUS_ALLOW_SKIP=1` accepts skips on purpose. `e2e`/`all` refuse to run without `LMNRADIUS_ALLOW_REAL=1` (a guard so heavy suites never fire by accident on the dev box). diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7711a7b..fc27edc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -116,7 +116,7 @@ jobs: # 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. + # gate first; release.yml carries this job character for character, but for its display name. lockfile: runs-on: ubuntu-24.04 steps: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2b4e7eb..8592db4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -48,7 +48,11 @@ on: default: '' jobs: + # Every job carries a display name with the prefix 'release: '. The main ruleset requires the + # ci.yml jobs BY NAME; a release run on the same commit (workflow_dispatch on a PR branch) + # with a job of the same name could otherwise stand in for a red ci.yml check. gate: + name: 'release: gate' runs-on: ubuntu-latest outputs: image: ${{ steps.meta.outputs.image }} @@ -72,10 +76,12 @@ jobs: 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). + # character for character the `lockfile` job of ci.yml (but for the display name, see above): + # 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: + name: 'release: lockfile' runs-on: ubuntu-24.04 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 @@ -87,6 +93,7 @@ jobs: run: bash scripts/check-lockfiles.sh build: + name: 'release: build' needs: gate runs-on: ubuntu-latest container: @@ -133,6 +140,7 @@ jobs: # 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: + name: 'release: file-tree' needs: build runs-on: ubuntu-latest # GitHub-hosted: gh is installed here, not in the container permissions: @@ -237,6 +245,7 @@ jobs: PY install-smoke: + name: 'release: install-smoke' needs: build runs-on: ubuntu-24.04 steps: @@ -272,6 +281,7 @@ jobs: # puts realistic config/state in place, upgrades to the freshly built package and # checks that nothing was lost. It skips itself on the very first release. upgrade-smoke: + name: 'release: upgrade-smoke' needs: build runs-on: ubuntu-24.04 permissions: @@ -525,6 +535,7 @@ jobs: run: sudo journalctl -u linuxmuster-radius.service --no-pager | tail -60 || true release: + name: 'release: release' needs: [gate, lockfile, build, file-tree, install-smoke, upgrade-smoke] if: github.ref_type == 'tag' runs-on: ubuntu-latest @@ -652,7 +663,15 @@ jobs: [ "$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" + if [ "$immutable" = false ]; then + echo "::error::$TAG is published but NOT immutable, its assets can still be replaced: delete release $rid (the tag stays), turn immutable releases on, re-run this job" + else + # Unreadable is not "false": the release may well be immutable (and then cannot be + # replaced anyway), so never tell anyone to delete it on a failed read. One line, or + # the annotation shows only the first line of a multi-line error answer. + shown=${immutable//$'\n'/ } + echo "::error::$TAG is published, but whether it is immutable could not be read (${shown:-no answer}). Do not delete it: check with gh api repos/$GH_REPO/releases/$rid --jq .immutable; only if that prints false, delete release $rid (the tag stays), turn immutable releases on and re-run this job" + fi exit 1 fi echo "$TAG is published and immutable" diff --git a/.github/workflows/renovate.yml b/.github/workflows/renovate.yml index f74df16..71d7668 100644 --- a/.github/workflows/renovate.yml +++ b/.github/workflows/renovate.yml @@ -2,9 +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. +# STATE (Kevin, 2026-09-25): this workflow is disabled in every faircomp repo (gh workflow disable, +# shown as disabled_manually). Nothing below runs and no Renovate pull requests arrive; pinned +# versions move only in reviewed pull requests raised by hand, until Renovate returns as a +# GitHub App, which replaces this workflow. The rest of this header describes it when 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 diff --git a/CLAUDE.md b/CLAUDE.md index 284770f..3d02f8f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -80,12 +80,34 @@ conventions are `../../docs/paket-konventionen.md` there. The rules that bite he 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. + itself, from the verified uv lock into an isolated venv, called by absolute path. + **The caller's environment (P1, an allowlist):** `scripts/check-lockfiles.sh`, + `packaging/build-venv.sh`, `packaging/make-deb.sh`, `scripts/tests/run.sh`, + `scripts/tests/lock_gates.sh` and `scripts/tests/make_deb_checks.sh` start with one and the same + block (`test_packaging.py` keeps it equal and first): unless it is the clean run already, the + script starts itself again under `env -i` through `/bin/bash -p` (which imports no function and + reads no `BASH_ENV`, `ENV`, `SHELLOPTS`, `BASHOPTS`) with exactly this environment: + `PATH=/usr/sbin:/usr/bin:/sbin:/bin`, `LANG`/`LC_ALL=C.UTF-8`, and where set `HOME`, `TMPDIR`, + the proxy variables (`http_proxy`, `https_proxy`, `no_proxy` and the upper-case three), the CA + variables (`SSL_CERT_FILE`, `SSL_CERT_DIR`, `REQUESTS_CA_BUNDLE`, `PIP_CERT`) and the switches + the repository's scripts pass each other (`LMNRADIUS_ALLOW_REAL`, `LMNRADIUS_ALLOW_SKIP`, + `LMNRADIUS_CALLER_PATH`, `LOCK_GATES_DEB`, `LOCK_GATES_VERBOSE`). Everything else is gone + without a list: venvs, `PYTHON*`, `UV_*`, `PIP_*`, `GIT_*`, Perl, make (`make -i deb` cannot + build past a failed gate, `make deb DEST=...` cannot move the venv), `TAR_OPTIONS`, + `GCONV_PATH`, `LD_LIBRARY_PATH`, `CDPATH`, and every function (`builtin`, `exec` included). Up + to the restart only keywords, assignments and `exec /usr/bin/env` run, with `POSIXLY_CORRECT` + set so that the special builtin `exec` comes before any function. The gates also read no + pip/uv config file and run `/usr/bin/python3 -I`. The Makefile starts `make-deb.sh`, and + `run.sh` its gate, with `/bin/bash -p`. `run.sh` keeps the caller's PATH aside + (`LMNRADIUS_CALLER_PATH`) and gives it back only after the gate passed: lint, unit and e2e use + the caller's tools on purpose. **Limit:** only what runs before the restart: the caller's shell + with its `BASH_ENV` and `SHELLOPTS` (`noexec` makes a directly started script do nothing and + end 0 — no verdict line, no summary line), `LD_PRELOAD` for that shell and `/usr/bin/env`, the + caller's own `make` of `make deb` (it reads `MAKEFLAGS`/`MAKEFILES` itself), and passing the + restart marker `--lmnradius-clean-env` as first argument by hand; plus what the allowlist + passes on purpose: files under `HOME` (git's and dpkg-buildpackage's configuration, pip/uv + caches: every installed file is hash-checked) and the proxy/CA variables, which decide whom + the gate trusts as PyPI. Whoever sets those already runs code as the caller. 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. @@ -246,16 +268,21 @@ real docker-compose winbind/EAP E2E (**Samba AD DC + joined FreeRADIUS + `eapol_test` supplicant**) that proves *teacher→Access-Accept (+correct VLAN) / student-on-teacher-SSID→Access-Reject / wrong-password→Reject / non-`wifi` user→Reject*, as well as multischool, update/rollback, and `.deb` install tests — needs real Linux -with **Docker**. **crabbox** leases an ephemeral Proxmox VM for this (provider in -`.claude/settings.json`, token only in the gitignored `.claude/settings.local.json`; -`crabbox doctor`). Rules/details: the `/test` skill (`.claude/skills/test/SKILL.md`). +with **Docker**. **crabbox** leases an ephemeral Proxmox VM for this (provider settings and +token only in the gitignored `.claude/settings.local.json`, never in the versioned +`.claude/settings.json`; `crabbox doctor`). **Not usable at the moment** (2026-09-27): its +Proxmox user was removed, so the heavy tier does not run until Kevin sets it up again. +Rules/details: the `/test` skill (`.claude/skills/test/SKILL.md`). - **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. + `N passed, M failed, K skipped`, then everything that was not checked (skipped, or not run + after a failed gate); steps dep-gated. Exit 0 only if every step ran and passed, 1 on a + failure, **77 if a step was skipped** (a missing tool, e2e without `LMNRADIUS_ALLOW_REAL=1`); + `LMNRADIUS_ALLOW_SKIP=1` accepts skips on purpose (exit 0, the last line still names them). - **Box lifecycle:** `crabbox warmup` → `crabbox run --id -- 'bash scripts/tests/crabbox_bootstrap.sh'` → `crabbox run --id -- 'LMNRADIUS_ALLOW_REAL=1 bash scripts/tests/run.sh e2e'` → `crabbox stop --id `. diff --git a/Makefile b/Makefile index 4692687..68fd9e7 100644 --- a/Makefile +++ b/Makefile @@ -23,10 +23,14 @@ # ghcr.io/linuxmuster/lmndev-runner:24.04@sha256:6b0c8ac994cf1d2da44b0b36ebd7b3b125094886e78293e04b9db5e515b8209e \ # 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`). +# make-deb.sh starts itself again under `env -i` with an allowlist (CLAUDE.md, "Python +# dependencies"); -p keeps the caller's SHELLOPTS (noexec would make bash run nothing and end 0), +# BASH_ENV and exported functions from the one bash that does that. This make itself reads the +# caller's MAKEFLAGS and MAKEFILES (the stated limit); none of them reaches debian/rules. .PHONY: deb clean deb: - /bin/bash packaging/make-deb.sh + /bin/bash -p packaging/make-deb.sh clean: debian/rules clean diff --git a/controlplane/lmnradius/api.py b/controlplane/lmnradius/api.py index 9515e8d..a1b1552 100644 --- a/controlplane/lmnradius/api.py +++ b/controlplane/lmnradius/api.py @@ -50,7 +50,9 @@ def create_app( ) -> FastAPI: """Build the FastAPI app wiring routes to the store, reconciler and docker service.""" verify = make_verify_token(settings) - app = FastAPI(title="linuxmuster-radius control plane") + # The OpenAPI document carries the package version (debian/changelog via setup.py), like + # GET /v1/version; without it FastAPI reports its own default, 0.1.0. + app = FastAPI(title="linuxmuster-radius control plane", version=dist_version("lmnradius")) @app.exception_handler(DockerException) async def _docker_unreachable(_request: Request, exc: DockerException) -> JSONResponse: diff --git a/controlplane/tests/test_api.py b/controlplane/tests/test_api.py index c0ccc16..0e61596 100644 --- a/controlplane/tests/test_api.py +++ b/controlplane/tests/test_api.py @@ -34,6 +34,14 @@ def test_version(client: TestClient, auth_headers: dict[str, str]) -> None: assert resp.json() == {"version": dist_version("lmnradius")} +def test_openapi_reports_the_package_version(client: TestClient) -> None: + # Up to 7.3.4 /openapi.json said "0.1.0" (FastAPI's default), whatever the package was. + resp = client.get("/openapi.json") + assert resp.status_code == 200 + assert resp.json()["info"]["version"] == dist_version("lmnradius") + assert resp.json()["info"]["version"] != "0.1.0" + + def test_missing_token_is_401(client: TestClient) -> None: resp = client.get("/v1/instances") assert resp.status_code == 401 diff --git a/controlplane/tests/test_packaging.py b/controlplane/tests/test_packaging.py index 334438f..2b58ed2 100644 --- a/controlplane/tests/test_packaging.py +++ b/controlplane/tests/test_packaging.py @@ -6,7 +6,9 @@ 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.""" +order from being edited away. The scripts a caller starts clean their environment with one and +the same block before any other command (A3), and run.sh calls nothing from the caller's PATH +before its gate (A4); lock_gates.sh (R1) and make_deb_checks.sh show that this holds.""" from __future__ import annotations @@ -118,11 +120,25 @@ def test_fast_tier_runs_the_gate_first_and_lockfile_jobs_are_only_the_gate() -> 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"] + ci_lockfile, release_lockfile = ( + dict(_jobs("ci.yml")["lockfile"]), + dict(_jobs("release.yml")["lockfile"]), + ) + assert release_lockfile.pop("name") == "release: lockfile" + assert ci_lockfile == release_lockfile # the release waits for it assert "lockfile" in _jobs("release.yml")["release"]["needs"] +def test_release_jobs_never_carry_the_name_of_a_required_ci_check() -> None: + # The main ruleset requires the ci.yml jobs by name; a release.yml run on the same commit + # (workflow_dispatch on a PR branch) must not report a check that could stand in for one. + ci_names = {spec.get("name", key) for key, spec in _jobs("ci.yml").items()} + for key, spec in _jobs("release.yml").items(): + assert spec.get("name") == f"release: {key}", f"release.yml/{key}: display name" + assert spec["name"] not in ci_names + + 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) @@ -132,3 +148,114 @@ def test_make_deb_never_waives_the_git_ownership_guard_wholesale() -> None: if line.lstrip().startswith("#"): continue assert line.strip() == 'git config --global --add safe.directory "$GITHUB_WORKSPACE"' + + +# The scripts a caller or the build starts: each starts itself again in a clean environment, +# with one and the same block, before any other command (P1). +ENV_SCRIPTS = ( + "scripts/check-lockfiles.sh", + "packaging/build-venv.sh", + "packaging/make-deb.sh", + "scripts/tests/lock_gates.sh", + "scripts/tests/make_deb_checks.sh", +) +BLOCK_FIRST = 'if [[ "${1-}" != --lmnradius-clean-env ]]; then' +ALLOWLIST = { + "HOME", + "TMPDIR", + "http_proxy", + "https_proxy", + "no_proxy", + "HTTP_PROXY", + "HTTPS_PROXY", + "NO_PROXY", + "SSL_CERT_FILE", + "SSL_CERT_DIR", + "REQUESTS_CA_BUNDLE", + "PIP_CERT", + "LMNRADIUS_ALLOW_REAL", + "LMNRADIUS_ALLOW_SKIP", + "LMNRADIUS_CALLER_PATH", + "LOCK_GATES_DEB", + "LOCK_GATES_VERBOSE", +} + + +def _code(path: str) -> list[str]: + """The lines of a shell script without comment lines and blank lines.""" + text = (ROOT / path).read_text(encoding="utf-8") + return [ln for ln in text.splitlines() if ln.strip() and not ln.lstrip().startswith("#")] + + +def _block(code: list[str], path: str) -> tuple[list[str], int]: + start = code.index(BLOCK_FIRST) + end = code.index("shift", start) + return code[start : end + 1], end + 1 + + +def test_entry_scripts_start_again_in_a_clean_environment_first() -> None: + blocks = {} + for path in ENV_SCRIPTS: + code = _code(path) + # before anything else, even `set`: a function of the caller may be named set + assert code[0] == BLOCK_FIRST, f"{path}: the first command must be the clean-env block" + blocks[path], after = _block(code, path) + assert code[after].startswith("set -"), f"{path}: `set` comes right after the block" + first = blocks[ENV_SCRIPTS[0]] + for path, block in blocks.items(): + assert block == first, f"{path}: its clean-env block differs from {ENV_SCRIPTS[0]}'s" + text = "\n".join(first) + # up to the exec: an assignment that makes `exec` win over functions, one absolute command + assert first[1].strip() == "POSIXLY_CORRECT=1" + assert first[2].strip().startswith("exec /usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin ") + assert "LANG=C.UTF-8 LC_ALL=C.UTF-8" in first[2] + assert '/bin/bash -p "$0" --lmnradius-clean-env "$@"' in text + passed = set(re.findall(r'\$\{(\w+)\+"\1=\$\1"\}', text)) + assert passed == ALLOWLIST, sorted(passed ^ ALLOWLIST) + # nothing else is passed on: every word of the exec is a fixed assignment or one of those + words = re.findall(r"\S+", " ".join(first[2:-2]).replace("\\", " ")) + for w in words: + assert ( + w in ("exec", "/usr/bin/env", "-i", "/bin/bash", "-p", '"$0"', '"$@"') + or w == "--lmnradius-clean-env" + or re.fullmatch(r'\$\{(\w+)\+"\1=\$\1"\}', w) + or w in ("PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C.UTF-8", "LC_ALL=C.UTF-8") + ), w + + +def test_run_sh_restarts_clean_and_calls_nothing_from_the_callers_path_before_its_gate() -> None: + code = _code("scripts/tests/run.sh") + assert code[0] == 'LMNRADIUS_CALLER_PATH="${LMNRADIUS_CALLER_PATH-$PATH}"' + block, after = _block(code, "scripts/tests/run.sh") + assert code[1] == BLOCK_FIRST + assert block == _block(_code(ENV_SCRIPTS[0]), ENV_SCRIPTS[0])[0] + assert code[after : after + 3] == [ + 'CALLER_PATH="$LMNRADIUS_CALLER_PATH"', + "unset LMNRADIUS_CALLER_PATH", + "set -uo pipefail", + ] + before_gate = code[: next(i for i, ln in enumerate(code) if ln.startswith("summary()"))] + assert any("/usr/bin/dirname" in ln for ln in before_gate) + for ln in before_gate: + assert not re.search(r"(? None: + makefile = (ROOT / "Makefile").read_text(encoding="utf-8") + assert "\n\t/bin/bash -p packaging/make-deb.sh\n" in makefile + + +def test_rules_refuse_a_build_directory_with_whitespace_and_quote_the_paths() -> None: + rules = (ROOT / "debian" / "rules").read_text(encoding="utf-8") + assert "ifneq ($(words $(CURDIR)),1)" in rules + assert '\tbash packaging/build-venv.sh "$(ROOT)$(DEST)"\n' in rules + assert '\tdebian/venv-relocate "$(ROOT)" "$(DEST)"\n' in rules + assert '\tdebian/venv-relocate --verify "$(ROOT)" "$(DEST)"\n' in rules + + +def test_build_venv_refuses_a_bad_venv_path_before_any_rm() -> None: + code = _code("packaging/build-venv.sh") + guard = next(i for i, ln in enumerate(code) if "refusing venv path with whitespace" in ln) + first_rm = next(i for i, ln in enumerate(code) if "rm -rf" in ln) + assert guard < first_rm diff --git a/debian/changelog b/debian/changelog index c96312a..6e97941 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,23 @@ +linuxmuster-radius (7.3.5) lmn73; urgency=medium + + * The API's OpenAPI document (/openapi.json, the interactive docs under + /docs) now reports the package version instead of 0.1.0, like + GET /v1/version. + * A failing git step in the instance change log + (/var/lib/linuxmuster-radius/instances) no longer aborts the package + configuration: up to 7.3.4 it left the package half-configured. Each + failure now prints a WARNING line with the step and the repository + (below git's own message), and the configuration and the service + handling go on as usual. Until the repository is repaired (see + docs/operations.md), instance changes are not versioned or are refused + with git's message. + * Correction to the 7.3.4 entry: the source tarball of a release holds the + files tracked in git except the CI workflows, the developer tool + settings and the two .gitignore files (.gitignore and + deploy/e2e/certs/.gitignore), which dpkg-source leaves out by default. + + -- Kevin Stenzel Sun, 27 Sep 2026 15:12:38 +0200 + linuxmuster-radius (7.3.4) lmn73; urgency=medium * The package is now built with debhelper (dpkg-buildpackage) instead of a diff --git a/debian/postinst b/debian/postinst index 330e60a..20042ef 100644 --- a/debian/postinst +++ b/debian/postinst @@ -55,26 +55,51 @@ chmod 700 /etc/linuxmuster-radius/secrets /etc/linuxmuster-radius/certs # 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. +# A failing git step never stops the configure and never passes silently: the service and the +# instance records do not depend on the change log (up to 7.3.4 `set -e` aborted the whole +# configure on it). Each failure prints one WARNING line on stderr with the step and the +# repository, below git's own message; the configure and the service handling below go on as +# without it. Until the repository is repaired (docs/operations.md), the service records +# instance changes unversioned or refuses them with git's message (Store). INST_DIR=/var/lib/linuxmuster-radius/instances if command -v git >/dev/null 2>&1; then # 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 "$@"; } + log_git() { as_lmnradius git -C "$INST_DIR" "$@"; } + log_warn() { + echo "linuxmuster-radius: WARNING: instance change log $INST_DIR: '$1' failed;" \ + "configuring goes on; repair the repository (docs/operations.md), until then" \ + "instance changes are not versioned or are refused" >&2 || : + } + log_ok=1 if [ ! -d "$INST_DIR/.git" ]; then - as_lmnradius git -C "$INST_DIR" -c init.defaultBranch=main init -q + log_git -c init.defaultBranch=main init -q || { log_warn "git init"; log_ok=; } + elif ! log_git rev-parse --git-dir >/dev/null; then + log_warn "git rev-parse (the repository is unusable, the other change-log steps are skipped)" + log_ok= 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 - [ -e "$f" ] && as_lmnradius git -C "$INST_DIR" add -- "$(basename "$f")" - done - if ! as_lmnradius git -C "$INST_DIR" diff --cached --quiet; then - as_lmnradius git -C "$INST_DIR" commit -q -m "lmnradius: import existing instance records (package configure)" + if [ -n "$log_ok" ]; then + log_git config user.name "linuxmuster-radius" || log_warn "git config user.name" + log_git config user.email "lmnradius@localhost" || log_warn "git config user.email" + log_git config maintenance.auto false || log_warn "git config maintenance.auto false" + log_git config gc.auto 0 || log_warn "git 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 + [ -e "$f" ] || continue + f="$(basename "$f")" + log_git add -- "$f" || log_warn "git add $f" + done + # 0: nothing staged, 1: records to commit, anything else: git could not compare. + if log_git diff --cached --quiet; then log_rc=0; else log_rc=$?; fi + if [ "$log_rc" = 1 ]; then + log_git commit -q -m "lmnradius: import existing instance records (package configure)" \ + || log_warn "git commit (import of existing instance records)" + elif [ "$log_rc" != 0 ]; then + log_warn "git diff --cached" + fi fi fi diff --git a/debian/rules b/debian/rules index 01442dc..678612f 100755 --- a/debian/rules +++ b/debian/rules @@ -13,6 +13,13 @@ PKG := linuxmuster-radius DEST := /opt/$(PKG)/venv ROOT := $(CURDIR)/debian/$(PKG) +# make splits paths at whitespace, and build-venv.sh starts with `rm -rf` on the venv path: a +# build directory containing a space (a TMPDIR like "/work/odd dir") would turn part of it into +# the venv path and delete it. Stop before anything runs; the paths below are quoted as well. +ifneq ($(words $(CURDIR)),1) +$(error build directory contains whitespace, refusing to build: '$(CURDIR)') +endif + %: dh $@ @@ -22,8 +29,8 @@ 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) + bash packaging/build-venv.sh "$(ROOT)$(DEST)" + debian/venv-relocate "$(ROOT)" "$(DEST)" override_dh_auto_clean: rm -rf controlplane/build controlplane/*.egg-info @@ -42,4 +49,4 @@ override_dh_fixperms: dh_fixperms -X$(DEST) execute_before_dh_builddeb: - debian/venv-relocate --verify $(ROOT) $(DEST) + debian/venv-relocate --verify "$(ROOT)" "$(DEST)" diff --git a/docs/decisions.md b/docs/decisions.md index 224270f..d6d9a35 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -289,14 +289,29 @@ genau das `uv==` aus `uv-requirements.in` mit von PyPI veröffentlichten Hashes 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 +Umgebung des Aufrufers nehmen die Tore, der Bau (`build-venv.sh`, `make-deb.sh`), `run.sh` und +die Test-Gerüste nur eine **Positivliste**: jedes dieser Skripte startet sich zuerst (derselbe +Block, vor jedem anderen Befehl) unter `env -i` über `/bin/bash -p` neu (keine Funktionen, kein +`BASH_ENV`/`ENV`/`SHELLOPTS`/`BASHOPTS`), mit festem `PATH=/usr/sbin:/usr/bin:/sbin:/bin`, +`LANG`/`LC_ALL=C.UTF-8` und, wenn gesetzt, `HOME`, `TMPDIR`, den Proxy-Variablen (`http_proxy`, +`https_proxy`, `no_proxy` in beiden Schreibweisen), den CA-Variablen (`SSL_CERT_FILE`, +`SSL_CERT_DIR`, `REQUESTS_CA_BUNDLE`, `PIP_CERT`) und den Schaltern, mit denen die Skripte des +Repos untereinander reden (`LMNRADIUS_ALLOW_REAL`, `LMNRADIUS_ALLOW_SKIP`, +`LMNRADIUS_CALLER_PATH`, `LOCK_GATES_DEB`, `LOCK_GATES_VERBOSE`). Alles andere fällt weg, ohne +Aufzählung (venvs, `PYTHON*`, `UV_*`, `PIP_*`, git, Perl, make — `make -i deb` baut nicht an +einem roten Tor vorbei, `make deb DEST=…` verlegt das venv nicht —, `TAR_OPTIONS`, `GCONV_PATH`, +`LD_LIBRARY_PATH`, jede Funktion). Bis zum Neustart laufen nur Schlüsselwörter, Zuweisungen und +`exec /usr/bin/env`, mit `POSIXLY_CORRECT`, damit das Spezial-Builtin `exec` vor jeder Funktion +kommt. Dazu keine pip-/uv-Konfigurationsdateien, `/usr/bin/python3 -I`, uv mit `--python +/usr/bin/python3 --no-config` (kein Projekt-venv, keine umgelenkte Paketquelle). **Grenze:** nur, +was vor dem Neustart läuft — die Shell des Aufrufers mit ihrem `BASH_ENV` und `SHELLOPTS` +(`noexec`: ein direkt gestartetes Skript tut nichts und endet mit 0, ohne Urteilszeile; das +Makefile und `run.sh` starten ihre Skripte deshalb mit `/bin/bash -p`), `LD_PRELOAD` für diese +Shell und `/usr/bin/env`, das eigene `make` des Aufrufers von `make deb` —, und was die +Positivliste bewusst durchlässt: Dateien unter `HOME` (Konfiguration von git und +dpkg-buildpackage, pip-/uv-Caches; jede installierte Datei ist hash-geprüft) und die +Proxy-/CA-Variablen, die bestimmen, wem das Tor als PyPI vertraut; wer das setzt, führt ohnehin +Code als der Aufrufer 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). diff --git a/docs/install.md b/docs/install.md index d3cf1bc..bf26093 100644 --- a/docs/install.md +++ b/docs/install.md @@ -51,8 +51,9 @@ lmnradius health # {"status":"ok"} ``` Der `postinst` legt den System-User `lmnradius`, `/etc/linuxmuster-radius/{config.yml (0600, zufälliges Token),secrets,certs}` und das State-Verzeichnis als Git-Repo an (jede Instanz- -Änderung ein Commit, `git -C /var/lib/linuxmuster-radius/instances log`) und startet den -Dienst. Das Image (`ghcr.io/faircomp/linuxmuster-radius`, **public**) wird bei `reconcile` +Änderung ein Commit, `sudo -u lmnradius git -C /var/lib/linuxmuster-radius/instances log` — +als der Besitzer `lmnradius`: root selbst lehnt git dort mit „dubious ownership“ ab) und startet +den Dienst. Das Image (`ghcr.io/faircomp/linuxmuster-radius`, **public**) wird bei `reconcile` gezogen. *(Optionale Härtung: `deploy/docker-socket-proxy.yml` starten und `docker_host: "tcp://127.0.0.1:2375"` in `config.yml` setzen.)* diff --git a/docs/operations.md b/docs/operations.md index 8862328..ec8c7d0 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -32,6 +32,18 @@ jedes `create`/`set-ldap-ca`/`rm` ist ein Commit, `sudo -u lmnradius git -C 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). +Scheitert dabei ein git-Schritt (ab 7.3.5), bricht die `postinst` nicht ab: je Fehlschlag steht +unter der Meldung von git eine Zeile `linuxmuster-radius: WARNING: instance change log +/var/lib/linuxmuster-radius/instances: '' failed; …` auf stderr (apt zeigt sie), Paket +und Dienst werden wie sonst eingerichtet. Bis zur Reparatur versioniert der Dienst +Instanz-Änderungen nicht oder lehnt sie mit der Meldung von git ab. Reparatur: die Ursache aus +der git-Meldung beheben (`sudo -u lmnradius git -C /var/lib/linuxmuster-radius/instances status`); +ist das Repo nicht zu retten, `.git` beiseite legen und die `postinst` erneut laufen lassen: +`mv /var/lib/linuxmuster-radius/instances/.git /root/instances-git.kaputt && dpkg-reconfigure +linuxmuster-radius` (als root). Sie legt ein neues Repo an und übernimmt die vorhandenen +Datensätze in einem Import-Commit; die alte Historie bleibt im beiseitegelegten Verzeichnis. Der +Dienst wird dabei neu gestartet (wie bei einem Upgrade). + ## Erstinbetriebnahme (einmalig) Reihenfolge — jeder Schritt setzt den vorigen voraus: diff --git a/docs/test-strategy.md b/docs/test-strategy.md index 0fbcfb8..6deca5b 100644 --- a/docs/test-strategy.md +++ b/docs/test-strategy.md @@ -15,6 +15,13 @@ SPDX-License-Identifier: GPL-3.0-or-later - 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. + Übersprungen ist nicht grün: fehlt ein Werkzeug (oder `LMNRADIUS_ALLOW_REAL=1` für e2e), endet + run.sh mit Exit 77 statt 0, bei einem Fehlschlag mit 1; die Schlusszeile nennt alles, was nicht + geprüft wurde (übersprungen oder nach rotem Tor nicht gelaufen). Wer Überspringen bewusst + zulässt, setzt `LMNRADIUS_ALLOW_SKIP=1` (Exit 0, die Schlusszeile nennt die Lücken trotzdem). + Vor dem Tor läuft nichts vom Aufrufer: run.sh startet sich zuerst unter `env -i` mit der + Positivliste neu (siehe unten), ruft `/usr/bin/dirname` mit absolutem Pfad und das Tor mit + `/bin/bash -p`; erst nach dem Tor bekommen lint, unit und e2e den PATH des Aufrufers zurück. - 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, @@ -22,9 +29,15 @@ SPDX-License-Identifier: GPL-3.0-or-later 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). + vorab. Unabhängig von der Umgebung des Aufrufers (P1): Tor, `build-venv.sh`, `make-deb.sh`, + `run.sh` und die beiden Test-Gerüste beginnen mit demselben Block und starten sich unter + `env -i` über `/bin/bash -p` neu, nur mit der Positivliste aus CLAUDE.md ("Python + dependencies"; fester PATH, C.UTF-8, `HOME`, `TMPDIR`, Proxy- und CA-Variablen, die Schalter + des Repos); keine Funktion, keine andere Variable. Grenze: nur, was vor dem Neustart läuft (die + Shell des Aufrufers mit `BASH_ENV`/`SHELLOPTS`, `LD_PRELOAD`, das eigene `make` des Aufrufers), + und die bewusst durchgelassenen Proxy-/CA-Variablen. Ohne Netz scheitert es nach Sekunden (kurze PyPI-Timeouts, Abbruch beim + ersten unlesbaren Pin) und sagt das ("PyPI gave no answer (offline?)"), statt einen Hash zu + beschuldigen; ebenso `build-venv.sh`/`make deb`. **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. @@ -47,10 +60,26 @@ SPDX-License-Identifier: GPL-3.0-or-later 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`. + - **R1/P3:** unter vergifteter Umgebung (aktiviertes venv mit dem Wheel vorn im PATH, darin + auch `dirname`, `VIRTUAL_ENV`, `PYTHONPATH` mit Marker-`sitecustomize`, `PYTHONHOME`, + `UV_*`/`PIP_*` samt Konfigurationsdateien, die Paketquelle und Interpreter umlenken, `.venv` + im Checkout; exportierte Funktionen `set`, `export`, `.`, `builtin`, `exec`, `exit`, `shift`, + `cd`, `unset`, `compgen`, `mapfile`, `dirname`; `PERL5OPT`/`PERL5LIB`, `CDPATH`, + `GCONV_PATH` mit einem gconv-Modul und `LD_LIBRARY_PATH` mit einer `libz.so.1`, beide + markerschreibend (mit gcc gebaut), `TAR_OPTIONS` mit Checkpoint-Aktion; für direkt + gestartete Skripte `MAKEFILES`, `MAKEFLAGS`/`GNUMAKEFLAGS` mit `-i` und fremder `SHELL`, + `MAKEOVERRIDES`) gleiche Urteile und kein Marker: `check-lockfiles.sh`, `build-venv.sh`, + `run.sh gate`/`lint`, mit `LOCK_GATES_DEB=1` auch `make deb`, `make-deb.sh` direkt, + `make -i deb`, `GNUMAKEFLAGS=-i make deb` und `SHELLOPTS=noexec make deb` (kein .deb). Der + Neustart-Block selbst unter demselben Gift sieht nur die Positivliste, keine Funktion, und + läuft als `bash -p`. Jeder Teil des Gifts ist nachweislich scharf (Gegenproben: eine bash, + die die Funktionen behält, `make`, `dpkg-parsechangelog`, `iconv`, `python3`, `tar`, + `dirname` aus dem PATH, ein relatives `cd` unter `CDPATH`). Die Grenze wird gezeigt: + `SHELLOPTS=noexec` bei direktem `bash`-Start lässt das Tor nichts tun (Exit 0, keine + Urteilszeile). + - **T2:** `build-venv.sh` weist einen venv-Pfad ab, der nicht absolut ist, Leerraum oder + `.`/`..`/`//` enthält oder nicht auf `/opt/linuxmuster-radius/venv` endet, bevor irgendetwas + läuft; das benannte Verzeichnis bleibt. - **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 @@ -64,11 +93,18 @@ SPDX-License-Identifier: GPL-3.0-or-later 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 + `.git` und mit `MAKEFILES`/`MAKEFLAGS`/`GNUMAKEFLAGS`, `PERL5OPT`/`PERL5LIB`, `CDPATH`, + `TAR_OPTIONS`, `SHELLOPTS=noexec` und Funktionen, die in jedem make-Lauf von `debian/rules` + bzw. jedem Perl-Programm oder tar den Marker schreiben würden, als `make deb DEST=…`: + 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. + **T1:** mit einem `TMPDIR`, der ein Leerzeichen enthält (der Bau läuft in einem Verzeichnis + darunter), bricht `debian/rules` ab, bevor etwas läuft; ein Verzeichnis, das wie der Teil vor + dem Leerzeichen heißt, bleibt (mit den alten, ungequoteten Pfaden in `debian/rules` löschte + `build-venv.sh` es per `rm -rf`). ## Heavy-Tier (crabbox, Docker) diff --git a/docs/threat-model.md b/docs/threat-model.md index e3b04f3..828a833 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -75,9 +75,12 @@ SPDX-License-Identifier: GPL-3.0-or-later 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. + im Checkout, Shell-Funktionen und jede Variable außerhalb einer kleinen Positivliste steuern + weder die Tore noch den Bau: die Einstiegsskripte starten sich unter `env -i` über + `/bin/bash -p` neu (Liste: ADR-016); nicht neutralisiert (Grenze) ist nur, was davor läuft (die + Shell des Aufrufers mit `BASH_ENV`, `SHELLOPTS`, `LD_PRELOAD`, sein eigenes `make`), sowie die + bewusst durchgelassenen Proxy-/CA-Variablen und Dateien unter `HOME` — 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 diff --git a/packaging/build-venv.sh b/packaging/build-venv.sh index 52710e6..905d9c8 100755 --- a/packaging/build-venv.sh +++ b/packaging/build-venv.sh @@ -7,31 +7,61 @@ # 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 +# debian/rules calls this script with a bare `bash`, and dpkg-buildpackage may be started by hand, +# so it starts itself again in a clean environment (R1, A3, P1: the block below), and reads no pip +# configuration file. +# ---- clean environment (P1): the same block in every entry script (test_packaging.py) ---- +# Unless this is the clean run already, start again under `env -i` with exactly this allowlist, +# through /bin/bash -p, which imports no function and reads no BASH_ENV, ENV, SHELLOPTS or +# BASHOPTS: PATH=/usr/sbin:/usr/bin:/sbin:/bin, LANG and LC_ALL C.UTF-8, and, where set, HOME, +# TMPDIR, http_proxy, https_proxy, no_proxy, HTTP_PROXY, HTTPS_PROXY, NO_PROXY, SSL_CERT_FILE, +# SSL_CERT_DIR, REQUESTS_CA_BUNDLE, PIP_CERT, and the switches the repository's scripts pass +# each other: LMNRADIUS_ALLOW_REAL, LMNRADIUS_ALLOW_SKIP, LMNRADIUS_CALLER_PATH (run.sh), +# LOCK_GATES_DEB, LOCK_GATES_VERBOSE (lock_gates.sh). Every other variable and every function of +# the caller is gone. Up to the exec only keywords, assignments and one command by absolute path +# run: POSIXLY_CORRECT puts bash into POSIX mode, where the special builtin `exec` comes before +# any function the caller exported. The clean run is told by its first argument. +if [[ "${1-}" != --lmnradius-clean-env ]]; then + POSIXLY_CORRECT=1 + exec /usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin LANG=C.UTF-8 LC_ALL=C.UTF-8 \ + ${HOME+"HOME=$HOME"} ${TMPDIR+"TMPDIR=$TMPDIR"} \ + ${http_proxy+"http_proxy=$http_proxy"} ${https_proxy+"https_proxy=$https_proxy"} \ + ${no_proxy+"no_proxy=$no_proxy"} ${HTTP_PROXY+"HTTP_PROXY=$HTTP_PROXY"} \ + ${HTTPS_PROXY+"HTTPS_PROXY=$HTTPS_PROXY"} ${NO_PROXY+"NO_PROXY=$NO_PROXY"} \ + ${SSL_CERT_FILE+"SSL_CERT_FILE=$SSL_CERT_FILE"} ${SSL_CERT_DIR+"SSL_CERT_DIR=$SSL_CERT_DIR"} \ + ${REQUESTS_CA_BUNDLE+"REQUESTS_CA_BUNDLE=$REQUESTS_CA_BUNDLE"} ${PIP_CERT+"PIP_CERT=$PIP_CERT"} \ + ${LMNRADIUS_ALLOW_REAL+"LMNRADIUS_ALLOW_REAL=$LMNRADIUS_ALLOW_REAL"} \ + ${LMNRADIUS_ALLOW_SKIP+"LMNRADIUS_ALLOW_SKIP=$LMNRADIUS_ALLOW_SKIP"} \ + ${LMNRADIUS_CALLER_PATH+"LMNRADIUS_CALLER_PATH=$LMNRADIUS_CALLER_PATH"} \ + ${LOCK_GATES_DEB+"LOCK_GATES_DEB=$LOCK_GATES_DEB"} \ + ${LOCK_GATES_VERBOSE+"LOCK_GATES_VERBOSE=$LOCK_GATES_VERBOSE"} \ + /bin/bash -p "$0" --lmnradius-clean-env "$@" +fi +shift +# ---- end of the clean environment block ---- +set -euo pipefail export PIP_CONFIG_FILE=/dev/null PIP_DISABLE_PIP_VERSION_CHECK=1 +die() { echo "build-venv.sh: $*" >&2; exit 1; } ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)" VENV="${1:?usage: build-venv.sh }" +# The venv path is removed with `rm -rf` further down. Refuse, before anything else, a path that +# could name something else: only an absolute path without whitespace and without . or .. +# components, ending in /opt/linuxmuster-radius/venv -- debian/rules passes +# /debian/linuxmuster-radius/opt/linuxmuster-radius/venv. (A build directory with a +# space once split that path, and the `rm -rf` hit a directory outside the build; T2.) +case "$VENV" in + *[[:space:]]*) die "refusing venv path with whitespace: '$VENV'" ;; + */./* | */../* | */. | */.. | *//*) die "refusing venv path with . or .. or //: '$VENV'" ;; + /*/opt/linuxmuster-radius/venv | /opt/linuxmuster-radius/venv) ;; + *) die "refusing venv path '$VENV': it must be absolute and end in /opt/linuxmuster-radius/venv" ;; +esac 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. @@ -51,7 +81,11 @@ echo "== lockfiles: grammar and published hashes ==" "$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" +prc=0 +"$PY" -I -B "$GATE" pypi "${LOCKS[@]}" || prc=$? +[ "$prc" != 3 ] || die "PyPI gave no answer (offline?): the lockfiles are NOT verified," \ + "nothing is built" +[ "$prc" = 0 ] || die "a lockfile pin or hash is not what PyPI publishes (FAIL lines above)" 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 diff --git a/packaging/make-deb.sh b/packaging/make-deb.sh index 82c9983..1521f57 100755 --- a/packaging/make-deb.sh +++ b/packaging/make-deb.sh @@ -18,7 +18,7 @@ # * 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. +# (developer tooling for Claude Code, not part of the package); 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 @@ -28,18 +28,46 @@ # 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 +# Which programs run is not left to the caller (R1, A3, P1): the block below starts this script +# again under `env -i` with an allowlist, so no variable or function of the caller reaches git, +# tar, dpkg-buildpackage, dpkg-parsechangelog and debhelper (Perl) or the make runs of +# debian/rules. So neither make flags (`make -i deb`: a failed gate would be ignored and a .deb +# written anyway) nor variables set on make's command line (`make deb DEST=...`: the venv would be +# built for another path), TAR_OPTIONS, PERL5OPT, GCONV_PATH or LD_LIBRARY_PATH get in. The +# Makefile starts this script with /bin/bash -p, so the caller's SHELLOPTS (noexec) and BASH_ENV +# do not apply to it either. The caller's own `make` of `make deb` has read MAKEFLAGS and +# MAKEFILES before this script starts (a stated limit, see CLAUDE.md). +# ---- clean environment (P1): the same block in every entry script (test_packaging.py) ---- +# Unless this is the clean run already, start again under `env -i` with exactly this allowlist, +# through /bin/bash -p, which imports no function and reads no BASH_ENV, ENV, SHELLOPTS or +# BASHOPTS: PATH=/usr/sbin:/usr/bin:/sbin:/bin, LANG and LC_ALL C.UTF-8, and, where set, HOME, +# TMPDIR, http_proxy, https_proxy, no_proxy, HTTP_PROXY, HTTPS_PROXY, NO_PROXY, SSL_CERT_FILE, +# SSL_CERT_DIR, REQUESTS_CA_BUNDLE, PIP_CERT, and the switches the repository's scripts pass +# each other: LMNRADIUS_ALLOW_REAL, LMNRADIUS_ALLOW_SKIP, LMNRADIUS_CALLER_PATH (run.sh), +# LOCK_GATES_DEB, LOCK_GATES_VERBOSE (lock_gates.sh). Every other variable and every function of +# the caller is gone. Up to the exec only keywords, assignments and one command by absolute path +# run: POSIXLY_CORRECT puts bash into POSIX mode, where the special builtin `exec` comes before +# any function the caller exported. The clean run is told by its first argument. +if [[ "${1-}" != --lmnradius-clean-env ]]; then + POSIXLY_CORRECT=1 + exec /usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin LANG=C.UTF-8 LC_ALL=C.UTF-8 \ + ${HOME+"HOME=$HOME"} ${TMPDIR+"TMPDIR=$TMPDIR"} \ + ${http_proxy+"http_proxy=$http_proxy"} ${https_proxy+"https_proxy=$https_proxy"} \ + ${no_proxy+"no_proxy=$no_proxy"} ${HTTP_PROXY+"HTTP_PROXY=$HTTP_PROXY"} \ + ${HTTPS_PROXY+"HTTPS_PROXY=$HTTPS_PROXY"} ${NO_PROXY+"NO_PROXY=$NO_PROXY"} \ + ${SSL_CERT_FILE+"SSL_CERT_FILE=$SSL_CERT_FILE"} ${SSL_CERT_DIR+"SSL_CERT_DIR=$SSL_CERT_DIR"} \ + ${REQUESTS_CA_BUNDLE+"REQUESTS_CA_BUNDLE=$REQUESTS_CA_BUNDLE"} ${PIP_CERT+"PIP_CERT=$PIP_CERT"} \ + ${LMNRADIUS_ALLOW_REAL+"LMNRADIUS_ALLOW_REAL=$LMNRADIUS_ALLOW_REAL"} \ + ${LMNRADIUS_ALLOW_SKIP+"LMNRADIUS_ALLOW_SKIP=$LMNRADIUS_ALLOW_SKIP"} \ + ${LMNRADIUS_CALLER_PATH+"LMNRADIUS_CALLER_PATH=$LMNRADIUS_CALLER_PATH"} \ + ${LOCK_GATES_DEB+"LOCK_GATES_DEB=$LOCK_GATES_DEB"} \ + ${LOCK_GATES_VERBOSE+"LOCK_GATES_VERBOSE=$LOCK_GATES_VERBOSE"} \ + /bin/bash -p "$0" --lmnradius-clean-env "$@" +fi +shift +# ---- end of the clean environment block ---- +set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)" PKG=linuxmuster-radius @@ -185,7 +213,8 @@ if [ -n "$missing" ]; then 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" +say "source tarball holds exactly the tracked files minus .github, .claude and the .gitignore" \ + "files ($(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. diff --git a/renovate.json b/renovate.json index f48a385..d743609 100644 --- a/renovate.json +++ b/renovate.json @@ -1,15 +1,15 @@ { "$schema": "https://docs.renovatebot.com/renovate-schema.json", - "description": "Supply chain (stage A): keep every pinned input current through reviewable PRs -- the data-plane image digest, the hash-pinned Python lockfiles, the SHA-pinned actions, the digest-pinned build image, the pinned CI tools and the pinned Renovate engine. Nothing is automerged.", + "description": "Renovate is disabled, see renovate.yml: it raises nothing now, and pins are raised by hand in reviewed PRs. When enabled again, this config (supply chain, stage A) keeps every pinned input current through reviewable PRs -- the data-plane image digest, the hash-pinned Python lockfiles, the SHA-pinned actions, the digest-pinned build image, the pinned CI tools and the pinned Renovate engine. Nothing is automerged.", "extends": ["config:recommended", "docker:pinDigests", "helpers:pinGitHubActionDigests"], "automerge": false, "semanticCommits": "enabled", "docker-compose": { "enabled": true }, "pip-compile": { - "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.", + "description": "The hash-pinned lockfiles packaging/build-venv.sh installs with --require-hashes. When enabled, 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.", + "description": "When enabled: the only way Renovate moves the Python lockfiles (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 then 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.", "enabled": true, "schedule": ["at any time"] } @@ -17,7 +17,7 @@ "customManagers": [ { "customType": "regex", - "description": "Bump the digest-pinned data-plane image (DEFAULT_IMAGE) in the control-plane code and the deploy examples. The reference is digest-only (@sha256:...), so we tell Renovate which tag's digest to follow via currentValueTemplate (the rolling :latest tag published by build-image).", + "description": "When enabled: bump the digest-pinned data-plane image (DEFAULT_IMAGE) in the control-plane code and the deploy examples. The reference is digest-only (@sha256:...), so we tell Renovate which tag's digest to follow via currentValueTemplate (the rolling :latest tag published by build-image).", "managerFilePatterns": [ "/^controlplane/lmnradius/models\\.py$/", "/^deploy/instances/[^/]+\\.ya?ml$/" @@ -49,7 +49,7 @@ }, { "customType": "regex", - "description": "Bump the PINNED CI tools (ruff/mypy/reuse/pytest/types-PyYAML, uv for the lockfile check) that ci.yml installs inside a `pip install` run-step. They are pinned so a linter widening its default rules cannot turn the pipeline red on its own; Renovate keeps them current as reviewable PRs. The version part accepts any number of dot-separated components (types-PyYAML uses four, e.g. 6.0.12.20260906).", + "description": "When enabled: bump the PINNED CI tools (ruff/mypy/reuse/pytest/types-PyYAML, uv for the lockfile check) that ci.yml installs inside a `pip install` run-step. They are pinned so a linter widening its default rules cannot turn the pipeline red on its own; Renovate then keeps them current as reviewable PRs. The version part accepts any number of dot-separated components (types-PyYAML uses four, e.g. 6.0.12.20260906).", "managerFilePatterns": ["/^\\.github/workflows/ci\\.yml$/"], "matchStrings": [ "(?ruff|mypy|reuse|pytest|types-PyYAML|uv)==(?[0-9]+(?:\\.[0-9]+)+)" @@ -59,7 +59,7 @@ ], "packageRules": [ { - "description": "Data-plane image: pin/update by immutable digest only. A human MUST merge (never auto-apply a new image to a school's live RADIUS).", + "description": "When enabled: the data-plane image is pinned and updated by immutable digest only. A human MUST merge (never auto-apply a new image to a school's live RADIUS).", "matchDatasources": ["docker"], "pinDigests": true, "automerge": false @@ -71,24 +71,24 @@ "enabled": false }, { - "description": "Build image digests in one PR, so ci.yml, release.yml and the Makefile always build with the same image. A human reviews and merges it.", + "description": "When enabled: build image digests in one PR, so ci.yml, release.yml and the Makefile always build with the same image. A human reviews and merges it.", "matchPackageNames": ["ghcr.io/linuxmuster/lmndev-runner"], "matchUpdateTypes": ["digest"], "groupName": "lmndev-runner build image", "automerge": false }, { - "description": "PyPI releases (the pinned CI tools) only once they are a week old, the window in which a compromised upload is usually noticed and yanked. PyPI only: ghcr.io gives no release timestamps, so an age rule on Docker would hold those updates forever (the workflow's Thursday cron is their age brake).", + "description": "When enabled, PyPI releases (the pinned CI tools) only once they are a week old, the window in which a compromised upload is usually noticed and yanked. PyPI only: ghcr.io gives no release timestamps, so an age rule on Docker would hold those updates forever (the workflow's Thursday cron is their age brake).", "matchDatasources": ["pypi"], "minimumReleaseAge": "7 days" }, { - "description": "Python lockfiles: every bump is a supply-chain change of the shipped venv; a human merges it after CI (lockfile, fast tier on the new versions, package, install and upgrade smoke) is green.", + "description": "When enabled: every Python lockfile bump is a supply-chain change of the shipped venv; a human merges it after CI (lockfile, fast tier on the new versions, package, install and upgrade smoke) is green.", "matchManagers": ["pip-compile"], "automerge": false }, { - "description": "Actions stay pinned by commit SHA with a # vN comment; a human merges every bump.", + "description": "Actions stay pinned by commit SHA with a # vN comment; when enabled, a human merges every bump.", "matchManagers": ["github-actions"], "automerge": false }, @@ -117,7 +117,7 @@ "enabled": false }, { - "description": "Renovate engine: one PR that moves along until it is merged.", + "description": "When enabled: one PR for the Renovate engine that moves along until it is merged.", "matchPackageNames": ["ghcr.io/renovatebot/renovate"], "groupName": "renovate engine", "automerge": false diff --git a/scripts/check-lockfiles.sh b/scripts/check-lockfiles.sh index 685c124..f0dd035 100755 --- a/scripts/check-lockfiles.sh +++ b/scripts/check-lockfiles.sh @@ -45,24 +45,50 @@ # 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. +# What it takes from the caller's environment (R1, S4, A3, P1): only the allowlist of the block +# below -- it starts again under `env -i` through /bin/bash -p, so no other variable (no venv, +# PYTHON*, UV_*, PIP_* but PIP_CERT, GIT_*, Perl, make, tar, GCONV_PATH, LD_LIBRARY_PATH, ...) and +# no function of the caller is left; no pip/uv configuration file either. 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. Passed on purpose: +# HOME (pip/uv caches; every file is hash-checked), TMPDIR, and the proxy/CA variables, which +# decide how and whom the gate trusts as PyPI. The limit is what runs before the restart: the +# caller's shell with its BASH_ENV and SHELLOPTS (with noexec it runs nothing and ends 0 without +# the final "ok ... verified" line), LD_PRELOAD for that shell and /usr/bin/env. Whoever sets +# those 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 -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 +# ---- clean environment (P1): the same block in every entry script (test_packaging.py) ---- +# Unless this is the clean run already, start again under `env -i` with exactly this allowlist, +# through /bin/bash -p, which imports no function and reads no BASH_ENV, ENV, SHELLOPTS or +# BASHOPTS: PATH=/usr/sbin:/usr/bin:/sbin:/bin, LANG and LC_ALL C.UTF-8, and, where set, HOME, +# TMPDIR, http_proxy, https_proxy, no_proxy, HTTP_PROXY, HTTPS_PROXY, NO_PROXY, SSL_CERT_FILE, +# SSL_CERT_DIR, REQUESTS_CA_BUNDLE, PIP_CERT, and the switches the repository's scripts pass +# each other: LMNRADIUS_ALLOW_REAL, LMNRADIUS_ALLOW_SKIP, LMNRADIUS_CALLER_PATH (run.sh), +# LOCK_GATES_DEB, LOCK_GATES_VERBOSE (lock_gates.sh). Every other variable and every function of +# the caller is gone. Up to the exec only keywords, assignments and one command by absolute path +# run: POSIXLY_CORRECT puts bash into POSIX mode, where the special builtin `exec` comes before +# any function the caller exported. The clean run is told by its first argument. +if [[ "${1-}" != --lmnradius-clean-env ]]; then + POSIXLY_CORRECT=1 + exec /usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin LANG=C.UTF-8 LC_ALL=C.UTF-8 \ + ${HOME+"HOME=$HOME"} ${TMPDIR+"TMPDIR=$TMPDIR"} \ + ${http_proxy+"http_proxy=$http_proxy"} ${https_proxy+"https_proxy=$https_proxy"} \ + ${no_proxy+"no_proxy=$no_proxy"} ${HTTP_PROXY+"HTTP_PROXY=$HTTP_PROXY"} \ + ${HTTPS_PROXY+"HTTPS_PROXY=$HTTPS_PROXY"} ${NO_PROXY+"NO_PROXY=$NO_PROXY"} \ + ${SSL_CERT_FILE+"SSL_CERT_FILE=$SSL_CERT_FILE"} ${SSL_CERT_DIR+"SSL_CERT_DIR=$SSL_CERT_DIR"} \ + ${REQUESTS_CA_BUNDLE+"REQUESTS_CA_BUNDLE=$REQUESTS_CA_BUNDLE"} ${PIP_CERT+"PIP_CERT=$PIP_CERT"} \ + ${LMNRADIUS_ALLOW_REAL+"LMNRADIUS_ALLOW_REAL=$LMNRADIUS_ALLOW_REAL"} \ + ${LMNRADIUS_ALLOW_SKIP+"LMNRADIUS_ALLOW_SKIP=$LMNRADIUS_ALLOW_SKIP"} \ + ${LMNRADIUS_CALLER_PATH+"LMNRADIUS_CALLER_PATH=$LMNRADIUS_CALLER_PATH"} \ + ${LOCK_GATES_DEB+"LOCK_GATES_DEB=$LOCK_GATES_DEB"} \ + ${LOCK_GATES_VERBOSE+"LOCK_GATES_VERBOSE=$LOCK_GATES_VERBOSE"} \ + /bin/bash -p "$0" --lmnradius-clean-env "$@" +fi +shift +# ---- end of the clean environment block ---- +set -euo pipefail export PIP_CONFIG_FILE=/dev/null PIP_DISABLE_PIP_VERSION_CHECK=1 ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)" @@ -85,8 +111,14 @@ 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 +prc=0 +"${PY[@]}" "$GATE" only uv "$UVLOCK" --input "$ROOT/controlplane/uv-requirements.in" \ + && "${PY[@]}" "$GATE" pypi "$UVLOCK" || prc=$? +if [ "$prc" = 3 ]; then + # (the first question to PyPI: offline, the gate stops here and says so) + echo "FAIL PyPI gave no answer (offline?): the lockfiles are NOT verified" + exit 1 +elif [ "$prc" != 0 ]; then echo "FAIL uv-requirements.lock is not exactly the published uv of uv-requirements.in" exit 1 fi diff --git a/scripts/lockfile_gate.py b/scripts/lockfile_gate.py index 14add66..6c89c0d 100755 --- a/scripts/lockfile_gate.py +++ b/scripts/lockfile_gate.py @@ -7,7 +7,9 @@ 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). + files pip never downloads (an sdist, another platform's wheel). Exit 3 when PyPI + gives no answer at all (offline, DNS, timeout): nothing was verified, which the + callers say instead of blaming a hash. 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. @@ -48,6 +50,7 @@ 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.+!]*)") +UNREACHABLE = 3 # `pypi`: PyPI gave no answer, nothing was verified @dataclass @@ -197,6 +200,17 @@ def cmd_pypi(args: argparse.Namespace) -> int: # PyPI would only fail every further pin after the same retries. try: known = published(pin) + # PyPI answered (e.g. 404: no such release), or gave no answer at all + # (URLError, TimeoutError and other OSErrors: offline, DNS). + except urllib.error.HTTPError as e: + errors.append(f"{path}: {pin}: cannot read PyPI: {e}") + return report(errors, "") + except (urllib.error.URLError, OSError) as e: + errors.append( + f"{path}: {pin}: cannot read PyPI, no answer (offline?): {e}" + ) + report(errors, "") + return UNREACHABLE except Exception as e: errors.append(f"{path}: {pin}: cannot read PyPI: {e}") return report(errors, "") diff --git a/scripts/tests/k1_wheel.py b/scripts/tests/k1_wheel.py index 01c8fa7..12c37e3 100755 --- a/scripts/tests/k1_wheel.py +++ b/scripts/tests/k1_wheel.py @@ -28,7 +28,7 @@ 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" + "head tail wc tr cat rm mv chmod touch readlink bash dirname" ).split() diff --git a/scripts/tests/lock_gates.sh b/scripts/tests/lock_gates.sh index 59c99de..7d66995 100755 --- a/scripts/tests/lock_gates.sh +++ b/scripts/tests/lock_gates.sh @@ -23,8 +23,15 @@ # 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; +# UV_*/PIP_* variables and config files that redirect the index or the interpreter, +# exported shell functions named like the builtins and tools a script could call (set, +# export, ., builtin, exec, exit, shift, cd, unset, compgen, mapfile, dirname), +# MAKEFILES/MAKEFLAGS/GNUMAKEFLAGS (with -i)/MAKEOVERRIDES, PERL5OPT/PERL5LIB, CDPATH, +# GCONV_PATH, LD_LIBRARY_PATH and TAR_OPTIONS (A3, P3) -- no marker, same verdicts; each of +# these parts is shown to run code where nothing removes it, and the clean-environment +# block run under all of it holds only its allowlist (P1); with LOCK_GATES_DEB, also +# `make -i deb`, GNUMAKEFLAGS=-i and SHELLOPTS=noexec write no .deb past a refused lock; +# T2 build-venv.sh refuses a venv path it must not remove, before anything runs; # 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. @@ -36,15 +43,38 @@ # 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. +# command is in the Makefile). The harness starts again in a clean environment with the same +# block as the gates (of its own switches, LOCK_GATES_DEB and LOCK_GATES_VERBOSE pass). +# ---- clean environment (P1): the same block in every entry script (test_packaging.py) ---- +# Unless this is the clean run already, start again under `env -i` with exactly this allowlist, +# through /bin/bash -p, which imports no function and reads no BASH_ENV, ENV, SHELLOPTS or +# BASHOPTS: PATH=/usr/sbin:/usr/bin:/sbin:/bin, LANG and LC_ALL C.UTF-8, and, where set, HOME, +# TMPDIR, http_proxy, https_proxy, no_proxy, HTTP_PROXY, HTTPS_PROXY, NO_PROXY, SSL_CERT_FILE, +# SSL_CERT_DIR, REQUESTS_CA_BUNDLE, PIP_CERT, and the switches the repository's scripts pass +# each other: LMNRADIUS_ALLOW_REAL, LMNRADIUS_ALLOW_SKIP, LMNRADIUS_CALLER_PATH (run.sh), +# LOCK_GATES_DEB, LOCK_GATES_VERBOSE (lock_gates.sh). Every other variable and every function of +# the caller is gone. Up to the exec only keywords, assignments and one command by absolute path +# run: POSIXLY_CORRECT puts bash into POSIX mode, where the special builtin `exec` comes before +# any function the caller exported. The clean run is told by its first argument. +if [[ "${1-}" != --lmnradius-clean-env ]]; then + POSIXLY_CORRECT=1 + exec /usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin LANG=C.UTF-8 LC_ALL=C.UTF-8 \ + ${HOME+"HOME=$HOME"} ${TMPDIR+"TMPDIR=$TMPDIR"} \ + ${http_proxy+"http_proxy=$http_proxy"} ${https_proxy+"https_proxy=$https_proxy"} \ + ${no_proxy+"no_proxy=$no_proxy"} ${HTTP_PROXY+"HTTP_PROXY=$HTTP_PROXY"} \ + ${HTTPS_PROXY+"HTTPS_PROXY=$HTTPS_PROXY"} ${NO_PROXY+"NO_PROXY=$NO_PROXY"} \ + ${SSL_CERT_FILE+"SSL_CERT_FILE=$SSL_CERT_FILE"} ${SSL_CERT_DIR+"SSL_CERT_DIR=$SSL_CERT_DIR"} \ + ${REQUESTS_CA_BUNDLE+"REQUESTS_CA_BUNDLE=$REQUESTS_CA_BUNDLE"} ${PIP_CERT+"PIP_CERT=$PIP_CERT"} \ + ${LMNRADIUS_ALLOW_REAL+"LMNRADIUS_ALLOW_REAL=$LMNRADIUS_ALLOW_REAL"} \ + ${LMNRADIUS_ALLOW_SKIP+"LMNRADIUS_ALLOW_SKIP=$LMNRADIUS_ALLOW_SKIP"} \ + ${LMNRADIUS_CALLER_PATH+"LMNRADIUS_CALLER_PATH=$LMNRADIUS_CALLER_PATH"} \ + ${LOCK_GATES_DEB+"LOCK_GATES_DEB=$LOCK_GATES_DEB"} \ + ${LOCK_GATES_VERBOSE+"LOCK_GATES_VERBOSE=$LOCK_GATES_VERBOSE"} \ + /bin/bash -p "$0" --lmnradius-clean-env "$@" +fi +shift +# ---- end of the clean environment block ---- 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)" @@ -120,6 +150,28 @@ if [ "$FAIL" != 0 ]; then exit 1 fi +# ---------------------------------------------------------------- T2: the venv path +# build-venv.sh removes its venv path with `rm -rf`: anything but an absolute path without +# whitespace or . / .. / // components that ends in /opt/linuxmuster-radius/venv is refused +# before anything runs, and the directory it names survives. +mkdir -p "$TMP/t2/keep/opt/linuxmuster-radius/venv" "$TMP/t2/keep dir" +echo keep > "$TMP/t2/keep/sentinel" +echo keep > "$TMP/t2/keep/opt/linuxmuster-radius/venv/sentinel" +T2_WHY="refusing venv path" +expect fail "T2 build-venv: a relative path" "$T2_WHY" \ + bash -c 'cd "$1" && bash "$2" keep/opt/linuxmuster-radius/venv' _ "$TMP/t2" "$ROOT/packaging/build-venv.sh" +expect fail "T2 build-venv: a path that is not .../opt/linuxmuster-radius/venv" "$T2_WHY" \ + bash "$ROOT/packaging/build-venv.sh" "$TMP/t2/keep" +expect fail "T2 build-venv: whitespace in the path" "$T2_WHY" \ + bash "$ROOT/packaging/build-venv.sh" "$TMP/t2/keep dir/opt/linuxmuster-radius/venv" +expect fail "T2 build-venv: a .. component" "$T2_WHY" \ + bash "$ROOT/packaging/build-venv.sh" "$TMP/t2/x/../keep/opt/linuxmuster-radius/venv" +if [ -f "$TMP/t2/keep/sentinel" ] && [ -f "$TMP/t2/keep/opt/linuxmuster-radius/venv/sentinel" ]; then + echo "ok T2 nothing was removed"; PASS=$((PASS + 1)) +else + echo "WRONG T2 build-venv.sh removed a directory it refused"; FAIL=$((FAIL + 1)) +fi + # ---------------------------------------------------------------- the F2 matrix # Each case edits controlplane/requirements.lock in a copy of the files both scripts read. # The first pin and its hashes are found at run time, so the cases follow lockfile bumps. @@ -171,7 +223,7 @@ for c in indented-url extra-index-url hashes-removed hash-changed extra-pin pin- cp "$ROOT/debian/changelog" "$dir/debian/" edit "$dir/controlplane/requirements.lock" "${EDIT[$c]}" expect fail "check: $c" "${CHECK_WHY[$c]}" bash "$dir/scripts/check-lockfiles.sh" - expect fail "build: $c" "${BUILD_WHY[$c]}" bash "$dir/packaging/build-venv.sh" "$dir/venv" + expect fail "build: $c" "${BUILD_WHY[$c]}" bash "$dir/packaging/build-venv.sh" "$dir/v/opt/linuxmuster-radius/venv" if [ -n "${LOCK_GATES_DEB:-}" ]; then copy_tree "$TMP/deb-$c/src" cp "$dir/controlplane/requirements.lock" "$TMP/deb-$c/src/controlplane/" @@ -281,7 +333,7 @@ k1_case() { rm -f "$MARK" expect fail "K1 check: $label" "$why" bash "$dir/scripts/check-lockfiles.sh" no_marker "K1 check: $label" - expect fail "K1 build-venv: $label" "$why" bash "$dir/packaging/build-venv.sh" "$dir/v" + expect fail "K1 build-venv: $label" "$why" bash "$dir/packaging/build-venv.sh" "$dir/v/opt/linuxmuster-radius/venv" no_marker "K1 build-venv: $label" if [ -n "${LOCK_GATES_DEB:-}" ]; then expect fail "K1 make deb: $label" "$why" make -C "$dir" deb @@ -348,12 +400,13 @@ assert s.count(old) == 1 open(p, "w").write(s.replace(old, "true")) PY rm -f "$MARK" -bash "$dir/packaging/build-venv.sh" "$dir/v" > "$TMP/out" 2>&1 +bash "$dir/packaging/build-venv.sh" "$dir/v/opt/linuxmuster-radius/venv" > "$TMP/out" 2>&1 marker_from_bin "R6 counter-probe: build-venv.sh without the gate" # ------------------------------------------------ R1: these parts of the caller's environment -# (BASH_ENV, exported shell functions and proxy/CA variables are the documented limit, not -# tested here: whoever sets them already runs code as the caller) +# (what the caller's bash does before the restart -- BASH_ENV, SHELLOPTS -- and the proxy/CA +# variables the allowlist passes are the documented limit, not tested as poison here: whoever +# sets them already runs code as the caller; SHELLOPTS=noexec is shown below as that limit) # An activated venv P with the wheel installed: its bin/ (diff, sort, awk, grep, python3, uv, # pip, bash, ...) first on PATH, VIRTUAL_ENV=P, UV_PYTHON pointing into it; PYTHONPATH with a # sitecustomize that writes the marker; PYTHONHOME that breaks every non-isolated Python; @@ -378,6 +431,136 @@ POISON=(env "PATH=$P/bin:/usr/sbin:/usr/bin:/sbin:/bin" "VIRTUAL_ENV=$P" "UV_FIND_LINKS=$WHEELDIR" "UV_CONFIG_FILE=$TMP/r1-uv.toml" "PIP_INDEX_URL=http://127.0.0.1:9/simple" "PIP_FIND_LINKS=$WHEELDIR" "PIP_CONFIG_FILE=$TMP/r1-pip.conf" "GIT_CONFIG_PARAMETERS='core.fsmonitor'='$TMP/r1-fsmonitor'") +# A3/P3: exported functions named like the builtins and tools a script could call before it is +# clean (each writes the marker, then does what the builtin does), `builtin` and `exec` among +# them; Perl's own variables, which dpkg-parsechangelog, dpkg-buildpackage and debhelper read; +# CDPATH, which would send `cd scripts/..` of a script started by a relative path into +# $TMP/r1-cdpath; GCONV_PATH with a gconv module and LD_LIBRARY_PATH with a libz.so.1 (a filter +# on the real one), both writing the marker when loaded; TAR_OPTIONS with a checkpoint action +# that writes the marker. gcc builds the two libraries (the test fails without it). +command -v gcc > /dev/null || { echo "lock_gates.sh: gcc is required (GCONV_PATH, LD_LIBRARY_PATH)"; exit 1; } +mkdir -p "$TMP/r1-perl" "$TMP/r1-cdpath/scripts/tests" "$TMP/r1-cdpath/packaging" \ + "$TMP/r1-gconv" "$TMP/r1-ld" +printf 'open(my $m, ">>", "%s"); print $m "perl ran PERL5OPT: $0\\n"; close $m; 1;\n' "$MARK" \ + > "$TMP/r1-perl/ZzzPoison.pm" +cat > "$TMP/r1-ld.c" << 'C' +#include +__attribute__((constructor)) static void zzz(void) { + FILE *f = fopen(MARK, "a"); + if (f) { fputs("LD_LIBRARY_PATH libz.so.1 ran\n", f); fclose(f); } +} +int gconv_init(void *step) { + FILE *f = fopen(MARK, "a"); + if (f) { fputs("GCONV_PATH module ran\n", f); fclose(f); } + return 1; +} +int gconv(void) { return 1; } +C +gcc -shared -fPIC -DMARK="\"$MARK\"" -o "$TMP/r1-ld/libz.so.1" "$TMP/r1-ld.c" \ + -Wl,-soname,libz.so.1 -Wl,--filter=/usr/lib/x86_64-linux-gnu/libz.so.1 +gcc -shared -fPIC -DMARK="\"$MARK\"" -o "$TMP/r1-gconv/ZZZPOISON.so" "$TMP/r1-ld.c" +printf 'module ZZZPOISON// INTERNAL ZZZPOISON 1\nmodule INTERNAL ZZZPOISON// ZZZPOISON 1\n' \ + > "$TMP/r1-gconv/gconv-modules" +printf '#!/bin/sh\necho "TAR_OPTIONS checkpoint ran" >> %s\n' "$MARK" > "$TMP/r1-tar-hook" +chmod +x "$TMP/r1-tar-hook" +for f in set export . builtin exec exit shift cd unset compgen mapfile; do + POISON+=("BASH_FUNC_$f%%=() { echo \"function $f ran\" >> '$MARK'; command $f \"\$@\"; }") +done +POISON+=("BASH_FUNC_dirname%%=() { echo \"function dirname ran\" >> '$MARK'; /usr/bin/dirname \"\$@\"; }") +POISON+=("PERL5OPT=-MZzzPoison" "PERL5LIB=$TMP/r1-perl" "CDPATH=$TMP/r1-cdpath" + "GCONV_PATH=$TMP/r1-gconv" "LD_LIBRARY_PATH=$TMP/r1-ld" + "TAR_OPTIONS=--checkpoint=1 --checkpoint-action=exec=$TMP/r1-tar-hook") +# make's own variables go only to the scripts started directly (POISON_MAKE): `make deb` is the +# caller's own make, which reads them before make-deb.sh starts (the stated limit); make-deb.sh +# must keep them from the make runs of debian/rules. MAKEFILES adds a makefile that writes the +# marker; MAKEFLAGS and GNUMAKEFLAGS set -i (ignore errors: a failed gate would not stop the +# build) and make's SHELL to a script that writes the marker, and MAKEOVERRIDES sets that SHELL +# in every recursive make (dh calls debian/rules again for its overrides). +printf '$(shell echo "MAKEFILES read by make in $(CURDIR)" >> %s)\n' "$MARK" > "$TMP/r1-poison.mk" +printf '#!/bin/sh\necho "make SHELL from MAKEFLAGS ran in $PWD" >> %s\nexec /bin/sh "$@"\n' "$MARK" \ + > "$TMP/r1-make-shell" +chmod +x "$TMP/r1-make-shell" +POISON_MAKE=("MAKEFILES=$TMP/r1-poison.mk" "MAKEFLAGS=-i -- SHELL=$TMP/r1-make-shell" + "GNUMAKEFLAGS=-i -- SHELL=$TMP/r1-make-shell" "MAKEOVERRIDES=SHELL=$TMP/r1-make-shell") +# Each new part of the poison is sharp: where nothing removes it, it runs code. +sharp() { #