#!/usr/bin/env bash # # run-tests.sh - Debian port test harness for the VDI-Linux provisioning repo. # # Proves the Debian side of the port works and that the Fedora side is # unregressed. Run as root on a Debian 13 (trixie) machine: # # sudo bash debian/test/run-tests.sh # # Exit status: 0 if no test FAILED, 1 otherwise. SKIPped tests do not fail the # run, but every SKIP prints why it skipped and what it would have checked. # # The harness is self-cleaning. It never writes to /var/local/citrix-repo, # never installs a package (apt-get install is only ever --simulate), and # removes every apt source file and cached index it adds. See README.md. set -uo pipefail # --------------------------------------------------------------------------- # Configuration # --------------------------------------------------------------------------- SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) REPO_ROOT=$(cd "$SCRIPT_DIR/../.." && pwd) # The two real Citrix .deb files live next to the repo, not inside it. DEB_DIR="${DEB_DIR:-$(dirname "$REPO_ROOT")}" ICACLIENT_DEB="icaclient_26.08.0.225_amd64.deb" CTXUSB_DEB="ctxusb_26.08.0.225_amd64.deb" EXPECTED_VERSION="26.08.0.225" # The production apt source file the Debian path installs. PROD_SOURCE_FILE="$REPO_ROOT/local-citrix-repo.list" PROD_REPO_DIR="/var/local/citrix-repo" TMP_DIR=$(mktemp -d "${TMPDIR:-/tmp}/vdi-debian-test.XXXXXX") REPO_DIR="$TMP_DIR/repo" TAMPER_DIR="$TMP_DIR/tamper" SANDBOX_DIR="$TMP_DIR/sandbox" LIST_FILE="/etc/apt/sources.list.d/zz-vdi-test-$$.list" KEYRING_DIR=/etc/apt/keyrings # Two concurrent runs share /var/lib/apt/lists and /etc/apt/sources.list.d. # Measured: with two runs in flight, one run's teardown deleted the other's # temp repo while apt was reading it, and `apt-get install --simulate` failed # with "Could not open file /var/lib/apt/lists/_tmp_vdi-debian-test." # - a failure that looks like a port bug but is a collision. Serialise instead. LOCK_FILE="/var/lock/vdi-debian-test.lock" if ! exec 9>"$LOCK_FILE"; then printf 'Cannot open lock file %s\n' "$LOCK_FILE" exit 1 fi if ! flock -n 9; then printf 'Another run of this harness is already in progress (lock: %s).\n' "$LOCK_FILE" printf 'They share apt state; run them one at a time.\n' exit 1 fi # Never let Python write __pycache__ into the repo: py_compile would otherwise # leave an untracked directory behind and dirty the working tree. export PYTHONPYCACHEPREFIX="$TMP_DIR/pycache" export PYTHONDONTWRITEBYTECODE=1 PASSED=0 FAILED=0 SKIPPED=0 FAILED_NAMES="" # /var/local/citrix-repo must not be touched; record its state up front. PROD_REPO_MTIME_BEFORE="" if [ -d "$PROD_REPO_DIR" ]; then PROD_REPO_MTIME_BEFORE=$(stat -c '%Y' "$PROD_REPO_DIR" 2>/dev/null || echo "") fi # T15 asserts nothing was installed; record the baseline now. INSTALLED_BEFORE="" if command -v dpkg-query >/dev/null 2>&1; then INSTALLED_BEFORE=$(dpkg-query -W -f='${Package}\n' 2>/dev/null | wc -l) fi # --------------------------------------------------------------------------- # Reporting helpers # --------------------------------------------------------------------------- pass() { printf 'PASS %s\n' "$1"; PASSED=$((PASSED + 1)); } # Keep failure messages readable: a Python traceback inside a FAIL line buries # the summary. The caller prints the full detail above the FAIL line. fail() { local msg="$1" if [ "${#msg}" -gt 240 ]; then msg="$(printf '%s' "$msg" | cut -c1-240)... (truncated; see output above)" fi printf 'FAIL %s\n' "$msg" FAILED=$((FAILED + 1)) FAILED_NAMES="$FAILED_NAMES - $msg" } skip() { printf 'SKIP %s\n' "$1"; SKIPPED=$((SKIPPED + 1)); } info() { printf ' %s\n' "$1"; } head2() { printf '\n== %s\n' "$1"; } # apt encodes a source path into a list filename by replacing '/' with '_', # e.g. file:/root/x/repo -> _root_x_repo_._Packages list_fragment() { printf '%s' "$1" | sed 's|/|_|g'; } purge_apt_lists_for() { local dir="$1" frag frag=$(list_fragment "$dir") rm -f /var/lib/apt/lists/*"$frag"* 2>/dev/null rm -f /var/lib/apt/lists/partial/*"$frag"* 2>/dev/null return 0 } # Also clear indexes left by any earlier run of this harness, including ones # whose temp directory no longer exists. A stale index pointing at a deleted # repo makes `apt-get install --simulate` fail for a reason unrelated to the # code under test. purge_all_harness_lists() { rm -f /var/lib/apt/lists/*vdi-debian-test* 2>/dev/null rm -f /var/lib/apt/lists/partial/*vdi-debian-test* 2>/dev/null return 0 } # Paths installed by update_local_repo.install_debian_update_policy(). These # are REAL system paths, so the tests that touch them back up whatever is # already there and restore it at teardown rather than deleting blindly. POLKIT_RULE_PATH="/etc/polkit-1/rules.d/60-vdi-no-password-updates.rules" OFFLINE_SCRIPT="/usr/local/sbin/vdi-offline-update" OFFLINE_SERVICE="/etc/systemd/system/vdi-offline-update.service" OFFLINE_TIMER="/etc/systemd/system/vdi-offline-update.timer" OFFLINE_STAMP="/var/lib/vdi-offline-update.last" SYSTEM_UPDATE_LINK="/system-update" BACKUP_DIR="$TMP_DIR/backup" mkdir -p "$BACKUP_DIR" # Save the current state of a path so teardown can put it back exactly. # Records "present" or "absent" in a marker file, so "it did not exist before" # is distinguishable from "the backup failed". backup_path() { local path="$1" name name=$(printf '%s' "$path" | tr '/' '_') if [ -L "$path" ]; then printf 'symlink\n' > "$BACKUP_DIR/$name.state" readlink "$path" > "$BACKUP_DIR/$name.target" elif [ -e "$path" ]; then printf 'present\n' > "$BACKUP_DIR/$name.state" cp -a "$path" "$BACKUP_DIR/$name" 2>/dev/null else printf 'absent\n' > "$BACKUP_DIR/$name.state" fi } restore_path() { local path="$1" name state name=$(printf '%s' "$path" | tr '/' '_') state=$(cat "$BACKUP_DIR/$name.state" 2>/dev/null || echo absent) case "$state" in symlink) # Never rm -rf a symlink target; only unlink the link itself. [ -L "$path" ] && rm -f "$path" ln -s "$(cat "$BACKUP_DIR/$name.target")" "$path" 2>/dev/null ;; present) cp -a "$BACKUP_DIR/$name" "$path" 2>/dev/null ;; *) # It did not exist before this run: remove it, but only if it is a # regular file or symlink - never recurse into a directory. if [ -L "$path" ]; then rm -f "$path" elif [ -f "$path" ]; then rm -f "$path" fi ;; esac } cleanup() { local status=$? # T15 already tore everything down and verified it, then printed the # summary. Running the teardown again here would only risk disturbing it. if [ "${CLEANED:-0}" = "1" ]; then exit $status fi printf '\n== cleanup\n' # Undo the machine mutations from T16-T19 first: a polkit rule or a systemd # unit left behind is more consequential than a temp directory. for mutating_path in "$POLKIT_RULE_PATH" "$OFFLINE_STAMP" "$SYSTEM_UPDATE_LINK" \ "$OFFLINE_SCRIPT" "$OFFLINE_SERVICE" "$OFFLINE_TIMER"; do restore_path "$mutating_path" 2>/dev/null done command -v systemctl >/dev/null 2>&1 && systemctl daemon-reload >/dev/null 2>&1 pkill -f 'vdi-test-sleeper' >/dev/null 2>&1 rm -f "$LIST_FILE" 2>/dev/null # Remove any keyring this run installed, by its unique name. rm -f "$KEYRING_DIR"/zz-vdi-test-* 2>/dev/null rmdir "$KEYRING_DIR" 2>/dev/null purge_apt_lists_for "$REPO_DIR" purge_apt_lists_for "$TAMPER_DIR" purge_apt_lists_for "$SANDBOX_DIR" # Refresh so apt forgets the source we just removed. apt-get update -qq >/dev/null 2>&1 rm -rf "$TMP_DIR" 2>/dev/null printf 'removed %s, %s and cached indexes\n' "$TMP_DIR" "$LIST_FILE" exit $status } trap cleanup EXIT INT TERM CLEANED=0 # --------------------------------------------------------------------------- # T00: environment sanity # --------------------------------------------------------------------------- head2 "T00 environment" if [ "$(id -u)" -ne 0 ]; then printf 'This harness must run as root (it adds and removes an apt source).\n' exit 1 fi for tool in apt-ftparchive apt-get apt-cache dpkg-deb python3 gzip; do if ! command -v "$tool" >/dev/null 2>&1; then printf 'Missing required tool: %s\n' "$tool" exit 1 fi done # Clear indexes from any earlier run before doing anything else. purge_all_harness_lists CODENAME="" if [ -r /etc/os-release ]; then # shellcheck disable=SC1091 . /etc/os-release CODENAME="${VERSION_CODENAME:-}" fi info "distribution: ${PRETTY_NAME:-unknown} (codename=${CODENAME:-unknown})" if [ "$CODENAME" != "trixie" ]; then info "WARNING: expected trixie; package dependency resolution is only proven there" fi if [ ! -f "$DEB_DIR/$ICACLIENT_DEB" ] || [ ! -f "$DEB_DIR/$CTXUSB_DEB" ]; then printf 'Missing fixture .deb files in %s\n' "$DEB_DIR" printf 'Expected:\n %s\n %s\n' "$ICACLIENT_DEB" "$CTXUSB_DEB" printf 'Override the directory with DEB_DIR=/path/to/debs\n' exit 1 fi info "fixtures: $DEB_DIR" # --------------------------------------------------------------------------- # T01: the .deb fixtures are what we think they are # --------------------------------------------------------------------------- # Without this, every later version assertion could be checking a stale file. head2 "T01 fixture .deb identity" for pkg in "$ICACLIENT_DEB" "$CTXUSB_DEB"; do got=$(dpkg-deb -f "$DEB_DIR/$pkg" Version 2>/dev/null) name=$(dpkg-deb -f "$DEB_DIR/$pkg" Package 2>/dev/null) if [ "$got" = "$EXPECTED_VERSION" ]; then pass "T01 $pkg declares Version $got (package $name)" else fail "T01 $pkg declares Version '$got', expected $EXPECTED_VERSION" fi done # --------------------------------------------------------------------------- # T02: Python syntax and import safety on Debian # --------------------------------------------------------------------------- head2 "T02 python3 -m py_compile" for py in update_local_repo.py configure_kde.py; do if [ ! -f "$REPO_ROOT/$py" ]; then fail "T02 $py is missing from the repo" continue fi if out=$(cd "$TMP_DIR" && python3 -m py_compile "$REPO_ROOT/$py" 2>&1); then pass "T02 $py compiles" else fail "T02 $py failed to compile: $out" fi done if [ -d "$REPO_ROOT/__pycache__" ]; then fail "T02 py_compile left __pycache__ inside the repo (working tree dirtied)" else pass "T02 no __pycache__ written into the repo" fi head2 "T03 import safety (module import must not explode or act)" # Importing must be side-effect free: run from a scratch cwd so a relative path # in module-level code cannot accidentally work, and compare state afterwards. import_probe() { local module="$1" cd "$TMP_DIR" || return 1 python3 - "$REPO_ROOT" "$module" <<'PYEOF' 2>&1 import sys, os repo, module = sys.argv[1], sys.argv[2] sys.path.insert(0, repo) os.chdir(os.environ["PYTHONPYCACHEPREFIX"]) try: __import__(module) except Exception as exc: print("IMPORT-FAILED: %s: %s" % (type(exc).__name__, exc)) raise SystemExit(1) print("IMPORT-OK") PYEOF } for module in configure_kde update_local_repo; do if out=$(import_probe "$module"); then if printf '%s' "$out" | grep -q 'IMPORT-OK'; then pass "T03 import $module succeeds on Debian" else fail "T03 import $module produced no confirmation: $out" fi else fail "T03 import $module raised: $(printf '%s' "$out" | tr '\n' ' ')" fi done # The tqdm fallback: a stock trixie has no tqdm and no pip. The import above # already covers the absent case. This asserts the fallback is a *working* # no-op, not merely an importable name. head2 "T04 tqdm fallback is functional, not just importable" if out=$(cd "$TMP_DIR" && python3 - "$REPO_ROOT" <<'PYEOF' 2>&1 import sys, os, importlib.util repo = sys.argv[1] sys.path.insert(0, repo) os.chdir(os.environ["PYTHONPYCACHEPREFIX"]) real_tqdm = importlib.util.find_spec("tqdm") is not None print("real tqdm installed:", real_tqdm) import update_local_repo as u bar = u.tqdm(total=10, unit="B", desc="probe", mininterval=0.1) bar.update(5) bar.update(5) bar.close() print("tqdm object constructed, updated and closed OK") print("is fallback class:", getattr(u.tqdm, "__module__", "") == "update_local_repo") PYEOF ); then pass "T04 tqdm object usable with tqdm absent (fallback exercised)" info "$(printf '%s' "$out" | tr '\n' ' ')" else fail "T04 tqdm fallback is broken: $(printf '%s' "$out" | tr '\n' ' ')" fi # --------------------------------------------------------------------------- # T05: the flat apt repository builds from the real .deb files # --------------------------------------------------------------------------- head2 "T05 flat repo build (apt-ftparchive)" mkdir -p "$REPO_DIR" chmod 755 "$REPO_DIR" "$TMP_DIR" cp "$DEB_DIR/$ICACLIENT_DEB" "$DEB_DIR/$CTXUSB_DEB" "$REPO_DIR"/ || fail "T05 could not copy fixtures" build_repo() { local dir="$1" ( cd "$dir" || exit 1 apt-ftparchive packages . > Packages || exit 1 gzip -c Packages > Packages.gz || exit 1 apt-ftparchive release . > Release || exit 1 ) local rc=$? chmod 644 "$dir"/Packages "$dir"/Packages.gz "$dir"/Release 2>/dev/null return $rc } if build_repo "$REPO_DIR"; then pass "T05 repo build command sequence succeeded" else fail "T05 repo build command sequence failed" fi stanzas=$(grep -c '^Package:' "$REPO_DIR/Packages" 2>/dev/null || echo 0) if [ "$stanzas" = "2" ]; then pass "T05 Packages contains exactly 2 stanzas" else fail "T05 Packages contains $stanzas stanzas, expected 2" info "stanzas: $(grep '^Package:' "$REPO_DIR/Packages" 2>/dev/null | tr '\n' ' ')" fi for pkg in icaclient ctxusb; do got=$(awk -v p="$pkg" ' /^Package:/ { in_pkg = ($2 == p) } in_pkg && /^Version:/ { print $2; exit } ' "$REPO_DIR/Packages") if [ "$got" = "$EXPECTED_VERSION" ]; then pass "T05 Packages declares $pkg $got" else fail "T05 Packages declares $pkg '${got:-nothing}', expected $EXPECTED_VERSION" fi done for f in Packages Packages.gz Release; do if [ -s "$REPO_DIR/$f" ]; then pass "T05 $f is present and non-empty" else fail "T05 $f is missing or empty" fi done # --------------------------------------------------------------------------- # T06/T07: apt can see and resolve the package from that repo # --------------------------------------------------------------------------- head2 "T06 sources.list entry and apt-get update" # The exact production form: flat repo, suite "./", trusted=yes. printf 'deb [trusted=yes] file:%s ./\n' "$REPO_DIR" > "$LIST_FILE" info "source: $(cat "$LIST_FILE")" purge_apt_lists_for "$REPO_DIR" update_out=$(apt-get update 2>&1) update_rc=$? # The spec'd check: exit 0 and no E: lines. if [ "$update_rc" -eq 0 ]; then pass "T06 apt-get update exits 0" else fail "T06 apt-get update exits $update_rc" fi e_count=$(printf '%s\n' "$update_out" | grep -c '^E:' || true) if [ "$e_count" -eq 0 ]; then pass "T06 apt-get update emitted no E: lines" else fail "T06 apt-get update emitted $e_count E: line(s)" printf '%s\n' "$update_out" | grep '^E:' | sed 's/^/ /' fi # The strong check. Measured on trixie: a repo whose Packages is unreadable # still yields exit 0 and no E: lines, but does emit "Err:" - so the weak form # above can pass on a broken repo. These lines are what actually catch it. err_count=$(printf '%s\n' "$update_out" | grep -c '^Err:' || true) if [ "$err_count" -eq 0 ]; then pass "T06 apt-get update emitted no Err: lines (stronger than the spec)" else fail "T06 apt-get update emitted $err_count Err: line(s) - the source is not readable" printf '%s\n' "$update_out" | grep '^Err:' | sed 's/^/ /' fi src_warn=$(printf '%s\n' "$update_out" | grep '^W:' | grep -F "$REPO_DIR" | grep -vc 'is not signed' || true) if [ "$src_warn" -eq 0 ]; then pass "T06 no unexpected W: lines for this source" else fail "T06 apt-get update warned $src_warn time(s) about this source" printf '%s\n' "$update_out" | grep '^W:' | grep -F "$REPO_DIR" | sed 's/^/ /' fi head2 "T07 apt can see the package (after purging the index cache)" # Purging matters: with a stale cached index a WRONG source still looks good. policy=$(apt-cache policy icaclient 2>&1) cand=$(printf '%s\n' "$policy" | awk '/Candidate:/ { print $2; exit }') if [ "$cand" = "$EXPECTED_VERSION" ]; then pass "T07 apt-cache policy icaclient -> Candidate $cand" else fail "T07 apt-cache policy icaclient -> Candidate '${cand:-none}', expected $EXPECTED_VERSION" printf '%s\n' "$policy" | sed 's/^/ /' fi if printf '%s\n' "$policy" | grep -qF "file:$REPO_DIR"; then pass "T07 the version comes from this local repo, not somewhere else" else fail "T07 apt-cache policy does not attribute icaclient to $REPO_DIR" fi show_version=$(apt-cache show icaclient 2>/dev/null | awk '/^Version:/ { print $2; exit }') if [ "$show_version" = "$EXPECTED_VERSION" ]; then pass "T07 apt-cache show icaclient -> Version $show_version" else fail "T07 apt-cache show icaclient -> Version '${show_version:-none}', expected $EXPECTED_VERSION" fi if apt-get install --simulate -y icaclient >"$TMP_DIR/simulate.log" 2>&1; then pass "T07 apt-get install --simulate -y icaclient resolves (no missing deps)" else # Distinguish "the repo is broken" from "something else touched apt". # A stale or vanished index for ANOTHER harness run produces a path we # never created, and blaming the port for that would be wrong. if grep -q 'vdi-debian-test' "$TMP_DIR/simulate.log" \ && ! grep -qF "$(list_fragment "$REPO_DIR")" "$TMP_DIR/simulate.log"; then fail "T07 simulation failed because another harness run's index vanished (concurrency, not the port)" else fail "T07 apt-get install --simulate -y icaclient did not resolve" fi tail -15 "$TMP_DIR/simulate.log" | sed 's/^/ /' fi if grep -q '^Inst icaclient' "$TMP_DIR/simulate.log"; then pass "T07 the simulated install actually selects icaclient" else fail "T07 simulation did not select icaclient (it may be already installed)" fi # --------------------------------------------------------------------------- # T08: idempotency # --------------------------------------------------------------------------- head2 "T08 rebuild is idempotent" cp "$REPO_DIR/Packages" "$TMP_DIR/Packages.first" build_repo "$REPO_DIR" >/dev/null 2>&1 stanzas2=$(grep -c '^Package:' "$REPO_DIR/Packages" 2>/dev/null || echo 0) if cmp -s "$TMP_DIR/Packages.first" "$REPO_DIR/Packages"; then pass "T08 Packages is byte-identical after a second build" else fail "T08 Packages changed on rebuild" fi if [ "$stanzas2" = "2" ]; then pass "T08 still exactly 2 stanzas after rebuild (no duplicates)" else fail "T08 rebuild produced $stanzas2 stanzas, expected 2" grep '^Package:' "$REPO_DIR/Packages" | sed 's/^/ /' fi # A duplicate stanza is what a naive "copy new, leave old" implementation # produces. Assert the count is exact, not merely non-zero. dup=$(grep '^Package:' "$REPO_DIR/Packages" 2>/dev/null | sort | uniq -d) if [ -z "$dup" ]; then pass "T08 no duplicated Package stanzas" else fail "T08 duplicated stanzas: $dup" fi # --------------------------------------------------------------------------- # T09: stale package pruning in sync_debian # --------------------------------------------------------------------------- # Debian .deb filenames embed the version, so copying without deleting would # leave every previous version in the repo and apt would always prefer the # highest - making a rollback impossible. This reproduces that scenario. head2 "T09 stale .deb is pruned by sync_debian" mkdir -p "$SANDBOX_DIR/repo" "$SANDBOX_DIR/staging" "$SANDBOX_DIR/src" cp "$DEB_DIR/$ICACLIENT_DEB" "$DEB_DIR/$CTXUSB_DEB" "$SANDBOX_DIR/src"/ # Pretend an older ctxusb is already published. cp "$DEB_DIR/$CTXUSB_DEB" "$SANDBOX_DIR/repo/ctxusb_26.07.0.100_amd64.deb" if out=$(python3 - "$REPO_ROOT" "$SANDBOX_DIR" <<'PYEOF' 2>&1 import sys, os, shutil, re, subprocess repo_root, work = sys.argv[1], sys.argv[2] sys.path.insert(0, repo_root) os.chdir(os.environ["PYTHONPYCACHEPREFIX"]) import update_local_repo as u repo_dir = os.path.join(work, "repo") stage = os.path.join(work, "staging") src = os.path.join(work, "src") # Redirect all module-level paths into the sandbox. u.LOCAL_REPO_DIR = repo_dir u.STAGING_DIR = stage u.DEBIAN_FALLBACK_DIR = src u.save_last_release = lambda rd: None # Never write to /etc and never run apt-get from inside a test. real_copyfile = shutil.copyfile def guarded_copyfile(s, d, *a, **k): if str(d).startswith("/etc/"): d = os.path.join(work, "etc-redirect", os.path.basename(str(d))) os.makedirs(os.path.dirname(d), exist_ok=True) return real_copyfile(s, d, *a, **k) u.shutil.copyfile = guarded_copyfile real_run = subprocess.run calls = [] def guarded_run(args, *a, **k): if isinstance(args, (list, tuple)) and args and args[0] == "apt-get": calls.append(list(args)) return subprocess.CompletedProcess(args, 0, b"", b"") return real_run(args, *a, **k) u.subprocess.run = guarded_run before = sorted(f for f in os.listdir(repo_dir) if f.endswith(".deb")) release = {"tag_name": "v26.08", "published_at": "2026-01-01T00:00:00Z", "assets": {}} u.sync_debian(True, release) after = sorted(f for f in os.listdir(repo_dir) if f.endswith(".deb")) pk = open(os.path.join(repo_dir, "Packages")).read() print("BEFORE:", before) print("AFTER:", after) print("APT-GET-CALLS:", calls) print("STANZAS:", len(re.findall(r"^Package: ", pk, re.M))) for m in re.finditer(r"^Package: (\S+)$\n(?:.*\n)*?^Version: (\S+)$", pk, re.M): print("VERSION: %s=%s" % (m.group(1), m.group(2))) PYEOF ); then printf '%s\n' "$out" | sed 's/^/ /' # Check the AFTER line specifically. Grepping the whole output would match # the BEFORE line, which deliberately contains the stale filename - the # test would then fail on its own evidence and could never pass. after_line=$(printf '%s\n' "$out" | grep '^AFTER:' || true) if printf '%s' "$after_line" | grep -q 'ctxusb_26\.07\.0\.100'; then fail "T09 the stale ctxusb_26.07.0.100 was not removed from the repo dir" else pass "T09 stale ctxusb_26.07.0.100 was pruned" fi # Stronger than a file count: a prune that deleted everything would also # give "2 stanzas" if the index were rebuilt from nothing. Assert both # current packages are actually present after the sync. for expected_deb in "$ICACLIENT_DEB" "$CTXUSB_DEB"; do if printf '%s' "$after_line" | grep -qF "$expected_deb"; then pass "T09 $expected_deb present after sync" else fail "T09 $expected_deb missing after sync (prune removed too much)" fi done if printf '%s\n' "$out" | grep -q 'STANZAS: 2'; then pass "T09 Packages holds exactly 2 stanzas after sync" else fail "T09 Packages does not hold exactly 2 stanzas after sync" fi if printf '%s\n' "$out" | grep -q "VERSION: ctxusb=$EXPECTED_VERSION"; then pass "T09 ctxusb resolves to $EXPECTED_VERSION" else fail "T09 ctxusb does not resolve to $EXPECTED_VERSION" fi else fail "T09 sandboxed sync_debian raised: $(printf '%s' "$out" | tr '\n' ' ')" fi if [ -e "$SANDBOX_DIR/etc-redirect/local-citrix-repo.list" ]; then pass "T09 sync_debian writes the apt source file (redirected to the sandbox)" else fail "T09 sync_debian did not write the apt source file" fi # --------------------------------------------------------------------------- # T10: trusted=yes still verifies the index (negative control) # --------------------------------------------------------------------------- # This is the control for T06/T07: it proves apt would actually fail on a # corrupt repo, so a PASS above is meaningful rather than vacuous. head2 "T10 corrupt index is rejected even with trusted=yes" mkdir -p "$TAMPER_DIR" cp "$REPO_DIR"/*.deb "$TAMPER_DIR"/ build_repo "$TAMPER_DIR" >/dev/null 2>&1 printf 'deb [trusted=yes] file:%s ./\n' "$TAMPER_DIR" > "$LIST_FILE" purge_apt_lists_for "$TAMPER_DIR" apt-get update -qq >/dev/null 2>&1 # Baseline: the package is visible from the untampered repo. base=$(apt-cache policy icaclient 2>/dev/null | grep -c "$EXPECTED_VERSION" || true) if [ "$base" -ge 1 ]; then pass "T10 baseline: icaclient visible before tampering" else fail "T10 baseline: icaclient not visible even before tampering" fi # Now corrupt Packages after Release recorded its hash. printf '\nPackage: evilpkg\nVersion: 6.6.6\nArchitecture: amd64\nFilename: ./evilpkg.deb\nSize: 1\n' \ >> "$TAMPER_DIR/Packages" purge_apt_lists_for "$TAMPER_DIR" tamper_out=$(apt-get update 2>&1) tamper_rc=$? if [ "$tamper_rc" -ne 0 ]; then pass "T10 apt-get update FAILS on a hash mismatch (exit $tamper_rc)" else fail "T10 apt-get update accepted a corrupted Packages file (exit 0)" fi if printf '%s\n' "$tamper_out" | grep -qi 'hash sum mismatch'; then pass "T10 failure is reported as a Hash Sum mismatch" else fail "T10 no Hash Sum mismatch reported" printf '%s\n' "$tamper_out" | grep -E '^(E:|W:|Err:)' | head -5 | sed 's/^/ /' fi if [ "$(apt-cache policy evilpkg 2>/dev/null | grep -c '6.6.6' || true)" -eq 0 ]; then pass "T10 the injected package is not available to apt" else fail "T10 the injected package became available - the index was trusted blindly" fi # Restore the good source for the remaining tests. printf 'deb [trusted=yes] file:%s ./\n' "$REPO_DIR" > "$LIST_FILE" purge_apt_lists_for "$REPO_DIR" apt-get update -qq >/dev/null 2>&1 # --------------------------------------------------------------------------- # T11: the production source file matches what the harness verified # --------------------------------------------------------------------------- head2 "T11 production sources.list shape" if [ -f "$PROD_SOURCE_FILE" ]; then active=$(grep -E '^[^#]*deb ' "$PROD_SOURCE_FILE" | head -1) if printf '%s' "$active" | grep -q 'trusted=yes'; then pass "T11 production source uses trusted=yes" else fail "T11 production source does not use trusted=yes: $active" fi if printf '%s' "$active" | grep -q 'file:/var/local/citrix-repo \./$'; then pass "T11 production source is the flat form (file:/var/local/citrix-repo ./)" else fail "T11 production source is not the flat form: $active" fi # The harness proved the same shape works, only with a different path. if printf '%s' "$active" | sed 's|/var/local/citrix-repo|REPO|' \ | grep -qx 'deb \[trusted=yes\] file:REPO ./'; then pass "T11 production source has the same shape the harness verified" else fail "T11 production source shape differs from what the harness tested" fi else skip "T11 production source file $PROD_SOURCE_FILE does not exist (owned by another change)" fi # --------------------------------------------------------------------------- # T12: GPG signing path # --------------------------------------------------------------------------- # Production deliberately does not sign (trusted=yes). This test exists to # check the decision, not to gate the port. It needs a signing tool; a stock # trixie ships only the sqv verifier, so without gpg or sq this SKIPs loudly. head2 "T12 GPG signed-by path (design check)" SIGNER="" if command -v gpg >/dev/null 2>&1; then SIGNER="gpg" fi if [ -z "$SIGNER" ]; then skip "T12 no gpg on this machine - signing untested here" if command -v sq >/dev/null 2>&1; then info "sq is present but this test is written against gpg; not attempted" fi info "would have checked: throwaway key -> Release.gpg -> apt with signed-by= ->" info "positive case succeeds, wrong-key case fails, and whether either is" info "more fragile than trusted=yes. Measured out-of-band; see README.md." else GNUPGHOME_T="$TMP_DIR/gnupg" mkdir -p "$GNUPGHOME_T"; chmod 700 "$GNUPGHOME_T" cat > "$TMP_DIR/keyparams" <<'KEYEOF' %echo generating test key Key-Type: RSA Key-Length: 2048 Name-Real: VDI Test Key Name-Email: vdi-test@example.invalid Expire-Date: 1 %no-protection %commit KEYEOF if gpg --batch --homedir "$GNUPGHOME_T" --gen-key "$TMP_DIR/keyparams" >/dev/null 2>&1; then gpg --batch --homedir "$GNUPGHOME_T" --armor --export > "$TMP_DIR/signer.asc" 2>/dev/null gpg --batch --homedir "$GNUPGHOME_T" --armor --detach-sign \ --output "$REPO_DIR/Release.gpg" "$REPO_DIR/Release" >/dev/null 2>&1 mkdir -p "$KEYRING_DIR" cp "$TMP_DIR/signer.asc" "$KEYRING_DIR/zz-vdi-test-signer.asc" chmod 644 "$KEYRING_DIR/zz-vdi-test-signer.asc" printf 'deb [signed-by=%s/zz-vdi-test-signer.asc] file:%s ./\n' \ "$KEYRING_DIR" "$REPO_DIR" > "$LIST_FILE" purge_apt_lists_for "$REPO_DIR" if apt-get update >/dev/null 2>&1; then pass "T12 signed-by with the correct key verifies" else fail "T12 signed-by with the correct key failed" fi # Control: sign with a key apt does not trust. rm -f "$KEYRING_DIR/zz-vdi-test-signer.asc" printf 'deb [signed-by=%s/zz-vdi-test-absent.asc] file:%s ./\n' \ "$KEYRING_DIR" "$REPO_DIR" > "$LIST_FILE" purge_apt_lists_for "$REPO_DIR" if apt-get update >/dev/null 2>&1; then fail "T12 apt accepted the repo without the signing key (signing is ineffective)" else pass "T12 apt rejects the repo when the signing key is absent" fi printf 'deb [trusted=yes] file:%s ./\n' "$REPO_DIR" > "$LIST_FILE" purge_apt_lists_for "$REPO_DIR" apt-get update -qq >/dev/null 2>&1 else skip "T12 throwaway key generation failed (gpg entropy/timeout); signing untested here" fi fi # --------------------------------------------------------------------------- # T13: Fedora regression # --------------------------------------------------------------------------- head2 "T13 Fedora path unregressed" if ! command -v git >/dev/null 2>&1; then skip "T13 git is not installed - cannot compare against main" info "would have checked: ks.cfg absent from main (vacuous), tracked Fedora" info "files identical to main modulo line endings, parent ks.cfg hash." info "Install git, or run the checks from a machine that has it." else GIT="git -C $REPO_ROOT -c safe.directory=*" # The spec'd check. Reported honestly: ks.cfg is not in the repo at all, so # this diff exits 0 without comparing anything. ks_diff=$($GIT diff main -- ks.cfg 2>&1) ks_rc=$? if [ "$ks_rc" -eq 0 ] && [ -z "$ks_diff" ]; then if $GIT cat-file -e main:ks.cfg >/dev/null 2>&1; then pass "T13 git diff main -- ks.cfg is empty and the path exists (real check)" else skip "T13 'git diff main -- ks.cfg' is empty but VACUOUS: ks.cfg is not in main" info "the spec'd assertion cannot fail; ks.cfg lives outside the repo" fi else fail "T13 git diff main -- ks.cfg is not empty (ks.cfg changed or appeared)" printf '%s\n' "$ks_diff" | head -10 | sed 's/^/ /' fi # The meaningful check: the tracked Fedora-side files must be unchanged. # Compared modulo CRLF, because this repo is checked out on Windows and the # blobs in git are LF - a raw diff reports every line as changed. for f in configure_kde.py local-citrix-repo.repo RPM-GPG-KEY-citrix-local; do if $GIT show "main:$f" > "$TMP_DIR/main_blob" 2>/dev/null; then if tr -d '\r' < "$REPO_ROOT/$f" | cmp -s - "$TMP_DIR/main_blob"; then pass "T13 $f is identical to main (ignoring line endings)" else fail "T13 $f differs from main beyond line endings" fi else fail "T13 could not read main:$f" fi done # update_local_repo.py is expected to differ: the Debian path lives inside # it behind a family dispatch. Assert the Fedora behaviour instead of the # file bytes - the .rpm asset names and the exact command sequence. if out=$(python3 - "$REPO_ROOT" <<'PYEOF' 2>&1 import ast, subprocess, sys, os repo = sys.argv[1] def load(text): return ast.parse(text) main_src = subprocess.run(["git", "-C", repo, "show", "main:update_local_repo.py"], capture_output=True, text=True) if main_src.returncode != 0: print("CANNOT-READ-MAIN") raise SystemExit(1) new_src = open(os.path.join(repo, "update_local_repo.py")).read() main = load(main_src.stdout) new = load(new_src) def system_cmds(tree, scope=None): """Return the os.system() command strings, in source order. Both plain strings and f-strings are collected. The Debian port rewrote "createrepo_c /var/local/citrix-repo" as f"createrepo_c {LOCAL_REPO_DIR}", and an extractor that only accepted ast.Constant would silently drop those commands and then report the resulting short list as a regression. That is a false negative, not evidence. """ body = tree.body if scope: body = [] for n in tree.body: if isinstance(n, ast.FunctionDef) and n.name == scope: body = n.body out = [] for node in ast.walk(ast.Module(body=body, type_ignores=[])): if not isinstance(node, ast.Call): continue f = node.func if not (isinstance(f, ast.Attribute) and f.attr == "system"): continue if not node.args: continue arg = node.args[0] if isinstance(arg, ast.Constant) and isinstance(arg.value, str): out.append(arg.value) elif isinstance(arg, ast.JoinedStr): parts = [] for v in arg.values: if isinstance(v, ast.Constant): parts.append(str(v.value)) elif isinstance(v, ast.FormattedValue): inner = v.value if isinstance(inner, ast.Name): parts.append("{VAR:%s}" % inner.id) else: parts.append("{EXPR}") out.append("".join(parts)) return out main_cmds = system_cmds(main) new_cmds = system_cmds(new, "sync_fedora") # Normalise BOTH sides: main hard-codes the path, the branch uses a constant. def norm(cmd): return (cmd.replace("/var/local/citrix-repo", "") .replace("{VAR:LOCAL_REPO_DIR}", "")) normed_main = [norm(c) for c in main_cmds] normed_new = [norm(c) for c in new_cmds] print("MAIN-CMDS:", normed_main) print("FEDORA-CMDS:", normed_new) print("SAME-SEQUENCE:", normed_new == normed_main) if normed_new != normed_main: print("MISSING-FROM-FEDORA:", [c for c in normed_main if c not in normed_new]) print("EXTRA-IN-FEDORA:", [c for c in normed_new if c not in normed_main]) # The Fedora asset names must still be matched exactly. names = set() for node in ast.walk(new): if isinstance(node, ast.Constant) and isinstance(node.value, str): if node.value.endswith(".rpm"): names.add(node.value) required = {"ctxusb.rpm", "ICAClient.rpm"} print("RPM-NAMES-PRESENT:", required.issubset(names)) PYEOF ); then printf '%s\n' "$out" | sed 's/^/ /' if printf '%s\n' "$out" | grep -q 'SAME-SEQUENCE: True'; then pass "T13 sync_fedora issues the same commands in the same order as main" else fail "T13 sync_fedora command sequence differs from main" fi if printf '%s\n' "$out" | grep -q 'RPM-NAMES-PRESENT: True'; then pass "T13 Fedora .rpm asset names still matched exactly" else fail "T13 Fedora .rpm asset names changed" fi else fail "T13 could not compare the Fedora code path: $(printf '%s' "$out" | tr '\n' ' ')" fi # ks.cfg lives outside the repo; assert the file the user actually has. OUTER_KS="$(dirname "$REPO_ROOT")/ks.cfg" if [ -f "$OUTER_KS" ]; then if $GIT cat-file -e main:ks.cfg >/dev/null 2>&1; then if $GIT show main:ks.cfg | tr -d '\r' | cmp -s - <(tr -d '\r' < "$OUTER_KS"); then pass "T13 out-of-tree ks.cfg matches main:ks.cfg" else fail "T13 out-of-tree ks.cfg differs from main:ks.cfg" fi else info "T13 out-of-tree ks.cfg sha256: $(sha256sum "$OUTER_KS" | cut -d' ' -f1)" info "no main:ks.cfg to compare against; the file was never committed" fi else skip "T13 no ks.cfg found at $OUTER_KS" fi # Record what the branch actually changes, so a future reader can see the # scope rather than trusting a summary. info "files changed vs main (ignoring line endings):" $GIT diff --ignore-cr-at-eol main --stat 2>/dev/null | sed 's/^/ /' fi # --------------------------------------------------------------------------- # T14: shell lint # --------------------------------------------------------------------------- head2 "T14 bash -n on shell scripts added by the port" found_any=0 while IFS= read -r script; do # This harness lints itself below; do not lint it twice. [ "$script" = "$SCRIPT_DIR/run-tests.sh" ] && continue found_any=1 if bash -n "$script" 2>"$TMP_DIR/basherr"; then pass "T14 bash -n $(printf '%s' "$script" | sed "s|$REPO_ROOT/||")" else fail "T14 bash -n failed for $script: $(cat "$TMP_DIR/basherr" | tr '\n' ' ')" fi done < <(find "$REPO_ROOT" -name '*.sh' -type f 2>/dev/null | grep -v '/\.git/' | sort) if [ "$found_any" -eq 0 ]; then skip "T14 the port adds no other shell scripts (only this harness exists)" info "when the port adds scripts, this test lints them automatically" fi # Always lint this harness, so the check is not vacuous while the port has no # scripts of its own. if bash -n "$SCRIPT_DIR/run-tests.sh" 2>"$TMP_DIR/basherr"; then pass "T14 bash -n debian/test/run-tests.sh" else fail "T14 bash -n failed for run-tests.sh: $(cat "$TMP_DIR/basherr" | tr '\n' ' ')" fi # --------------------------------------------------------------------------- # T16: polkit rule installed and correct # --------------------------------------------------------------------------- # These tests MUTATE the machine: they install a polkit rule and systemd units. # Everything is backed up first and restored at teardown, and T15 verifies it. head2 "T16 polkit rule for passwordless updates" POLKIT_OK=0 if ! command -v pkcheck >/dev/null 2>&1; then skip "T16 pkcheck not installed (no polkit) - cannot test authorisation" elif [ ! -d /usr/share/polkit-1 ] && [ ! -d /etc/polkit-1 ]; then skip "T16 polkit is not installed on this machine" else POLKIT_OK=1 backup_path "$POLKIT_RULE_PATH" # Start from a known-clean slate: if the rule is already installed we still # want to prove install_debian_update_policy() produces it. rm -f "$POLKIT_RULE_PATH" # Drive the real function, not a copy of its text. if out=$(cd "$REPO_ROOT" && python3 - "$REPO_ROOT" <<'PYEOF' 2>&1 import sys, os sys.path.insert(0, sys.argv[1]) os.chdir(sys.argv[1]) import update_local_repo as u u.install_debian_update_policy() print("CALLED") PYEOF ); then if printf '%s' "$out" | grep -q 'CALLED'; then pass "T16 install_debian_update_policy() ran" else fail "T16 install_debian_update_policy() did not complete: $(printf '%s' "$out" | tail -3 | tr '\n' ' ')" fi else fail "T16 install_debian_update_policy() raised: $(printf '%s' "$out" | tail -3 | tr '\n' ' ')" fi if [ -f "$POLKIT_RULE_PATH" ]; then pass "T16 rule file created at $POLKIT_RULE_PATH" else fail "T16 rule file was not created" fi rule_mode=$(stat -c '%a' "$POLKIT_RULE_PATH" 2>/dev/null || echo missing) if [ "$rule_mode" = "644" ]; then pass "T16 rule mode is 644" else fail "T16 rule mode is '$rule_mode', expected 644" fi for action in system-sources-refresh system-update; do if grep -q "org.freedesktop.packagekit.$action" "$POLKIT_RULE_PATH" 2>/dev/null; then pass "T16 rule covers org.freedesktop.packagekit.$action" else fail "T16 rule does not mention $action" fi done # The rule must not over-grant. package-remove is the one that matters: # a user who can remove packages without a password can break the machine. for action in package-remove package-reinstall package-install-untrusted; do if grep -q "org.freedesktop.packagekit.$action" "$POLKIT_RULE_PATH" 2>/dev/null; then fail "T16 rule over-grants: mentions $action" else pass "T16 rule does not grant $action" fi done # Structural check: the JS must be balanced. `node` is not installed, so # this is a counting check, not a parse - it catches truncation and the # common copy/paste damage, not every syntax error. if python3 - "$POLKIT_RULE_PATH" <<'PYEOF' 2>&1 import sys src = open(sys.argv[1], encoding="utf-8").read() # Strip // comments and string literals so braces inside them do not count. out, i, n = [], 0, len(src) while i < n: if src.startswith("//", i): while i < n and src[i] != "\n": i += 1 elif src[i] in "\"'": q = src[i]; i += 1 while i < n and src[i] != q: i += 2 if src[i] == "\\" else 1 i += 1 else: out.append(src[i]); i += 1 code = "".join(out) pairs = {"}": "{", "]": "[", ")": "("} stack = [] for ch in code: if ch in "{[(": stack.append(ch) elif ch in pairs: if not stack or stack.pop() != pairs[ch]: print("UNBALANCED at %r" % ch); raise SystemExit(1) print("BALANCED" if not stack else "UNCLOSED: %r" % stack) raise SystemExit(0 if not stack else 1) PYEOF then pass "T16 rule has balanced braces and parens" else fail "T16 rule is structurally unbalanced" fi if grep -q 'polkit.addRule' "$POLKIT_RULE_PATH" 2>/dev/null; then pass "T16 rule registers via polkit.addRule" else fail "T16 rule does not call polkit.addRule - it would have no effect" fi # REGRESSION GUARD. An earlier version of the rule included # `subject.local == true`, intending to restrict it to a seat physically in # front of the machine. It never matches: pkcheck returns 2 with the clause # and 0 without it, for the same sudo-group user. If it comes back, the # passwordless update silently stops working while every other assertion in # this test still passes - which is exactly why it is asserted here. if grep -q 'subject\.local' "$POLKIT_RULE_PATH" 2>/dev/null; then fail "T16 rule contains subject.local, which never matches (regression)" else pass "T16 rule does not contain the non-matching subject.local clause" fi # Idempotency: a second call must not rewrite the file. first_hash=$(sha256sum "$POLKIT_RULE_PATH" 2>/dev/null | cut -d' ' -f1) first_mtime=$(stat -c '%Y' "$POLKIT_RULE_PATH" 2>/dev/null) sleep 1 ( cd "$REPO_ROOT" && python3 -c " import sys; sys.path.insert(0, '$REPO_ROOT'); import update_local_repo as u u.install_debian_update_policy()" ) >/dev/null 2>&1 second_hash=$(sha256sum "$POLKIT_RULE_PATH" 2>/dev/null | cut -d' ' -f1) if [ "$first_hash" = "$second_hash" ] && [ -n "$first_hash" ]; then pass "T16 rule is byte-identical after a second call (idempotent)" else fail "T16 rule changed on a second call" fi fi # --------------------------------------------------------------------------- # T17: a sudo-group user is authorised WITHOUT a password # --------------------------------------------------------------------------- # This is the actual requirement. Testing the file's contents proves nothing # about whether polkit acts on it, so this asks polkit itself, about a real # process owned by a real sudo-group user. The control (rule removed -> rc=2) # is what stops the test from passing on a machine where pkcheck is simply # permissive. head2 "T17 sudo-group user authorised without a password" POLKIT_ACTION="org.freedesktop.packagekit.system-sources-refresh" restart_polkit() { if command -v systemctl >/dev/null 2>&1; then systemctl restart polkit >/dev/null 2>&1 || systemctl restart polkitd >/dev/null 2>&1 # polkitd caches rules; give it a moment to re-read them. sleep 1 fi } pkcheck_for_user() { # Run pkcheck as root against a process owned by $1. Echoes the rc. local user="$1" pid rc pkill -u "$user" -f 'vdi-test-sleeper' >/dev/null 2>&1 setsid runuser -u "$user" -- bash -c 'exec -a vdi-test-sleeper sleep 120' >/dev/null 2>&1 & sleep 1 pid=$(pgrep -u "$user" -f 'vdi-test-sleeper' | head -1) if [ -z "$pid" ]; then echo "NOPROC" return fi pkcheck --action-id "$POLKIT_ACTION" --process "$pid" >/dev/null 2>&1 rc=$? pkill -u "$user" -f 'vdi-test-sleeper' >/dev/null 2>&1 echo "$rc" } TEST_USER="" if [ "$POLKIT_OK" != "1" ]; then skip "T17 skipped with T16: no polkit on this machine" elif ! systemctl is-system-running >/dev/null 2>&1 && ! systemctl is-active polkit >/dev/null 2>&1; then skip "T17 polkit is not running and cannot be started (no systemd?) - authorisation untestable" else # Find a real, non-root user in the sudo group. A machine with none cannot # answer the question the test is asking. # NOTE: `getent group sudo` is "name:passwd:gid:members" - FOUR fields. # Reading five would put the member list in the wrong variable and find # nobody, which looks exactly like "no sudo user exists". while IFS=: read -r _grp _pw _gid members; do for member in $(printf '%s' "${members:-}" | tr ',' ' '); do [ "$member" = "root" ] && continue if id "$member" >/dev/null 2>&1; then TEST_USER="$member" break 2 fi done done < <(getent group sudo 2>/dev/null) if [ -z "$TEST_USER" ]; then skip "T17 no non-root user in group 'sudo' - cannot test the authorisation" info "would have checked: pkcheck --process -> rc=0" info "with the rule installed, and rc=2 with the rule removed (control)." else info "test user: $TEST_USER (in group sudo)" # Make sure the rule is installed before the positive case. if [ ! -f "$POLKIT_RULE_PATH" ]; then ( cd "$REPO_ROOT" && python3 -c " import sys; sys.path.insert(0, '$REPO_ROOT'); import update_local_repo as u u.install_debian_update_policy()" ) >/dev/null 2>&1 fi restart_polkit with_rule=$(pkcheck_for_user "$TEST_USER") case "$with_rule" in 0) pass "T17 $TEST_USER is authorised without a password (pkcheck rc=0)" ;; NOPROC) fail "T17 could not start a process as $TEST_USER" ;; *) fail "T17 $TEST_USER still requires authentication (pkcheck rc=$with_rule, expected 0)" ;; esac # THE CONTROL. Without this the positive case proves nothing: a polkit # that answers YES to everything would also produce rc=0. mv "$POLKIT_RULE_PATH" "$TMP_DIR/rule.parked" 2>/dev/null restart_polkit without_rule=$(pkcheck_for_user "$TEST_USER") mv "$TMP_DIR/rule.parked" "$POLKIT_RULE_PATH" 2>/dev/null restart_polkit case "$without_rule" in 2) pass "T17 control: without the rule, authentication IS required (rc=2)" ;; 0) fail "T17 control failed: authorised even without the rule - the test proves nothing" ;; NOPROC) fail "T17 control could not start a process as $TEST_USER" ;; *) fail "T17 control returned unexpected rc=$without_rule (expected 2)" ;; esac # The action the rule must NOT grant. denied=$(pkcheck --action-id org.freedesktop.packagekit.package-remove \ --process "$(pgrep -u "$TEST_USER" -f 'vdi-test-sleeper' | head -1 || echo 0)" >/dev/null 2>&1; echo $?) if [ "$denied" = "2" ] || [ "$denied" = "3" ]; then pass "T17 package-remove still requires authentication (not over-granted)" elif [ "$denied" = "0" ]; then fail "T17 package-remove is authorised without a password - the rule over-grants" else info "T17 package-remove pkcheck rc=$denied (no process to check against)" fi fi fi # --------------------------------------------------------------------------- # T18: offline-update script and systemd units # --------------------------------------------------------------------------- head2 "T18 offline-update script and units" if [ ! -f "$OFFLINE_SCRIPT" ]; then skip "T18 $OFFLINE_SCRIPT is not installed (update_local_repo.py has not run here)" info "would have checked: mode 755, bash -n, systemd-analyze verify on both" info "units, timer enabled, stamp written, throttle on a second run, and that" info "any /system-update symlink points at something that exists." else mode=$(stat -c '%a' "$OFFLINE_SCRIPT" 2>/dev/null) if [ "$mode" = "755" ]; then pass "T18 $OFFLINE_SCRIPT is mode 755" else fail "T18 $OFFLINE_SCRIPT is mode '$mode', expected 755" fi if bash -n "$OFFLINE_SCRIPT" 2>"$TMP_DIR/offerr"; then pass "T18 offline-update script passes bash -n" else fail "T18 offline-update script fails bash -n: $(cat "$TMP_DIR/offerr" | tr '\n' ' ')" fi if command -v systemd-analyze >/dev/null 2>&1; then for unit in "$OFFLINE_SERVICE" "$OFFLINE_TIMER"; do if [ ! -f "$unit" ]; then fail "T18 $unit is missing" continue fi if verr=$(systemd-analyze verify "$unit" 2>&1) && [ -z "$verr" ]; then pass "T18 systemd-analyze verify is clean for $(basename "$unit")" else fail "T18 systemd-analyze verify complained about $(basename "$unit"): $(printf '%s' "$verr" | head -3 | tr '\n' ' ')" fi done # The Documentation=man:pkcon(1) trap: verify runs the man binary. if grep -q 'Documentation=man:' "$OFFLINE_SERVICE" "$OFFLINE_TIMER" 2>/dev/null; then fail "T18 a unit has Documentation=man: which systemd-analyze verify tries to execute" else pass "T18 no Documentation=man: lines (they break verify)" fi # Enabling is done by `systemctl enable vdi-offline-update.timer` inside # install_debian_update_policy(). That only persists when systemd is the # running init - in a d-i chroot or a container it silently does nothing. # So: assert it is enabled AFTER driving the installer function, and skip # the assertion outright when systemd is not PID 1 rather than failing on # an environment that cannot express the answer. if [ "$(cat /proc/1/comm 2>/dev/null)" != "systemd" ]; then skip "T18 timer-enabled assertion skipped: systemd is not PID 1 here" info "would have checked: systemctl is-enabled vdi-offline-update.timer" info "after install_debian_update_policy() ran." else ( cd "$REPO_ROOT" && python3 -c " import sys; sys.path.insert(0, '$REPO_ROOT'); import update_local_repo as u u.install_debian_update_policy()" ) >/dev/null 2>&1 if systemctl is-enabled vdi-offline-update.timer >/dev/null 2>&1; then pass "T18 vdi-offline-update.timer is enabled after install_debian_update_policy()" else fail "T18 vdi-offline-update.timer is not enabled after install_debian_update_policy()" fi fi else skip "T18 systemd-analyze not available; unit files not verified" fi # Behavioural: the stamp, the throttle, and the /system-update safety rule. backup_path "$OFFLINE_STAMP" backup_path "$SYSTEM_UPDATE_LINK" rm -f "$OFFLINE_STAMP" run1=$(timeout 300 "$OFFLINE_SCRIPT" 2>&1); rc1=$? if [ -s "$OFFLINE_STAMP" ]; then pass "T18 running the script writes the throttle stamp" else fail "T18 running the script did not write $OFFLINE_STAMP" fi # Exit 5 from pkcon means "no packages to update" and must not be reported # as a download failure. This box is up to date, so that is the case here. if printf '%s' "$run1" | grep -qi 'download failed'; then fail "T18 script reported a download failure on an up-to-date box (pkcon exit 5 misclassified)" printf '%s' "$run1" | grep -i 'download failed' | head -2 | sed 's/^/ /' else pass "T18 no spurious 'download failed' on an up-to-date box" fi if printf '%s' "$run1" | grep -qi 'no updates available'; then pass "T18 pkcon exit 5 is reported as 'no updates available'" else info "T18 (this box may have had real updates; exit-5 path not exercised)" fi # THE DANGEROUS ONE: a dangling /system-update fails the next boot. if [ -L "$SYSTEM_UPDATE_LINK" ]; then target=$(readlink -f "$SYSTEM_UPDATE_LINK" 2>/dev/null) if [ -n "$target" ] && [ -e "$target" ]; then pass "T18 /system-update symlink target exists ($target)" else fail "T18 /system-update is DANGLING (-> '$target') - the next boot would fail" fi elif [ -e "$SYSTEM_UPDATE_LINK" ]; then info "T18 /system-update exists but is not a symlink - left alone" else pass "T18 no /system-update armed (nothing was prepared)" fi # Throttle: a second run immediately after must not re-run pkcon. run2=$(timeout 60 "$OFFLINE_SCRIPT" 2>&1) if printf '%s' "$run2" | grep -qi 'skipping'; then pass "T18 a second run immediately is throttled ('skipping')" else fail "T18 a second run was not throttled: $(printf '%s' "$run2" | head -2 | tr '\n' ' ')" fi # Stamp of 0 must defeat the throttle, proving the throttle is time-based # and not a permanent latch. printf '0\n' > "$OFFLINE_STAMP" run3=$(timeout 300 "$OFFLINE_SCRIPT" 2>&1) if printf '%s' "$run3" | grep -qi 'skipping'; then fail "T18 a stamp of 0 did not defeat the throttle" else pass "T18 a stamp of 0 makes the script run again" fi # Re-check the symlink after the forced run, since this is the run that may # have armed it. if [ -L "$SYSTEM_UPDATE_LINK" ]; then target=$(readlink -f "$SYSTEM_UPDATE_LINK" 2>/dev/null) if [ -n "$target" ] && [ -e "$target" ]; then pass "T18 after the forced run, /system-update target still exists" else fail "T18 after the forced run, /system-update is DANGLING" fi fi fi # --------------------------------------------------------------------------- # T19: the preseed still generates a working post-install script # --------------------------------------------------------------------------- # Runs the preseed's own printf in a sandbox to regenerate /root/vdi-post.sh, # then checks the result. It never executes the script: it writes /etc/hostname, # /etc/crontab and systemd units by absolute path and would reconfigure the # machine running the test. head2 "T19 preseed generates a working post-install script" PRESEED="$REPO_ROOT/debian/preseed.cfg" if [ ! -f "$PRESEED" ]; then skip "T19 no debian/preseed.cfg in this repo (owned by another change)" else if out=$(python3 - "$PRESEED" "$TMP_DIR" <<'PYEOF' 2>&1 import os, re, subprocess, sys preseed, work = sys.argv[1], sys.argv[2] lines = open(preseed, encoding="utf-8").read().splitlines() # The late_command is one logical line continued with trailing backslashes. start = None for i, ln in enumerate(lines): if ln.startswith("d-i preseed/late_command"): start = i break if start is None: print("NO-LATE-COMMAND") raise SystemExit(1) block, i = [], start while i < len(lines): block.append(lines[i]) if not lines[i].rstrip().endswith("\\"): break i += 1 cmd = "\n".join(block) # Anchor on the vdi-post.sh redirect. A non-greedy match that is allowed to # cross a ';' would also capture the firefox printf before it - which then # tries to write /target/etc/firefox and fails. Anchor from the previous # statement boundary instead. # The late_command is a chain of statements, and the payload it writes itself # contains ';' and '>' inside quoted arguments, so neither splitting on ';' nor # a bare backwards search is safe. Anchor on the two unambiguous markers: the # payload's own first argument ('#!/bin/bash') and the redirect target. The # earlier firefox printf is excluded by construction, because it does not start # with '#!/bin/bash'. marker = "> /target/root/vdi-post.sh" pos = cmd.find(marker) if pos < 0: print("NO-REDIRECT") raise SystemExit(1) anchor = 'printf "%s\\n" \'#!/bin/bash\'' start = cmd.find(anchor) if start < 0: print("NO-PRINTF-ANCHOR") raise SystemExit(1) if start > pos: print("ANCHOR-AFTER-REDIRECT") raise SystemExit(1) args = cmd[start + len('printf "%s\\n" '):pos].strip() if not args: print("EMPTY-ARGS") raise SystemExit(1) # Sanity: the captured argument list must contain the script's first line and # must not contain the firefox policy payload. if "#!/bin/bash" not in args: print("CAPTURED-WRONG-ARGUMENT") raise SystemExit(1) if "ManagedBookmarks" in args: print("CAPTURED-FIREFOX-BLOCK") raise SystemExit(1) # Run the printf exactly as the preseed does, but write into our sandbox. dest = os.path.join(work, "vdi-post.sh") script = 'printf "%s\\n" ' + args + ' > ' + dest proc = subprocess.run(["bash", "-c", script], capture_output=True, text=True) if proc.returncode != 0: print("PRINTF-FAILED: " + proc.stderr.strip()[:200]) raise SystemExit(1) if not os.path.exists(dest) or os.path.getsize(dest) == 0: print("EMPTY-OUTPUT") raise SystemExit(1) print("GENERATED " + dest) PYEOF ); then printf '%s\n' "$out" | sed 's/^/ /' GEN="$TMP_DIR/vdi-post.sh" pass "T19 preseed regenerates /root/vdi-post.sh" if bash -n "$GEN" 2>"$TMP_DIR/err"; then pass "T19 generated script passes bash -n" else fail "T19 generated script fails bash -n: $(cat "$TMP_DIR/err" | tr '\n' ' ')" fi # It must delegate, not duplicate, the pkcon sequence. Comments are # stripped first: the generated script explains the delegation in a # comment, and matching that would be a false positive. if grep -v '^[[:space:]]*#' "$GEN" | grep -qE 'pkcon[[:space:]]+(refresh|offline-trigger|update)'; then fail "T19 generated script still runs pkcon inline instead of delegating" grep -v '^[[:space:]]*#' "$GEN" | grep -nE 'pkcon' | head -3 | sed 's/^/ /' else pass "T19 generated script delegates to vdi-offline-update (no inline pkcon)" fi if grep -q '/usr/local/sbin/vdi-offline-update' "$GEN"; then pass "T19 generated script references /usr/local/sbin/vdi-offline-update" else fail "T19 generated script does not reference the offline-update script" fi if grep -qE 'systemctl enable cron' "$GEN"; then pass "T19 generated script enables cron" else fail "T19 generated script does not enable cron" fi if grep -qE 'systemctl enable vdi-offline-update\.timer' "$GEN"; then pass "T19 generated script enables vdi-offline-update.timer" else fail "T19 generated script does not enable vdi-offline-update.timer" fi else fail "T19 could not extract the post-install script from preseed.cfg: $(printf '%s' "$out" | tail -3 | tr '\n' ' ')" fi fi # --------------------------------------------------------------------------- # T15: the harness left nothing behind # --------------------------------------------------------------------------- # The residue half of this test must run AFTER the cleanup, not before it, or it # can never pass - and a permanently-red test trains people to ignore the # summary. So: check what can be checked now, then tear down, then verify the # teardown actually happened, then print the summary. head2 "T15 no collateral damage" if [ -d "$PROD_REPO_DIR" ]; then now=$(stat -c '%Y' "$PROD_REPO_DIR" 2>/dev/null || echo "") if [ "$now" = "$PROD_REPO_MTIME_BEFORE" ]; then pass "T15 $PROD_REPO_DIR was not modified" else fail "T15 $PROD_REPO_DIR changed during the run" fi else pass "T15 $PROD_REPO_DIR does not exist and was not created" fi if [ -d "$REPO_ROOT/__pycache__" ]; then fail "T15 __pycache__ was written into the repo" else pass "T15 the repo working tree was not dirtied by Python" fi # T16-T19 install a polkit rule and systemd units and arm /system-update. # Assert that none of that survives: restore each path to its pre-run state and # then check it took. This is what makes "self-cleaning" a claim rather than # an intention. for mutating_path in "$POLKIT_RULE_PATH" "$OFFLINE_STAMP" "$SYSTEM_UPDATE_LINK"; do restore_path "$mutating_path" done # The units and script are only removed if this run created them. for created_path in "$OFFLINE_SCRIPT" "$OFFLINE_SERVICE" "$OFFLINE_TIMER"; do restore_path "$created_path" done # systemd cached the units; make it re-read whatever is there now. if command -v systemctl >/dev/null 2>&1; then systemctl daemon-reload >/dev/null 2>&1 fi for mutating_path in "$POLKIT_RULE_PATH" "$OFFLINE_STAMP" "$SYSTEM_UPDATE_LINK" \ "$OFFLINE_SCRIPT" "$OFFLINE_SERVICE" "$OFFLINE_TIMER"; do name=$(printf '%s' "$mutating_path" | tr '/' '_') was=$(cat "$BACKUP_DIR/$name.state" 2>/dev/null || echo absent) if [ "$was" = "absent" ]; then if [ -e "$mutating_path" ] || [ -L "$mutating_path" ]; then fail "T15 $mutating_path was created by this run and not removed" else pass "T15 $mutating_path restored to its pre-run state (absent)" fi else if [ -e "$mutating_path" ] || [ -L "$mutating_path" ]; then pass "T15 $mutating_path restored (existed before the run)" else fail "T15 $mutating_path existed before the run and was not restored" fi fi done # A dangling /system-update is the dangerous residue: it fails the next boot. if [ -L "$SYSTEM_UPDATE_LINK" ]; then target=$(readlink -f "$SYSTEM_UPDATE_LINK" 2>/dev/null) if [ -n "$target" ] && [ -e "$target" ]; then pass "T15 any /system-update left behind points at an existing target" else fail "T15 /system-update is left DANGLING - the next boot would fail" fi fi # Did anything get installed? Every apt-get install this harness issues is # --simulate, so the set of installed packages must be unchanged. if command -v dpkg-query >/dev/null 2>&1; then installed_now=$(dpkg-query -W -f='${Package}\n' 2>/dev/null | wc -l) if [ -n "${INSTALLED_BEFORE:-}" ]; then if [ "$installed_now" = "$INSTALLED_BEFORE" ]; then pass "T15 installed package count unchanged ($installed_now)" else fail "T15 installed package count changed: $INSTALLED_BEFORE -> $installed_now" fi fi fi # ---- teardown, then verify the teardown ---- printf '\n removing temporary source, keyring, caches and %s\n' "$TMP_DIR" rm -f "$LIST_FILE" 2>/dev/null rm -f "$KEYRING_DIR"/zz-vdi-test-* 2>/dev/null rmdir "$KEYRING_DIR" 2>/dev/null purge_apt_lists_for "$REPO_DIR" purge_apt_lists_for "$TAMPER_DIR" purge_apt_lists_for "$SANDBOX_DIR" purge_all_harness_lists rm -rf "$TMP_DIR" 2>/dev/null apt-get update -qq >/dev/null 2>&1 if [ -f "$LIST_FILE" ]; then fail "T15 the temporary apt source $LIST_FILE survived teardown" else pass "T15 temporary apt source removed from /etc/apt/sources.list.d" fi leftover=$(ls /var/lib/apt/lists/*"$(list_fragment "$REPO_DIR")"* 2>/dev/null | wc -l) if [ "$leftover" -eq 0 ]; then pass "T15 no cached apt indexes left behind" else fail "T15 $leftover cached apt index file(s) left behind" fi if [ -e "$TMP_DIR" ]; then fail "T15 temporary directory $TMP_DIR survived teardown" else pass "T15 temporary directory removed" fi # From here on the EXIT trap has nothing left to do; make sure it cannot undo # the summary by re-running apt-get update and removing things again. CLEANED=1 # --------------------------------------------------------------------------- # Summary # --------------------------------------------------------------------------- printf '\n%s\n' "----------------------------------------------------------------" printf 'SUMMARY: %d passed, %d failed, %d skipped\n' "$PASSED" "$FAILED" "$SKIPPED" if [ "$FAILED" -ne 0 ]; then printf 'FAILED tests:%s\n' "$FAILED_NAMES" printf 'RESULT: FAIL\n' exit 1 fi printf 'RESULT: PASS\n' if [ "$SKIPPED" -ne 0 ]; then printf '(%d test(s) skipped - read the SKIP lines above; a skip is not a pass)\n' "$SKIPPED" fi exit 0