diff --git a/docs/skills/ddi-installer.md b/docs/skills/ddi-installer.md index 7550e484..80b9403c 100644 --- a/docs/skills/ddi-installer.md +++ b/docs/skills/ddi-installer.md @@ -4,7 +4,7 @@ description: Use when building or debugging the Bluefin Server DDI live installe metadata: type: reference status: stable - last_updated: "2026-09-09" + last_updated: "2026-09-24" context7-sources: - /systemd/systemd - /apache/buildstream @@ -108,6 +108,28 @@ container runtime pod sandboxes. | `bluefin-server-root-a` | XFS | 4 GiB – 8 GiB | OS root filesystem (copied from installer data partition) | | `var` | XFS | ≥ 4 GiB | Writable persistent `/var`; grows to fill remaining disk | +## State Across Updates + +`systemd-sysupdate` replaces the root partition block-for-block in each A/B slot, +so everything under `/etc` is re-created from the new DDI on every update. Only +the `var` partition, the ESP, and the bootloader state survive. + +The root credential is the one piece of `/etc` an operator changes at runtime, +so the image keeps the authoritative root entry of `/etc/shadow` in +`/var/lib/bluefin-server/root-shadow`: + +- `bluefin-root-cred.service` restores the persisted entry into `/etc/shadow` + before `multi-user.target` — and therefore before `getty`, `sshd`, and the k0s + console — seeding the persisted copy from the image on the first boot after + install. +- `bluefin-root-cred-persist.path` copies `/etc/shadow` back out whenever it + changes, so a password rotated with `passwd` or `chage` is what the next slot + boots with. + +Removing the persisted copy and rebooting falls back to the credential baked +into the image. Removing that baked credential entirely is the operator-login +redesign in [`#80`](https://github.com/projectbluefin/server/issues/80). + ## Installer Boot Flow ```text diff --git a/elements/bluefin-server/os-root-cred.bst b/elements/bluefin-server/os-root-cred.bst new file mode 100644 index 00000000..790b0cbe --- /dev/null +++ b/elements/bluefin-server/os-root-cred.bst @@ -0,0 +1,42 @@ +kind: manual +description: | + Install the root credential persistence helper and enable its units. + + /etc/shadow lives inside the OS DDI, which systemd-sysupdate replaces in both + root slots on every update. A root password rotated on the running host would + otherwise roll back to the credential baked into the image as soon as the + other slot boots, so this image keeps the authoritative root entry in the + persistent /var partition and reconciles /etc/shadow with it on every boot. + + The units themselves are staged by bluefin-server/os-k0s-first-boot.bst, which + installs files/os/systemd/system into /usr/lib/systemd/system. Enablement is an + explicit multi-user.target.wants symlink created here: systemd presets are not + applied in this image, so a preset would not enable anything. + + bluefin-root-cred-persist.service is intentionally left unenabled — it is the + triggered half of bluefin-root-cred-persist.path, and starting it at boot + could persist the image's baked-in credential over the operator's. + +build-depends: + - base/base-stack.bst + +sources: + - kind: local + path: files/os/libexec + directory: libexec-src + +# Disable binary stripping; this element only installs a shell script and the +# runtime-minimal sandbox does not include the stripper toolchain. +variables: + strip-binaries: "" + +config: + install-commands: + - install -Dm755 libexec-src/bluefin-root-cred-sync + "%{install-root}%{prefix}/libexec/bluefin-root-cred-sync" + - | + set -euo pipefail + wants="%{install-root}%{prefix}/lib/systemd/system/multi-user.target.wants" + install -d -m 0755 "${wants}" + ln -sf ../bluefin-root-cred.service "${wants}/bluefin-root-cred.service" + ln -sf ../bluefin-root-cred-persist.path "${wants}/bluefin-root-cred-persist.path" \ No newline at end of file diff --git a/elements/bluefin-server/os-stack.bst b/elements/bluefin-server/os-stack.bst index 44f80576..bfcf42e8 100644 --- a/elements/bluefin-server/os-stack.bst +++ b/elements/bluefin-server/os-stack.bst @@ -38,6 +38,9 @@ depends: # A/B System Update Configurations - bluefin-server/os-sysupdate.bst + # Root credential persistence across A/B DDI replacements + - bluefin-server/os-root-cred.bst + # k0s component system update configuration - bluefin-server/os-k0s-sysupdate.bst diff --git a/files/os/libexec/bluefin-root-cred-sync b/files/os/libexec/bluefin-root-cred-sync new file mode 100755 index 00000000..1a5c14b0 --- /dev/null +++ b/files/os/libexec/bluefin-root-cred-sync @@ -0,0 +1,137 @@ +#!/bin/bash +# bluefin-root-cred-sync — keep the root credential outside the replaceable DDI. +# +# /etc/shadow ships inside the OS DDI, and systemd-sysupdate replaces that whole +# filesystem image in both root slots on every update. A root password rotated +# on the running host therefore rolls back to the credential baked into the +# image as soon as the other slot boots. This helper keeps the authoritative +# root entry in the persistent /var partition instead, and reconciles the image +# with it: +# +# boot restore the persisted root entry into /etc/shadow, seeding the +# persisted copy from the image on the first boot after install +# persist copy the current /etc/shadow root entry into the persisted copy +# +# bluefin-root-cred.service runs `boot` before every login path; +# bluefin-root-cred-persist.path runs `persist` whenever /etc/shadow changes. +# +# Only the root entry is kept, never the whole file: every other shadow entry is +# an image-managed system account that must track the image, not the host. +# +# Recovery: remove the persisted copy and reboot to fall back to the credential +# baked into the image (the documented console bring-up credential). +# +# Deliberately pure bash builtins plus coreutils. The DDI runtime is +# runtime-minimal: /bin/sh, sed, awk and grep are not guaranteed to exist, and +# this code runs before the login services it protects. +# +# Usage: bluefin-root-cred-sync {boot|persist} [shadow-file] [state-file] +# The two paths are overridable for tests only; the shipped units pass neither. + +set -euo pipefail +umask 077 + +PROG="${0##*/}" +MODE="${1:-}" +SHADOW="${2:-/etc/shadow}" +STATE="${3:-/var/lib/bluefin-server/root-shadow}" + +log() { printf '%s: %s\n' "$PROG" "$*" >&2; } +die() { log "$*"; exit 1; } + +# Print the entry for a user out of a colon-separated shadow database. +user_entry() { # $1 = file, $2 = user + local line + while IFS= read -r line || [ -n "$line" ]; do + if [ "${line%%:*}" = "$2" ]; then + printf '%s\n' "$line" + return 0 + fi + done < "$1" + return 1 +} + +# A shadow entry is name:password:lastchange:min:max:warn:inactive:expire:reserved. +# Refuse anything else: a truncated or half-written entry must never replace +# either copy of the credential. +shadow_entry_is_sane() { # $1 = entry + local entry="$1" rest="$1" fields=1 hash + while [ "${rest#*:}" != "$rest" ]; do + fields=$((fields + 1)) + rest="${rest#*:}" + done + [ "$fields" -eq 9 ] || return 1 + hash="${entry#*:}" + hash="${hash%%:*}" + [ -n "$hash" ] || return 1 + return 0 +} + +# Replace the entry for a user in a shadow database, or append it when absent. +# Writes next to the target and renames, so the database is never truncated, +# and re-asserts 0600 on the result. +set_user_entry() { # $1 = file, $2 = user, $3 = entry + local file="$1" user="$2" entry="$3" tmp line replaced=0 + tmp="$(mktemp "${file}.XXXXXX")" || + die "cannot create a temporary file next to ${file}" + while IFS= read -r line || [ -n "$line" ]; do + if [ "${line%%:*}" = "$user" ]; then + printf '%s\n' "$entry" >>"$tmp" + replaced=1 + else + printf '%s\n' "$line" >>"$tmp" + fi + done <"$file" + [ "$replaced" -eq 1 ] || printf '%s\n' "$entry" >>"$tmp" + chmod 0600 "$tmp" + mv -f "$tmp" "$file" +} + +# Copy the live root entry into the persistent store. +persist() { + local entry tmp dir + entry="$(user_entry "$SHADOW" root)" || + die "no root entry in ${SHADOW}; refusing to persist" + shadow_entry_is_sane "$entry" || + die "root entry in ${SHADOW} is malformed; refusing to persist" + case "$STATE" in + */*) dir="${STATE%/*}" ;; + *) dir="." ;; + esac + [ -d "$dir" ] || mkdir -p "$dir" || die "cannot create ${dir}" + tmp="$(mktemp "${STATE}.XXXXXX")" || + die "cannot create a temporary file next to ${STATE}" + printf '%s\n' "$entry" >"$tmp" + chmod 0600 "$tmp" + mv -f "$tmp" "$STATE" + log "persisted the root entry from ${SHADOW} in ${STATE}" +} + +# Make the persisted root entry authoritative for this boot. +boot() { + local entry current="" + if [ ! -e "$STATE" ]; then + log "no persisted root credential in ${STATE}; seeding it from ${SHADOW}" + persist + return 0 + fi + entry="$(user_entry "$STATE" root)" || + die "${STATE} holds no root entry; leaving ${SHADOW} untouched" + shadow_entry_is_sane "$entry" || + die "${STATE} holds a malformed root entry; leaving ${SHADOW} untouched" + current="$(user_entry "$SHADOW" root)" || current="" + if [ "$current" = "$entry" ]; then + log "root entry in ${SHADOW} already matches ${STATE}" + return 0 + fi + set_user_entry "$SHADOW" root "$entry" + log "restored the persisted root entry into ${SHADOW}" +} + +case "$MODE" in +boot) boot ;; +persist) persist ;; +*) + die "usage: ${PROG} {boot|persist} [shadow-file] [state-file]" + ;; +esac \ No newline at end of file diff --git a/files/os/systemd/system/bluefin-root-cred-persist.path b/files/os/systemd/system/bluefin-root-cred-persist.path new file mode 100644 index 00000000..b00ac108 --- /dev/null +++ b/files/os/systemd/system/bluefin-root-cred-persist.path @@ -0,0 +1,22 @@ +# Persist root credential changes made on the running host. +# +# Changing the root password (passwd, chage) rewrites /etc/shadow in the root +# slot the host is currently booted from, and systemd-sysupdate replaces that +# slot wholesale on the next update. Watching /etc/shadow keeps the persisted +# copy in the persistent /var partition in step with the host, so the slot that +# boots next gets the operator's credential instead of the image's. +# +# Enablement is the explicit multi-user.target.wants symlink created by +# elements/bluefin-server/os-root-cred.bst; systemd presets are not applied in +# this image. +[Unit] +Description=Persist root credential changes to the /var root credential store +# Arm the watch only once the boot-time restore has settled /etc/shadow. +After=bluefin-root-cred.service + +[Path] +PathChanged=/etc/shadow +Unit=bluefin-root-cred-persist.service + +[Install] +WantedBy=multi-user.target \ No newline at end of file diff --git a/files/os/systemd/system/bluefin-root-cred-persist.service b/files/os/systemd/system/bluefin-root-cred-persist.service new file mode 100644 index 00000000..67cbb0ff --- /dev/null +++ b/files/os/systemd/system/bluefin-root-cred-persist.service @@ -0,0 +1,16 @@ +# Copy the live root credential out of /etc/shadow into the persistent store. +# +# Triggered by bluefin-root-cred-persist.path whenever /etc/shadow changes. +# Deliberately not enabled at boot: bluefin-root-cred.service owns the boot-time +# direction, and running both concurrently could persist the image's baked-in +# credential over the operator's. +[Unit] +Description=Persist the /etc/shadow root credential into /var +RequiresMountsFor=/var/lib/bluefin-server +ConditionPathExists=/etc/shadow + +[Service] +Type=oneshot +StateDirectory=bluefin-server +StateDirectoryMode=0700 +ExecStart=/usr/libexec/bluefin-root-cred-sync persist \ No newline at end of file diff --git a/files/os/systemd/system/bluefin-root-cred.service b/files/os/systemd/system/bluefin-root-cred.service new file mode 100644 index 00000000..96304b9e --- /dev/null +++ b/files/os/systemd/system/bluefin-root-cred.service @@ -0,0 +1,31 @@ +# Restore the authoritative root credential into /etc/shadow. +# +# /etc/shadow ships inside the OS DDI, and systemd-sysupdate replaces that +# filesystem image in both root slots on every update. Without this unit a root +# password rotated on the running host would roll back to the credential baked +# into the image as soon as the other slot boots. bluefin-root-cred-sync keeps +# the authoritative root entry in the persistent /var partition and reconciles +# the image with it here, before any process can authenticate. +# +# Enablement is the explicit multi-user.target.wants symlink created by +# elements/bluefin-server/os-root-cred.bst: systemd presets are not applied in +# this image, so a preset would enable nothing. +[Unit] +Description=Restore the persisted root credential into /etc/shadow +Documentation=man:shadow(5) +# /var must be mounted, and every login path (getty, sshd, k0s console) hangs +# off multi-user.target. +RequiresMountsFor=/var/lib/bluefin-server +After=local-fs.target +Before=multi-user.target +ConditionPathExists=/etc/shadow + +[Service] +Type=oneshot +RemainAfterExit=yes +StateDirectory=bluefin-server +StateDirectoryMode=0700 +ExecStart=/usr/libexec/bluefin-root-cred-sync boot + +[Install] +WantedBy=multi-user.target \ No newline at end of file diff --git a/tests/unit/test_root_credential_persistence.py b/tests/unit/test_root_credential_persistence.py new file mode 100644 index 00000000..98ad9d95 --- /dev/null +++ b/tests/unit/test_root_credential_persistence.py @@ -0,0 +1,317 @@ +"""Contracts for root credential persistence across DDI slot replacement. + +``/etc/shadow`` ships inside the OS DDI, and ``50-root.transfer`` replaces that +filesystem image in both ``bluefin-server-root-*`` slots on every update. The +root credential a host rotates at the console therefore used to roll back to the +credential baked into the image as soon as the other slot booted — the finding +recorded in issue #244. + +The fix keeps the authoritative root entry in the persistent ``/var`` partition: +``bluefin-root-cred.service`` restores it into ``/etc/shadow`` before every login +path, and ``bluefin-root-cred-persist.path`` copies changes back out. + +These tests pin the parts that fail silently if they drift — the helper's +behaviour against real shadow files, the unit ordering that decides whether a +restore lands before ``getty``/``sshd``, and the enablement symlinks, because +systemd presets are not applied in this image and a unit without one never runs. +""" + +from __future__ import annotations + +import re +import subprocess +from pathlib import Path + +import pytest +import yaml + +REPO_ROOT = Path(__file__).resolve().parents[2] +ELEMENT = REPO_ROOT / "elements" / "bluefin-server" / "os-root-cred.bst" +STACK = REPO_ROOT / "elements" / "bluefin-server" / "os-stack.bst" +UNITS_ELEMENT = REPO_ROOT / "elements" / "bluefin-server" / "os-k0s-first-boot.bst" +DDI_ELEMENT = REPO_ROOT / "elements" / "oci" / "bluefin-server-ddi.bst" +HELPER = REPO_ROOT / "files" / "os" / "libexec" / "bluefin-root-cred-sync" +SYSTEM_DIR = REPO_ROOT / "files" / "os" / "systemd" / "system" +RESTORE_UNIT = SYSTEM_DIR / "bluefin-root-cred.service" +PERSIST_PATH_UNIT = SYSTEM_DIR / "bluefin-root-cred-persist.path" +PERSIST_UNIT = SYSTEM_DIR / "bluefin-root-cred-persist.service" + +SHADOW_PATH = "/etc/shadow" +STATE_PATH = "/var/lib/bluefin-server/root-shadow" + +# The credential the image bakes in, and a credential an operator would rotate +# to. Both are written the way shadow(5) writes them, and the hash values are +# irrelevant to the mechanism under test. +IMAGE_ENTRY = ( + "root:$6$bluefin123$o2pQjPN1n3ZCnYUROlA01xAdnGO7mhVRAVw98x4xc8LAUIJv7b44bBNoER6" + "fM4P.rrj4ePYFfkx9WvZICU8nt/:19700:0:99999:7:::" +) +ROTATED_ENTRY = "root:$6$rotatedhash$6W8pQ1uZ/:19932:0:99999:7:::" +SYSTEM_ENTRY = "systemd-network:!:19000:0:99999:7:::" + + +def shadow_db(entry: str) -> str: + """A shadow database holding the root entry plus a system account.""" + return f"{entry}\n{SYSTEM_ENTRY}\n" + + +def render(tmp_path: Path, entry: str) -> Path: + shadow = tmp_path / "shadow" + shadow.write_text(shadow_db(entry), encoding="utf-8") + shadow.chmod(0o600) + return shadow + + +def run(mode: str, shadow: Path, state: Path) -> subprocess.CompletedProcess: + return subprocess.run( + [str(HELPER), mode, str(shadow), str(state)], + capture_output=True, + text=True, + ) + + +def root_entry(shadow: Path) -> str: + for line in shadow.read_text(encoding="utf-8").splitlines(): + if line.startswith("root:"): + return line + raise AssertionError(f"{shadow} holds no root entry") + + +# ── The helper is shippable ──────────────────────────────────────────────── + + +def test_helper_ships_as_an_executable_bash_script(): + assert HELPER.is_file(), f"{HELPER.relative_to(REPO_ROOT)} is missing" + mode = HELPER.stat().st_mode + assert mode & 0o111, "systemd cannot exec a helper without the execute bit" + assert HELPER.read_text(encoding="utf-8").startswith("#!/bin/bash\n"), ( + "the helper must run under bash: the DDI runtime is runtime-minimal and " + "does not guarantee /bin/sh" + ) + + +def test_helper_needs_no_tool_the_ddi_runtime_may_lack(): + """runtime-minimal ships no sed/awk/grep; the helper runs before login.""" + code = "\n".join( + line + for line in HELPER.read_text(encoding="utf-8").splitlines() + if not line.strip().startswith("#") + ) + for tool in ("awk", "sed", "grep", "python"): + assert not re.search(rf"(^|[|;&(`]\s*){tool}\b", code, re.MULTILINE), ( + f"the helper invokes {tool}, which the DDI runtime does not guarantee" + ) + + +# ── Packaging and enablement ─────────────────────────────────────────────── + + +def test_persistence_element_is_part_of_the_ddi_stack(): + assert "bluefin-server/os-root-cred.bst" in STACK.read_text(encoding="utf-8") + + +def test_units_come_from_the_element_that_stages_the_systemd_tree(): + """The symlinks below only resolve while that element stages this tree.""" + units_element = UNITS_ELEMENT.read_text(encoding="utf-8") + assert "path: files/os/systemd/system" in units_element + assert "target: /usr/lib/systemd/system" in units_element + for unit in (RESTORE_UNIT, PERSIST_PATH_UNIT, PERSIST_UNIT): + assert unit.is_file(), f"{unit.name} is staged by no element" + + +def test_every_shipped_unit_is_enabled_by_an_explicit_symlink(): + """Presets are not applied in this image, so enablement must be explicit.""" + install_commands = "\n".join( + yaml.safe_load(ELEMENT.read_text(encoding="utf-8"))["config"][ + "install-commands" + ] + ) + enabled = set(re.findall(r"ln -sf \.\./(\S+) ", install_commands)) + assert enabled == { + RESTORE_UNIT.name, + PERSIST_PATH_UNIT.name, + }, f"unexpected enablement set: {sorted(enabled)}" + for name in enabled: + assert (SYSTEM_DIR / name).is_file(), ( + f"{name} is enabled but no such unit ships" + ) + + +def test_the_triggered_persist_half_is_not_enabled_at_boot(): + install_commands = yaml.safe_load(ELEMENT.read_text(encoding="utf-8"))["config"][ + "install-commands" + ] + element_text = "\n".join(install_commands) + assert PERSIST_UNIT.name not in element_text, ( + "the persist service must stay untriggered at boot: running both halves " + "concurrently could overwrite the operator's credential with the image's" + ) + assert ( + "install -Dm755 libexec-src/bluefin-root-cred-sync " + '"%{install-root}%{prefix}/libexec/bluefin-root-cred-sync"' + ) in element_text + + +def test_helper_lands_on_the_path_the_units_exec(): + for unit in (RESTORE_UNIT, PERSIST_UNIT): + assert ( + f"ExecStart=/usr/libexec/bluefin-root-cred-sync " + f"{'boot' if unit is RESTORE_UNIT else 'persist'}" + ) in unit.read_text(encoding="utf-8") + + +def test_boot_restore_runs_before_every_login_path(): + restore = RESTORE_UNIT.read_text(encoding="utf-8") + assert "Type=oneshot" in restore + assert "After=local-fs.target" in restore + # getty, sshd, and the k0s console all start from multi-user.target. + assert "Before=multi-user.target" in restore + assert "ConditionPathExists=/etc/shadow" in restore + + +def test_both_halves_write_to_a_root_only_store_on_persistent_var(): + for unit in (RESTORE_UNIT, PERSIST_UNIT): + text = unit.read_text(encoding="utf-8") + assert "RequiresMountsFor=/var/lib/bluefin-server" in text, ( + f"{unit.name} could run against an unmounted /var and silently " + "write the store to the replaceable root filesystem" + ) + assert "StateDirectory=bluefin-server" in text + assert "StateDirectoryMode=0700" in text + + +def test_persist_watcher_tracks_the_shadow_file_only(): + watcher = PERSIST_PATH_UNIT.read_text(encoding="utf-8") + assert f"Unit={PERSIST_UNIT.name}" in watcher + # The watcher must not be armed while the boot-time restore writes. + assert f"After={RESTORE_UNIT.name}" in watcher + watched = [ + line for line in watcher.splitlines() if line.startswith("PathChanged=") + ] + assert watched == [f"PathChanged={SHADOW_PATH}"], ( + "watch /etc/shadow alone: a directory watch would capture the file " + "mid-write, and any other /etc path is not this unit's business" + ) + + +def test_image_still_bakes_the_bootstrap_credential(): + """This layer restores a rotated credential; removing the baked one is #80.""" + ddi = DDI_ELEMENT.read_text(encoding="utf-8") + assert "> /layer/etc/shadow" in ddi, ( + "the DDI no longer seeds /etc/shadow — revisit whether the persistence " + "layer still has a bootstrap credential to seed from (issue #80)" + ) + + +# ── Helper behaviour ─────────────────────────────────────────────────────── + + +def test_first_boot_seeds_the_persisted_copy_from_the_image(tmp_path): + shadow = render(tmp_path, IMAGE_ENTRY) + state = tmp_path / "state" / "root-shadow" + + result = run("boot", shadow, state) + + assert result.returncode == 0, result.stderr + assert state.read_text(encoding="utf-8") == f"{IMAGE_ENTRY}\n" + assert state.stat().st_mode & 0o777 == 0o600 + assert shadow.read_text(encoding="utf-8") == shadow_db(IMAGE_ENTRY), ( + "seeding must not rewrite the image's own shadow database" + ) + + +def test_a_rotated_credential_survives_a_replaced_image_slot(tmp_path): + """The regression from issue #244: the seeded hash must not come back.""" + shadow = render(tmp_path, IMAGE_ENTRY) + state = tmp_path / "state" / "root-shadow" + + assert run("boot", shadow, state).returncode == 0 + # The operator rotates the root password at the console... + shadow.write_text(shadow_db(ROTATED_ENTRY), encoding="utf-8") + assert run("persist", shadow, state).returncode == 0 + # ...then systemd-sysupdate boots the other slot, whose /etc/shadow is the + # one baked into the new DDI. + shadow.write_text(shadow_db(IMAGE_ENTRY), encoding="utf-8") + assert run("boot", shadow, state).returncode == 0 + + assert root_entry(shadow) == ROTATED_ENTRY + assert IMAGE_ENTRY.split(":")[1] not in shadow.read_text(encoding="utf-8") + + +def test_restore_replaces_only_the_root_entry(tmp_path): + shadow = render(tmp_path, IMAGE_ENTRY) + state = tmp_path / "state" / "root-shadow" + state.parent.mkdir(parents=True) + state.write_text(f"{ROTATED_ENTRY}\n", encoding="utf-8") + + assert run("boot", shadow, state).returncode == 0 + + assert shadow.read_text(encoding="utf-8") == shadow_db(ROTATED_ENTRY) + assert shadow.stat().st_mode & 0o777 == 0o600 + + +def test_restore_is_idempotent(tmp_path): + shadow = render(tmp_path, IMAGE_ENTRY) + state = tmp_path / "state" / "root-shadow" + state.parent.mkdir(parents=True) + state.write_text(f"{ROTATED_ENTRY}\n", encoding="utf-8") + + assert run("boot", shadow, state).returncode == 0 + before = shadow.stat().st_mtime_ns + result = run("boot", shadow, state) + + assert result.returncode == 0 + assert root_entry(shadow) == ROTATED_ENTRY + assert shadow.stat().st_mtime_ns == before, ( + "a matching credential must not be rewritten on every boot" + ) + + +def test_persisted_copy_is_root_only(tmp_path): + shadow = render(tmp_path, IMAGE_ENTRY) + state = tmp_path / "state" / "root-shadow" + + assert run("persist", shadow, state).returncode == 0 + + assert state.stat().st_mode & 0o777 == 0o600 + # The helper creates the store directory under umask 077, and the units + # declare StateDirectoryMode=0700 for the systemd-created directory. + assert state.parent.stat().st_mode & 0o077 == 0 + + +def test_corrupt_persisted_copy_fails_loudly_and_leaves_shadow_alone(tmp_path): + """No silent fallback to the baked-in credential when the store is broken.""" + shadow = render(tmp_path, IMAGE_ENTRY) + before = shadow.read_text(encoding="utf-8") + state = tmp_path / "state" / "root-shadow" + state.parent.mkdir(parents=True) + state.write_text("", encoding="utf-8") + + result = run("boot", shadow, state) + + assert result.returncode != 0 + assert shadow.read_text(encoding="utf-8") == before + + +def test_malformed_and_rootless_shadow_entries_are_refused(tmp_path): + state = tmp_path / "state" / "root-shadow" + + truncated = render(tmp_path, "root:$6$broken") + result = run("persist", truncated, state) + assert result.returncode != 0 + assert not state.exists(), "a truncated entry must never be persisted" + + rootless = tmp_path / "rootless" + rootless.write_text(f"{SYSTEM_ENTRY}\n", encoding="utf-8") + result = run("persist", rootless, state) + assert result.returncode != 0 + assert not state.exists() + + +def test_an_unusable_invocation_is_rejected(tmp_path): + shadow = render(tmp_path, IMAGE_ENTRY) + state = tmp_path / "state" / "root-shadow" + + assert run("restore", shadow, state).returncode != 0 + assert run("", shadow, state).returncode != 0 + assert not state.exists() \ No newline at end of file