From 272c06de613bd0eda185b913cd51ba846cfe4305 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Fri, 11 Sep 2026 17:04:42 -0600 Subject: [PATCH 01/31] Run development containers with rootless Docker --- bin/omarchy-install-docker-dbs | 14 +- bin/omarchy-launch-docker-tui | 18 +- bin/omarchy-provision-owner | 3 + bin/omarchy-remove-security-sudoless-docker | 34 - bin/omarchy-setup-security-sudoless-docker | 49 -- bin/omarchy-sudo-docker | 44 -- bin/omarchy-upgrade-to-quattro | 6 +- bin/omarchy-windows-vm | 128 ++-- config/docker/daemon.json | 7 + default/bash/env-bootstrap | 10 + default/docker/rootless/migrate.py | 658 ++++++++++++++++++ default/docker/rootless/volume-manifest.py | 45 ++ default/omarchy/omarchy-menu.jsonc | 2 - .../docker.socket.d/10-omarchy-rootful.conf | 4 + .../60-omarchy-rootless-docker | 6 + docs/file-layout.md | 2 + docs/rootless-docker.md | 25 + install/config/docker.sh | 27 +- install/config/enable-services.sh | 3 + install/helpers/rootless-docker.sh | 60 ++ install/omarchy-base.packages | 4 + install/user/all.sh | 1 + install/user/docker.sh | 11 + install/user/first-run/enable-user-units.sh | 1 + manual/18-development-tools.md | 8 +- manual/28-windows-vm.md | 2 + manual/48-security.md | 8 + migrations/1787580187.sh | 26 +- migrations/1789164756.sh | 145 ++++ test/acceptance.d/system-test.sh | 22 +- test/shell.d/config-test.sh | 2 + test/shell.d/docker-group-migration-test.sh | 10 +- test/shell.d/provisioning-groups-test.sh | 15 +- .../shell.d/rootless-docker-migration-test.sh | 225 ++++++ test/shell.d/rootless-docker-posture-test.sh | 66 ++ test/shell.d/sudo-docker-test.sh | 67 -- test/shell.d/sudoless-docker-toggle-test.sh | 93 --- test/shell.d/windows-vm-auth-test.sh | 47 ++ .../shell.d/windows-vm-mount-boundary-test.sh | 2 +- 39 files changed, 1463 insertions(+), 437 deletions(-) delete mode 100755 bin/omarchy-remove-security-sudoless-docker delete mode 100755 bin/omarchy-setup-security-sudoless-docker delete mode 100755 bin/omarchy-sudo-docker create mode 100644 config/docker/daemon.json create mode 100644 default/docker/rootless/migrate.py create mode 100644 default/docker/rootless/volume-manifest.py create mode 100644 default/systemd/system/docker.socket.d/10-omarchy-rootful.conf create mode 100755 default/systemd/user-environment-generators/60-omarchy-rootless-docker create mode 100644 docs/rootless-docker.md create mode 100644 install/helpers/rootless-docker.sh create mode 100644 install/user/docker.sh create mode 100644 migrations/1789164756.sh create mode 100755 test/shell.d/rootless-docker-migration-test.sh create mode 100755 test/shell.d/rootless-docker-posture-test.sh delete mode 100644 test/shell.d/sudo-docker-test.sh delete mode 100644 test/shell.d/sudoless-docker-toggle-test.sh create mode 100644 test/shell.d/windows-vm-auth-test.sh diff --git a/bin/omarchy-install-docker-dbs b/bin/omarchy-install-docker-dbs index 26e850f78d9c..1b6ae82f024c 100755 --- a/bin/omarchy-install-docker-dbs +++ b/bin/omarchy-install-docker-dbs @@ -1,8 +1,6 @@ #!/bin/bash # omarchy:summary=Install one of the supported databases in a Docker container with the suitable development options. -# omarchy:requires-sudo=true - options=("MySQL" "PostgreSQL" "Redis" "MongoDB" "MariaDB" "MSSQL") if (( $# == 0 )); then @@ -15,12 +13,12 @@ if [[ -n $choices ]]; then for db in $choices; do echo "Installing $db..." case $db in - MySQL) sudo docker run -d --restart unless-stopped -p "127.0.0.1:3306:3306" --name=mysql8 -e MYSQL_ROOT_PASSWORD= -e MYSQL_ALLOW_EMPTY_PASSWORD=true mysql:8.4 ;; - PostgreSQL) sudo docker run -d --restart unless-stopped -p "127.0.0.1:5432:5432" --name=postgres18 -e POSTGRES_HOST_AUTH_METHOD=trust postgres:18 ;; - MariaDB) sudo docker run -d --restart unless-stopped -p "127.0.0.1:3306:3306" --name=mariadb11 -e MARIADB_ROOT_PASSWORD= -e MARIADB_ALLOW_EMPTY_ROOT_PASSWORD=true mariadb:11.8 ;; - Redis) sudo docker run -d --restart unless-stopped -p "127.0.0.1:6379:6379" --name=redis redis:7 ;; - MongoDB) sudo docker run -d --restart unless-stopped -p "127.0.0.1:27017:27017" --name mongodb -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=admin123 mongo:noble ;; - MSSQL) sudo docker run -d --restart unless-stopped -p "127.0.0.1:1433:1433" --name mssql -e MSSQL_PID=Developer -e ACCEPT_EULA=Y -e "MSSQL_SA_PASSWORD=@dmin123" mcr.microsoft.com/mssql/server:2022-CU12-ubuntu-22.04 ;; + MySQL) docker run -d --restart unless-stopped -p "127.0.0.1:3306:3306" --name=mysql8 -e MYSQL_ROOT_PASSWORD= -e MYSQL_ALLOW_EMPTY_PASSWORD=true mysql:8.4 ;; + PostgreSQL) docker run -d --restart unless-stopped -p "127.0.0.1:5432:5432" --name=postgres18 -e POSTGRES_HOST_AUTH_METHOD=trust postgres:18 ;; + MariaDB) docker run -d --restart unless-stopped -p "127.0.0.1:3306:3306" --name=mariadb11 -e MARIADB_ROOT_PASSWORD= -e MARIADB_ALLOW_EMPTY_ROOT_PASSWORD=true mariadb:11.8 ;; + Redis) docker run -d --restart unless-stopped -p "127.0.0.1:6379:6379" --name=redis redis:7 ;; + MongoDB) docker run -d --restart unless-stopped -p "127.0.0.1:27017:27017" --name mongodb -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=admin123 mongo:noble ;; + MSSQL) docker run -d --restart unless-stopped -p "127.0.0.1:1433:1433" --name mssql -e MSSQL_PID=Developer -e ACCEPT_EULA=Y -e "MSSQL_SA_PASSWORD=@dmin123" mcr.microsoft.com/mssql/server:2022-CU12-ubuntu-22.04 ;; esac done else diff --git a/bin/omarchy-launch-docker-tui b/bin/omarchy-launch-docker-tui index 8d09894a5fb2..9277bdbbbea7 100755 --- a/bin/omarchy-launch-docker-tui +++ b/bin/omarchy-launch-docker-tui @@ -1,20 +1,6 @@ #!/bin/bash -# omarchy:summary=Open the Docker TUI (lazydocker) with access to the Docker daemon +# omarchy:summary=Open the Docker TUI (lazydocker) for rootless development containers # omarchy:hidden=true -# By default the install user is NOT in the docker group: membership is -# root-equivalent (a container can bind-mount / and rewrite the host as root), -# so a single process running as the user could otherwise escalate to root with -# no prompt. lazydocker needs the root-owned Docker socket, so when the group is -# absent, gate that access behind a polkit prompt. If the user has opted into -# sudoless Docker (omarchy-setup-security-sudoless-docker), the socket is already -# reachable, so run lazydocker directly — omarchy-sudo-docker answers that for -# this session, so the prompt stays until the reboot that grants the group. -# pkexec sanitizes the environment, so carry TERM through for the TUI to render -# and run lazydocker from root's PATH. -if omarchy-sudo-docker; then - exec pkexec /usr/bin/env TERM="${TERM:-xterm-256color}" lazydocker -else - exec lazydocker -fi +exec lazydocker diff --git a/bin/omarchy-provision-owner b/bin/omarchy-provision-owner index b5321a4d118f..12a2c6602c2a 100755 --- a/bin/omarchy-provision-owner +++ b/bin/omarchy-provision-owner @@ -737,6 +737,9 @@ create_user() { ${full_name:+-c "$full_name"} "$username" fi + source "$OMARCHY_PATH/install/helpers/rootless-docker.sh" + rootless_docker_ensure_subids "$username" + printf '%s:%s\n' "$username" "$password" | chpasswd printf '%s:%s\n' root "$password" | chpasswd diff --git a/bin/omarchy-remove-security-sudoless-docker b/bin/omarchy-remove-security-sudoless-docker deleted file mode 100755 index dd4c6175fba2..000000000000 --- a/bin/omarchy-remove-security-sudoless-docker +++ /dev/null @@ -1,34 +0,0 @@ -#!/bin/bash - -# omarchy:summary=Disable sudoless Docker by removing your user from the docker group -# omarchy:requires-sudo=true - -set -e - -# Ask about the configured groups, not this session's: right after enabling, -# sudoless Docker is on for the account even though the running session still -# needs a prompt, and this command is what turns it back off. -if omarchy-sudo-docker --configured; then - echo "Sudoless Docker is not enabled: $USER is not in the docker group." - exit 0 -fi - -echo "Removing $USER from the docker group..." -sudo gpasswd -d "$USER" docker >/dev/null - -# Group membership is only re-read by a fresh session, and in practice logging -# out or newgrp isn't enough — only a reboot reliably applies it. Record it so a -# later `omarchy update` still prompts (omarchy-update-restart reads this), then -# offer to do it now. -omarchy-state set reboot-required - -echo "" -echo "Sudoless Docker DISABLED. Docker access goes through a polkit/sudo prompt" -echo "again: the Docker TUI (Super + Shift + D) and the Windows VM ask when they" -echo "need it, and the plain 'docker' CLI runs under sudo. It takes effect after a reboot." -echo "" -# The migration reuses this command during 'omarchy update' and defers the -# reboot to omarchy-update-restart, so it doesn't cut the update short. -if [[ -z ${OMARCHY_DEFER_REBOOT:-} ]] && gum confirm "Reboot now to apply?"; then - omarchy-system-reboot -fi diff --git a/bin/omarchy-setup-security-sudoless-docker b/bin/omarchy-setup-security-sudoless-docker deleted file mode 100755 index 4577cbf162ed..000000000000 --- a/bin/omarchy-setup-security-sudoless-docker +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/bash - -# omarchy:summary=Enable sudoless Docker by adding your user to the docker group (root-equivalent!) -# omarchy:requires-sudo=true - -set -e - -# Ask about the configured groups, not this session's: once enabled it stays -# enabled for the account even before the reboot that lets this session use it. -if ! omarchy-sudo-docker --configured; then - echo "Sudoless Docker is already enabled: $USER is in the docker group." - echo "To disable it again, run: omarchy-remove-security-sudoless-docker" - exit 0 -fi - -echo "" -echo "⚠️ WARNING: Enabling sudoless Docker adds you to the 'docker' group." -echo "" -echo "The Docker daemon runs as root, so membership in the docker group is" -echo "equivalent to passwordless root. Any process running as your user could" -echo "then run, for example:" -echo "" -echo " docker run -v /:/host alpine # full read/write of the host, as root" -echo "" -echo "and take over the machine with no password prompt. A single rogue script," -echo "dependency, or plugin running as you is enough. It is convenient for" -echo "development, but it removes the protection Omarchy keeps by default, where" -echo "Docker access goes through a polkit/sudo prompt." -echo "" - -if gum confirm "Enable sudoless Docker? This gives anything running as you passwordless root."; then - sudo usermod -aG docker "$USER" - # A new docker group membership is only picked up by a fresh session, and in - # practice logging out or newgrp isn't enough — only a reboot reliably applies - # it. Record it so a later `omarchy update` still prompts - # (omarchy-update-restart reads this), then offer to do it now. - omarchy-state set reboot-required - echo "" - echo "Sudoless Docker ENABLED. It takes effect after a reboot." - echo "To disable it again: Setup > Security > Sudoless Docker." - echo "" - # The migration reuses this command during 'omarchy update' and defers the - # reboot to omarchy-update-restart, so it doesn't cut the update short. - if [[ -z ${OMARCHY_DEFER_REBOOT:-} ]] && gum confirm "Reboot now to apply?"; then - omarchy-system-reboot - fi -else - echo "Aborted. No changes made. Docker access still goes through a prompt." -fi diff --git a/bin/omarchy-sudo-docker b/bin/omarchy-sudo-docker deleted file mode 100755 index 19399cc46584..000000000000 --- a/bin/omarchy-sudo-docker +++ /dev/null @@ -1,44 +0,0 @@ -#!/bin/bash - -# omarchy:summary=Succeed when Docker needs sudo, fail when it can be used directly -# omarchy:args=[--configured] -# omarchy:examples=omarchy-sudo-docker && echo "needs sudo" | omarchy-sudo-docker --configured -# omarchy:hidden=true - -# The docker group is root-equivalent, so Omarchy leaves users out of it by -# default and reaches the daemon through a prompt instead. Everything that has -# to make that choice asks here rather than testing group membership itself. -# -# Two questions, because they have different answers between toggling sudoless -# Docker and the reboot that applies it (group membership is fixed when the -# session is created): -# -# (default) Does Docker need sudo *right now*? Answered by whether this -# process can actually reach the socket, which is what decides -# if a command must elevate. Still true in the window after -# sudoless Docker is enabled but before the reboot. -# --configured Will it need sudo once the account's groups take effect? -# Answered from the account's configured groups, so the menu -# offers the toggle that can actually change state. -# -# Succeeds (exit 0) when sudo is needed, so it reads as `if omarchy-sudo-docker`. - -DOCKER_SOCKET="${OMARCHY_DOCKER_SOCKET:-/var/run/docker.sock}" - -case "${1:-}" in ---configured) - # An account in the docker group will not need sudo after the next login. - id -nG "$USER" 2>/dev/null | grep -qw docker && exit 1 - exit 0 - ;; -"") - # A socket we can write is a daemon we can drive without elevating. A missing - # socket counts as needing sudo: reaching it means starting it as root anyway. - [[ -w $DOCKER_SOCKET ]] && exit 1 - exit 0 - ;; -*) - echo "Usage: omarchy-sudo-docker [--configured]" >&2 - exit 2 - ;; -esac diff --git a/bin/omarchy-upgrade-to-quattro b/bin/omarchy-upgrade-to-quattro index e6a27ee610b6..2a70e15ac55c 100755 --- a/bin/omarchy-upgrade-to-quattro +++ b/bin/omarchy-upgrade-to-quattro @@ -1345,9 +1345,9 @@ apply_system_transition() { printf '%s\n' '{"distribution":{"require_eula":false},"browser":{"theme":{"color_scheme":0,"color_scheme2":0}}}' | \ as_root tee /usr/lib/chromium/initial_preferences >/dev/null - # Deliberately do NOT add the user to the docker group. That group is - # root-equivalent, so it is opt-in now (Setup > Security > Sudoless Docker); - # re-granting it on upgrade would silently undo that default for everyone. + # Deliberately do not add the user to the root-equivalent docker group. The + # ordered post-upgrade migration moves compatible workloads to rootless + # Docker and reserves the rootful daemon for authenticated Windows use. if [[ -f /usr/bin/powerprofilesctl ]]; then as_root sed -i '/env python3/ c\#!/bin/python3' /usr/bin/powerprofilesctl || true diff --git a/bin/omarchy-windows-vm b/bin/omarchy-windows-vm index f672ed7eee1d..af18a8a36848 100755 --- a/bin/omarchy-windows-vm +++ b/bin/omarchy-windows-vm @@ -5,11 +5,8 @@ # omarchy:requires-sudo=true # The Windows VM runs a privileged container (KVM, /dev/net/tun, NET_ADMIN), so -# it needs the root-owned Docker daemon. By default the user is NOT in the docker -# group (that group is root-equivalent), so Docker access is gated behind a -# single polkit prompt. If the user opted into sudoless Docker -# (omarchy-setup-security-sudoless-docker), the socket is reachable directly and -# no prompt appears. +# it cannot use the rootless development daemon. Every operation uses the +# root-owned Docker socket through an authenticated sudo or polkit boundary. # # The compose file lives in a root-owned directory and is only ever written by # the elevated, input-validated write_compose action below. That is the whole @@ -22,9 +19,9 @@ RUNTIME_DIR="${OMARCHY_WINDOWS_DIR:-/var/lib/omarchy/windows}" COMPOSE_FILE="$RUNTIME_DIR/docker-compose.yml" LEGACY_COMPOSE_FILE="$HOME/.config/windows/docker-compose.yml" -# The guest password lives in the root-owned compose (readable by root and the -# docker group), but RDP needs it as the user. Keep a private copy here, 0600 in -# the user's own config, so the plaintext password is never world-readable. +# The guest password lives in the root-only compose, but RDP needs it as the +# user. Keep a private copy in the user's own config, mode 0600, so the +# plaintext password is never world-readable. CREDENTIALS_FILE="$HOME/.config/windows/credentials" IMAGE="dockurr/windows" CONTAINER="omarchy-windows" @@ -48,12 +45,6 @@ fi # --- privilege helpers ------------------------------------------------------- -# True when this session can reach the Docker socket directly (sudoless Docker -# on and in effect). Asking about the socket rather than the configured groups -# keeps the prompt in place through the window where sudoless Docker is enabled -# but the reboot that grants the group has not happened yet. -docker_needs_sudo() { omarchy-sudo-docker; } - # The command to hand pkexec for the privileged re-exec. pkexec runs whatever # executable it is given (after authorization) and only shows the path in the # prompt — it does NOT require the target to be root-owned. So resolve to the @@ -77,47 +68,39 @@ priv_target() { printf '%s\n' "$candidate" } -# Run a privileged VM action. write_compose always elevates (the compose is -# root-owned); the daemon operations run directly when sudoless Docker is on and -# otherwise behind a polkit prompt. The stock org.freedesktop.policykit.exec -# policy is auth_admin (not auth_admin_keep), so each elevated action prompts: -# a launch asks once to start and, unless authorization is still cached by the -# agent, again to stop. +# Run every VM action through authentication. A visible terminal uses sudo so +# the password prompt stays in that terminal; graphical launches use polkit. priv() { - local action="$1" + local action="$1" target shift - if [[ $action != write_compose && $action != remove ]] && ! docker_needs_sudo; then - # Bring-up normally runs directly for a docker-group user, but recreating - # the protected bind anchors after reboot (or migrating an old compose) - # still needs one privileged invocation. - if [[ -d $VM_LOCK_DIR && ! -L $VM_LOCK_DIR && -r $VM_LOCK_DIR && -x $VM_LOCK_DIR ]] && { - [[ $action != up && $action != up_wait ]] || { - ! compose_needs_security_migration && mounts_ready >/dev/null 2>&1 - } - }; then - with_vm_lock "__priv_$action" "$@" - return - fi - fi - local target target=$(priv_target) || { echo "omarchy-windows-vm: refusing to run a non-root-owned command as root" >&2 return 1 } - pkexec "$target" __priv "$action" "$@" + if [[ -t 0 || -t 1 || -t 2 ]]; then + sudo "$target" __priv "$action" "$@" + else + pkexec "$target" __priv "$action" "$@" + fi } -dc() { docker-compose -f "$COMPOSE_FILE" "$@"; } +# Pin Windows to the rootful socket even when the caller's session exports the +# rootless DOCKER_HOST. Socket activation keeps that rootful daemon off until an +# authenticated VM operation needs it. +docker() { + if ((EUID == 0)); then + /usr/bin/systemctl start docker.socket || return 1 + fi + command /usr/bin/docker --host unix:///run/docker.sock "$@" +} + +dc() { docker compose -f "$COMPOSE_FILE" "$@"; } with_vm_lock() { local fd rc=0 if ((EUID == 0)); then assert_boundary_dir /run 0 && assert_boundary_dir /run/lock 0 || return 1 - if getent group docker >/dev/null 2>&1; then - install -d -o root -g docker -m 0750 -- "$VM_LOCK_DIR" || return 1 - else - install -d -o root -g root -m 0700 -- "$VM_LOCK_DIR" || return 1 - fi + install -d -o root -g root -m 0700 -- "$VM_LOCK_DIR" || return 1 fi assert_boundary_dir "$VM_LOCK_DIR" 0 || return 1 # Flock the directory inode itself. Concurrent first callers may both run @@ -151,20 +134,21 @@ valid_priv_action() { esac } -# --- privileged actions (run as root via pkexec, or directly when sudoless) --- +# --- privileged actions (run as root via sudo or pkexec) --------------------- -# Resolve the account that authorized pkexec. Never trust HOME or a caller- -# supplied mount path in the privileged process: pkexec can reset HOME, and the +# Resolve the account that authorized sudo or pkexec. Never trust HOME or a +# caller-supplied mount path in the privileged process: pkexec can reset HOME, and the # old path arguments were the source of an arbitrary host bind-mount primitive. resolve_caller() { - local entry canonical parent owner mode + local entry canonical parent owner mode authorized_uid if ((EUID == 0)); then - [[ ${PKEXEC_UID:-} =~ ^[0-9]{1,10}$ ]] && ((10#$PKEXEC_UID > 0)) || { + authorized_uid=${SUDO_UID:-${PKEXEC_UID:-}} + [[ $authorized_uid =~ ^[0-9]{1,10}$ ]] && ((10#$authorized_uid > 0)) || { echo "omarchy-windows-vm: cannot identify the user who authorized this action" >&2 return 1 } - CALLER_UID=$((10#$PKEXEC_UID)) + CALLER_UID=$((10#$authorized_uid)) else CALLER_UID=$(id -u) fi @@ -232,8 +216,7 @@ resolve_caller() { } boundary_owner() { - # Production boundaries remain root-owned even when a docker-group user runs - # the read-only bring-up checks directly. A non-standard runtime is supported + # Production boundaries are always root-owned. A non-standard runtime is supported # only for unprivileged tests/development and is owned by that caller. if ((EUID == 0)) || [[ $RUNTIME_DIR == /var/lib/omarchy/windows ]]; then printf '0' @@ -725,9 +708,9 @@ services: restart: "no" stop_grace_period: 2m EOF - chmod 0640 "$tmp" || exit 1 + chmod 0600 "$tmp" || exit 1 if ((EUID == 0)); then - chown root:docker "$tmp" 2>/dev/null || chown root:root "$tmp" || exit 1 + chown root:root "$tmp" || exit 1 fi mv -fT -- "$tmp" "$COMPOSE_FILE" || exit 1 tmp="" @@ -760,7 +743,7 @@ __priv_write_compose() { valid_password "$password" || { echo "invalid password" >&2; exit 2; } valid_tz "$tz" || tz="UTC" prepare_caller_mounts || exit 2 - # Readable by root and the docker group only. Any failure after mounting rolls + # Readable by root only. Any failure after mounting rolls # back just the binds this writer created and leaves an old compose untouched. write_compose_atomically "$ram" "$cores" "$disk" "$username" "$password" "$tz" || exit 2 } @@ -771,7 +754,7 @@ get_mount_source() { } # True only when a trusted compose has an exact security upgrade path. The -# result forces a one-time elevated migration for sudoless-Docker users. An +# result forces a one-time authenticated migration. An # arbitrary or mixed bind pair is never classified as migratable. compose_needs_security_migration() { local storage shared @@ -783,7 +766,9 @@ compose_needs_security_migration() { if compose_mount_pair_is_migratable "$storage" "$shared"; then return 0 fi - [[ $storage == "$EXPECTED_STORAGE" && $shared == "$EXPECTED_SHARED" ]] && ! compose_web_protected + [[ $storage == "$EXPECTED_STORAGE" && $shared == "$EXPECTED_SHARED" ]] && { + ! compose_web_protected || ! compose_root_private + } } compose_mount_pair_is_migratable() { @@ -802,6 +787,12 @@ compose_web_protected() { $(sed -n 's/^[[:space:]]*PROTECT:[[:space:]]*"Y"[[:space:]]*$/x/p' "$COMPOSE_FILE" | wc -l) == 1 ]] } +compose_root_private() { + local expected + expected=$(boundary_owner) + [[ $(stat -Lc '%u:%g:%a' "$COMPOSE_FILE" 2>/dev/null) == "$expected:$expected:600" ]] +} + rewrite_compose_security() { local tmp tmp=$(mktemp "$RUNTIME_DIR/.compose.XXXXXX") || return 1 @@ -817,9 +808,9 @@ rewrite_compose_security() { rm -f "$tmp" return 1 } - chmod 0640 "$tmp" || { rm -f "$tmp"; return 1; } + chmod 0600 "$tmp" || { rm -f "$tmp"; return 1; } if ((EUID == 0)); then - chown root:docker "$tmp" 2>/dev/null || chown root:root "$tmp" || { + chown root:root "$tmp" || { rm -f "$tmp" return 1 } @@ -876,14 +867,21 @@ assert_mounts_safe() { needs_rewrite=1 fi + if ! compose_root_private; then + ((EUID == 0)) || { + echo "omarchy-windows-vm: compose permissions need an authorized migration" >&2 + return 1 + } + needs_rewrite=1 + fi + if ((needs_rewrite)) && ! rewrite_compose_security; then if ((mounts_prepared)); then rollback_new_caller_mounts || true; fi return 1 fi # Mounts disappear at reboot. Root recreates them from the already-opened, - # caller-owned sources; a docker-group invocation may proceed directly only - # while the exact pinned pair is still present. + # caller-owned sources before Docker consumes the protected compose. if ((EUID == 0)); then prepare_caller_mounts || return 1 fi @@ -1306,8 +1304,8 @@ EOF local tz tz=$(timedatectl show -p Timezone --value 2>/dev/null || echo UTC) - # Write the root-owned compose from the validated settings (one prompt if - # sudoless Docker is off). The writer pins the familiar home directories (or + # Write the root-owned compose from the validated settings. The writer pins + # the familiar home directories (or # their legitimate symlink targets) into root-protected bind anchors. write_compose "$SELECTED_RAM" "$SELECTED_CORES" "$SELECTED_DISK" \ "$USERNAME" "$PASSWORD" "$tz" || { @@ -1326,11 +1324,11 @@ EOF echo "Monitor installation progress at: http://127.0.0.1:8006" echo "" - echo "Starting Windows VM with docker-compose..." + echo "Starting Windows VM with rootful Docker Compose..." if ! priv up; then echo "❌ Failed to start Windows VM!" echo " Common issues:" - echo " - Docker daemon not running: sudo systemctl start docker" + echo " - Rootful Docker socket could not start" echo " - Port already in use: check if another VM is running" exit 1 fi @@ -1396,8 +1394,8 @@ launch_windows() { fi fi - # RDP credentials come from the private per-user file. Fall back to the compose - # only when it is readable (sudoless mode), reversing the writer's escaping. + # RDP credentials come from the private per-user file. Older installs may + # still have a readable compose, so retain that migration fallback. WIN_USER=$(read_credential USERNAME) || WIN_USER="" WIN_PASS=$(read_credential PASSWORD) || WIN_PASS="" if [[ -z $WIN_USER || -z $WIN_PASS ]] && [[ -r $COMPOSE_FILE ]]; then diff --git a/config/docker/daemon.json b/config/docker/daemon.json new file mode 100644 index 000000000000..ec6e60f2be30 --- /dev/null +++ b/config/docker/daemon.json @@ -0,0 +1,7 @@ +{ + "log-driver": "json-file", + "log-opts": { + "max-size": "10m", + "max-file": "5" + } +} diff --git a/default/bash/env-bootstrap b/default/bash/env-bootstrap index 2bc6d1f3771f..6a3307884a13 100644 --- a/default/bash/env-bootstrap +++ b/default/bash/env-bootstrap @@ -39,3 +39,13 @@ case ":$PATH:" in *) PATH="${PATH:+$PATH:}$HOME/.local/bin" ;; esac export PATH + +# The marker is written only after a fresh rootless setup or a verified workload +# migration. Explicit user config can still override this later in the shell or +# UWSM environment chain. +if [ -f "$HOME/.local/state/omarchy/rootless-docker/enabled" ]; then + rootless_docker_runtime=${XDG_RUNTIME_DIR:-/run/user/$(id -u)} + DOCKER_HOST="unix://$rootless_docker_runtime/docker.sock" + export DOCKER_HOST + unset rootless_docker_runtime +fi diff --git a/default/docker/rootless/migrate.py b/default/docker/rootless/migrate.py new file mode 100644 index 000000000000..38a4bb27f42f --- /dev/null +++ b/default/docker/rootless/migrate.py @@ -0,0 +1,658 @@ +"""Move compatible rootful containers into the desktop user's rootless Docker store.""" + +import hashlib +import json +import os +import re +import subprocess +import sys +from decimal import Decimal +from pathlib import Path + + +LABEL = "io.omarchy.rootless-docker.source-id" +SOURCE = "source" +TARGET = "target" +MASKED_PATHS = { + "/proc/acpi", "/proc/asound", "/proc/interrupts", "/proc/kcore", "/proc/keys", + "/proc/latency_stats", "/proc/sched_debug", "/proc/scsi", "/proc/timer_list", + "/proc/timer_stats", "/sys/devices/virtual/powercap", "/sys/firmware", +} +READONLY_PATHS = {"/proc/bus", "/proc/fs", "/proc/irq", "/proc/sys", "/proc/sysrq-trigger"} +DOCKER_CAPABILITIES = { + "AUDIT_WRITE", "CHOWN", "DAC_OVERRIDE", "FOWNER", "FSETID", "KILL", "MKNOD", + "NET_BIND_SERVICE", "NET_RAW", "SETFCAP", "SETGID", "SETPCAP", "SETUID", "SYS_CHROOT", +} +RESOURCE_FLAGS = { + "Memory": "--memory", "MemoryReservation": "--memory-reservation", + "MemorySwap": "--memory-swap", "CpuShares": "--cpu-shares", + "CpuQuota": "--cpu-quota", "CpuPeriod": "--cpu-period", + "CpusetCpus": "--cpuset-cpus", "CpusetMems": "--cpuset-mems", +} + + +def daemon_security(engine): + return json.loads(run(engine, "info", "--format", "{{json .SecurityOptions}}", capture=True)) + + +def validate_source_daemon(options): + # Daemon defaults (including no-new-privileges and seccomp profiles) need + # not appear in individual HostConfig records. Userns remapping also changes + # the meaning of numeric volume ownership. Do not guess these policies. + defaults = {"name=seccomp,profile=builtin", "name=seccomp,profile=default", "name=cgroupns"} + if not isinstance(options, list) or not options or set(options) - defaults: + raise ValueError("rootful Docker daemon confinement or user mapping needs an explicit migration") + + +def validate_target_daemon(options): + if not isinstance(options, list) or "name=rootless" not in options: + raise ValueError("the destination Docker daemon is not running rootlessly") + allowed = { + "name=rootless", "name=cgroupns", "name=seccomp,profile=builtin", + "name=seccomp,profile=default", + } + if set(options) - allowed: + raise ValueError("rootless Docker daemon confinement needs an explicit migration") + + +def validate_volumes(container): + name = container["Name"].lstrip("/") + host = container["HostConfig"] + mounts = container.get("Mounts", []) + for mount in mounts: + if mount.get("Type") != "volume" or mount.get("Driver") != "local": + raise ValueError(f"{name}: host mounts or custom storage need an explicit transfer") + if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]*", mount["Name"]): + raise ValueError(f"{name}: unsupported volume name") + if not mount["Destination"].startswith("/") or ":" in mount["Destination"]: + raise ValueError(f"{name}: unsupported volume destination") + # -v also records named volumes in Binds. Accept only an exact match to a + # local volume; never treat a host directory or socket as a named volume. + for binding in host.get("Binds") or []: + fields = binding.split(":") + if (len(fields) not in (2, 3) or (len(fields) == 3 and fields[2] not in ("rw", "ro")) or + not any(fields[:2] == [mount["Name"], mount["Destination"]] and + (len(fields) == 2 or (fields[2] == "rw") == mount.get("RW")) + for mount in mounts)): + raise ValueError(f"{name}: custom Binds need an explicit volume transfer") + for requested in host.get("Mounts") or []: + allowed = {"Type", "Source", "Target", "ReadOnly", "Consistency", "VolumeOptions"} + options = requested.get("VolumeOptions") or {} + if (set(requested) - allowed or requested.get("Type") != "volume" or + requested.get("Consistency") not in (None, "") or + set(options) - {"NoCopy"} or + options.get("NoCopy") not in (None, False, True)): + raise ValueError(f"{name}: custom mount options need an explicit volume transfer") + matching = [mount for mount in mounts + if mount["Destination"] == requested.get("Target") and + (not requested.get("Source") or mount["Name"] == requested["Source"])] + if (len(matching) != 1 or matching[0].get("Type") != "volume" or + bool(matching[0].get("RW")) == bool(requested.get("ReadOnly"))): + raise ValueError(f"{name}: Docker mount configuration does not match its private volume") + + +def validate_security(container): + name = container["Name"].lstrip("/") + host = container["HostConfig"] + if host.get("Privileged"): + raise ValueError(f"{name}: privileged containers require a manual migration") + if host.get("CapAdd"): + raise ValueError(f"{name}: added Linux capabilities require a manual migration") + if host.get("Devices") or host.get("DeviceRequests") or host.get("DeviceCgroupRules"): + raise ValueError(f"{name}: host device access requires a manual migration") + if container.get("AppArmorProfile") or container.get("ProcessLabel"): + raise ValueError(f"{name}: mandatory access-control profiles need an explicit migration") + if host.get("Runtime") not in (None, "", "runc"): + raise ValueError(f"{name}: custom Runtime needs an explicit migration") + if host.get("CgroupnsMode") not in (None, "", "private"): + raise ValueError(f"{name}: host cgroup access needs an explicit migration") + for key, expected in (("MaskedPaths", MASKED_PATHS), ("ReadonlyPaths", READONLY_PATHS)): + if key in host and set(host[key] or []) != expected: + raise ValueError(f"{name}: custom {key} must not be silently changed") + if any(option not in ("no-new-privileges", "no-new-privileges=true", "no-new-privileges:true") + for option in host.get("SecurityOpt") or []): + raise ValueError(f"{name}: custom SecurityOpt needs an explicit migration") + handled = { + "NetworkMode", "IpcMode", "ShmSize", "PortBindings", "RestartPolicy", "Binds", + "PidsLimit", "Runtime", "CgroupnsMode", "MaskedPaths", "ReadonlyPaths", + "SecurityOpt", "CapDrop", "LogConfig", "NanoCpus", "Mounts", *RESOURCE_FLAGS, + } + for key, value in host.items(): + if key in handled or value in (None, False, "", [], {}): + continue + if key == "ConsoleSize" and value == [0, 0]: + continue + # Unknown nondefault settings fail closed, including future Docker + # device, namespace, runtime, mount and resource options. + raise ValueError(f"{name}: custom {key} needs an explicit rootless Docker configuration") + log = host.get("LogConfig") or {} + if (log.get("Type") not in (None, "", "json-file") or + (log.get("Config") or {}) not in ({}, {"max-size": "10m", "max-file": "5"})): + raise ValueError(f"{name}: custom logging needs an explicit migration") + + +def runtime_arguments(container): + host = container["HostConfig"] + arguments = ["--shm-size", str(host["ShmSize"])] + if host.get("PidsLimit") not in (None, 0, -1): + arguments.append(f'--pids-limit={host["PidsLimit"]}') + for key, flag in RESOURCE_FLAGS.items(): + if host.get(key): + arguments += [flag, str(host[key])] + if host.get("NanoCpus"): + arguments += ["--cpus", format(Decimal(host["NanoCpus"]) / 1_000_000_000, "f")] + arguments += ["--cap-drop", "ALL"] + for capability in sorted(allowed_capabilities(container)): + arguments += ["--cap-add", capability] + if host.get("SecurityOpt"): + arguments += ["--security-opt", "no-new-privileges"] + return arguments + + +def allowed_capabilities(container): + # Explicit --cap-add gives even non-root processes capabilities. Docker's + # default non-root process has none, so keep that source boundary. + user = (container["Config"].get("User") or "").split(":")[0] + if user not in ("", "0", "root"): + return set() + # Docker API clients can retain mixed-case names in inspected CapDrop. + dropped = {capability.upper().removeprefix("CAP_") for capability in container["HostConfig"].get("CapDrop") or []} + return set() if "ALL" in dropped else DOCKER_CAPABILITIES - dropped + + +def verify_environment(container, values): + # The committed image contains the source environment exactly. A temporary + # empty DOCKER_CONFIG prevents the destination CLI from injecting proxy + # variables from the user's client configuration. + def mapping(entries): + if not isinstance(entries, list) or any(not isinstance(entry, str) or "=" not in entry for entry in entries): + raise RuntimeError("Cannot verify container environment") + result = dict(entry.split("=", 1) for entry in entries) + if len(result) != len(entries): + raise RuntimeError("Cannot verify duplicate container environment variables") + return result + source = mapping(container["Config"].get("Env") or []) + target = mapping(values) + if target != source: + # Environment names and values may contain secrets. Never print them. + raise RuntimeError("rootless Docker did not preserve the source environment; application was not started") + + +def verify_runtime(container): + name = container["Name"].lstrip("/") + target = inspect(TARGET, "container", name) + verify_environment(container, target["Config"].get("Env")) + source_host, target_host = container["HostConfig"], target["HostConfig"] + if target_host.get("Privileged") is not False: + raise RuntimeError(f"{name}: refusing privileged destination") + if target_host.get("Devices") or target_host.get("DeviceRequests") or target_host.get("DeviceCgroupRules"): + raise RuntimeError(f"{name}: refusing destination device access") + private_modes = { + "NetworkMode": "bridge", "IpcMode": "private", "PidMode": "", + "UTSMode": "", "CgroupnsMode": "private", + } + if any(target_host.get(key, "") != value for key, value in private_modes.items()): + raise RuntimeError(f"{name}: rootless Docker changed a private namespace boundary") + expected_mounts = sorted((mount["Destination"], destination_volume(container, mount), bool(mount.get("RW"))) + for mount in container.get("Mounts", [])) + actual_mounts = target.get("Mounts") or [] + if (any(mount.get("Type") != "volume" for mount in actual_mounts) or + sorted((mount["Destination"], mount["Name"], bool(mount.get("RW"))) for mount in actual_mounts) != expected_mounts): + raise RuntimeError(f"{name}: destination mounts differ from the validated private volumes") + expected = {"ShmSize": source_host["ShmSize"]} + expected.update({key: source_host[key] for key in RESOURCE_FLAGS if source_host.get(key)}) + for key, value in expected.items(): + if target_host.get(key) != value: + raise RuntimeError(f"{name}: rootless Docker did not preserve {key}; application was not started") + source_pids = source_host.get("PidsLimit") + target_pids = target_host.get("PidsLimit") + if (-1 if source_pids in (None, 0, -1) else source_pids) != (-1 if target_pids in (None, 0, -1) else target_pids): + raise RuntimeError(f"{name}: rootless Docker did not preserve PidsLimit; application was not started") + if target_host.get("NanoCpus") != source_host.get("NanoCpus"): + raise RuntimeError(f"{name}: rootless Docker did not preserve the CPU limit; application was not started") + if source_host.get("SecurityOpt") and not any( + option in ("no-new-privileges", "no-new-privileges=true") + for option in target_host.get("SecurityOpt") or []): + raise RuntimeError(f"{name}: rootless Docker did not preserve no-new-privileges") + expected_add = sorted(allowed_capabilities(container)) + actual_add = sorted(capability.upper().removeprefix("CAP_") + for capability in target_host.get("CapAdd") or []) + actual_drop = {capability.upper().removeprefix("CAP_") + for capability in target_host.get("CapDrop") or []} + if actual_add != expected_add or "ALL" not in actual_drop: + raise RuntimeError(f"{name}: rootless Docker changed the capability ceiling") + expected_labels = dict(container["Config"].get("Labels") or {}) + expected_labels[LABEL] = container["Id"] + if target["Config"].get("Labels") != expected_labels: + raise RuntimeError(f"{name}: rootless Docker changed the container labels") + source_config = dict(container["Config"]) + target_config = dict(target["Config"]) + for config in (source_config, target_config): + config.pop("Image", None) + config.pop("Labels", None) + # A committed Docker image causes a later `docker create` to report + # stdout/stderr attachment even when its detached source did not. These + # flags describe the original create client's stream attachment; they + # do not change the stored logs or a later `docker attach` operation. + config.pop("AttachStdout", None) + config.pop("AttachStderr", None) + if target_config != source_config: + changed = sorted(key for key in source_config.keys() | target_config.keys() + if source_config.get(key) != target_config.get(key)) + raise RuntimeError(f'{name}: rootless Docker changed application fields: {", ".join(changed)}') + if target_host.get("PortBindings") != source_host.get("PortBindings"): + raise RuntimeError(f"{name}: rootless Docker changed the published ports") + if target_host.get("RestartPolicy") != source_host.get("RestartPolicy"): + raise RuntimeError(f"{name}: rootless Docker changed the restart policy") + if target_host.get("LogConfig") != source_host.get("LogConfig"): + raise RuntimeError(f"{name}: rootless Docker changed the logging policy") + + +def local_command(args): + if args[0] == SOURCE: + return ["sudo", "/usr/bin/docker", "--host", "unix:///run/docker.sock", *args[1:]] + if args[0] == TARGET: + runtime = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}" + return ["/usr/bin/docker", "--host", f"unix://{runtime}/docker.sock", *args[1:]] + if args[0] == "target-namespace": + runtime = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") + child_pid = (runtime / "dockerd-rootless/child_pid").read_text().strip() + if not child_pid.isdigit() or int(child_pid) <= 1: + raise RuntimeError("cannot identify the rootless Docker namespace") + return ["/usr/bin/nsenter", "-U", "--preserve-credentials", "-m", "-t", child_pid, *args[1:]] + return args + + +def run(*args, capture=False): + environment = os.environ.copy() + if args[0] == TARGET: + runtime = environment.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}" + config = Path(runtime) / "omarchy-rootless-docker-migration-client" + config.mkdir(mode=0o700, exist_ok=True) + environment["DOCKER_CONFIG"] = str(config) + environment.pop("DOCKER_CONTEXT", None) + result = subprocess.run(local_command(args), check=True, text=True, capture_output=capture, env=environment) + return result.stdout.strip() if capture else None + + +def inspect(engine, kind, name): + return json.loads(run(engine, kind, "inspect", name, capture=True))[0] + + +def exists(kind, name): + result = subprocess.run(local_command([TARGET, kind, "inspect", name]), + text=True, capture_output=True) + if result.returncode == 0: + return True + subprocess.run(local_command([TARGET, "info"]), check=True, + text=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + return False + + +def destination_volume(container, mount): + explicit = any(binding.split(":")[0] == mount["Name"] + for binding in container["HostConfig"].get("Binds") or []) + explicit = explicit or any(requested.get("Source") == mount["Name"] + for requested in container["HostConfig"].get("Mounts") or []) + return mount["Name"] if explicit else f'omarchy-migrated-{mount["Name"]}' + + +def completion_path(identity): + if not re.fullmatch(r"[a-f0-9]{64}", identity): + raise ValueError("Unsupported Docker container identity") + return Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state") / "omarchy/rootless-docker-migration" / identity + + +def completed(container, target): + if (target["Config"].get("Labels") or {}).get(LABEL) != container["Id"]: + return False + receipt = completion_path(container["Id"]) + if not receipt.is_file(): + return False + try: + saved = json.loads(receipt.read_text()) + return (saved["target"] == target.get("Id") and + saved["source"] == stopped_identity(container["State"]) and + isinstance(saved["target_running"], bool) and + saved["target_running"] == bool(target["State"]["Running"]) and + saved["source_snapshot"] == snapshot_digest(container) and + saved["target_snapshot"] == snapshot_digest(target)) + except (ValueError, KeyError, TypeError): + # Older identity-only receipts cannot prove the source stayed stopped. + return False + + +def stopped_identity(state): + if state["Running"] or not state.get("StartedAt") or not state.get("FinishedAt"): + raise ValueError("Docker source was restarted or its stopped state cannot be verified") + return {key: state[key] for key in ("StartedAt", "FinishedAt")} + + +def record_completion(container, source_state, target_running): + target = inspect(TARGET, "container", container["Name"].lstrip("/")) + receipt = completion_path(container["Id"]) + receipt.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + temporary = receipt.with_suffix(f".tmp-{os.getpid()}") + try: + descriptor = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(descriptor, "w") as output: + json.dump({"target": target["Id"], "source": stopped_identity(source_state), + "target_running": target_running, + "source_snapshot": snapshot_digest(container), + "target_snapshot": snapshot_digest(target)}, output) + output.write("\n") + output.flush() + os.fsync(output.fileno()) + temporary.replace(receipt) + finally: + temporary.unlink(missing_ok=True) + + +def validate(container): + name = container["Name"].lstrip("/") + if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]*", name): + raise ValueError("Unsupported container name") + if not re.fullmatch(r"[a-f0-9]{64}", container["Id"]): + raise ValueError("Unsupported Docker container identity") + validate_security(container) + if container["Config"].get("Domainname"): + raise ValueError(f"{name}: custom domain names require an explicit rootless Docker configuration") + health = container["Config"].get("Healthcheck") or {} + if health.get("StartInterval"): + raise ValueError(f"{name}: custom health start intervals require an explicit configuration") + host = container["HostConfig"] + if host.get("NetworkMode") not in ("default", "bridge"): + raise ValueError(f"{name}: custom networking requires its original Compose definition") + # Connecting another network does not update HostConfig.NetworkMode. + # Only the stock bridge attachment can be recreated without losing intent. + networks = container.get("NetworkSettings", {}).get("Networks") or {} + if set(networks) != {"bridge"}: + raise ValueError(f"{name}: custom network attachments require its original Compose definition") + if any(networks["bridge"].get(key) for key in ("IPAMConfig", "Links", "DriverOpts", "Aliases")): + raise ValueError(f"{name}: custom network addressing or aliases need an explicit migration") + if not isinstance(host.get("ShmSize"), int) or host["ShmSize"] <= 0: + raise ValueError(f"{name}: unsupported ShmSize") + if (host.get("PidsLimit") not in (None, 0, -1) and + (not isinstance(host["PidsLimit"], int) or host["PidsLimit"] <= 0)): + raise ValueError(f"{name}: unsupported PidsLimit") + if host.get("PidMode") or host.get("UTSMode") or host.get("UsernsMode"): + raise ValueError(f"{name}: custom namespaces need an explicit rootless Docker configuration") + if host.get("IpcMode") not in (None, "", "private"): + raise ValueError(f"{name}: custom IPC requires its original Compose definition") + for port, bindings in (host.get("PortBindings") or {}).items(): + if not re.fullmatch(r"\d+/(tcp|udp)", port): + raise ValueError(f"{name}: unsupported port {port}") + for binding in bindings or []: + if binding.get("HostIp") != "127.0.0.1" or not binding.get("HostPort", "").isdigit(): + raise ValueError(f"{name}: only the stock localhost port bindings can migrate automatically") + minimum = int(Path("/proc/sys/net/ipv4/ip_unprivileged_port_start").read_text()) + if not max(1, minimum) <= int(binding["HostPort"]) <= 65535: + raise ValueError(f"{name}: published port needs explicit handling; host policy will not be weakened") + validate_volumes(container) + return name + + +def pipe(producer, consumer): + with subprocess.Popen(local_command(producer), stdout=subprocess.PIPE) as source: + try: + destination = subprocess.run(local_command(consumer), stdin=source.stdout, check=False) + source.stdout.close() + source_code = source.wait() + except BaseException: + source.kill() + source.wait() + raise + if source_code or destination.returncode: + raise RuntimeError("Container image or volume transfer failed; Docker data was retained") + + +def transfer_volume(volume, target): + destination = inspect(TARGET, "volume", target)["Mountpoint"] + # Native tar inside RootlessKit's user/mount namespace preserves numeric + # container ownership, root mode, PAX timestamps, ACLs and xattrs. + pipe(["sudo", "tar", "--format=pax", "--numeric-owner", "--sparse", "--acls", "--xattrs", + "--xattrs-include=*", "-C", volume["Mountpoint"], "-cpf", "-", "."], + ["target-namespace", "/usr/bin/tar", "--numeric-owner", "--same-owner", "--same-permissions", + "--sparse", "--acls", "--xattrs", "--xattrs-include=*", "-C", destination, "-xpf", "-"]) + manifest = str(Path(__file__).with_name("volume-manifest.py")) + source_digest = run("sudo", "python3", manifest, volume["Mountpoint"], capture=True) + verify_volume(target, source_digest) + return source_digest + + +def verify_volume(target, expected): + destination = inspect(TARGET, "volume", target)["Mountpoint"] + manifest = str(Path(__file__).with_name("volume-manifest.py")) + target_digest = run("target-namespace", "/usr/bin/python3", manifest, destination, capture=True) + if expected != target_digest: + raise RuntimeError("Volume content or metadata verification failed; Docker data was retained") + + +def source_snapshot(container): + # Health probes and process IDs are observations, not workload settings. + # Keep lifecycle timestamps/flags, complete creation/runtime configuration, + # attachments and security labels so a batch cannot use an obsolete plan. + fields = ("Id", "Name", "Image", "Config", "HostConfig", "Mounts", "NetworkSettings", + "AppArmorProfile", "ProcessLabel", "MountLabel", "RestartCount") + snapshot = {field: container.get(field) for field in fields} + snapshot["State"] = {key: value for key, value in container["State"].items() if key not in ("Health", "Pid")} + return snapshot + + +def snapshot_digest(container): + fields = ("Id", "Name", "Image", "Config", "HostConfig", "Mounts", + "AppArmorProfile", "ProcessLabel", "MountLabel") + snapshot = {field: container.get(field) for field in fields} + networks = container.get("NetworkSettings", {}).get("Networks") or {} + snapshot["Networks"] = { + name: {key: network.get(key) for key in ("IPAMConfig", "Links", "Aliases", "DriverOpts")} + for name, network in networks.items() + } + encoded = json.dumps(snapshot, sort_keys=True, separators=(",", ":")) + return hashlib.sha256(encoded.encode()).hexdigest() + + +def refresh_source(container): + latest = inspect(SOURCE, "container", container["Id"]) + if source_snapshot(latest) != source_snapshot(container): + raise ValueError(f'{container["Name"].lstrip("/")}: Docker source changed after preflight; rerun migration after workloads are stable') + validate(latest) + return latest + + +def migrate(container): + container = refresh_source(container) + name = container["Name"].lstrip("/") + identity = container["Id"] + if exists("container", name): + target = inspect(TARGET, "container", name) + container = refresh_source(container) + if completed(container, target): + print(f"{name}: already migrated") + return + raise ValueError(f"{name}: an existing rootless Docker container needs review; no completed transfer matches it") + if completion_path(identity).exists(): + raise ValueError(f"{name}: a previously migrated destination is missing; inspect retained data before retrying") + + container = refresh_source(container) + running = container["State"]["Running"] + created = False + image_loaded = False + start_attempted = False + restart_changed = False + new_volumes = [] + verified_volumes = {} + try: + run(SOURCE, "stop", "-t", "120", identity) + state = inspect(SOURCE, "container", identity)["State"] + if state["Running"] or (running and state["ExitCode"] in (137, 139)): + raise RuntimeError(f"{name}: container did not stop cleanly; transfer aborted") + stopped_identity(state) + # Container names allow uppercase, repeated dots and lengths that image + # repositories reject. The full engine ID is a valid, unique image tag. + image = f"omarchy-migrated:{identity}" + # Commit includes writable-layer changes and the exact image config. + # Volume data is copied separately while the source container is stopped. + run(SOURCE, "commit", identity, image) + pipe([SOURCE, "image", "save", image], [TARGET, "image", "load", "--quiet"]) + image_loaded = True + run(SOURCE, "image", "rm", image) + arguments = [TARGET, "create", "--pull=never", "--name", name, + "--label", f"{LABEL}={identity}", "--privileged=false", + "--ipc=private", "--cgroupns=private", "--network=bridge"] + arguments += runtime_arguments(container) + config = container["Config"] + if config.get("Hostname"): + arguments += ["--hostname", config["Hostname"]] + if config.get("StopTimeout") is not None: + arguments += ["--stop-timeout", str(config["StopTimeout"])] + for field, stream in (("AttachStdin", "stdin"), ("AttachStdout", "stdout"), ("AttachStderr", "stderr")): + if config.get(field): + arguments += ["--attach", stream] + if config.get("Tty"): + arguments += ["--tty"] + if config.get("OpenStdin"): + arguments += ["--interactive"] + restart = container["HostConfig"].get("RestartPolicy") or {} + policy = restart.get("Name") or "no" + if policy == "on-failure" and restart.get("MaximumRetryCount"): + policy += f':{restart["MaximumRetryCount"]}' + arguments += ["--restart", policy] + for port, bindings in (container["HostConfig"].get("PortBindings") or {}).items(): + for binding in bindings or []: + arguments += ["--publish", f'127.0.0.1:{binding["HostPort"]}:{port}'] + for mount in container.get("Mounts", []): + volume = inspect(SOURCE, "volume", mount["Name"]) + if volume.get("Options"): + raise ValueError(f"{name}: volume driver options require an explicit transfer") + target = destination_volume(container, mount) + if exists("volume", target): + raise ValueError(f"{name}: destination volume already exists; retained it for inspection") + volume_arguments = [TARGET, "volume", "create"] + for key, value in (volume.get("Labels") or {}).items(): + volume_arguments += ["--label", f"{key}={value}"] + run(*volume_arguments, target) + new_volumes.append(target) + verified_volumes[target] = transfer_volume(volume, target) + mount_arg = f'type=volume,src={target},dst={mount["Destination"]},volume-nocopy' + if not mount.get("RW"): + mount_arg += ",readonly" + arguments += ["--mount", mount_arg] + arguments.append(image) + run(*arguments) + created = True + # The container has not started, and volume-nocopy prevents image data + # from replacing the restored volume contents. + verify_runtime(container) + for target, expected in verified_volumes.items(): + verify_volume(target, expected) + # A later workload may fail, leaving Docker installed. Prevent a daemon + # restart from reviving this stale source alongside its migrated copy. + restart_changed = True + run(SOURCE, "update", "--restart=no", identity) + source_after = inspect(SOURCE, "container", identity) + if stopped_identity(source_after["State"]) != stopped_identity(state): + raise RuntimeError(f"{name}: Docker source restarted during transfer; inspect both engines") + if running: + # Even a failed start command may have launched an application that + # accepted writes. From this point the destination is recovery data. + start_attempted = True + run(TARGET, "start", name) + # A crash before this receipt leaves the destination for review. Its + # label alone must never turn a partial transfer into a successful retry. + target_state = inspect(TARGET, "container", name)["State"] + if bool(target_state["Running"]) != bool(running): + raise RuntimeError(f"{name}: destination lifecycle differs from the source") + record_completion(source_after, state, bool(running)) + print(f"{name}: migrated to rootless Docker; rootful copy retained for recovery") + except BaseException: + if start_attempted: + print(f"{name}: destination start was attempted; both copies were retained for recovery. " + "Inspect rootless Docker before resuming the rootful copy or retrying migration.", file=sys.stderr) + raise + recovery = [] + if created: + recovery.append((TARGET, "rm", "--force", name)) + for volume in new_volumes: + recovery.append((TARGET, "volume", "rm", volume)) + if image_loaded: + recovery.append((TARGET, "image", "rm", image)) + if restart_changed: + recovery.append((SOURCE, "update", f"--restart={policy}", identity)) + if running: + recovery.append((SOURCE, "start", identity)) + for command in recovery: + try: + run(*command) + except Exception: + # A failed cleanup must not prevent trying to restart Docker. + print(f"{name}: a recovery step failed; inspect both engines before retrying", file=sys.stderr) + raise + + +def main(): + if os.geteuid() == 0: + raise ValueError("Run the migration as the desktop user; the destination is always rootless") + os.environ.setdefault("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}") + check_completed = sys.argv[1:2] == ["--check-completed"] + check_only = check_completed or sys.argv[1:2] == ["--check"] + names = sys.argv[2:] if check_only else sys.argv[1:] + if names: + validate_source_daemon(daemon_security(SOURCE)) + validate_target_daemon(daemon_security(TARGET)) + containers = [inspect(SOURCE, "container", name) for name in names] + volumes = set() + blockers = [] + for container in containers: + try: + validate(container) + except ValueError as error: + blockers.append(str(error)) + continue + for mount in container.get("Mounts", []): + volume = inspect(SOURCE, "volume", mount["Name"]) + if volume.get("Options") or mount["Name"] in volumes: + blockers.append(f'{container["Name"].lstrip("/")}: custom or shared volumes require an explicit transfer') + volumes.add(mount["Name"]) + if blockers: + raise ValueError("\n".join(blockers)) + if check_completed: + for container in containers: + name = container["Name"].lstrip("/") + if (not exists("container", name) or + not completed(container, inspect(TARGET, "container", name)) or + (container["HostConfig"].get("RestartPolicy") or {}).get("Name") != "no"): + raise ValueError(f"{name}: completed transfer changed; Docker must remain available for recovery") + return + if not check_only: + # Check all destination names before stopping the first source. + for container in containers: + name = container["Name"].lstrip("/") + if exists("container", name): + target = inspect(TARGET, "container", name) + if not completed(container, target): + raise ValueError(f"{name}: an existing rootless Docker container needs review; no completed transfer matches it") + continue + if completion_path(container["Id"]).exists(): + raise ValueError(f"{name}: a previously migrated destination is missing; inspect retained data before retrying") + for mount in container.get("Mounts", []): + if exists("volume", destination_volume(container, mount)): + raise ValueError(f"{name}: destination volume already exists; retained it for inspection") + if check_only: + for container in containers: + print(f'{container["Name"].lstrip("/")}: ready for rootless Docker migration') + if not check_only: + for container in containers: + migrate(container) + + +if __name__ == "__main__": + try: + main() + except subprocess.CalledProcessError as error: + # Do not print argv: health commands and volume labels can hold secrets. + print(f"Rootless Docker migration command failed (exit {error.returncode}); rootful Docker data was retained", file=sys.stderr) + sys.exit(1) + except (ValueError, RuntimeError) as error: + print(f"Rootless Docker migration stopped: {error}", file=sys.stderr) + sys.exit(1) diff --git a/default/docker/rootless/volume-manifest.py b/default/docker/rootless/volume-manifest.py new file mode 100644 index 000000000000..f39b3cb058ac --- /dev/null +++ b/default/docker/rootless/volume-manifest.py @@ -0,0 +1,45 @@ +"""Fingerprint a quiesced volume, using the caller's numeric UID/GID namespace.""" + +import hashlib +import json +import os +from pathlib import Path +import stat +import sys + + +def fingerprint(root): + digest = hashlib.sha256() + hardlinks = {} + + def visit(path, relative): + info = path.lstat() + # Unix sockets are transient process endpoints; tar does not copy them. + if stat.S_ISSOCK(info.st_mode): + return + attributes = [(name, os.getxattr(path, name, follow_symlinks=False).hex()) + for name in sorted(os.listxattr(path, follow_symlinks=False))] + row = [str(relative), stat.S_IFMT(info.st_mode), stat.S_IMODE(info.st_mode), + info.st_uid, info.st_gid, info.st_mtime_ns, attributes] + if stat.S_ISREG(info.st_mode): + contents = hashlib.sha256() + with path.open('rb') as source: + for block in iter(lambda: source.read(1024 * 1024), b''): + contents.update(block) + first_link = hardlinks.setdefault((info.st_dev, info.st_ino), str(relative)) + row += [info.st_size, contents.hexdigest(), first_link] + elif stat.S_ISLNK(info.st_mode): + row.append(os.readlink(path)) + elif stat.S_ISCHR(info.st_mode) or stat.S_ISBLK(info.st_mode): + row.append(info.st_rdev) + digest.update(json.dumps(row, ensure_ascii=True, separators=(',', ':')).encode() + b'\n') + if stat.S_ISDIR(info.st_mode): + for child in sorted(path.iterdir(), key=lambda item: item.name): + visit(child, relative / child.name) + + visit(Path(root), Path('.')) + return digest.hexdigest() + + +if __name__ == '__main__': + print(fingerprint(sys.argv[1])) diff --git a/default/omarchy/omarchy-menu.jsonc b/default/omarchy/omarchy-menu.jsonc index 7583d8d8ce95..14740ffa1610 100644 --- a/default/omarchy/omarchy-menu.jsonc +++ b/default/omarchy/omarchy-menu.jsonc @@ -183,7 +183,6 @@ "setup.security.fido2": {"icon":"","label":"Fido2","action":"omarchy-launch-floating-terminal-with-presentation omarchy-setup-security-fido2"}, "setup.security.sshd": {"icon":"󰣀","label":"SSHD","action":"omarchy-launch-floating-terminal-with-presentation omarchy-setup-security-sshd"}, "setup.security.passwordless-sudo": {"icon":"󰟵","label":"Passwordless Sudo","action":"omarchy-launch-floating-terminal-with-presentation omarchy-sudo-passwordless"}, - "setup.security.sudoless-docker": {"icon":"󰡨","label":"Sudoless Docker","when":"omarchy-sudo-docker --configured","action":"omarchy-launch-floating-terminal-with-presentation omarchy-setup-security-sudoless-docker"}, "setup.config.hyprland": {"icon":"","label":"Hyprland","action":"omarchy-launch-config-editor \"$HOME/.config/hypr/hyprland.lua\""}, "setup.config.hyprsunset": {"icon":"","label":"Hyprsunset","action":"omarchy-launch-config-editor ~/.config/hypr/hyprsunset.conf && omarchy-restart-hyprsunset"}, "setup.config.xcompose": {"icon":"󰞅","label":"XCompose","action":"omarchy-launch-config-editor ~/.XCompose && omarchy-restart-xcompose"}, @@ -299,7 +298,6 @@ "remove.security.fingerprint": {"icon":"󰈷","label":"Fingerprint","when":"omarchy-pkg-present fprintd","action":"omarchy-launch-floating-terminal-with-presentation omarchy-remove-security-fingerprint"}, "remove.security.fido2": {"icon":"","label":"Fido2","when":"omarchy-pkg-present pam-u2f","action":"omarchy-launch-floating-terminal-with-presentation omarchy-remove-security-fido2"}, "remove.security.sshd": {"icon":"󰣀","label":"SSHD","when":"systemctl is-enabled --quiet sshd","action":"omarchy-launch-floating-terminal-with-presentation omarchy-remove-security-sshd"}, - "remove.security.sudoless-docker": {"icon":"󰡨","label":"Sudoless Docker","when":"! omarchy-sudo-docker --configured","action":"omarchy-launch-floating-terminal-with-presentation omarchy-remove-security-sudoless-docker"}, "remove.ai.hermes": {"icon":"","iconFont":"omarchy","label":"Hermes Desktop","when":"omarchy-pkg-present hermes-desktop","action":"omarchy-launch-floating-terminal-with-presentation omarchy-remove-ai-hermes"}, "remove.browser.chrome": {"icon":"","label":"Chrome","when":"omarchy-pkg-present google-chrome","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-browser chrome'"}, "remove.browser.edge": {"icon":"󰇩","label":"Edge","when":"omarchy-pkg-present microsoft-edge-stable-bin","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-browser edge'"}, diff --git a/default/systemd/system/docker.socket.d/10-omarchy-rootful.conf b/default/systemd/system/docker.socket.d/10-omarchy-rootful.conf new file mode 100644 index 000000000000..0a6b292aec3f --- /dev/null +++ b/default/systemd/system/docker.socket.d/10-omarchy-rootful.conf @@ -0,0 +1,4 @@ +[Socket] +SocketUser=root +SocketGroup=root +SocketMode=0600 diff --git a/default/systemd/user-environment-generators/60-omarchy-rootless-docker b/default/systemd/user-environment-generators/60-omarchy-rootless-docker new file mode 100755 index 000000000000..28bf653f8bed --- /dev/null +++ b/default/systemd/user-environment-generators/60-omarchy-rootless-docker @@ -0,0 +1,6 @@ +#!/bin/sh + +if [ -f "$HOME/.local/state/omarchy/rootless-docker/enabled" ]; then + runtime_dir=${XDG_RUNTIME_DIR:-/run/user/$(id -u)} + printf 'DOCKER_HOST=unix://%s/docker.sock\n' "$runtime_dir" +fi diff --git a/docs/file-layout.md b/docs/file-layout.md index f261085f0eae..756b5c8c5181 100644 --- a/docs/file-layout.md +++ b/docs/file-layout.md @@ -124,6 +124,8 @@ default/** ──► omarchy-settings /usr/share/omarchy ├─ xdg-terminal-exec/*.list /usr/share/xdg-terminal-exec/ ├─ applications/mimeapps.list /usr/share/applications/mimeapps.list ├─ systemd/user/*.service /usr/lib/systemd/user/ + ├─ systemd/user-environment-generators/* /usr/lib/systemd/user-environment-generators/ + ├─ systemd/system/docker.socket.d/* /usr/lib/systemd/system/docker.socket.d/ ├─ systemd/user/app.slice.d/10-oomd.conf /usr/lib/systemd/user/app.slice.d/ ├─ systemd/system-sleep/unmount-fuse /usr/lib/systemd/system-sleep/ ├─ systemd/zram-generator.conf.d/90-omarchy.conf /usr/lib/systemd/zram-generator.conf.d/ diff --git a/docs/rootless-docker.md b/docs/rootless-docker.md new file mode 100644 index 000000000000..49328119d266 --- /dev/null +++ b/docs/rootless-docker.md @@ -0,0 +1,25 @@ +# Rootless Docker + +Omarchy runs ordinary development containers in a per-user rootless Docker daemon while retaining a separate rootful Docker daemon for the Windows VM. This keeps the Docker CLI, Compose, Buildx, and image format unchanged while removing the root-equivalent `docker` group from the development path. + +## Runtime boundary + +The user daemon is `docker.service` from `docker-rootless-extras`. It listens on `$XDG_RUNTIME_DIR/docker.sock`, stores engine data below `~/.local/share/docker`, and reads daemon configuration from `~/.config/docker/daemon.json`. `default/systemd/user-environment-generators/60-omarchy-rootless-docker` and `default/bash/env-bootstrap` export `DOCKER_HOST` only after `~/.local/state/omarchy/rootless-docker/enabled` exists. + +The system daemon remains socket-activated for `omarchy-windows-vm`. Its vendor drop-in makes `/run/docker.sock` root-owned with mode `0600`, and the Windows command always selects that socket explicitly after authenticating with `sudo` or `pkexec`. User Docker settings and `DOCKER_HOST` cannot redirect the privileged VM command. + +## Fresh installs and additional users + +The root setup allocates each account a nonoverlapping subordinate UID and GID range of at least 65,536 IDs, enables the rootless service globally, and writes `/var/lib/omarchy/rootless-docker/enabled`. User finalization then creates the private marker and daemon config before first login starts the service. + +The migration's machine-wide enabled marker is written only after the shared rootful inventory has migrated and `/run/docker.sock` has been restricted. When another account later runs the per-user migration, it initializes that account's rootless daemon and returns before inspecting the retained rootful recovery store. + +## Existing-install migration + +`migrations/1789164756.sh` installs the rootless runtime, allocates subordinate IDs, starts and proves the rootless daemon, claims the machine-wide source inventory for one account, and preflights every rootful container except `omarchy-windows`. A blocker in any source prevents the batch from stopping its first container. + +The automatic path accepts stock bridge networking with localhost-only unprivileged published ports, private local named volumes, supported resource limits, the stock runtime and namespace boundaries, and Docker's default capability ceiling or stricter settings. It rejects privileged containers, added capabilities, devices, host or shared mounts, custom networks, namespace sharing, custom runtimes, altered confinement, custom logging, and unknown nondefault host settings. + +For each accepted container, the migrator stops the source cleanly, commits its writable layer, transfers that image through Docker's native save/load format, copies named-volume contents and metadata inside the RootlessKit user and mount namespace, and recreates the container with explicit private and restrictive settings. It verifies environment, application config, limits, capabilities, mounts, ports, restart policy, logging, volume fingerprints, and lifecycle before writing a receipt bound to full source and destination snapshots. + +Before the destination is first started, an error removes newly created destination objects and restores the source. Once a destination start has been attempted, both copies remain stopped or in their observed state for manual recovery because either side may contain new writes. Successful sources remain stopped with their restart policy disabled; they are retained in the rootful engine as recovery copies. diff --git a/install/config/docker.sh b/install/config/docker.sh index 397439057648..19112e8c2300 100644 --- a/install/config/docker.sh +++ b/install/config/docker.sh @@ -1,16 +1,11 @@ -# The Docker daemon runs as root and its socket is root-owned, so membership in -# the docker group is equivalent to passwordless root: any process in it can -# `docker run -v /:/host` and rewrite the host as root. We therefore do NOT add -# the install user to the docker group by default, so a single rogue process -# running as the user cannot silently escalate to root. -# -# The daemon is still enabled (docker.socket, in enable-services.sh) for system -# use. The Docker TUI (Super + Shift + D) and the Windows VM reach it through a -# polkit prompt, and the plain `docker` CLI runs under sudo. Users who want the -# convenience back can opt in, behind a warning, with: -# -# omarchy-setup-security-sudoless-docker (Setup > Security > Sudoless Docker) -# -# Nothing to do here now that the group is no longer granted, but the file stays -# as the recorded home of this decision and a hook for future daemon config. -: +# Development containers run in the install user's rootless daemon. The system +# daemon remains socket-activated for the Windows VM, whose KVM/TUN devices need +# an authenticated rootful boundary. +source "$OMARCHY_INSTALL/helpers/rootless-docker.sh" + +if [[ -n ${OMARCHY_INSTALL_USER:-} ]]; then + rootless_docker_ensure_subids "$OMARCHY_INSTALL_USER" +fi + +install -d -m 0755 /var/lib/omarchy/rootless-docker +install -m 0644 /dev/null /var/lib/omarchy/rootless-docker/enabled diff --git a/install/config/enable-services.sh b/install/config/enable-services.sh index 964f08675f91..d2bc653efd47 100644 --- a/install/config/enable-services.sh +++ b/install/config/enable-services.sh @@ -3,7 +3,10 @@ systemctl enable cups.service systemctl enable avahi-daemon.service systemctl enable linux-modules-cleanup.service +# The root-owned socket is reserved for authenticated Windows VM operations. systemctl enable docker.socket +# Development containers use each desktop user's rootless daemon. +systemctl --global enable docker.service systemctl enable systemd-resolved.service systemctl enable NetworkManager.service # Don't let network-online.target hold up graphical.target waiting for diff --git a/install/helpers/rootless-docker.sh b/install/helpers/rootless-docker.sh new file mode 100644 index 000000000000..b0ff2c797b42 --- /dev/null +++ b/install/helpers/rootless-docker.sh @@ -0,0 +1,60 @@ +rootless_docker_ensure_subids() { + local account="$1" + + /usr/bin/python3 - "$account" <<'PY' +import fcntl +import os +import pwd +import stat +import subprocess +import sys + + +account = pwd.getpwnam(sys.argv[1]) +if account.pw_uid == 0: + raise SystemExit("rootless Docker cannot be configured for root") + +lock_path = "/run/lock/omarchy-rootless-docker-subids.lock" +fd = os.open(lock_path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) +with os.fdopen(fd, "w") as lock: + metadata = os.fstat(lock.fileno()) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != 0 or metadata.st_mode & 0o022: + raise SystemExit(f"unsafe subordinate-ID lock: {lock_path}") + fcntl.flock(lock, fcntl.LOCK_EX) + + for path, option in (("/etc/subuid", "--add-subuids"), ("/etc/subgid", "--add-subgids")): + ranges = [] + try: + with open(path, encoding="utf-8") as source: + for number, line in enumerate(source, 1): + line = line.strip() + if not line or line.startswith("#"): + continue + try: + name, start, count = line.split(":") + start, count = int(start), int(count) + except ValueError as error: + raise SystemExit(f"cannot parse {path}:{number}") from error + if start < 0 or count <= 0 or start + count - 1 > 4294967295: + raise SystemExit(f"invalid subordinate-ID range in {path}:{number}") + ranges.append((name, start, count)) + except FileNotFoundError: + pass + + identities = {account.pw_name, str(account.pw_uid)} + owned = [(start, count) for name, start, count in ranges if name in identities] + for owned_start, owned_count in owned: + if any(other_name not in identities and + max(owned_start, other_start) < min(owned_start + owned_count, other_start + other_count) + for other_name, other_start, other_count in ranges): + raise SystemExit(f"overlapping subordinate-ID range for {account.pw_name} in {path}") + if any(count >= 65536 for _, count in owned): + continue + + start = max([100000, *(range_start + count for _, range_start, count in ranges)]) + end = start + 65535 + if end > 4294967295: + raise SystemExit(f"no subordinate-ID range is available in {path}") + subprocess.run(["/usr/bin/usermod", option, f"{start}-{end}", account.pw_name], check=True) +PY +} diff --git a/install/omarchy-base.packages b/install/omarchy-base.packages index 76e741108cf6..743ca47a3023 100644 --- a/install/omarchy-base.packages +++ b/install/omarchy-base.packages @@ -23,6 +23,7 @@ ddcutil docker docker-buildx docker-compose +docker-rootless-extras dosfstools dotnet-runtime dua-cli @@ -40,6 +41,7 @@ ffmpegthumbnailer fontconfig foot fzf +fuse-overlayfs git gnome-keyring gnome-themes-extra @@ -112,9 +114,11 @@ qt6-multimedia qt6-multimedia-ffmpeg quickshell ripgrep +rootlesskit ruby tensaku sddm +slirp4netns slurp socat starship diff --git a/install/user/all.sh b/install/user/all.sh index 39d98ea57f44..5c3cdadcfdda 100644 --- a/install/user/all.sh +++ b/install/user/all.sh @@ -2,6 +2,7 @@ run_logged "$OMARCHY_INSTALL/user/theme.sh" run_logged "$OMARCHY_INSTALL/user/chromium.sh" run_logged "$OMARCHY_INSTALL/user/git.sh" run_logged "$OMARCHY_INSTALL/user/xcompose.sh" +run_logged "$OMARCHY_INSTALL/user/docker.sh" run_logged "$OMARCHY_INSTALL/user/mise-work.sh" run_logged "$OMARCHY_INSTALL/user/hardware/asus/fix-audio-mixer.sh" diff --git a/install/user/docker.sh b/install/user/docker.sh new file mode 100644 index 000000000000..5c2752f4479f --- /dev/null +++ b/install/user/docker.sh @@ -0,0 +1,11 @@ +rootless_state="$HOME/.local/state/omarchy/rootless-docker" + +if [[ -f /var/lib/omarchy/rootless-docker/enabled ]]; then + mkdir -p "$rootless_state" "$HOME/.config/docker" + touch "$rootless_state/enabled" + chmod 0600 "$rootless_state/enabled" + + if [[ ! -e $HOME/.config/docker/daemon.json ]]; then + install -m 0644 "$OMARCHY_PATH/config/docker/daemon.json" "$HOME/.config/docker/daemon.json" + fi +fi diff --git a/install/user/first-run/enable-user-units.sh b/install/user/first-run/enable-user-units.sh index 9865fc207e4c..04ec096374e6 100755 --- a/install/user/first-run/enable-user-units.sh +++ b/install/user/first-run/enable-user-units.sh @@ -13,6 +13,7 @@ set -euo pipefail systemctl --user daemon-reload systemctl --user enable --now \ + docker.service \ bt-agent.service \ omarchy-recover-internal-monitor.service \ omarchy-sleep-lock.service \ diff --git a/manual/18-development-tools.md b/manual/18-development-tools.md index f49125d9e7ce..740dc4ec06f0 100644 --- a/manual/18-development-tools.md +++ b/manual/18-development-tools.md @@ -20,11 +20,13 @@ To install, say, Ruby, you'd run `mise use -g ruby`, which will both install Rub ## Docker -[Docker](https://www.docker.com/) hardly needs any introduction. It allows you to run isolated containers, and Omarchy installs everything needed to run it well, including Docker itself and [Docker Compose](https://docs.docker.com/compose/). +[Docker](https://www.docker.com/) hardly needs any introduction. It allows you to run isolated containers, and Omarchy installs everything needed to run it well, including Docker itself, [Docker Compose](https://docs.docker.com/compose/), Buildx, and a rootless Docker daemon for your account. -By default your user is *not* in the `docker` group. That group is effectively passwordless root — anything in it can `docker run -v /:/host` and take over the machine — so a single rogue script or dependency running as you would otherwise be one command away from root. So on the command line you run Docker with `sudo` (`sudo docker ps`, `sudo docker compose up`), and the graphical tools that talk to the daemon — the Docker TUI on `Super + Shift + D` and the Windows VM — ask for authorization when they need it. If you want the convenience of a groupless setup back and understand the tradeoff, enable it from **Setup > Security > Sudoless Docker** (or run `omarchy-setup-security-sudoless-docker`), which adds you to the `docker` group after a warning; then plain `docker` and the `d` alias work without `sudo` again. +The daemon for development containers runs as your user and keeps its data in your home directory. Plain `docker`, `docker compose`, `docker buildx`, and the `d` alias use it directly, without `sudo` and without membership in the root-equivalent `docker` group. A container that escapes this daemon reaches only your user privileges rather than root privileges on the host. -Remember to checkout the Lazydocker command to manage your containers in a cool TUI using `Super + Shift + D`; it asks for authorization the first time unless you have enabled sudoless Docker. +Existing installs automatically move compatible development containers and private named volumes into the rootless Docker store during update. The old rootful containers remain stopped as recovery copies. Containers that depend on elevated privileges, host directories, devices, custom runtimes, or custom networks stay untouched and stop the migration with an explanation so Omarchy never silently weakens or changes their access. + +Remember to check out Lazydocker to manage your development containers in a cool TUI using `Super + Shift + D`. It connects to the same rootless daemon and does not need an authorization prompt. You can setup the common databases for local development in Docker using _Install > Development > Docker DB_ in the Omarchy menu. diff --git a/manual/28-windows-vm.md b/manual/28-windows-vm.md index 0551b23f9d40..e87acd101e48 100644 --- a/manual/28-windows-vm.md +++ b/manual/28-windows-vm.md @@ -2,6 +2,8 @@ Omarchy offers an easy way to run Windows through a Docker VM. You can install it using _Install > Windows_ from the Omarchy menu (`Super + Space`). +Windows needs KVM, TUN, and network administration access that a rootless development container cannot receive safely. Omarchy therefore keeps the Windows VM on a separate rootful Docker daemon whose socket is accessible only to root. Starting, stopping, checking, changing, or removing the VM asks for `sudo` in a terminal or shows the system authorization prompt when launched graphically. Development containers continue to use your rootless Docker daemon. + Your machine needs KVM virtualization for this, which most do — but it's sometimes switched off in the BIOS, and the installer will tell you if that's the case. You'll also want the disk space: whatever you give Windows, plus about 10GB for the image itself. The installer asks how much RAM, how many CPU cores, and how much disk to hand over (64GB or more is the sensible floor), then for a Windows username and password. Leave those blank and you get `docker` / `admin`. The download takes a while — 10-15 minutes is normal — and you can follow the progress in the browser at `http://127.0.0.1:8006`. The browser prompts for the same username and password before opening the console. diff --git a/manual/48-security.md b/manual/48-security.md index 45750398e309..064e794689e6 100644 --- a/manual/48-security.md +++ b/manual/48-security.md @@ -8,6 +8,14 @@ Omarchy takes security extremely seriously. This is meant to be an operating sys 4. *Omarchy maintains its own packages and mirror*: Omarchy only relies on packages from Arch's own core/extra/multilib repositories and its own Omarchy Package Repository by default. You can install software directly from AUR, but the base install doesn't — only a few optional installs, like the third-party browsers, pull from the AUR. 5. *Cloudflare protects us from DDoS*: All the Omarchy distribution infrastructure — the ISOs, the Omarchy packages, the Arch mirror — is protected behind Cloudflare's formidable DDoS shield and hosted on their CDN. This provides superb availability. +## Docker isolation + +Development containers run in a rootless Docker daemon owned by your account. The normal Docker CLI, Compose, Buildx, the Docker database helpers, and Lazydocker all connect to that daemon without `sudo`; your account is not placed in the root-equivalent `docker` group. + +The Windows VM needs host devices and elevated networking, so it uses a separate rootful Docker daemon. Its API socket is owned by root with mode `0600`, its Compose definition and secrets are root-only, and every VM operation requires `sudo` or the graphical system authorization prompt. + +During an upgrade, Omarchy preflights the complete rootful development-container inventory before stopping anything. It automatically transfers only containers whose behavior can be reproduced safely in rootless Docker, verifies their images, settings, private named-volume contents and metadata, and then leaves the rootful copies stopped for recovery. A privileged container, host bind mount, device, shared volume, custom runtime, custom network, or unknown nondefault setting stops the migration and leaves the original workloads unchanged. + ## Changing your passwords You have two passwords on an encrypted install: the one that unlocks the drive at boot, and the one you log in and `sudo` with. Both can be changed under _Update > Password_ in the Omarchy menu — _Drive Encryption_ for the first, _User_ for the second. Changing the drive password asks for the current one first, so have it handy. diff --git a/migrations/1787580187.sh b/migrations/1787580187.sh index cf07cc6624ae..e24e54c78bc9 100644 --- a/migrations/1787580187.sh +++ b/migrations/1787580187.sh @@ -1,22 +1,18 @@ -echo "Move this install to the opt-in docker group default (the group is root-equivalent)" +echo "Remove root-equivalent Docker group access" # The docker group grants passwordless root (a container can bind-mount / and -# rewrite the host), so Omarchy no longer puts users in it by default. Bring -# existing installs in line: remove this user from the group if present. The -# change applies after a reboot, so it stays reachable until then. Anyone who -# wants passwordless docker back can opt in, behind a warning, with -# Setup > Security > Sudoless Docker. Reuses the removal command so there is one -# source of truth for the privileged change and its notice; DEFER_REBOOT keeps -# it from prompting mid-update — omarchy-update-restart handles the reboot once -# the whole update has finished. -if id -nG "$USER" | grep -qw docker; then - OMARCHY_DEFER_REBOOT=1 omarchy-remove-security-sudoless-docker +# rewrite the host), so remove the current user from it when present. The later +# rootless Docker migration provides unprivileged CLI access and restricts the +# old socket immediately; this historical step still marks the required login +# refresh and stays self-contained after retiring the old toggle commands. +docker_user=$(id -un) +if id -nG "$docker_user" | grep -qw docker; then + sudo gpasswd -d "$docker_user" docker >/dev/null + omarchy-state set reboot-required fi -# The Docker app entry copied into ~/.local/share/applications used to run -# lazydocker directly; it now needs the wrapper that prompts for daemon access -# (or runs directly under sudoless Docker). Refresh just that file. +# Refresh the Docker app entry so it uses the current rootless-aware launcher. dest="$HOME/.local/share/applications/Docker.desktop" -if [[ -f $dest ]]; then +if [[ -f $dest && -f $OMARCHY_PATH/applications/Docker.desktop ]]; then cp "$OMARCHY_PATH/applications/Docker.desktop" "$dest" fi diff --git a/migrations/1789164756.sh b/migrations/1789164756.sh new file mode 100644 index 000000000000..71624e401697 --- /dev/null +++ b/migrations/1789164756.sh @@ -0,0 +1,145 @@ +echo "Move development containers to rootless Docker" + +migration_uid=$(id -u) +migration_user=$(id -un) +if (( migration_uid == 0 )); then + echo "Run this migration as the desktop user" >&2 + exit 1 +fi + +export XDG_RUNTIME_DIR="/run/user/$migration_uid" +export DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/bus" +if ! systemctl --user show-environment >/dev/null; then + echo "Log in as $migration_user and rerun omarchy-migrate. Rootful Docker has not been changed." >&2 + exit 1 +fi + +omarchy-pkg-add docker-rootless-extras rootlesskit slirp4netns fuse-overlayfs + +# Allocate a nonoverlapping subordinate-ID range before the rootless daemon can +# open its store. The root lock also serializes simultaneous user migrations. +sudo /usr/bin/bash -euo pipefail -c ' + # This absolute path is intentional: privileged migration code must come + # from the root-owned package tree, never a caller-controlled checkout. + source /usr/share/omarchy/install/helpers/rootless-docker.sh + rootless_docker_ensure_subids "$1" +' bash "$migration_user" + +rootless_state="$HOME/.local/state/omarchy/rootless-docker" +mkdir -p "$HOME/.config/docker" "$rootless_state" +if [[ ! -e $HOME/.config/docker/daemon.json ]]; then + install -m 0644 "$OMARCHY_PATH/config/docker/daemon.json" "$HOME/.config/docker/daemon.json" +fi + +systemctl --user daemon-reload +systemctl --user enable --now docker.service +target_host="unix://$XDG_RUNTIME_DIR/docker.sock" +if ! /usr/bin/docker --host "$target_host" info >/dev/null; then + echo "Rootless Docker did not start. Rootful Docker has not been changed." >&2 + exit 1 +fi + +# Completion of the shared rootful-store migration is machine-wide. Later +# accounts only need their own rootless daemon and marker; they must never +# inspect or claim the retained recovery copies owned by the first account. +machine_state=/var/lib/omarchy/rootless-docker +if sudo /usr/bin/test -f "$machine_state/enabled"; then + sudo /usr/bin/systemctl --global enable docker.service + touch "$rootless_state/enabled" + chmod 0600 "$rootless_state/enabled" + export DOCKER_HOST="$target_host" + systemctl --user set-environment DOCKER_HOST="$DOCKER_HOST" + dbus-update-activation-environment --systemd DOCKER_HOST + echo "Rootless Docker is ready for $migration_user. The machine-wide rootful recovery store was left untouched." + exit 0 +fi + +# The rootful store is machine-wide. The first user to begin its transfer owns +# the recovery copies until the migration completes, so another account cannot +# split one source inventory across two private stores. +sudo /usr/bin/python3 - "$migration_uid" "$migration_user" <<'PY' +import fcntl +import os +from pathlib import Path +import stat +import sys + + +uid, name = int(sys.argv[1]), sys.argv[2] +root = Path("/var/lib/omarchy/rootless-docker") +root.mkdir(mode=0o755, parents=True, exist_ok=True) +lock_fd = os.open("/run/lock/omarchy-rootless-docker-owner.lock", + os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) +with os.fdopen(lock_fd, "w") as lock: + metadata = os.fstat(lock.fileno()) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != 0 or metadata.st_mode & 0o022: + raise SystemExit("unsafe rootless Docker owner lock") + fcntl.flock(lock, fcntl.LOCK_EX) + owner = root / "migration-owner" + expected = f"{uid}:{name}\n" + if owner.exists(): + if owner.is_symlink() or owner.read_text() != expected: + raise SystemExit("another user owns the rootful Docker migration; finish it from that account") + else: + temporary = root / f".migration-owner.{os.getpid()}" + fd = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, "w") as output: + output.write(expected) + output.flush() + os.fsync(output.fileno()) + temporary.replace(owner) +PY + +sudo /usr/bin/systemctl start docker.socket +source_host="unix:///run/docker.sock" +docker_inventory=$(sudo /usr/bin/docker --host "$source_host" ps -a --no-trunc --format '{{.ID}} {{.Names}}' | sort) +mapfile -t container_names < <(printf '%s\n' "$docker_inventory" | awk '$2 != "omarchy-windows" { print $2 }') + +migrator="$OMARCHY_PATH/default/docker/rootless/migrate.py" +if (( ${#container_names[@]} )); then + if ! /usr/bin/python3 "$migrator" --check "${container_names[@]}"; then + echo "Rootful Docker and its data have been retained. This migration remains pending." >&2 + exit 1 + fi + /usr/bin/python3 "$migrator" "${container_names[@]}" + /usr/bin/python3 "$migrator" --check-completed "${container_names[@]}" +fi + +latest_inventory=$(sudo /usr/bin/docker --host "$source_host" ps -a --no-trunc --format '{{.ID}} {{.Names}}' | sort) +if [[ $latest_inventory != "$docker_inventory" ]]; then + echo "Rootful Docker containers changed during migration. Both stores were retained; review them and rerun." >&2 + exit 1 +fi + +# Remove direct access to the rootful Windows daemon immediately, including for +# a login that still carries an old docker supplementary group. The packaged +# socket drop-in preserves this root-only mode after later socket activation. +sudo /usr/bin/systemctl daemon-reload +if sudo /usr/bin/test -S /run/docker.sock; then + sudo /usr/bin/setfacl -b /run/docker.sock + sudo /usr/bin/chown root:root /run/docker.sock + sudo /usr/bin/chmod 0600 /run/docker.sock +fi +socket_owner=$(sudo /usr/bin/stat -Lc '%u:%g:%a' /run/docker.sock) +if [[ $socket_owner != "0:0:600" ]]; then + echo "The rootful Docker socket could not be restricted to root. This migration remains pending." >&2 + exit 1 +fi + +if id -nG "$migration_user" | grep -qw docker; then + sudo /usr/bin/gpasswd -d "$migration_user" docker >/dev/null + omarchy-state set reboot-required +fi + +sudo /usr/bin/systemctl --global enable docker.service +sudo /usr/bin/touch /var/lib/omarchy/rootless-docker/enabled +sudo /usr/bin/chown root:root /var/lib/omarchy/rootless-docker/enabled +sudo /usr/bin/chmod 0644 /var/lib/omarchy/rootless-docker/enabled +touch "$rootless_state/enabled" +chmod 0600 "$rootless_state/enabled" + +export DOCKER_HOST="$target_host" +systemctl --user set-environment DOCKER_HOST="$DOCKER_HOST" +dbus-update-activation-environment --systemd DOCKER_HOST + +echo "Rootless Docker is ready. Rootful development containers remain stopped as recovery copies; Windows stays on authenticated rootful Docker." diff --git a/test/acceptance.d/system-test.sh b/test/acceptance.d/system-test.sh index 0d648e9c16ea..637c422e3edb 100644 --- a/test/acceptance.d/system-test.sh +++ b/test/acceptance.d/system-test.sh @@ -67,23 +67,23 @@ verify_services() { systemctl --user is-active --quiet pipewire.service pipewire-pulse.service wireplumber.service || fail "user audio services are running" pass "user audio services are running" + + systemctl --user is-enabled --quiet docker.service || fail "rootless Docker user service is enabled" + systemctl --user is-active --quiet docker.service || fail "rootless Docker user service is active" + pass "rootless Docker user service is enabled and active" } verify_runtime_tools() { - # Docker access is intentionally NOT granted to the desktop user: the docker - # group is root-equivalent, so a rogue process running as the user could - # otherwise `docker run -v /:/host` its way to passwordless root. The daemon is - # still enabled (docker.socket, checked in verify_services) and reached through - # a polkit/sudo prompt; opting into sudoless Docker is a separate, warned step. command -v docker >/dev/null 2>&1 || fail "Docker CLI is installed" ! id -nG | grep -qw docker || fail "desktop user must not be in the docker group" - # The group name being absent is not sufficient — a world-writable socket or an - # ACL would still hand the user the root daemon. Prove it is actually - # unreachable without elevation. - if timeout 10 docker info >/dev/null 2>&1; then - fail "desktop user must not reach the Docker daemon without elevation" + [[ ${DOCKER_HOST:-} == "unix://$XDG_RUNTIME_DIR/docker.sock" ]] || fail "Docker CLI points at the user's rootless socket" + timeout 10 docker info >/dev/null 2>&1 || fail "desktop user can reach rootless Docker" + docker info --format '{{json .SecurityOptions}}' | jq -e 'index("name=rootless")' >/dev/null || fail "Docker daemon does not report rootless mode" + [[ $(stat -Lc '%u:%g:%a' /run/docker.sock) == "0:0:600" ]] || fail "rootful Docker socket is not root-only" + if timeout 10 docker --host unix:///run/docker.sock info >/dev/null 2>&1; then + fail "desktop user must not reach the rootful Docker daemon" fi - pass "Docker is installed but unreachable by the desktop user without elevation" + pass "Docker development tooling is rootless and the Windows daemon remains root-only" nvim --headless '+qa' >/dev/null 2>&1 || fail "Neovim starts headlessly" pass "Neovim starts headlessly" diff --git a/test/shell.d/config-test.sh b/test/shell.d/config-test.sh index 355ca26b9e02..6523eb223504 100755 --- a/test/shell.d/config-test.sh +++ b/test/shell.d/config-test.sh @@ -139,6 +139,7 @@ package_defaults = [ ("default/uwsm/env.d/10-omarchy", "/usr/share/uwsm/env.d/10-omarchy", "uwsm/env"), ("default/uwsm/default", None, "uwsm/default"), ("default/environment.d/10-omarchy-fcitx.conf", "/usr/lib/environment.d/10-omarchy-fcitx.conf", "environment.d/fcitx.conf"), + ("default/systemd/user-environment-generators/60-omarchy-rootless-docker", "/usr/lib/systemd/user-environment-generators/60-omarchy-rootless-docker", "systemd/user-environment-generators/60-omarchy-rootless-docker"), ("default/fontconfig/conf.avail/50-omarchy.conf", "/usr/share/fontconfig/conf.avail/50-omarchy.conf", "fontconfig/fonts.conf"), ("default/xdg-terminal-exec/hyprland-xdg-terminals.list", "/usr/share/xdg-terminal-exec/hyprland-xdg-terminals.list", "xdg-terminals.list"), ("default/applications/mimeapps.list", "/usr/share/applications/mimeapps.list", "mimeapps.list"), @@ -152,6 +153,7 @@ package_defaults = [ ("default/systemd/user/omarchy-crash-watch.service", "/usr/lib/systemd/user/omarchy-crash-watch.service", "systemd/user/omarchy-crash-watch.service"), ("default/systemd/zram-generator.conf.d/90-omarchy.conf", "/usr/lib/systemd/zram-generator.conf.d/90-omarchy.conf", "systemd/zram-generator.conf.d/90-omarchy.conf"), ("default/systemd/system/plocate-updatedb.service.d/10-omarchy.conf", "/usr/lib/systemd/system/plocate-updatedb.service.d/10-omarchy.conf", "systemd/system/plocate-updatedb.service.d/10-omarchy.conf"), + ("default/systemd/system/docker.socket.d/10-omarchy-rootful.conf", "/usr/lib/systemd/system/docker.socket.d/10-omarchy-rootful.conf", "systemd/system/docker.socket.d/10-omarchy-rootful.conf"), ("default/fonts/omarchy/omarchy.ttf", "/usr/share/fonts/omarchy/omarchy.ttf", "omarchy.ttf"), ("default/snapper/root", "/etc/snapper/config-templates/omarchy", "snapper/root"), ] diff --git a/test/shell.d/docker-group-migration-test.sh b/test/shell.d/docker-group-migration-test.sh index d382f88faf90..aa5c86de97a9 100644 --- a/test/shell.d/docker-group-migration-test.sh +++ b/test/shell.d/docker-group-migration-test.sh @@ -5,8 +5,8 @@ # the group change actually takes effect (group membership is fixed at login), # refresh the stale Docker launcher entry, and stay idempotent on reruns. # -# The real omarchy-remove-security-sudoless-docker and omarchy-state run here -# (from the repo bin); only the privileged/system calls are stubbed, so the whole +# The historical migration and real omarchy-state run here. Only the +# privileged/system calls are stubbed, so the whole # chain — including the reboot flag — is exercised. set -euo pipefail @@ -29,7 +29,11 @@ printf 'OLD-LAUNCHER\n' >"$home/.local/share/applications/Docker.desktop" # records its call instead of touching the real system. cat >"$stub_bin/id" <<'STUB' #!/bin/bash -printf '%s\n' "${STUB_GROUPS:-wheel input}" +if [[ ${1:-} == "-un" ]]; then + printf 'tester\n' +else + printf '%s\n' "${STUB_GROUPS:-wheel input}" +fi STUB cat >"$stub_bin/sudo" <<'STUB' #!/bin/bash diff --git a/test/shell.d/provisioning-groups-test.sh b/test/shell.d/provisioning-groups-test.sh index ae47748e7eda..7e85e28090e0 100644 --- a/test/shell.d/provisioning-groups-test.sh +++ b/test/shell.d/provisioning-groups-test.sh @@ -1,8 +1,8 @@ #!/bin/bash # -# Privileged groups are never granted by the default install. Docker remains an -# explicit opt-in, and raw input-device access is granted only by the optional -# controller and ydotool installers. +# Privileged groups are never granted by the default install. Docker uses a +# per-user rootless daemon, and raw input-device access is granted only by the +# optional controller and ydotool installers. set -euo pipefail @@ -38,6 +38,7 @@ STUB chmod +x "$TMPDIR/bin"/{usermod,groupadd,install,find,sudo} export PATH="$TMPDIR/bin:$PATH" export OMARCHY_PATH="$ROOT" +export OMARCHY_INSTALL="$ROOT/install" # A deferred-provisioning install records neither privileged group. OMARCHY_INSTALL_USER="" bash -eE "$ROOT/install/config/docker.sh" @@ -53,10 +54,10 @@ grep -F -- '-d -m 0755 -o root -g root /etc/chromium/policies/managed' "$TMPDIR/ fail "browser-policy directory is created root-owned" pass "deferred provisioning records no privileged groups" -# The same remains true when an install user already exists. -OMARCHY_INSTALL_USER=existing bash -eE "$ROOT/install/config/docker.sh" -OMARCHY_INSTALL_USER=existing bash -eE "$ROOT/install/config/browser-policy.sh" -[[ ! -f $TMPDIR/usermod.calls ]] || fail "default install must not grant privileged groups" +# The same remains true when an install user already exists. Subordinate-ID +# allocation may call usermod, so pin the group-specific invariant directly. +! rg -q 'usermod .*-[aA][gG].*docker|gpasswd .*docker' "$ROOT/install/config/docker.sh" || + fail "default install must not grant the docker group" pass "existing install user gets neither docker nor input access" ! grep -q 'hardware/input-group.sh' "$ROOT/install/hardware/all.sh" || diff --git a/test/shell.d/rootless-docker-migration-test.sh b/test/shell.d/rootless-docker-migration-test.sh new file mode 100755 index 000000000000..eefe531957f2 --- /dev/null +++ b/test/shell.d/rootless-docker-migration-test.sh @@ -0,0 +1,225 @@ +#!/bin/bash + +set -euo pipefail +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +python3 - <<'PY' +import copy +import importlib.util +import os +import sys +import tempfile + + +sys.dont_write_bytecode = True +path = os.path.join(os.environ["ROOT"], "default/docker/rootless/migrate.py") +spec = importlib.util.spec_from_file_location("rootless_docker_migration", path) +migration = importlib.util.module_from_spec(spec) +spec.loader.exec_module(migration) + +source_security = ["name=seccomp,profile=builtin", "name=cgroupns"] +target_security = ["name=seccomp,profile=builtin", "name=rootless", "name=cgroupns"] +migration.validate_source_daemon(source_security) +migration.validate_target_daemon(target_security) +for options in (None, [], ["name=rootless"], ["name=userns"], ["name=no-new-privileges"]): + try: + migration.validate_source_daemon(options) + except ValueError: + pass + else: + raise AssertionError(f"unsafe rootful daemon policy passed: {options}") +for options in (None, [], source_security, target_security + ["name=apparmor"]): + try: + migration.validate_target_daemon(options) + except ValueError: + pass + else: + raise AssertionError(f"destination was not proven rootless: {options}") +print("ok - migration pins known source confinement and proves the destination daemon is rootless") + +container = { + "Name": "/project-worker", + "Id": "a" * 64, + "State": {"Running": True, "StartedAt": "start", "FinishedAt": "finish"}, + "Config": { + "Image": "local/project-worker:v1", "Hostname": "worker", "Domainname": "", + "User": "1000", "Env": ["PRIVATE=not-logged"], "Labels": {"project": "fixture"}, + "Tty": False, "OpenStdin": False, + }, + "HostConfig": { + "NetworkMode": "bridge", "IpcMode": "private", "ShmSize": 128 * 1024 * 1024, + "Binds": ["project-data:/data:rw"], "Memory": 128 * 1024 * 1024, + "MemorySwap": 256 * 1024 * 1024, "PidsLimit": 64, "NanoCpus": 500000000, + "CapDrop": ["ALL"], "SecurityOpt": ["no-new-privileges"], + "MaskedPaths": sorted(migration.MASKED_PATHS), + "ReadonlyPaths": sorted(migration.READONLY_PATHS), + "Runtime": "runc", "CgroupnsMode": "private", "ConsoleSize": [0, 0], + "PortBindings": {"8080/tcp": [{"HostIp": "127.0.0.1", "HostPort": "18080"}]}, + "RestartPolicy": {"Name": "unless-stopped", "MaximumRetryCount": 0}, + "LogConfig": {"Type": "json-file", "Config": {"max-size": "10m", "max-file": "5"}}, + }, + "NetworkSettings": {"Networks": {"bridge": {}}}, + "Mounts": [{"Type": "volume", "Driver": "local", "Name": "project-data", + "Destination": "/data", "RW": True}], +} +assert migration.validate(container) == "project-worker" +arguments = migration.runtime_arguments(container) +for flag, value in (("--pids-limit=64", None), ("--shm-size", "134217728"), + ("--memory", "134217728"), ("--memory-swap", "268435456"), + ("--cpus", "0.5"), ("--cap-drop", "ALL")): + if value is None: + assert flag in arguments + else: + assert arguments[arguments.index(flag) + 1] == value +assert "--cap-add" not in arguments +assert migration.destination_volume(container, container["Mounts"][0]) == "project-data" +unlimited = copy.deepcopy(container) +unlimited["HostConfig"]["PidsLimit"] = 0 +assert not any(argument.startswith("--pids-limit=") for argument in migration.runtime_arguments(unlimited)) +modern_mount = copy.deepcopy(container) +modern_mount["HostConfig"]["Binds"] = [] +modern_mount["HostConfig"]["Mounts"] = [{ + "Type": "volume", "Source": "project-data", "Target": "/data", + "ReadOnly": False, "VolumeOptions": {"NoCopy": True}, +}] +assert migration.validate(modern_mount) == "project-worker" +assert migration.destination_volume(modern_mount, modern_mount["Mounts"][0]) == "project-data" +print("ok - compatible custom workloads retain resources, private volumes, ports and restrictive capabilities") + +blocked = ( + ("Privileged", True), ("CapAdd", ["SYS_ADMIN"]), + ("Devices", [{"PathOnHost": "/dev/kvm"}]), + ("DeviceRequests", [{"Driver": "nvidia"}]), + ("DeviceCgroupRules", ["a *:* rwm"]), ("NetworkMode", "host"), + ("Runtime", "nvidia"), ("CgroupnsMode", "host"), + ("SecurityOpt", ["seccomp=unconfined"]), + ("Binds", ["/home/example/project:/data:rw"]), + ("Mounts", [{"Type": "bind", "Source": "/home/example", "Target": "/data"}]), + ("FuturePrivilegeOption", {"enabled": True}), +) +for field, value in blocked: + changed = copy.deepcopy(container) + changed["HostConfig"][field] = value + try: + migration.validate(changed) + except ValueError: + pass + else: + raise AssertionError(f"unsupported {field} passed preflight") +for networks in ({"bridge": {}, "project": {}}, {"project": {}}, {}): + changed = copy.deepcopy(container) + changed["NetworkSettings"]["Networks"] = networks + try: + migration.validate(changed) + except ValueError: + pass + else: + raise AssertionError(f"unsupported networks passed: {networks}") +print("ok - privileged, device, host-path, custom-network and unknown settings fail closed") + +records = {} +for index, field in enumerate(("Privileged", "Runtime"), 1): + changed = copy.deepcopy(container) + changed["Name"] = f"/blocked-{index}" + changed["Id"] = str(index) * 64 + changed["HostConfig"][field] = True if field == "Privileged" else "nvidia" + records[changed["Name"].lstrip("/")] = changed +migration.daemon_security = lambda engine: source_security if engine == migration.SOURCE else target_security +migration.inspect = lambda engine, kind, name: records[name] +migration.run = lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("preflight changed a workload")) +sys.argv = ["migrate.py", "--check", *records] +try: + migration.main() +except ValueError as error: + message = str(error) + assert all(name in message for name in records) + assert "PRIVATE" not in message and "not-logged" not in message +else: + raise AssertionError("blocked batch passed preflight") +print("ok - complete-batch preflight reports every blocker without exposing container secrets") + +stopped = copy.deepcopy(container) +stopped["State"] = {"Running": False, "StartedAt": "start", "FinishedAt": "finish", "ExitCode": 0} +stopped["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} +target = copy.deepcopy(stopped) +target["Id"] = "b" * 64 +target["Config"]["Labels"][migration.LABEL] = stopped["Id"] +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + migration.inspect = lambda engine, kind, name: copy.deepcopy(target) + migration.record_completion(stopped, stopped["State"], False) + assert migration.completed(stopped, target) + stopped["RestartCount"] = 4 + stopped["NetworkSettings"]["SandboxID"] = "changed-by-daemon-restart" + target["RestartCount"] = 2 + target["State"]["StartedAt"] = "later-start" + target["NetworkSettings"]["Networks"]["bridge"]["EndpointID"] = "later-endpoint" + assert migration.completed(stopped, target) + changed = copy.deepcopy(stopped) + changed["Config"]["Hostname"] = "changed-after-transfer" + assert not migration.completed(changed, target) + target["State"]["Running"] = True + assert not migration.completed(stopped, target) +print("ok - completion receipts bind both immutable workload snapshots and lifecycle state") + + +def exercise_failed_transfer(after_start): + source = copy.deepcopy(container) + source["Id"] = ("d" if after_start else "c") * 64 + source["Name"] = "/post-start" if after_start else "/pre-start" + source["Mounts"] = [] + source["HostConfig"]["Binds"] = [] + current_source = copy.deepcopy(source) + current_target = {"State": {"Running": False}} + calls = [] + + def fake_inspect(engine, kind, name): + return copy.deepcopy(current_source if engine == migration.SOURCE else current_target) + + def fake_run(*args, **kwargs): + calls.append(args) + if args[:2] == (migration.SOURCE, "stop"): + current_source["State"] = { + "Running": False, "StartedAt": "start", "FinishedAt": "finish", "ExitCode": 0, + } + elif args[:2] == (migration.SOURCE, "update"): + current_source["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} + elif args[:2] == (migration.SOURCE, "start"): + current_source["State"]["Running"] = True + + migration.inspect = fake_inspect + migration.run = fake_run + migration.exists = lambda kind, name: False + migration.pipe = lambda producer, consumer: None + if after_start: + migration.verify_runtime = lambda value: None + else: + migration.verify_runtime = lambda value: (_ for _ in ()).throw(RuntimeError("verification failed")) + + with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + try: + migration.migrate(source) + except RuntimeError: + pass + else: + raise AssertionError("failed transfer was reported as complete") + return calls, current_source + + +calls, source = exercise_failed_transfer(False) +assert (migration.TARGET, "rm", "--force", "pre-start") in calls +assert (migration.TARGET, "image", "rm", "omarchy-migrated:" + "c" * 64) in calls +assert (migration.SOURCE, "start", "c" * 64) in calls +assert source["State"]["Running"] +print("ok - verification failure before first start removes the destination and restores the source") + +calls, source = exercise_failed_transfer(True) +assert (migration.TARGET, "start", "post-start") in calls +assert not any(call[:2] == (migration.TARGET, "rm") for call in calls) +assert not any(call[:3] == (migration.TARGET, "image", "rm") for call in calls) +assert not any(call[:2] == (migration.SOURCE, "start") for call in calls) +assert source["HostConfig"]["RestartPolicy"]["Name"] == "no" +assert not source["State"]["Running"] +print("ok - any destination start attempt retains both copies and keeps the source stopped") +PY diff --git a/test/shell.d/rootless-docker-posture-test.sh b/test/shell.d/rootless-docker-posture-test.sh new file mode 100755 index 000000000000..6cecb2f6bac5 --- /dev/null +++ b/test/shell.d/rootless-docker-posture-test.sh @@ -0,0 +1,66 @@ +#!/bin/bash + +set -euo pipefail +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +for package in docker docker-buildx docker-compose docker-rootless-extras rootlesskit slirp4netns fuse-overlayfs lazydocker; do + grep -qx "$package" "$ROOT/install/omarchy-base.packages" || fail "rootless Docker dependency is in the base install: $package" +done +pass "the base install keeps Docker tooling and adds the rootless runtime" + +grep -q 'systemctl --global enable docker.service' "$ROOT/install/config/enable-services.sh" || + fail "fresh installs globally enable the rootless Docker user service" +grep -q 'docker.service' "$ROOT/install/user/first-run/enable-user-units.sh" || + fail "first login starts the rootless Docker user service" +grep -q 'rootless_docker_ensure_subids' "$ROOT/install/config/docker.sh" || + fail "fresh installs allocate subordinate IDs before rootless Docker starts" +grep -q 'rootless_docker_ensure_subids' "$ROOT/bin/omarchy-provision-owner" || + fail "deferred provisioning allocates subordinate IDs" +pass "fresh and deferred installs prepare the rootless user daemon" + +test_dir=$(mktemp -d) +trap 'rm -rf "$test_dir"' EXIT +home="$test_dir/home" +mkdir -p "$home/.local/state/omarchy/rootless-docker" +touch "$home/.local/state/omarchy/rootless-docker/enabled" +generator="$ROOT/default/systemd/user-environment-generators/60-omarchy-rootless-docker" +expected="DOCKER_HOST=unix://$test_dir/runtime/docker.sock" +actual=$(HOME="$home" XDG_RUNTIME_DIR="$test_dir/runtime" "$generator") +[[ $actual == "$expected" ]] || fail "the rootless Docker API endpoint is exported" "$actual" +rm "$home/.local/state/omarchy/rootless-docker/enabled" +[[ -z $(HOME="$home" XDG_RUNTIME_DIR="$test_dir/runtime" "$generator") ]] || + fail "the API endpoint stays unchanged before migration completes" +pass "the Docker endpoint activates only after rootless setup completes" + +migration="$ROOT/migrations/1789164756.sh" +grep -q 'migration_user=$(id -un)' "$migration" || fail "migration trusts the USER environment instead of the current account" +completion_line=$(grep -n 'test -f "$machine_state/enabled"' "$migration" | cut -d: -f1) +inventory_line=$(grep -n 'docker_inventory=' "$migration" | cut -d: -f1) +[[ -n $completion_line && -n $inventory_line ]] && (( completion_line < inventory_line )) || + fail "later accounts can reach the machine-wide retained rootful store" +grep -q 'machine-wide rootful recovery store was left untouched' "$migration" || + fail "later accounts do not have an explicit rootful-store no-op path" +pass "later accounts initialize only their private rootless daemon" + +grep -q "alias d='docker'" "$ROOT/default/bash/aliases" || fail "the d alias remains Docker" +! rg -q 'sudo[[:space:]]+docker' "$ROOT/bin/omarchy-install-docker-dbs" || + fail "development database installs still use rootful Docker" +! rg -q 'pkexec|omarchy-sudo-docker' "$ROOT/bin/omarchy-launch-docker-tui" || + fail "lazydocker still crosses a root boundary" +[[ ! -e $ROOT/bin/omarchy-sudo-docker && ! -e $ROOT/bin/omarchy-setup-security-sudoless-docker && ! -e $ROOT/bin/omarchy-remove-security-sudoless-docker ]] || + fail "the obsolete docker-group toggle remains installed" +! rg -q 'sudoless-docker|Sudoless Docker' "$ROOT/default/omarchy/omarchy-menu.jsonc" || + fail "the obsolete docker-group toggle remains in the menu" +pass "Docker CLI, Compose, Buildx, databases and lazydocker use the user daemon directly" + +socket_policy="$ROOT/default/systemd/system/docker.socket.d/10-omarchy-rootful.conf" +grep -qx 'SocketUser=root' "$socket_policy" || fail "the Windows Docker socket is root-owned" +grep -qx 'SocketGroup=root' "$socket_policy" || fail "the Windows Docker socket has no docker-group access" +grep -qx 'SocketMode=0600' "$socket_policy" || fail "the Windows Docker socket is root-only" +grep -q -- '--host unix:///run/docker.sock' "$ROOT/bin/omarchy-windows-vm" || + fail "Windows is not pinned to the rootful Docker socket" +grep -q 'sudo "$target" __priv' "$ROOT/bin/omarchy-windows-vm" || + fail "terminal Windows operations do not authenticate" +grep -q 'pkexec "$target" __priv' "$ROOT/bin/omarchy-windows-vm" || + fail "graphical Windows operations do not authenticate" +pass "Windows remains on an authenticated root-only Docker daemon" diff --git a/test/shell.d/sudo-docker-test.sh b/test/shell.d/sudo-docker-test.sh deleted file mode 100644 index d108030abdd3..000000000000 --- a/test/shell.d/sudo-docker-test.sh +++ /dev/null @@ -1,67 +0,0 @@ -#!/bin/bash -# -# omarchy-sudo-docker is the single answer to "does Docker need sudo", and it -# answers two different questions on purpose. The default asks whether this -# session can reach the socket, which is what decides if a command must elevate. -# --configured asks whether the account is set up for sudoless Docker, which is -# what the menu needs so it offers the toggle that can change state. Between -# enabling sudoless Docker and the reboot that grants the group, those disagree. - -set -euo pipefail - -source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" - -TMPDIR=$(mktemp -d) -trap 'rm -rf "$TMPDIR"' EXIT - -command="$ROOT/bin/omarchy-sudo-docker" - -# Stub id so the configured groups are controllable. -mkdir -p "$TMPDIR/bin" -cat >"$TMPDIR/bin/id" <<'STUB' -#!/bin/bash -printf '%s\n' "${STUB_GROUPS:-wheel input}" -STUB -chmod +x "$TMPDIR/bin/id" - -# A writable stand-in means the socket is reachable; an unwritable one means it -# is not. Test the file mode rather than a live daemon. -reachable_socket="$TMPDIR/reachable.sock" -blocked_socket="$TMPDIR/blocked.sock" -touch "$reachable_socket" "$blocked_socket" -chmod 600 "$reachable_socket" -chmod 400 "$blocked_socket" - -run() { # SOCKET GROUPS [--configured] - env PATH="$TMPDIR/bin:$PATH" OMARCHY_DOCKER_SOCKET="$1" STUB_GROUPS="$2" USER=tester \ - bash "$command" ${3:+"$3"} -} - -# Default mode follows the socket, not the group list. -run "$blocked_socket" "wheel input" || fail "an unreachable socket means Docker needs sudo" -run "$reachable_socket" "wheel input" && fail "a reachable socket means Docker does not need sudo" -pass "default mode answers from the socket this session can reach" - -# A socket that isn't there at all still needs elevation (starting it is root work). -run "$TMPDIR/absent.sock" "wheel input docker" || fail "a missing socket means Docker needs sudo" -pass "a missing socket counts as needing sudo" - -# --configured follows the account's groups, not the socket. -run "$blocked_socket" "wheel input docker" --configured && fail "a configured docker group means no sudo is needed" -run "$reachable_socket" "wheel input" --configured || fail "no docker group means sudo is needed" -pass "--configured answers from the account's groups" - -# The window this split exists for: sudoless Docker has just been enabled, so the -# account carries the group while the running session still cannot use it. The -# menu must offer Remove (--configured says no sudo) while lazydocker and the -# Windows VM must still prompt (default says sudo). -run "$blocked_socket" "wheel input docker" || fail "the session still needs sudo before the reboot" -run "$blocked_socket" "wheel input docker" --configured && fail "the account is already configured for sudoless Docker" -pass "the two modes disagree between enabling sudoless Docker and the reboot" - -# An unknown argument is a usage error, not a silent answer either way. -run "$reachable_socket" "wheel input" --bogus 2>/dev/null && fail "an unknown flag exits non-zero" -status=0 -run "$reachable_socket" "wheel input" --bogus >/dev/null 2>&1 || status=$? -(( status == 2 )) || fail "an unknown flag exits 2, not the boolean 1" -pass "an unknown flag is a usage error" diff --git a/test/shell.d/sudoless-docker-toggle-test.sh b/test/shell.d/sudoless-docker-toggle-test.sh deleted file mode 100644 index ffa18316f719..000000000000 --- a/test/shell.d/sudoless-docker-toggle-test.sh +++ /dev/null @@ -1,93 +0,0 @@ -#!/bin/bash -# -# Toggling sudoless Docker changes the docker group, which only takes effect on a -# reboot. The setup/remove commands must flag the reboot and offer to do it now -# (gum confirm), but defer it when OMARCHY_DEFER_REBOOT is set (the migration -# reuses them inside `omarchy update`, where omarchy-update-restart handles it). - -set -euo pipefail - -source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" - -test_dir=$(mktemp -d) -trap 'rm -rf "$test_dir"' EXIT -home="$test_dir/home" -stub_bin="$test_dir/bin" -mkdir -p "$home" "$stub_bin" - -cat >"$stub_bin/id" <<'STUB' -#!/bin/bash -printf '%s\n' "${STUB_GROUPS:-wheel input}" -STUB -cat >"$stub_bin/sudo" <<'STUB' -#!/bin/bash -exec "$@" -STUB -cat >"$stub_bin/usermod" <<'STUB' -#!/bin/bash -echo "$@" >>"${USERMOD_CALLS:?}" -STUB -cat >"$stub_bin/gpasswd" <<'STUB' -#!/bin/bash -echo "$@" >>"${GPASSWD_CALLS:?}" -STUB -cat >"$stub_bin/gum" <<'STUB' -#!/bin/bash -touch "${GUM_CALLED:?}" -exit "${GUM_ANSWER:-0}" -STUB -cat >"$stub_bin/omarchy-system-reboot" <<'STUB' -#!/bin/bash -touch "${REBOOT_CALLED:?}" -STUB -chmod +x "$stub_bin"/* - -reboot_flag="$home/.local/state/omarchy/reboot-required" -gum_called="$test_dir/gum-called" -reboot_called="$test_dir/reboot-called" -gpasswd_calls="$test_dir/gpasswd-calls" -usermod_calls="$test_dir/usermod-calls" - -run() { # command STUB_GROUPS GUM_ANSWER DEFER(0|1) - rm -f "$reboot_flag" "$gum_called" "$reboot_called" "$gpasswd_calls" "$usermod_calls" - local defer_env=() - [[ ${4:-0} == 1 ]] && defer_env=(OMARCHY_DEFER_REBOOT=1) - env HOME="$home" USER="tester" STUB_GROUPS="$2" GUM_ANSWER="$3" \ - GUM_CALLED="$gum_called" REBOOT_CALLED="$reboot_called" \ - GPASSWD_CALLS="$gpasswd_calls" USERMOD_CALLS="$usermod_calls" \ - PATH="$stub_bin:$ROOT/bin:$PATH" "${defer_env[@]}" \ - bash "$ROOT/bin/$1" >/dev/null 2>&1 -} - -# Remove, interactive, reboot confirmed -> group removed, flag set, reboot fired. -run omarchy-remove-security-sudoless-docker "wheel input docker" 0 0 -grep -q -- "-d tester docker" "$gpasswd_calls" || fail "remove drops the user from the docker group" -[[ -f $reboot_flag ]] || fail "remove flags a reboot" -[[ -f $reboot_called ]] || fail "remove reboots when the prompt is confirmed" -pass "remove drops the group, flags a reboot, and reboots on confirm" - -# Remove, interactive, reboot declined -> flag set, but no reboot. -run omarchy-remove-security-sudoless-docker "wheel input docker" 1 0 -[[ -f $reboot_flag ]] || fail "remove still flags a reboot when the prompt is declined" -[[ ! -f $reboot_called ]] || fail "remove does not reboot when the prompt is declined" -pass "remove leaves the reboot to the user when declined" - -# Remove, deferred (migration/update) -> flag set, prompt never shown. -run omarchy-remove-security-sudoless-docker "wheel input docker" 0 1 -[[ -f $reboot_flag ]] || fail "deferred remove still flags a reboot" -[[ ! -f $gum_called ]] || fail "deferred remove must not prompt to reboot" -[[ ! -f $reboot_called ]] || fail "deferred remove must not reboot" -pass "deferred remove flags the reboot without prompting" - -# Remove, already out of the group -> no-op, nothing flagged. -run omarchy-remove-security-sudoless-docker "wheel input" 0 0 -[[ ! -f $gpasswd_calls ]] || fail "remove is a no-op when the user is not in the docker group" -[[ ! -f $reboot_flag ]] || fail "remove does not flag a reboot when nothing changed" -pass "remove is a no-op when sudoless Docker is already off" - -# Setup, enable confirmed then reboot confirmed -> group added, flag set, reboot. -run omarchy-setup-security-sudoless-docker "wheel input" 0 0 -grep -q -- "-aG docker tester" "$usermod_calls" || fail "setup adds the user to the docker group" -[[ -f $reboot_flag ]] || fail "setup flags a reboot" -[[ -f $reboot_called ]] || fail "setup reboots when the prompt is confirmed" -pass "setup adds the group, flags a reboot, and reboots on confirm" diff --git a/test/shell.d/windows-vm-auth-test.sh b/test/shell.d/windows-vm-auth-test.sh new file mode 100644 index 000000000000..65a9580c5ae4 --- /dev/null +++ b/test/shell.d/windows-vm-auth-test.sh @@ -0,0 +1,47 @@ +#!/bin/bash + +set -euo pipefail +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +python3 - <<'PY' +import os +import pty +import subprocess +import tempfile +from pathlib import Path + + +script = r''' +set -e +set -- help +source "$ROOT/bin/omarchy-windows-vm" >/dev/null +priv_target() { printf '/fixture/omarchy-windows-vm\n'; } +sudo() { printf sudo >"$MODE_LOG"; printf exited; } +pkexec() { printf pkexec >"$MODE_LOG"; printf exited; } +migrate_legacy_compose() { :; } +status_windows +''' +with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "docker-compose.yml").touch() + log = root / "mode" + env = dict(os.environ, OMARCHY_WINDOWS_DIR=str(root), MODE_LOG=str(log), HOME=str(root)) + for name, terminal_input, terminal_error, expected in ( + ("terminal status", True, True, "sudo"), + ("redirected stdin", False, True, "sudo"), + ("graphical caller", False, False, "pkexec")): + master, slave = pty.openpty() + try: + result = subprocess.run(["/bin/bash", "-c", script], env=env, + stdin=slave if terminal_input else subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=slave if terminal_error else subprocess.PIPE, + text=True, timeout=10) + assert result.returncode == 0, (name, result.stdout, result.stderr) + assert log.read_text() == expected, (name, log.read_text(), expected) + assert "Windows VM is stopped" in result.stdout + finally: + os.close(slave) + os.close(master) + print(f"ok - {name} uses {expected} while privileged status output is captured") +PY diff --git a/test/shell.d/windows-vm-mount-boundary-test.sh b/test/shell.d/windows-vm-mount-boundary-test.sh index 13623d816456..66b4111ebe73 100644 --- a/test/shell.d/windows-vm-mount-boundary-test.sh +++ b/test/shell.d/windows-vm-mount-boundary-test.sh @@ -152,7 +152,7 @@ pass "disk-space accounting measures the actual storage filesystem, not home" # Exercise the real root writer and final guard against the production paths. printf 'RAM=4G\nCORES=2\nDISK=64G\nUSERNAME=alice\nPASSWORD=pw\nTZ=UTC\n' | with_vm_lock __priv_write_compose -[[ $(command stat -Lc '%u:%a' "$COMPOSE_FILE") == 0:640 ]] || fail "root compose ownership/mode is wrong" +[[ $(command stat -Lc '%u:%g:%a' "$COMPOSE_FILE") == 0:0:600 ]] || fail "root compose ownership/mode is wrong" with_vm_lock assert_mounts_safe || fail "final root mount/compose assertion rejected the verified pair" pass "root writer and final pre-Docker guard revalidate the pinned production mounts" From 14a765da192c25f96f18e9d82cba8b8f374345ad Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Sat, 12 Sep 2026 00:41:18 -0600 Subject: [PATCH 02/31] Harden rootless Docker migration races --- default/docker/rootless/migrate.py | 152 +++++++++++++++--- docs/rootless-docker.md | 4 +- migrations/1789164756.sh | 72 ++++++--- .../shell.d/rootless-docker-migration-test.sh | 113 ++++++++++++- test/shell.d/rootless-docker-posture-test.sh | 14 +- 5 files changed, 302 insertions(+), 53 deletions(-) diff --git a/default/docker/rootless/migrate.py b/default/docker/rootless/migrate.py index 38a4bb27f42f..affac267d4be 100644 --- a/default/docker/rootless/migrate.py +++ b/default/docker/rootless/migrate.py @@ -4,6 +4,7 @@ import json import os import re +import stat import subprocess import sys from decimal import Decimal @@ -13,6 +14,8 @@ LABEL = "io.omarchy.rootless-docker.source-id" SOURCE = "source" TARGET = "target" +TRUSTED_MANIFEST = "/usr/share/omarchy/default/docker/rootless/volume-manifest.py" +SECCOMP_OPTIONS = {"name=seccomp,profile=builtin", "name=seccomp,profile=default"} MASKED_PATHS = { "/proc/acpi", "/proc/asound", "/proc/interrupts", "/proc/kcore", "/proc/keys", "/proc/latency_stats", "/proc/sched_debug", "/proc/scsi", "/proc/timer_list", @@ -39,19 +42,23 @@ def validate_source_daemon(options): # Daemon defaults (including no-new-privileges and seccomp profiles) need # not appear in individual HostConfig records. Userns remapping also changes # the meaning of numeric volume ownership. Do not guess these policies. - defaults = {"name=seccomp,profile=builtin", "name=seccomp,profile=default", "name=cgroupns"} - if not isinstance(options, list) or not options or set(options) - defaults: + defaults = {*SECCOMP_OPTIONS, "name=cgroupns"} + configured = set(options) if isinstance(options, list) else set() + if (not configured or configured - defaults or "name=cgroupns" not in configured or + len(configured & SECCOMP_OPTIONS) != 1): raise ValueError("rootful Docker daemon confinement or user mapping needs an explicit migration") def validate_target_daemon(options): - if not isinstance(options, list) or "name=rootless" not in options: - raise ValueError("the destination Docker daemon is not running rootlessly") allowed = { "name=rootless", "name=cgroupns", "name=seccomp,profile=builtin", "name=seccomp,profile=default", } - if set(options) - allowed: + configured = set(options) if isinstance(options, list) else set() + if "name=rootless" not in configured: + raise ValueError("the destination Docker daemon is not running rootlessly") + if (configured - allowed or "name=cgroupns" not in configured or + len(configured & SECCOMP_OPTIONS) != 1): raise ValueError("rootless Docker daemon confinement needs an explicit migration") @@ -152,8 +159,10 @@ def runtime_arguments(container): def allowed_capabilities(container): # Explicit --cap-add gives even non-root processes capabilities. Docker's # default non-root process has none, so keep that source boundary. - user = (container["Config"].get("User") or "").split(":")[0] - if user not in ("", "0", "root"): + user = (container["Config"].get("User") or "").split(":", 1)[0] + if user and not user.isdecimal(): + raise ValueError(f'{container["Name"].lstrip("/")}: named image users need an explicit migration') + if user and int(user) != 0: return set() # Docker API clients can retain mixed-case names in inspected CapDrop. dropped = {capability.upper().removeprefix("CAP_") for capability in container["HostConfig"].get("CapDrop") or []} @@ -250,7 +259,7 @@ def verify_runtime(container): def local_command(args): if args[0] == SOURCE: - return ["sudo", "/usr/bin/docker", "--host", "unix:///run/docker.sock", *args[1:]] + return ["/usr/bin/sudo", "/usr/bin/docker", "--host", "unix:///run/docker.sock", *args[1:]] if args[0] == TARGET: runtime = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}" return ["/usr/bin/docker", "--host", f"unix://{runtime}/docker.sock", *args[1:]] @@ -329,6 +338,11 @@ def stopped_identity(state): def record_completion(container, source_state, target_running): + latest_source = inspect(SOURCE, "container", container["Id"]) + if (stopped_identity(latest_source["State"]) != stopped_identity(source_state) or + snapshot_digest(latest_source) != snapshot_digest(container)): + raise RuntimeError(f'{container["Name"].lstrip("/")}: Docker source changed before completion; inspect both engines') + container = latest_source target = inspect(TARGET, "container", container["Name"].lstrip("/")) receipt = completion_path(container["Id"]) receipt.parent.mkdir(parents=True, exist_ok=True, mode=0o700) @@ -354,6 +368,15 @@ def validate(container): raise ValueError("Unsupported container name") if not re.fullmatch(r"[a-f0-9]{64}", container["Id"]): raise ValueError("Unsupported Docker container identity") + labels = container["Config"].get("Labels") or {} + if LABEL in labels: + raise ValueError(f"{name}: reserved Omarchy migration labels need an explicit migration") + allowed_capabilities(container) + environment = container["Config"].get("Env") or [] + if (not isinstance(environment, list) or + any(not isinstance(entry, str) or "=" not in entry for entry in environment) or + len({entry.split("=", 1)[0] for entry in environment}) != len(environment)): + raise ValueError(f"{name}: ambiguous container environment needs an explicit migration") validate_security(container) if container["Config"].get("Domainname"): raise ValueError(f"{name}: custom domain names require an explicit rootless Docker configuration") @@ -392,6 +415,43 @@ def validate(container): return name +def validate_windows_exception(container): + name = container["Name"].lstrip("/") + config = container["Config"] + host = container["HostConfig"] + labels = config.get("Labels") or {} + devices = {(device.get("PathOnHost"), device.get("PathInContainer")) + for device in host.get("Devices") or []} + ports = host.get("PortBindings") or {} + expected_ports = { + "8006/tcp": [{"HostIp": "127.0.0.1", "HostPort": "8006"}], + "3389/tcp": [{"HostIp": "127.0.0.1", "HostPort": "3389"}], + "3389/udp": [{"HostIp": "127.0.0.1", "HostPort": "3389"}], + } + mounts = container.get("Mounts") or [] + mounts_by_destination = {mount.get("Destination"): mount for mount in mounts} + storage = mounts_by_destination.get("/storage") or {} + shared = mounts_by_destination.get("/shared") or {} + storage_match = re.fullmatch(r"/var/lib/omarchy/windows/mounts/users/([1-9][0-9]*)/storage", + storage.get("Source") or "") + if (name != "omarchy-windows" or + not re.fullmatch(r"[a-f0-9]{64}", container["Id"]) or + config.get("Image") not in ("dockurr/windows", "dockurr/windows:latest") or + labels.get("com.docker.compose.project") != "windows" or + labels.get("com.docker.compose.service") != "windows" or + host.get("Privileged") is not False or + {capability.upper().removeprefix("CAP_") for capability in host.get("CapAdd") or []} != {"NET_ADMIN"} or + devices != {("/dev/kvm", "/dev/kvm"), ("/dev/net/tun", "/dev/net/tun")} or + ports != expected_ports or + (host.get("RestartPolicy") or {}).get("Name") != "no" or + len(mounts) != 2 or any(mount.get("Type") != "bind" for mount in mounts) or + any(mount.get("RW") is not True for mount in mounts) or + not storage_match or + shared.get("Source") != f"/var/lib/omarchy/windows/mounts/users/{storage_match.group(1)}/shared"): + raise ValueError("omarchy-windows: the rootful exception does not match Omarchy's managed Windows VM") + return name + + def pipe(producer, consumer): with subprocess.Popen(local_command(producer), stdout=subprocess.PIPE) as source: try: @@ -410,20 +470,39 @@ def transfer_volume(volume, target): destination = inspect(TARGET, "volume", target)["Mountpoint"] # Native tar inside RootlessKit's user/mount namespace preserves numeric # container ownership, root mode, PAX timestamps, ACLs and xattrs. - pipe(["sudo", "tar", "--format=pax", "--numeric-owner", "--sparse", "--acls", "--xattrs", + pipe(["/usr/bin/sudo", "/usr/bin/tar", "--format=pax", "--numeric-owner", "--sparse", "--acls", "--xattrs", "--xattrs-include=*", "-C", volume["Mountpoint"], "-cpf", "-", "."], ["target-namespace", "/usr/bin/tar", "--numeric-owner", "--same-owner", "--same-permissions", "--sparse", "--acls", "--xattrs", "--xattrs-include=*", "-C", destination, "-xpf", "-"]) - manifest = str(Path(__file__).with_name("volume-manifest.py")) - source_digest = run("sudo", "python3", manifest, volume["Mountpoint"], capture=True) + source_digest = source_volume_digest(volume) verify_volume(target, source_digest) return source_digest +def source_volume_digest(volume): + return run("/usr/bin/sudo", "/usr/bin/python3", TRUSTED_MANIFEST, + volume["Mountpoint"], capture=True) + + +def validate_trusted_manifest(): + path = Path(TRUSTED_MANIFEST) + try: + metadata = path.lstat() + except FileNotFoundError as error: + raise ValueError("the packaged rootless Docker volume verifier is missing") from error + if (path.is_symlink() or not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != 0 or + metadata.st_mode & 0o022): + raise ValueError("the packaged rootless Docker volume verifier is not trusted") + for parent in path.parents: + metadata = parent.stat() + if metadata.st_uid != 0 or metadata.st_mode & 0o022: + raise ValueError("the packaged rootless Docker volume verifier path is not trusted") + + def verify_volume(target, expected): destination = inspect(TARGET, "volume", target)["Mountpoint"] - manifest = str(Path(__file__).with_name("volume-manifest.py")) - target_digest = run("target-namespace", "/usr/bin/python3", manifest, destination, capture=True) + target_digest = run("target-namespace", "/usr/bin/python3", TRUSTED_MANIFEST, + destination, capture=True) if expected != target_digest: raise RuntimeError("Volume content or metadata verification failed; Docker data was retained") @@ -439,10 +518,13 @@ def source_snapshot(container): return snapshot -def snapshot_digest(container): +def snapshot_digest(container, ignore_restart=False): fields = ("Id", "Name", "Image", "Config", "HostConfig", "Mounts", "AppArmorProfile", "ProcessLabel", "MountLabel") snapshot = {field: container.get(field) for field in fields} + if ignore_restart: + snapshot["HostConfig"] = dict(snapshot["HostConfig"] or {}) + snapshot["HostConfig"].pop("RestartPolicy", None) networks = container.get("NetworkSettings", {}).get("Networks") or {} snapshot["Networks"] = { name: {key: network.get(key) for key in ("IPAMConfig", "Links", "Aliases", "DriverOpts")} @@ -477,6 +559,7 @@ def migrate(container): container = refresh_source(container) running = container["State"]["Running"] created = False + image = None image_loaded = False start_attempted = False restart_changed = False @@ -484,16 +567,19 @@ def migrate(container): verified_volumes = {} try: run(SOURCE, "stop", "-t", "120", identity) - state = inspect(SOURCE, "container", identity)["State"] + stopped_source = inspect(SOURCE, "container", identity) + state = stopped_source["State"] if state["Running"] or (running and state["ExitCode"] in (137, 139)): raise RuntimeError(f"{name}: container did not stop cleanly; transfer aborted") stopped_identity(state) - # Container names allow uppercase, repeated dots and lengths that image - # repositories reject. The full engine ID is a valid, unique image tag. - image = f"omarchy-migrated:{identity}" + if snapshot_digest(stopped_source) != snapshot_digest(container): + raise RuntimeError(f"{name}: Docker source configuration changed while stopping; rerun after workloads are stable") + container = stopped_source # Commit includes writable-layer changes and the exact image config. # Volume data is copied separately while the source container is stopped. - run(SOURCE, "commit", identity, image) + image = run(SOURCE, "commit", identity, capture=True) + if not re.fullmatch(r"sha256:[a-f0-9]{64}", image or ""): + raise RuntimeError(f"{name}: Docker did not return a transferable committed image") pipe([SOURCE, "image", "save", image], [TARGET, "image", "load", "--quiet"]) image_loaded = True run(SOURCE, "image", "rm", image) @@ -533,7 +619,7 @@ def migrate(container): volume_arguments += ["--label", f"{key}={value}"] run(*volume_arguments, target) new_volumes.append(target) - verified_volumes[target] = transfer_volume(volume, target) + verified_volumes[target] = (volume, transfer_volume(volume, target)) mount_arg = f'type=volume,src={target},dst={mount["Destination"]},volume-nocopy' if not mount.get("RW"): mount_arg += ",readonly" @@ -545,14 +631,23 @@ def migrate(container): # from replacing the restored volume contents. verify_runtime(container) for target, expected in verified_volumes.items(): - verify_volume(target, expected) + volume, digest = expected + verify_volume(target, digest) + if source_volume_digest(volume) != digest: + raise RuntimeError(f"{name}: source volume changed during transfer; inspect both engines") + latest_source = inspect(SOURCE, "container", identity) + if (stopped_identity(latest_source["State"]) != stopped_identity(state) or + snapshot_digest(latest_source) != snapshot_digest(container)): + raise RuntimeError(f"{name}: Docker source changed during transfer; inspect both engines") # A later workload may fail, leaving Docker installed. Prevent a daemon # restart from reviving this stale source alongside its migrated copy. restart_changed = True run(SOURCE, "update", "--restart=no", identity) source_after = inspect(SOURCE, "container", identity) - if stopped_identity(source_after["State"]) != stopped_identity(state): - raise RuntimeError(f"{name}: Docker source restarted during transfer; inspect both engines") + if (stopped_identity(source_after["State"]) != stopped_identity(state) or + snapshot_digest(source_after, ignore_restart=True) != snapshot_digest(container, ignore_restart=True) or + (source_after["HostConfig"].get("RestartPolicy") or {}).get("Name") != "no"): + raise RuntimeError(f"{name}: Docker source changed during finalization; inspect both engines") if running: # Even a failed start command may have launched an application that # accepted writes. From this point the destination is recovery data. @@ -563,6 +658,7 @@ def migrate(container): target_state = inspect(TARGET, "container", name)["State"] if bool(target_state["Running"]) != bool(running): raise RuntimeError(f"{name}: destination lifecycle differs from the source") + verify_runtime(container) record_completion(source_after, state, bool(running)) print(f"{name}: migrated to rootless Docker; rootful copy retained for recovery") except BaseException: @@ -594,6 +690,14 @@ def main(): if os.geteuid() == 0: raise ValueError("Run the migration as the desktop user; the destination is always rootless") os.environ.setdefault("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}") + check_windows = sys.argv[1:2] == ["--check-windows"] + if check_windows: + if len(sys.argv) != 3: + raise ValueError("Expected one Windows container identity") + validate_source_daemon(daemon_security(SOURCE)) + validate_windows_exception(inspect(SOURCE, "container", sys.argv[2])) + print("omarchy-windows: verified managed rootful exception") + return check_completed = sys.argv[1:2] == ["--check-completed"] check_only = check_completed or sys.argv[1:2] == ["--check"] names = sys.argv[2:] if check_only else sys.argv[1:] @@ -616,6 +720,8 @@ def main(): volumes.add(mount["Name"]) if blockers: raise ValueError("\n".join(blockers)) + if volumes: + validate_trusted_manifest() if check_completed: for container in containers: name = container["Name"].lstrip("/") diff --git a/docs/rootless-docker.md b/docs/rootless-docker.md index 49328119d266..21ff6d13e059 100644 --- a/docs/rootless-docker.md +++ b/docs/rootless-docker.md @@ -16,9 +16,9 @@ The migration's machine-wide enabled marker is written only after the shared roo ## Existing-install migration -`migrations/1789164756.sh` installs the rootless runtime, allocates subordinate IDs, starts and proves the rootless daemon, claims the machine-wide source inventory for one account, and preflights every rootful container except `omarchy-windows`. A blocker in any source prevents the batch from stopping its first container. +`migrations/1789164756.sh` installs the rootless runtime, allocates subordinate IDs, starts and proves the rootless daemon, claims the machine-wide source inventory for one account, restricts the old API socket to root, and preflights every rootful development container. A container named `omarchy-windows` is exempt only when its image, Compose identity, devices, capabilities, ports, and mounts match Omarchy's managed VM. A blocker in any source prevents the batch from stopping its first container. -The automatic path accepts stock bridge networking with localhost-only unprivileged published ports, private local named volumes, supported resource limits, the stock runtime and namespace boundaries, and Docker's default capability ceiling or stricter settings. It rejects privileged containers, added capabilities, devices, host or shared mounts, custom networks, namespace sharing, custom runtimes, altered confinement, custom logging, and unknown nondefault host settings. +The automatic path accepts stock bridge networking with localhost-only unprivileged published ports, private local named volumes, supported resource limits, numeric container users, the stock runtime and namespace boundaries, and Docker's default capability ceiling or stricter settings. It rejects privileged containers, added capabilities, devices, host or shared mounts, named image users whose effective UID is ambiguous, custom networks, namespace sharing, custom runtimes, altered confinement, custom logging, reserved migration labels, and unknown nondefault host settings. For each accepted container, the migrator stops the source cleanly, commits its writable layer, transfers that image through Docker's native save/load format, copies named-volume contents and metadata inside the RootlessKit user and mount namespace, and recreates the container with explicit private and restrictive settings. It verifies environment, application config, limits, capabilities, mounts, ports, restart policy, logging, volume fingerprints, and lifecycle before writing a receipt bound to full source and destination snapshots. diff --git a/migrations/1789164756.sh b/migrations/1789164756.sh index 71624e401697..1c81e4a30384 100644 --- a/migrations/1789164756.sh +++ b/migrations/1789164756.sh @@ -14,6 +14,21 @@ if ! systemctl --user show-environment >/dev/null; then exit 1 fi +remove_legacy_docker_group() { + if id -nG "$migration_user" | grep -qw docker; then + sudo /usr/bin/gpasswd -d "$migration_user" docker >/dev/null + omarchy-state set reboot-required + fi +} + +# A second invocation by the same account could otherwise race destination +# creation and let one rollback disturb the other's transfer. +exec {migration_lock_fd}>"$XDG_RUNTIME_DIR/omarchy-rootless-docker-migration.lock" +if ! /usr/bin/flock -n "$migration_lock_fd"; then + echo "Another rootless Docker migration is already running for $migration_user." >&2 + exit 1 +fi + omarchy-pkg-add docker-rootless-extras rootlesskit slirp4netns fuse-overlayfs # Allocate a nonoverlapping subordinate-ID range before the rootless daemon can @@ -45,6 +60,7 @@ fi machine_state=/var/lib/omarchy/rootless-docker if sudo /usr/bin/test -f "$machine_state/enabled"; then sudo /usr/bin/systemctl --global enable docker.service + remove_legacy_docker_group touch "$rootless_state/enabled" chmod 0600 "$rootless_state/enabled" export DOCKER_HOST="$target_host" @@ -90,12 +106,44 @@ with os.fdopen(lock_fd, "w") as lock: temporary.replace(owner) PY +sudo /usr/bin/systemctl daemon-reload sudo /usr/bin/systemctl start docker.socket source_host="unix:///run/docker.sock" -docker_inventory=$(sudo /usr/bin/docker --host "$source_host" ps -a --no-trunc --format '{{.ID}} {{.Names}}' | sort) -mapfile -t container_names < <(printf '%s\n' "$docker_inventory" | awk '$2 != "omarchy-windows" { print $2 }') +# Load the packaged socket policy and revoke the legacy docker group's access +# before inspecting or stopping workloads. This also closes the interval where +# an ordinary new Docker client could restart a source after verification. +if sudo /usr/bin/test -S /run/docker.sock; then + sudo /usr/bin/setfacl -b /run/docker.sock + sudo /usr/bin/chown root:root /run/docker.sock + sudo /usr/bin/chmod 0600 /run/docker.sock +fi +socket_owner=$(sudo /usr/bin/stat -Lc '%u:%g:%a' /run/docker.sock) +if [[ $socket_owner != "0:0:600" ]]; then + echo "The rootful Docker socket could not be restricted to root. This migration remains pending." >&2 + exit 1 +fi +remove_legacy_docker_group + +docker_inventory=$(sudo /usr/bin/docker --host "$source_host" ps -a --no-trunc --format '{{.ID}} {{.Names}}' | sort) migrator="$OMARCHY_PATH/default/docker/rootless/migrate.py" +container_names=() +windows_id="" +while read -r container_id container_name; do + [[ -n $container_id ]] || continue + if [[ $container_name == "omarchy-windows" ]]; then + windows_id="$container_id" + else + container_names+=("$container_name") + fi +done <<<"$docker_inventory" + +# A container is exempt from rootless transfer only when its immutable runtime +# identity matches the Windows VM Omarchy manages through authenticated actions. +if [[ -n $windows_id ]]; then + /usr/bin/python3 "$migrator" --check-windows "$windows_id" +fi + if (( ${#container_names[@]} )); then if ! /usr/bin/python3 "$migrator" --check "${container_names[@]}"; then echo "Rootful Docker and its data have been retained. This migration remains pending." >&2 @@ -111,26 +159,6 @@ if [[ $latest_inventory != "$docker_inventory" ]]; then exit 1 fi -# Remove direct access to the rootful Windows daemon immediately, including for -# a login that still carries an old docker supplementary group. The packaged -# socket drop-in preserves this root-only mode after later socket activation. -sudo /usr/bin/systemctl daemon-reload -if sudo /usr/bin/test -S /run/docker.sock; then - sudo /usr/bin/setfacl -b /run/docker.sock - sudo /usr/bin/chown root:root /run/docker.sock - sudo /usr/bin/chmod 0600 /run/docker.sock -fi -socket_owner=$(sudo /usr/bin/stat -Lc '%u:%g:%a' /run/docker.sock) -if [[ $socket_owner != "0:0:600" ]]; then - echo "The rootful Docker socket could not be restricted to root. This migration remains pending." >&2 - exit 1 -fi - -if id -nG "$migration_user" | grep -qw docker; then - sudo /usr/bin/gpasswd -d "$migration_user" docker >/dev/null - omarchy-state set reboot-required -fi - sudo /usr/bin/systemctl --global enable docker.service sudo /usr/bin/touch /var/lib/omarchy/rootless-docker/enabled sudo /usr/bin/chown root:root /var/lib/omarchy/rootless-docker/enabled diff --git a/test/shell.d/rootless-docker-migration-test.sh b/test/shell.d/rootless-docker-migration-test.sh index eefe531957f2..6919e0ff751c 100755 --- a/test/shell.d/rootless-docker-migration-test.sh +++ b/test/shell.d/rootless-docker-migration-test.sh @@ -16,19 +16,25 @@ path = os.path.join(os.environ["ROOT"], "default/docker/rootless/migrate.py") spec = importlib.util.spec_from_file_location("rootless_docker_migration", path) migration = importlib.util.module_from_spec(spec) spec.loader.exec_module(migration) +assert migration.TRUSTED_MANIFEST == "/usr/share/omarchy/default/docker/rootless/volume-manifest.py" +assert migration.local_command([migration.SOURCE, "info"])[:2] == ["/usr/bin/sudo", "/usr/bin/docker"] +print("ok - privileged migration helpers resolve only through packaged absolute paths") source_security = ["name=seccomp,profile=builtin", "name=cgroupns"] target_security = ["name=seccomp,profile=builtin", "name=rootless", "name=cgroupns"] migration.validate_source_daemon(source_security) migration.validate_target_daemon(target_security) -for options in (None, [], ["name=rootless"], ["name=userns"], ["name=no-new-privileges"]): +for options in (None, [], ["name=rootless"], ["name=userns"], ["name=no-new-privileges"], + ["name=cgroupns"], ["name=seccomp,profile=builtin"]): try: migration.validate_source_daemon(options) except ValueError: pass else: raise AssertionError(f"unsafe rootful daemon policy passed: {options}") -for options in (None, [], source_security, target_security + ["name=apparmor"]): +for options in (None, [], source_security, target_security + ["name=apparmor"], + ["name=rootless", "name=cgroupns"], + ["name=rootless", "name=seccomp,profile=builtin"]): try: migration.validate_target_daemon(options) except ValueError: @@ -86,6 +92,82 @@ assert migration.validate(modern_mount) == "project-worker" assert migration.destination_volume(modern_mount, modern_mount["Mounts"][0]) == "project-data" print("ok - compatible custom workloads retain resources, private volumes, ports and restrictive capabilities") +numeric_root = copy.deepcopy(container) +numeric_root["Config"]["User"] = "00:1000" +numeric_root["HostConfig"]["CapDrop"] = [] +assert migration.allowed_capabilities(numeric_root) == migration.DOCKER_CAPABILITIES +for named_user in ("root", "daemon", "root:root"): + changed = copy.deepcopy(container) + changed["Config"]["User"] = named_user + try: + migration.validate(changed) + except ValueError: + pass + else: + raise AssertionError(f"ambiguous named user passed preflight: {named_user}") +print("ok - numeric UID zero keeps its capabilities and ambiguous named users fail closed") + +for field, value in (("Labels", {migration.LABEL: "old"}), + ("Env", ["DUPLICATE=one", "DUPLICATE=two"])): + changed = copy.deepcopy(container) + changed["Config"][field] = value + try: + migration.validate(changed) + except ValueError: + pass + else: + raise AssertionError(f"ambiguous {field} passed preflight") +print("ok - reserved labels and duplicate environment keys fail before transfer") + +windows = copy.deepcopy(container) +windows["Name"] = "/omarchy-windows" +windows["Id"] = "f" * 64 +windows["Config"]["Image"] = "dockurr/windows" +windows["Config"]["Labels"] = { + "com.docker.compose.project": "windows", + "com.docker.compose.service": "windows", +} +windows["HostConfig"]["Privileged"] = False +windows["HostConfig"]["CapAdd"] = ["NET_ADMIN"] +windows["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} +windows["HostConfig"]["Devices"] = [ + {"PathOnHost": "/dev/kvm", "PathInContainer": "/dev/kvm"}, + {"PathOnHost": "/dev/net/tun", "PathInContainer": "/dev/net/tun"}, +] +windows["HostConfig"]["PortBindings"] = { + "8006/tcp": [{"HostIp": "127.0.0.1", "HostPort": "8006"}], + "3389/tcp": [{"HostIp": "127.0.0.1", "HostPort": "3389"}], + "3389/udp": [{"HostIp": "127.0.0.1", "HostPort": "3389"}], +} +windows["Mounts"] = [ + {"Type": "bind", "Source": "/var/lib/omarchy/windows/mounts/users/1000/storage", + "Destination": "/storage", "RW": True}, + {"Type": "bind", "Source": "/var/lib/omarchy/windows/mounts/users/1000/shared", + "Destination": "/shared", "RW": True}, +] +assert migration.validate_windows_exception(windows) == "omarchy-windows" +for mutation in ("image", "labels", "devices", "mounts", "mount-source", "restart"): + changed = copy.deepcopy(windows) + if mutation == "image": + changed["Config"]["Image"] = "example/custom" + elif mutation == "labels": + changed["Config"]["Labels"] = {} + elif mutation == "devices": + changed["HostConfig"]["Devices"] = [] + elif mutation == "mounts": + changed["Mounts"] = [] + elif mutation == "mount-source": + changed["Mounts"][0]["Source"] = "/home/example/.windows" + else: + changed["HostConfig"]["RestartPolicy"] = {"Name": "always", "MaximumRetryCount": 0} + try: + migration.validate_windows_exception(changed) + except ValueError: + pass + else: + raise AssertionError(f"unmanaged Windows exception passed: {mutation}") +print("ok - only Omarchy's managed Windows runtime qualifies for the rootful exception") + blocked = ( ("Privileged", True), ("CapAdd", ["SYS_ADMIN"]), ("Devices", [{"PathOnHost": "/dev/kvm"}]), @@ -146,7 +228,7 @@ target["Id"] = "b" * 64 target["Config"]["Labels"][migration.LABEL] = stopped["Id"] with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory - migration.inspect = lambda engine, kind, name: copy.deepcopy(target) + migration.inspect = lambda engine, kind, name: copy.deepcopy(stopped if engine == migration.SOURCE else target) migration.record_completion(stopped, stopped["State"], False) assert migration.completed(stopped, target) stopped["RestartCount"] = 4 @@ -162,8 +244,19 @@ with tempfile.TemporaryDirectory() as directory: assert not migration.completed(stopped, target) print("ok - completion receipts bind both immutable workload snapshots and lifecycle state") +restarted = copy.deepcopy(stopped) +restarted["State"]["Running"] = True +migration.inspect = lambda engine, kind, name: copy.deepcopy(restarted if engine == migration.SOURCE else target) +try: + migration.record_completion(stopped, stopped["State"], False) +except ValueError: + pass +else: + raise AssertionError("a restarted source received a completion receipt") +print("ok - completion re-inspects the source and refuses a stale stopped state") + -def exercise_failed_transfer(after_start): +def exercise_failed_transfer(after_start, mutate_source=False): source = copy.deepcopy(container) source["Id"] = ("d" if after_start else "c") * 64 source["Name"] = "/post-start" if after_start else "/pre-start" @@ -182,10 +275,14 @@ def exercise_failed_transfer(after_start): current_source["State"] = { "Running": False, "StartedAt": "start", "FinishedAt": "finish", "ExitCode": 0, } + if mutate_source: + current_source["HostConfig"]["Memory"] += 4096 elif args[:2] == (migration.SOURCE, "update"): current_source["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} elif args[:2] == (migration.SOURCE, "start"): current_source["State"]["Running"] = True + elif args[:2] == (migration.SOURCE, "commit"): + return "sha256:" + ("f" if after_start else "e") * 64 migration.inspect = fake_inspect migration.run = fake_run @@ -209,11 +306,17 @@ def exercise_failed_transfer(after_start): calls, source = exercise_failed_transfer(False) assert (migration.TARGET, "rm", "--force", "pre-start") in calls -assert (migration.TARGET, "image", "rm", "omarchy-migrated:" + "c" * 64) in calls +assert (migration.TARGET, "image", "rm", "sha256:" + "e" * 64) in calls assert (migration.SOURCE, "start", "c" * 64) in calls assert source["State"]["Running"] print("ok - verification failure before first start removes the destination and restores the source") +calls, source = exercise_failed_transfer(False, mutate_source=True) +assert not any(call[:2] == (migration.SOURCE, "commit") for call in calls) +assert (migration.SOURCE, "start", "c" * 64) in calls +assert source["State"]["Running"] +print("ok - source configuration changes during stop abort before image transfer") + calls, source = exercise_failed_transfer(True) assert (migration.TARGET, "start", "post-start") in calls assert not any(call[:2] == (migration.TARGET, "rm") for call in calls) diff --git a/test/shell.d/rootless-docker-posture-test.sh b/test/shell.d/rootless-docker-posture-test.sh index 6cecb2f6bac5..fcc29f54e1c9 100755 --- a/test/shell.d/rootless-docker-posture-test.sh +++ b/test/shell.d/rootless-docker-posture-test.sh @@ -34,13 +34,25 @@ pass "the Docker endpoint activates only after rootless setup completes" migration="$ROOT/migrations/1789164756.sh" grep -q 'migration_user=$(id -un)' "$migration" || fail "migration trusts the USER environment instead of the current account" +lock_line=$(grep -n '/usr/bin/flock -n' "$migration" | cut -d: -f1) +package_line=$(grep -n '^omarchy-pkg-add docker-rootless-extras' "$migration" | cut -d: -f1) +[[ -n $lock_line && -n $package_line ]] && (( lock_line < package_line )) || + fail "same-account migrations are not serialized before any setup or transfer" completion_line=$(grep -n 'test -f "$machine_state/enabled"' "$migration" | cut -d: -f1) inventory_line=$(grep -n 'docker_inventory=' "$migration" | cut -d: -f1) [[ -n $completion_line && -n $inventory_line ]] && (( completion_line < inventory_line )) || fail "later accounts can reach the machine-wide retained rootful store" grep -q 'machine-wide rootful recovery store was left untouched' "$migration" || fail "later accounts do not have an explicit rootful-store no-op path" -pass "later accounts initialize only their private rootless daemon" +completion_return=$(grep -n 'machine-wide rootful recovery store was left untouched' "$migration" | cut -d: -f1) +later_group_drop=$(sed -n "${completion_line},${completion_return}p" "$migration" | grep -n '^ remove_legacy_docker_group' | cut -d: -f1) +[[ -n $later_group_drop ]] || fail "later accounts retain legacy docker-group membership" +socket_line=$(grep -n "socket_owner=" "$migration" | cut -d: -f1) +[[ -n $socket_line && -n $inventory_line ]] && (( socket_line < inventory_line )) || + fail "the legacy group socket remains writable during source migration" +grep -q -- '--check-windows "$windows_id"' "$migration" || + fail "the name-based Windows exception is not authenticated against its managed runtime" +pass "migration serializes ownership, restricts the source socket, and validates the Windows exception" grep -q "alias d='docker'" "$ROOT/default/bash/aliases" || fail "the d alias remains Docker" ! rg -q 'sudo[[:space:]]+docker' "$ROOT/bin/omarchy-install-docker-dbs" || From 876097937cf7f94c2cf817610cbb991d02cb752b Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Sat, 12 Sep 2026 01:31:55 -0600 Subject: [PATCH 03/31] Harden interrupted Docker migrations --- bin/omarchy-windows-vm | 16 +- default/docker/rootless/migrate.py | 263 +++++++++++++++--- migrations/1789164756.sh | 5 + .../shell.d/rootless-docker-migration-test.sh | 179 +++++++++++- test/shell.d/rootless-docker-posture-test.sh | 3 + test/shell.d/windows-vm-auth-test.sh | 21 ++ .../shell.d/windows-vm-mount-boundary-test.sh | 6 +- 7 files changed, 432 insertions(+), 61 deletions(-) diff --git a/bin/omarchy-windows-vm b/bin/omarchy-windows-vm index af18a8a36848..5a2ed9b63162 100755 --- a/bin/omarchy-windows-vm +++ b/bin/omarchy-windows-vm @@ -129,7 +129,7 @@ valid_password() { [[ $1 =~ ^[[:print:]]{1,64}$ ]]; } # ../tmp/evil from running an arbitrary file as root. valid_priv_action() { case "$1" in - write_compose | up | up_wait | down | status | remove) return 0 ;; + write_compose | secure | up | up_wait | down | status | remove) return 0 ;; *) return 1 ;; esac } @@ -893,6 +893,8 @@ assert_mounts_safe() { __priv_up() { assert_mounts_safe && dc up -d; } +__priv_secure() { assert_mounts_safe; } + __priv_down() { dc down; } # Bring the VM up and wait until the guest reports it is ready, all under a @@ -1119,6 +1121,15 @@ migrate_legacy_compose() { rm -f "$LEGACY_COMPOSE_FILE" } +secure_windows_migration() { + if [[ ! -f $COMPOSE_FILE && -f $LEGACY_COMPOSE_FILE ]]; then + migrate_legacy_compose || return 1 + fi + if [[ -f $COMPOSE_FILE ]]; then + priv secure || return 1 + fi +} + # --- prerequisites ----------------------------------------------------------- check_prerequisites() { @@ -1549,6 +1560,9 @@ show_usage() { # Main command dispatcher case "$1" in +__migration-secure) + secure_windows_migration + ;; __priv) ((EUID == 0)) || { echo "omarchy-windows-vm __priv must run as root" >&2 diff --git a/default/docker/rootless/migrate.py b/default/docker/rootless/migrate.py index affac267d4be..fda18f135505 100644 --- a/default/docker/rootless/migrate.py +++ b/default/docker/rootless/migrate.py @@ -3,15 +3,19 @@ import hashlib import json import os +import pwd import re +import secrets import stat import subprocess import sys +from copy import deepcopy from decimal import Decimal from pathlib import Path LABEL = "io.omarchy.rootless-docker.source-id" +VOLUME_LABEL = "io.omarchy.rootless-docker.source-volume" SOURCE = "source" TARGET = "target" TRUSTED_MANIFEST = "/usr/share/omarchy/default/docker/rootless/volume-manifest.py" @@ -160,7 +164,7 @@ def allowed_capabilities(container): # Explicit --cap-add gives even non-root processes capabilities. Docker's # default non-root process has none, so keep that source boundary. user = (container["Config"].get("User") or "").split(":", 1)[0] - if user and not user.isdecimal(): + if user and not re.fullmatch(r"[0-9]+", user): raise ValueError(f'{container["Name"].lstrip("/")}: named image users need an explicit migration') if user and int(user) != 0: return set() @@ -306,12 +310,125 @@ def destination_volume(container, mount): return mount["Name"] if explicit else f'omarchy-migrated-{mount["Name"]}' +def volume_identity(container, mount): + # Docker volume create is idempotent rather than exclusive. An unpredictable + # token lets us prove that the volume returned by that call is the one this + # migration just requested, even if another client races the predictable + # destination name between the existence check and creation. + return f'{container["Id"]}:{mount["Name"]}:{secrets.token_hex(32)}' + + def completion_path(identity): if not re.fullmatch(r"[a-f0-9]{64}", identity): raise ValueError("Unsupported Docker container identity") return Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state") / "omarchy/rootless-docker-migration" / identity +def intent_path(identity): + receipt = completion_path(identity) + return receipt.with_name(f"{receipt.name}.in-progress") + + +def write_private_json(path, payload): + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + temporary = path.with_suffix(f"{path.suffix}.tmp-{os.getpid()}") + try: + descriptor = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(descriptor, "w") as output: + json.dump(payload, output) + output.write("\n") + output.flush() + os.fsync(output.fileno()) + temporary.replace(path) + directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(directory) + finally: + os.close(directory) + finally: + temporary.unlink(missing_ok=True) + + +def record_migration_intent(container, stopped_state=None, saved=None, restart_disabled=False): + state = container["State"] + if saved is None: + payload = { + "source": container["Id"], + "source_snapshot": snapshot_digest(container), + "source_snapshot_ignore_restart": snapshot_digest(container, ignore_restart=True), + "source_restart_policy": deepcopy(container["HostConfig"].get("RestartPolicy") or {}), + "started_at": state["StartedAt"], + "target_running": bool(state["Running"]), + "restart_disabled": False, + } + if not state["Running"]: + payload["stopped"] = stopped_identity(state) + else: + payload = deepcopy(saved) + if stopped_state is not None: + payload["stopped"] = stopped_identity(stopped_state) + if restart_disabled: + payload["restart_disabled"] = True + write_private_json(intent_path(container["Id"]), payload) + return payload + + +def migration_intent(container): + path = intent_path(container["Id"]) + if not path.exists(): + return None + try: + saved = json.loads(path.read_text()) + restart_policy = saved["source_restart_policy"] + if (saved["source"] != container["Id"] or + not isinstance(saved["target_running"], bool) or + not isinstance(saved["restart_disabled"], bool) or + not isinstance(restart_policy, dict) or + saved["started_at"] != container["State"]["StartedAt"]): + raise ValueError + exact_snapshot = saved["source_snapshot"] == snapshot_digest(container) + disabled_snapshot = ( + saved["restart_disabled"] is True and + (container["HostConfig"].get("RestartPolicy") or {}).get("Name") == "no" and + saved["source_snapshot_ignore_restart"] == snapshot_digest(container, ignore_restart=True) + ) + if not exact_snapshot and not disabled_snapshot: + raise ValueError + if container["State"]["Running"]: + if saved["target_running"] is not True or "stopped" in saved: + raise ValueError + else: + current_stopped = stopped_identity(container["State"]) + if "stopped" in saved and saved["stopped"] != current_stopped: + raise ValueError + return saved + except (OSError, json.JSONDecodeError, KeyError, TypeError, ValueError) as error: + raise ValueError(f'{container["Name"].lstrip("/")}: interrupted migration state changed; inspect both engines') from error + + +def planned_source(container, intent): + if intent is None: + return container + planned = deepcopy(container) + planned["HostConfig"]["RestartPolicy"] = deepcopy(intent["source_restart_policy"]) + if snapshot_digest(planned) != intent["source_snapshot"]: + raise ValueError(f'{container["Name"].lstrip("/")}: interrupted migration cannot reconstruct the source configuration') + return planned + + +def clear_migration_intent(identity): + path = intent_path(identity) + try: + path.unlink() + except FileNotFoundError: + return + directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(directory) + finally: + os.close(directory) + + def completed(container, target): if (target["Config"].get("Labels") or {}).get(LABEL) != container["Id"]: return False @@ -344,22 +461,12 @@ def record_completion(container, source_state, target_running): raise RuntimeError(f'{container["Name"].lstrip("/")}: Docker source changed before completion; inspect both engines') container = latest_source target = inspect(TARGET, "container", container["Name"].lstrip("/")) - receipt = completion_path(container["Id"]) - receipt.parent.mkdir(parents=True, exist_ok=True, mode=0o700) - temporary = receipt.with_suffix(f".tmp-{os.getpid()}") - try: - descriptor = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) - with os.fdopen(descriptor, "w") as output: - json.dump({"target": target["Id"], "source": stopped_identity(source_state), - "target_running": target_running, - "source_snapshot": snapshot_digest(container), - "target_snapshot": snapshot_digest(target)}, output) - output.write("\n") - output.flush() - os.fsync(output.fileno()) - temporary.replace(receipt) - finally: - temporary.unlink(missing_ok=True) + write_private_json(completion_path(container["Id"]), { + "target": target["Id"], "source": stopped_identity(source_state), + "target_running": target_running, + "source_snapshot": snapshot_digest(container), + "target_snapshot": snapshot_digest(target), + }) def validate(container): @@ -372,6 +479,10 @@ def validate(container): if LABEL in labels: raise ValueError(f"{name}: reserved Omarchy migration labels need an explicit migration") allowed_capabilities(container) + stop_timeout = container["Config"].get("StopTimeout") + if (stop_timeout is not None and + (isinstance(stop_timeout, bool) or not isinstance(stop_timeout, int) or stop_timeout < -1)): + raise ValueError(f"{name}: unsupported stop timeout") environment = container["Config"].get("Env") or [] if (not isinstance(environment, list) or any(not isinstance(entry, str) or "=" not in entry for entry in environment) or @@ -432,22 +543,38 @@ def validate_windows_exception(container): mounts_by_destination = {mount.get("Destination"): mount for mount in mounts} storage = mounts_by_destination.get("/storage") or {} shared = mounts_by_destination.get("/shared") or {} - storage_match = re.fullmatch(r"/var/lib/omarchy/windows/mounts/users/([1-9][0-9]*)/storage", - storage.get("Source") or "") + account = pwd.getpwuid(os.getuid()) + protected = f"/var/lib/omarchy/windows/mounts/users/{account.pw_uid}" + legacy = account.pw_dir + previous = f'{Path(account.pw_dir).parent}/.omarchy-windows/users/{account.pw_uid}' + allowed_mounts = { + (f"{protected}/storage", f"{protected}/shared"), + (f"{legacy}/.windows", f"{legacy}/Windows"), + (f"{previous}/storage", f"{previous}/shared"), + } + networks = container.get("NetworkSettings", {}).get("Networks") or {} if (name != "omarchy-windows" or not re.fullmatch(r"[a-f0-9]{64}", container["Id"]) or config.get("Image") not in ("dockurr/windows", "dockurr/windows:latest") or labels.get("com.docker.compose.project") != "windows" or labels.get("com.docker.compose.service") != "windows" or host.get("Privileged") is not False or + host.get("AutoRemove") not in (None, False) or host.get("ReadonlyRootfs") not in (None, False) or {capability.upper().removeprefix("CAP_") for capability in host.get("CapAdd") or []} != {"NET_ADMIN"} or + host.get("CapDrop") or host.get("DeviceRequests") or host.get("DeviceCgroupRules") or + host.get("SecurityOpt") or host.get("PidMode") or host.get("UTSMode") or host.get("UsernsMode") or + host.get("NetworkMode") != "windows_default" or + host.get("IpcMode") not in (None, "", "private") or + host.get("CgroupnsMode") not in (None, "", "private") or + host.get("Runtime") not in (None, "", "runc") or devices != {("/dev/kvm", "/dev/kvm"), ("/dev/net/tun", "/dev/net/tun")} or + len(host.get("Devices") or []) != 2 or ports != expected_ports or (host.get("RestartPolicy") or {}).get("Name") != "no" or len(mounts) != 2 or any(mount.get("Type") != "bind" for mount in mounts) or any(mount.get("RW") is not True for mount in mounts) or - not storage_match or - shared.get("Source") != f"/var/lib/omarchy/windows/mounts/users/{storage_match.group(1)}/shared"): + (storage.get("Source"), shared.get("Source")) not in allowed_mounts or + set(networks) != {"windows_default"}): raise ValueError("omarchy-windows: the rootful exception does not match Omarchy's managed Windows VM") return name @@ -484,6 +611,22 @@ def source_volume_digest(volume): volume["Mountpoint"], capture=True) +def validate_source_volume(container, volume): + name = container["Name"].lstrip("/") + if (volume.get("Driver") != "local" or volume.get("Options") or + VOLUME_LABEL in (volume.get("Labels") or {})): + raise ValueError(f"{name}: custom volume configuration requires an explicit transfer") + + +def verify_volume_definition(volume, target, ownership): + expected_labels = dict(volume.get("Labels") or {}) + expected_labels[VOLUME_LABEL] = ownership + actual = inspect(TARGET, "volume", target) + if (actual.get("Name") != target or actual.get("Driver") != "local" or + actual.get("Options") not in (None, {}) or actual.get("Labels") != expected_labels): + raise RuntimeError("Destination volume ownership or configuration changed; retained it for inspection") + + def validate_trusted_manifest(): path = Path(TRUSTED_MANIFEST) try: @@ -546,10 +689,12 @@ def migrate(container): container = refresh_source(container) name = container["Name"].lstrip("/") identity = container["Id"] + intent = migration_intent(container) if exists("container", name): target = inspect(TARGET, "container", name) container = refresh_source(container) if completed(container, target): + clear_migration_intent(identity) print(f"{name}: already migrated") return raise ValueError(f"{name}: an existing rootless Docker container needs review; no completed transfer matches it") @@ -557,16 +702,27 @@ def migrate(container): raise ValueError(f"{name}: a previously migrated destination is missing; inspect retained data before retrying") container = refresh_source(container) - running = container["State"]["Running"] + intent = migration_intent(container) + planned = planned_source(container, intent) + running = intent["target_running"] if intent is not None else bool(container["State"]["Running"]) created = False image = None + image_committed = False image_loaded = False start_attempted = False restart_changed = False new_volumes = [] verified_volumes = {} + restart = planned["HostConfig"].get("RestartPolicy") or {} + policy = restart.get("Name") or "no" + if policy == "on-failure" and restart.get("MaximumRetryCount"): + policy += f':{restart["MaximumRetryCount"]}' try: - run(SOURCE, "stop", "-t", "120", identity) + if intent is None: + intent = record_migration_intent(container) + configured_timeout = planned["Config"].get("StopTimeout") + stop_timeout = -1 if configured_timeout == -1 else max(120, configured_timeout or 0) + run(SOURCE, "stop", "-t", str(stop_timeout), identity) stopped_source = inspect(SOURCE, "container", identity) state = stopped_source["State"] if state["Running"] or (running and state["ExitCode"] in (137, 139)): @@ -575,19 +731,23 @@ def migrate(container): if snapshot_digest(stopped_source) != snapshot_digest(container): raise RuntimeError(f"{name}: Docker source configuration changed while stopping; rerun after workloads are stable") container = stopped_source + intent = record_migration_intent(container, state, intent) # Commit includes writable-layer changes and the exact image config. # Volume data is copied separately while the source container is stopped. image = run(SOURCE, "commit", identity, capture=True) if not re.fullmatch(r"sha256:[a-f0-9]{64}", image or ""): raise RuntimeError(f"{name}: Docker did not return a transferable committed image") - pipe([SOURCE, "image", "save", image], [TARGET, "image", "load", "--quiet"]) - image_loaded = True + image_committed = True + if not exists("image", image): + pipe([SOURCE, "image", "save", image], [TARGET, "image", "load", "--quiet"]) + image_loaded = True run(SOURCE, "image", "rm", image) + image_committed = False arguments = [TARGET, "create", "--pull=never", "--name", name, "--label", f"{LABEL}={identity}", "--privileged=false", "--ipc=private", "--cgroupns=private", "--network=bridge"] - arguments += runtime_arguments(container) - config = container["Config"] + arguments += runtime_arguments(planned) + config = planned["Config"] if config.get("Hostname"): arguments += ["--hostname", config["Hostname"]] if config.get("StopTimeout") is not None: @@ -599,27 +759,25 @@ def migrate(container): arguments += ["--tty"] if config.get("OpenStdin"): arguments += ["--interactive"] - restart = container["HostConfig"].get("RestartPolicy") or {} - policy = restart.get("Name") or "no" - if policy == "on-failure" and restart.get("MaximumRetryCount"): - policy += f':{restart["MaximumRetryCount"]}' arguments += ["--restart", policy] - for port, bindings in (container["HostConfig"].get("PortBindings") or {}).items(): + for port, bindings in (planned["HostConfig"].get("PortBindings") or {}).items(): for binding in bindings or []: arguments += ["--publish", f'127.0.0.1:{binding["HostPort"]}:{port}'] - for mount in container.get("Mounts", []): + for mount in planned.get("Mounts", []): volume = inspect(SOURCE, "volume", mount["Name"]) - if volume.get("Options"): - raise ValueError(f"{name}: volume driver options require an explicit transfer") - target = destination_volume(container, mount) + validate_source_volume(container, volume) + target = destination_volume(planned, mount) if exists("volume", target): raise ValueError(f"{name}: destination volume already exists; retained it for inspection") volume_arguments = [TARGET, "volume", "create"] for key, value in (volume.get("Labels") or {}).items(): volume_arguments += ["--label", f"{key}={value}"] + ownership = volume_identity(planned, mount) + volume_arguments += ["--label", f"{VOLUME_LABEL}={ownership}"] run(*volume_arguments, target) + verify_volume_definition(volume, target, ownership) new_volumes.append(target) - verified_volumes[target] = (volume, transfer_volume(volume, target)) + verified_volumes[target] = (volume, ownership, transfer_volume(volume, target)) mount_arg = f'type=volume,src={target},dst={mount["Destination"]},volume-nocopy' if not mount.get("RW"): mount_arg += ",readonly" @@ -629,9 +787,10 @@ def migrate(container): created = True # The container has not started, and volume-nocopy prevents image data # from replacing the restored volume contents. - verify_runtime(container) + verify_runtime(planned) for target, expected in verified_volumes.items(): - volume, digest = expected + volume, ownership, digest = expected + verify_volume_definition(volume, target, ownership) verify_volume(target, digest) if source_volume_digest(volume) != digest: raise RuntimeError(f"{name}: source volume changed during transfer; inspect both engines") @@ -641,11 +800,12 @@ def migrate(container): raise RuntimeError(f"{name}: Docker source changed during transfer; inspect both engines") # A later workload may fail, leaving Docker installed. Prevent a daemon # restart from reviving this stale source alongside its migrated copy. + intent = record_migration_intent(container, state, intent, restart_disabled=True) restart_changed = True run(SOURCE, "update", "--restart=no", identity) source_after = inspect(SOURCE, "container", identity) if (stopped_identity(source_after["State"]) != stopped_identity(state) or - snapshot_digest(source_after, ignore_restart=True) != snapshot_digest(container, ignore_restart=True) or + snapshot_digest(source_after, ignore_restart=True) != snapshot_digest(planned, ignore_restart=True) or (source_after["HostConfig"].get("RestartPolicy") or {}).get("Name") != "no"): raise RuntimeError(f"{name}: Docker source changed during finalization; inspect both engines") if running: @@ -658,8 +818,9 @@ def migrate(container): target_state = inspect(TARGET, "container", name)["State"] if bool(target_state["Running"]) != bool(running): raise RuntimeError(f"{name}: destination lifecycle differs from the source") - verify_runtime(container) + verify_runtime(planned) record_completion(source_after, state, bool(running)) + clear_migration_intent(identity) print(f"{name}: migrated to rootless Docker; rootful copy retained for recovery") except BaseException: if start_attempted: @@ -667,13 +828,16 @@ def migrate(container): "Inspect rootless Docker before resuming the rootful copy or retrying migration.", file=sys.stderr) raise recovery = [] + recovery_failed = False if created: recovery.append((TARGET, "rm", "--force", name)) for volume in new_volumes: recovery.append((TARGET, "volume", "rm", volume)) if image_loaded: recovery.append((TARGET, "image", "rm", image)) - if restart_changed: + if image_committed: + recovery.append((SOURCE, "image", "rm", image)) + if restart_changed or (container["HostConfig"].get("RestartPolicy") or {}) != restart: recovery.append((SOURCE, "update", f"--restart={policy}", identity)) if running: recovery.append((SOURCE, "start", identity)) @@ -682,7 +846,16 @@ def migrate(container): run(*command) except Exception: # A failed cleanup must not prevent trying to restart Docker. + recovery_failed = True print(f"{name}: a recovery step failed; inspect both engines before retrying", file=sys.stderr) + if not recovery_failed: + try: + restored = inspect(SOURCE, "container", identity) + if (bool(restored["State"]["Running"]) == bool(running) and + snapshot_digest(restored) == snapshot_digest(planned)): + clear_migration_intent(identity) + except Exception: + pass raise @@ -715,7 +888,11 @@ def main(): continue for mount in container.get("Mounts", []): volume = inspect(SOURCE, "volume", mount["Name"]) - if volume.get("Options") or mount["Name"] in volumes: + try: + validate_source_volume(container, volume) + except ValueError as error: + blockers.append(str(error)) + if mount["Name"] in volumes: blockers.append(f'{container["Name"].lstrip("/")}: custom or shared volumes require an explicit transfer') volumes.add(mount["Name"]) if blockers: diff --git a/migrations/1789164756.sh b/migrations/1789164756.sh index 1c81e4a30384..f70fff9ffd3c 100644 --- a/migrations/1789164756.sh +++ b/migrations/1789164756.sh @@ -106,6 +106,11 @@ with os.fdopen(lock_fd, "w") as lock: temporary.replace(owner) PY +# Migrate any legacy user-side definition, pin its data into the protected root +# anchors, and rewrite the credential-bearing Compose file to root:root 0600. +# This performs no Docker lifecycle action. +/usr/bin/omarchy-windows-vm __migration-secure + sudo /usr/bin/systemctl daemon-reload sudo /usr/bin/systemctl start docker.socket source_host="unix:///run/docker.sock" diff --git a/test/shell.d/rootless-docker-migration-test.sh b/test/shell.d/rootless-docker-migration-test.sh index 6919e0ff751c..e5fd187a7acb 100755 --- a/test/shell.d/rootless-docker-migration-test.sh +++ b/test/shell.d/rootless-docker-migration-test.sh @@ -50,7 +50,7 @@ container = { "Config": { "Image": "local/project-worker:v1", "Hostname": "worker", "Domainname": "", "User": "1000", "Env": ["PRIVATE=not-logged"], "Labels": {"project": "fixture"}, - "Tty": False, "OpenStdin": False, + "Tty": False, "OpenStdin": False, "StopTimeout": 300, }, "HostConfig": { "NetworkMode": "bridge", "IpcMode": "private", "ShmSize": 128 * 1024 * 1024, @@ -96,7 +96,7 @@ numeric_root = copy.deepcopy(container) numeric_root["Config"]["User"] = "00:1000" numeric_root["HostConfig"]["CapDrop"] = [] assert migration.allowed_capabilities(numeric_root) == migration.DOCKER_CAPABILITIES -for named_user in ("root", "daemon", "root:root"): +for named_user in ("root", "daemon", "root:root", "\u0660"): changed = copy.deepcopy(container) changed["Config"]["User"] = named_user try: @@ -107,6 +107,21 @@ for named_user in ("root", "daemon", "root:root"): raise AssertionError(f"ambiguous named user passed preflight: {named_user}") print("ok - numeric UID zero keeps its capabilities and ambiguous named users fail closed") +for stop_timeout in (None, -1, 0, 300): + changed = copy.deepcopy(container) + changed["Config"]["StopTimeout"] = stop_timeout + assert migration.validate(changed) == "project-worker" +for stop_timeout in (True, -2, "300"): + changed = copy.deepcopy(container) + changed["Config"]["StopTimeout"] = stop_timeout + try: + migration.validate(changed) + except ValueError: + pass + else: + raise AssertionError(f"unsupported stop timeout passed preflight: {stop_timeout!r}") +print("ok - stop timeouts are type checked and larger application grace periods are retained") + for field, value in (("Labels", {migration.LABEL: "old"}), ("Env", ["DUPLICATE=one", "DUPLICATE=two"])): changed = copy.deepcopy(container) @@ -129,7 +144,12 @@ windows["Config"]["Labels"] = { } windows["HostConfig"]["Privileged"] = False windows["HostConfig"]["CapAdd"] = ["NET_ADMIN"] +windows["HostConfig"]["CapDrop"] = [] +windows["HostConfig"]["DeviceRequests"] = [] +windows["HostConfig"]["DeviceCgroupRules"] = [] +windows["HostConfig"]["SecurityOpt"] = [] windows["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} +windows["HostConfig"]["NetworkMode"] = "windows_default" windows["HostConfig"]["Devices"] = [ {"PathOnHost": "/dev/kvm", "PathInContainer": "/dev/kvm"}, {"PathOnHost": "/dev/net/tun", "PathInContainer": "/dev/net/tun"}, @@ -139,14 +159,22 @@ windows["HostConfig"]["PortBindings"] = { "3389/tcp": [{"HostIp": "127.0.0.1", "HostPort": "3389"}], "3389/udp": [{"HostIp": "127.0.0.1", "HostPort": "3389"}], } +uid = os.getuid() windows["Mounts"] = [ - {"Type": "bind", "Source": "/var/lib/omarchy/windows/mounts/users/1000/storage", + {"Type": "bind", "Source": f"/var/lib/omarchy/windows/mounts/users/{uid}/storage", "Destination": "/storage", "RW": True}, - {"Type": "bind", "Source": "/var/lib/omarchy/windows/mounts/users/1000/shared", + {"Type": "bind", "Source": f"/var/lib/omarchy/windows/mounts/users/{uid}/shared", "Destination": "/shared", "RW": True}, ] +windows["NetworkSettings"]["Networks"] = {"windows_default": {}} assert migration.validate_windows_exception(windows) == "omarchy-windows" -for mutation in ("image", "labels", "devices", "mounts", "mount-source", "restart"): +legacy_windows = copy.deepcopy(windows) +account = migration.pwd.getpwuid(uid) +legacy_windows["Mounts"][0]["Source"] = f"{account.pw_dir}/.windows" +legacy_windows["Mounts"][1]["Source"] = f"{account.pw_dir}/Windows" +assert migration.validate_windows_exception(legacy_windows) == "omarchy-windows" +for mutation in ("image", "labels", "devices", "extra-device", "device-rules", "security-opt", + "mounts", "mount-source", "restart", "network-mode", "extra-network", "autoremove"): changed = copy.deepcopy(windows) if mutation == "image": changed["Config"]["Image"] = "example/custom" @@ -154,12 +182,24 @@ for mutation in ("image", "labels", "devices", "mounts", "mount-source", "restar changed["Config"]["Labels"] = {} elif mutation == "devices": changed["HostConfig"]["Devices"] = [] + elif mutation == "extra-device": + changed["HostConfig"]["Devices"].append({"PathOnHost": "/dev/null", "PathInContainer": "/dev/null"}) + elif mutation == "device-rules": + changed["HostConfig"]["DeviceCgroupRules"] = ["a *:* rwm"] + elif mutation == "security-opt": + changed["HostConfig"]["SecurityOpt"] = ["seccomp=unconfined"] elif mutation == "mounts": changed["Mounts"] = [] elif mutation == "mount-source": - changed["Mounts"][0]["Source"] = "/home/example/.windows" - else: + changed["Mounts"][0]["Source"] = "/tmp/unmanaged-windows" + elif mutation == "restart": changed["HostConfig"]["RestartPolicy"] = {"Name": "always", "MaximumRetryCount": 0} + elif mutation == "network-mode": + changed["HostConfig"]["NetworkMode"] = "host" + elif mutation == "extra-network": + changed["NetworkSettings"]["Networks"]["unexpected"] = {} + else: + changed["HostConfig"]["AutoRemove"] = True try: migration.validate_windows_exception(changed) except ValueError: @@ -168,6 +208,33 @@ for mutation in ("image", "labels", "devices", "mounts", "mount-source", "restar raise AssertionError(f"unmanaged Windows exception passed: {mutation}") print("ok - only Omarchy's managed Windows runtime qualifies for the rootful exception") +source_volume = {"Name": "project-data", "Driver": "local", "Options": None, + "Labels": {"project": "fixture"}} +ownership = migration.volume_identity(container, container["Mounts"][0]) +assert ownership != migration.volume_identity(container, container["Mounts"][0]) +raced_volume = copy.deepcopy(source_volume) +raced_volume["Labels"] = {"project": "fixture"} +migration.inspect = lambda engine, kind, name: copy.deepcopy(raced_volume) +try: + migration.verify_volume_definition(source_volume, "project-data", ownership) +except RuntimeError: + pass +else: + raise AssertionError("an independently created destination volume was claimed") +owned_volume = copy.deepcopy(source_volume) +owned_volume["Labels"][migration.VOLUME_LABEL] = ownership +migration.inspect = lambda engine, kind, name: copy.deepcopy(owned_volume) +migration.verify_volume_definition(source_volume, "project-data", ownership) +reserved_source = copy.deepcopy(source_volume) +reserved_source["Labels"][migration.VOLUME_LABEL] = "foreign" +try: + migration.validate_source_volume(container, reserved_source) +except ValueError: + pass +else: + raise AssertionError("a source volume with the migration ownership label was accepted") +print("ok - destination volumes require an unpredictable ownership label before copy or cleanup") + blocked = ( ("Privileged", True), ("CapAdd", ["SYS_ADMIN"]), ("Devices", [{"PathOnHost": "/dev/kvm"}]), @@ -255,8 +322,39 @@ else: raise AssertionError("a restarted source received a completion receipt") print("ok - completion re-inspects the source and refuses a stale stopped state") +intent_source = copy.deepcopy(container) +intent_source["Mounts"] = [] +intent_source["HostConfig"]["Binds"] = [] +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + intent = migration.record_migration_intent(intent_source) + assert migration.migration_intent(intent_source) == intent + stopped_intent_source = copy.deepcopy(intent_source) + stopped_intent_source["State"] = { + "Running": False, "StartedAt": "start", "FinishedAt": "stopped", "ExitCode": 0, + } + intent = migration.record_migration_intent(stopped_intent_source, stopped_intent_source["State"], intent) + intent = migration.record_migration_intent(stopped_intent_source, stopped_intent_source["State"], intent, + restart_disabled=True) + disabled_source = copy.deepcopy(stopped_intent_source) + disabled_source["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} + loaded = migration.migration_intent(disabled_source) + restored_plan = migration.planned_source(disabled_source, loaded) + assert restored_plan["HostConfig"]["RestartPolicy"] == intent_source["HostConfig"]["RestartPolicy"] + assert migration.snapshot_digest(restored_plan) == migration.snapshot_digest(stopped_intent_source) + changed = copy.deepcopy(disabled_source) + changed["Config"]["Hostname"] = "changed-during-interruption" + try: + migration.migration_intent(changed) + except ValueError: + pass + else: + raise AssertionError("interrupted source configuration drift was accepted") + assert migration.intent_path(intent_source["Id"]).stat().st_mode & 0o777 == 0o600 +print("ok - durable migration intent restores lifecycle and restart policy after interruption") + -def exercise_failed_transfer(after_start, mutate_source=False): +def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image=False): source = copy.deepcopy(container) source["Id"] = ("d" if after_start else "c") * 64 source["Name"] = "/post-start" if after_start else "/pre-start" @@ -265,6 +363,7 @@ def exercise_failed_transfer(after_start, mutate_source=False): current_source = copy.deepcopy(source) current_target = {"State": {"Running": False}} calls = [] + pipes = [] def fake_inspect(engine, kind, name): return copy.deepcopy(current_source if engine == migration.SOURCE else current_target) @@ -286,8 +385,8 @@ def exercise_failed_transfer(after_start, mutate_source=False): migration.inspect = fake_inspect migration.run = fake_run - migration.exists = lambda kind, name: False - migration.pipe = lambda producer, consumer: None + migration.exists = lambda kind, name: preexisting_image and kind == "image" + migration.pipe = lambda producer, consumer: pipes.append((producer, consumer)) if after_start: migration.verify_runtime = lambda value: None else: @@ -301,28 +400,80 @@ def exercise_failed_transfer(after_start, mutate_source=False): pass else: raise AssertionError("failed transfer was reported as complete") - return calls, current_source + intent_retained = migration.intent_path(source["Id"]).exists() + return calls, current_source, pipes, intent_retained -calls, source = exercise_failed_transfer(False) +calls, source, pipes, intent_retained = exercise_failed_transfer(False) assert (migration.TARGET, "rm", "--force", "pre-start") in calls assert (migration.TARGET, "image", "rm", "sha256:" + "e" * 64) in calls +assert (migration.SOURCE, "stop", "-t", "300", "c" * 64) in calls assert (migration.SOURCE, "start", "c" * 64) in calls assert source["State"]["Running"] +assert not intent_retained print("ok - verification failure before first start removes the destination and restores the source") -calls, source = exercise_failed_transfer(False, mutate_source=True) +calls, source, pipes, intent_retained = exercise_failed_transfer(False, mutate_source=True) assert not any(call[:2] == (migration.SOURCE, "commit") for call in calls) assert (migration.SOURCE, "start", "c" * 64) in calls assert source["State"]["Running"] +assert intent_retained print("ok - source configuration changes during stop abort before image transfer") -calls, source = exercise_failed_transfer(True) +calls, source, pipes, intent_retained = exercise_failed_transfer(True) assert (migration.TARGET, "start", "post-start") in calls assert not any(call[:2] == (migration.TARGET, "rm") for call in calls) assert not any(call[:3] == (migration.TARGET, "image", "rm") for call in calls) assert not any(call[:2] == (migration.SOURCE, "start") for call in calls) assert source["HostConfig"]["RestartPolicy"]["Name"] == "no" assert not source["State"]["Running"] +assert intent_retained print("ok - any destination start attempt retains both copies and keeps the source stopped") + +calls, source, pipes, intent_retained = exercise_failed_transfer(False, preexisting_image=True) +assert not pipes +assert not any(call[:3] == (migration.TARGET, "image", "rm") for call in calls) +assert (migration.SOURCE, "image", "rm", "sha256:" + "e" * 64) in calls +print("ok - a preexisting target image digest is reused without claiming or deleting it") + +retry_original = copy.deepcopy(container) +retry_original["Id"] = "9" * 64 +retry_original["Name"] = "/interrupted-retry" +retry_original["Mounts"] = [] +retry_original["HostConfig"]["Binds"] = [] +retry_source = copy.deepcopy(retry_original) +retry_source["State"] = { + "Running": False, "StartedAt": "start", "FinishedAt": "power-loss-stop", "ExitCode": 0, +} +retry_source["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} +retry_target = {"State": {"Running": False}} +retry_calls = [] +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + retry_intent = migration.record_migration_intent(retry_original) + retry_intent = migration.record_migration_intent(retry_original, retry_source["State"], retry_intent, + restart_disabled=True) + + def retry_inspect(engine, kind, name): + return copy.deepcopy(retry_source if engine == migration.SOURCE else retry_target) + + def retry_run(*args, **kwargs): + retry_calls.append(args) + if args[:2] == (migration.SOURCE, "commit"): + return "sha256:" + "8" * 64 + if args[:2] == (migration.TARGET, "start"): + retry_target["State"]["Running"] = True + + migration.inspect = retry_inspect + migration.run = retry_run + migration.exists = lambda kind, name: False + migration.pipe = lambda producer, consumer: None + migration.verify_runtime = lambda value: None + migration.record_completion = lambda source, state, running: None + migration.migrate(retry_source) + create_call = next(call for call in retry_calls if call[:2] == (migration.TARGET, "create")) + assert create_call[create_call.index("--restart") + 1] == "unless-stopped" + assert (migration.TARGET, "start", "interrupted-retry") in retry_calls + assert not migration.intent_path(retry_source["Id"]).exists() +print("ok - a fresh process resumes a stopped migration with the original running and restart intent") PY diff --git a/test/shell.d/rootless-docker-posture-test.sh b/test/shell.d/rootless-docker-posture-test.sh index fcc29f54e1c9..bfa76441d5e6 100755 --- a/test/shell.d/rootless-docker-posture-test.sh +++ b/test/shell.d/rootless-docker-posture-test.sh @@ -52,6 +52,9 @@ socket_line=$(grep -n "socket_owner=" "$migration" | cut -d: -f1) fail "the legacy group socket remains writable during source migration" grep -q -- '--check-windows "$windows_id"' "$migration" || fail "the name-based Windows exception is not authenticated against its managed runtime" +windows_secure_line=$(grep -n '^/usr/bin/omarchy-windows-vm __migration-secure$' "$migration" | cut -d: -f1) +[[ -n $windows_secure_line && -n $inventory_line ]] && (( windows_secure_line < inventory_line )) || + fail "legacy Windows credentials and mounts are not secured before rootful inventory" pass "migration serializes ownership, restricts the source socket, and validates the Windows exception" grep -q "alias d='docker'" "$ROOT/default/bash/aliases" || fail "the d alias remains Docker" diff --git a/test/shell.d/windows-vm-auth-test.sh b/test/shell.d/windows-vm-auth-test.sh index 65a9580c5ae4..6f58c9e2ba1d 100644 --- a/test/shell.d/windows-vm-auth-test.sh +++ b/test/shell.d/windows-vm-auth-test.sh @@ -45,3 +45,24 @@ with tempfile.TemporaryDirectory() as directory: os.close(master) print(f"ok - {name} uses {expected} while privileged status output is captured") PY + +test_dir=$(mktemp -d) +trap 'rm -rf "$test_dir"' EXIT +touch "$test_dir/docker-compose.yml" +MODE_LOG="$test_dir/mode" OMARCHY_WINDOWS_DIR="$test_dir" ROOT="$ROOT" bash -c ' + set -e + set -- help + source "$ROOT/bin/omarchy-windows-vm" >/dev/null + priv() { printf "%s" "$1" >"$MODE_LOG"; } + secure_windows_migration + [[ $(<"$MODE_LOG") == "secure" ]] + valid_priv_action secure + rm "$OMARCHY_WINDOWS_DIR/docker-compose.yml" + mkdir -p "$HOME/.config/windows" + touch "$HOME/.config/windows/docker-compose.yml" + migrate_legacy_compose() { return 23; } + if secure_windows_migration; then + exit 1 + fi +' +pass "migration security repair authenticates and propagates upgrade failures" diff --git a/test/shell.d/windows-vm-mount-boundary-test.sh b/test/shell.d/windows-vm-mount-boundary-test.sh index 66b4111ebe73..10a9ac008743 100644 --- a/test/shell.d/windows-vm-mount-boundary-test.sh +++ b/test/shell.d/windows-vm-mount-boundary-test.sh @@ -153,7 +153,7 @@ pass "disk-space accounting measures the actual storage filesystem, not home" printf 'RAM=4G\nCORES=2\nDISK=64G\nUSERNAME=alice\nPASSWORD=pw\nTZ=UTC\n' | with_vm_lock __priv_write_compose [[ $(command stat -Lc '%u:%g:%a' "$COMPOSE_FILE") == 0:0:600 ]] || fail "root compose ownership/mode is wrong" -with_vm_lock assert_mounts_safe || fail "final root mount/compose assertion rejected the verified pair" +with_vm_lock __priv_secure || fail "migration security action rejected the verified pair" pass "root writer and final pre-Docker guard revalidate the pinned production mounts" # Upgrade the exact sibling-anchor pair emitted by the earlier fix without @@ -162,7 +162,7 @@ sed -i "s|$EXPECTED_STORAGE:/storage|$OLD_EXPECTED_STORAGE:/storage|" "$COMPOSE_ sed -i "s|$EXPECTED_SHARED:/shared|$OLD_EXPECTED_SHARED:/shared|" "$COMPOSE_FILE" sed -i '/PROTECT: "Y"/d' "$COMPOSE_FILE" compose_needs_security_migration || fail "previous protected compose was not recognized for upgrade" -with_vm_lock assert_mounts_safe || fail "root could not upgrade previous protected anchors" +with_vm_lock __priv_secure || fail "root could not upgrade previous protected anchors" grep -q -- "- $EXPECTED_STORAGE:/storage" "$COMPOSE_FILE" || fail "upgrade did not rewrite storage anchor" grep -q -- "- $EXPECTED_SHARED:/shared" "$COMPOSE_FILE" || fail "upgrade did not rewrite shared anchor" grep -q 'PROTECT: "Y"' "$COMPOSE_FILE" || fail "upgrade did not protect the web console" @@ -173,7 +173,7 @@ pass "previous sibling-anchor installs upgrade in place to the fixed /var/lib bo # upgrade when it predates web-console authentication. sed -i '/PROTECT: "Y"/d' "$COMPOSE_FILE" compose_needs_security_migration || fail "unprotected fixed-anchor compose was not recognized for upgrade" -with_vm_lock assert_mounts_safe || fail "root could not protect an existing fixed-anchor compose" +with_vm_lock __priv_secure || fail "root could not protect an existing fixed-anchor compose" grep -q 'PROTECT: "Y"' "$COMPOSE_FILE" || fail "fixed-anchor upgrade did not protect the web console" pass "existing fixed-anchor compose gains web-console authentication" From 9db8650d82fd0d72512409713df201b58cc931cb Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Sat, 12 Sep 2026 02:33:12 -0600 Subject: [PATCH 04/31] Harden rootless Docker recovery --- default/docker/rootless/migrate.py | 383 ++++++++++++++++-- docs/rootless-docker.md | 4 +- migrations/1789164756.sh | 60 ++- .../shell.d/rootless-docker-migration-test.sh | 173 +++++++- test/shell.d/rootless-docker-posture-test.sh | 12 +- 5 files changed, 569 insertions(+), 63 deletions(-) diff --git a/default/docker/rootless/migrate.py b/default/docker/rootless/migrate.py index fda18f135505..a673279b07c4 100644 --- a/default/docker/rootless/migrate.py +++ b/default/docker/rootless/migrate.py @@ -15,6 +15,7 @@ LABEL = "io.omarchy.rootless-docker.source-id" +OWNERSHIP_LABEL = "io.omarchy.rootless-docker.ownership" VOLUME_LABEL = "io.omarchy.rootless-docker.source-volume" SOURCE = "source" TARGET = "target" @@ -167,6 +168,10 @@ def allowed_capabilities(container): if user and not re.fullmatch(r"[0-9]+", user): raise ValueError(f'{container["Name"].lstrip("/")}: named image users need an explicit migration') if user and int(user) != 0: + dropped = {capability.upper().removeprefix("CAP_") + for capability in container["HostConfig"].get("CapDrop") or []} + if "ALL" not in dropped: + raise ValueError(f'{container["Name"].lstrip("/")}: non-root image users need cap-drop ALL for an exact migration') return set() # Docker API clients can retain mixed-case names in inspected CapDrop. dropped = {capability.upper().removeprefix("CAP_") for capability in container["HostConfig"].get("CapDrop") or []} @@ -191,7 +196,7 @@ def mapping(entries): raise RuntimeError("rootless Docker did not preserve the source environment; application was not started") -def verify_runtime(container): +def verify_runtime(container, ownership=None): name = container["Name"].lstrip("/") target = inspect(TARGET, "container", name) verify_environment(container, target["Config"].get("Env")) @@ -236,6 +241,8 @@ def verify_runtime(container): raise RuntimeError(f"{name}: rootless Docker changed the capability ceiling") expected_labels = dict(container["Config"].get("Labels") or {}) expected_labels[LABEL] = container["Id"] + if ownership is not None: + expected_labels[OWNERSHIP_LABEL] = ownership if target["Config"].get("Labels") != expected_labels: raise RuntimeError(f"{name}: rootless Docker changed the container labels") source_config = dict(container["Config"]) @@ -360,6 +367,10 @@ def record_migration_intent(container, stopped_state=None, saved=None, restart_d "started_at": state["StartedAt"], "target_running": bool(state["Running"]), "restart_disabled": False, + "restore_started": False, + "start_attempted": False, + "target_ownership": secrets.token_hex(32), + "volumes": {}, } if not state["Running"]: payload["stopped"] = stopped_identity(state) @@ -367,6 +378,7 @@ def record_migration_intent(container, stopped_state=None, saved=None, restart_d payload = deepcopy(saved) if stopped_state is not None: payload["stopped"] = stopped_identity(stopped_state) + payload["restore_started"] = False if restart_disabled: payload["restart_disabled"] = True write_private_json(intent_path(container["Id"]), payload) @@ -383,8 +395,12 @@ def migration_intent(container): if (saved["source"] != container["Id"] or not isinstance(saved["target_running"], bool) or not isinstance(saved["restart_disabled"], bool) or + not isinstance(saved["restore_started"], bool) or + not isinstance(saved["start_attempted"], bool) or + not re.fullmatch(r"[a-f0-9]{64}", saved["target_ownership"]) or + not isinstance(saved["volumes"], dict) or not isinstance(restart_policy, dict) or - saved["started_at"] != container["State"]["StartedAt"]): + not isinstance(saved["started_at"], str)): raise ValueError exact_snapshot = saved["source_snapshot"] == snapshot_digest(container) disabled_snapshot = ( @@ -395,9 +411,15 @@ def migration_intent(container): if not exact_snapshot and not disabled_snapshot: raise ValueError if container["State"]["Running"]: - if saved["target_running"] is not True or "stopped" in saved: + resumed_restore = (saved["restore_started"] is True and + saved["target_running"] is True and exact_snapshot) + if (saved["target_running"] is not True or + ("stopped" in saved and not resumed_restore) or + (saved["started_at"] != container["State"]["StartedAt"] and not resumed_restore)): raise ValueError else: + if saved["started_at"] != container["State"]["StartedAt"]: + raise ValueError current_stopped = stopped_identity(container["State"]) if "stopped" in saved and saved["stopped"] != current_stopped: raise ValueError @@ -429,6 +451,17 @@ def clear_migration_intent(identity): os.close(directory) +def persist_migration_intent(container, intent): + write_private_json(intent_path(container["Id"]), intent) + return intent + + +def target_owned(container, target, intent): + labels = target["Config"].get("Labels") or {} + return (labels.get(LABEL) == container["Id"] and + labels.get(OWNERSHIP_LABEL) == intent["target_ownership"]) + + def completed(container, target): if (target["Config"].get("Labels") or {}).get(LABEL) != container["Id"]: return False @@ -476,8 +509,12 @@ def validate(container): if not re.fullmatch(r"[a-f0-9]{64}", container["Id"]): raise ValueError("Unsupported Docker container identity") labels = container["Config"].get("Labels") or {} - if LABEL in labels: + if labels.keys() & {LABEL, OWNERSHIP_LABEL}: raise ValueError(f"{name}: reserved Omarchy migration labels need an explicit migration") + state = container["State"] + if (state.get("Paused") or state.get("Restarting") or state.get("Dead") or + state.get("RemovalInProgress")): + raise ValueError(f"{name}: paused or transitional lifecycle state requires an explicit migration") allowed_capabilities(container) stop_timeout = container["Config"].get("StopTimeout") if (stop_timeout is not None and @@ -627,6 +664,14 @@ def verify_volume_definition(volume, target, ownership): raise RuntimeError("Destination volume ownership or configuration changed; retained it for inspection") +def validate_volume_record(container, mount, record): + expected = rf'{container["Id"]}:{re.escape(mount["Name"])}:[a-f0-9]{{64}}' + if (not isinstance(record, dict) or record.get("source") != mount["Name"] or + not re.fullmatch(expected, record.get("ownership") or "")): + raise ValueError(f'{container["Name"].lstrip("/")}: interrupted destination volume record changed') + return record["ownership"] + + def validate_trusted_manifest(): path = Path(TRUSTED_MANIFEST) try: @@ -665,8 +710,16 @@ def snapshot_digest(container, ignore_restart=False): fields = ("Id", "Name", "Image", "Config", "HostConfig", "Mounts", "AppArmorProfile", "ProcessLabel", "MountLabel") snapshot = {field: container.get(field) for field in fields} + # Docker can rewrite top-level API defaults across a daemon restart (for + # example HostConfig.Dns changes from null to []). These representations + # have the same runtime meaning and must not invalidate a durable journal. + snapshot["HostConfig"] = { + key: value for key, value in (snapshot["HostConfig"] or {}).items() + if not (value is None or value is False or value == "" or value == [] or value == {}) + } + snapshot["Mounts"] = sorted(snapshot["Mounts"] or [], + key=lambda mount: json.dumps(mount, sort_keys=True, separators=(",", ":"))) if ignore_restart: - snapshot["HostConfig"] = dict(snapshot["HostConfig"] or {}) snapshot["HostConfig"].pop("RestartPolicy", None) networks = container.get("NetworkSettings", {}).get("Networks") or {} snapshot["Networks"] = { @@ -677,14 +730,149 @@ def snapshot_digest(container, ignore_restart=False): return hashlib.sha256(encoded.encode()).hexdigest() -def refresh_source(container): +def refresh_source(container, validator=validate): latest = inspect(SOURCE, "container", container["Id"]) if source_snapshot(latest) != source_snapshot(container): raise ValueError(f'{container["Name"].lstrip("/")}: Docker source changed after preflight; rerun migration after workloads are stable') - validate(latest) + validator(latest) return latest +def configured_stop_timeout(container): + configured = container["Config"].get("StopTimeout") + return -1 if configured == -1 else max(120, configured or 0) + + +def restart_policy_argument(container): + restart = container["HostConfig"].get("RestartPolicy") or {} + policy = restart.get("Name") or "no" + if policy == "on-failure" and restart.get("MaximumRetryCount"): + policy += f':{restart["MaximumRetryCount"]}' + return policy + + +def restore_source(identity, validator=validate): + current = inspect(SOURCE, "container", identity) + validator(current) + intent = migration_intent(current) + if intent is None: + return + planned = planned_source(current, intent) + desired_restart = planned["HostConfig"].get("RestartPolicy") or {} + if (current["HostConfig"].get("RestartPolicy") or {}) != desired_restart: + run(SOURCE, "update", f"--restart={restart_policy_argument(planned)}", identity) + current = inspect(SOURCE, "container", identity) + if intent["target_running"]: + if not current["State"]["Running"]: + intent["restore_started"] = True + persist_migration_intent(current, intent) + run(SOURCE, "start", identity) + elif current["State"]["Running"]: + raise RuntimeError(f'{current["Name"].lstrip("/")}: stopped source restarted during recovery') + restored = inspect(SOURCE, "container", identity) + validator(restored) + if (bool(restored["State"]["Running"]) != intent["target_running"] or + snapshot_digest(restored) != snapshot_digest(planned)): + raise RuntimeError(f'{restored["Name"].lstrip("/")}: source lifecycle could not be restored') + # A retry can enter batch quiescing with destination artifacts from an + # earlier interrupted transfer. If a later workload then fails to quiesce, + # restore this source without discarding the ownership needed to resume or + # inspect those artifacts safely. + if not intent["volumes"] and intent.get("destination") is None and not intent["start_attempted"]: + clear_migration_intent(identity) + + +def quiesce(container, validator=validate): + container = refresh_source(container, validator) + intent = migration_intent(container) + planned = planned_source(container, intent) + if intent is None: + intent = record_migration_intent(container) + if container["State"]["Running"]: + run(SOURCE, "stop", "-t", str(configured_stop_timeout(planned)), container["Id"]) + stopped = inspect(SOURCE, "container", container["Id"]) + state = stopped["State"] + if state["Running"] or state.get("ExitCode") in (137, 139): + raise RuntimeError(f'{container["Name"].lstrip("/")}: container did not stop cleanly; migration aborted') + if snapshot_digest(stopped) != snapshot_digest(container): + raise RuntimeError(f'{container["Name"].lstrip("/")}: Docker source changed while stopping; migration aborted') + container = stopped + state = container["State"] + stopped_identity(state) + intent = record_migration_intent(container, state, intent) + if (container["HostConfig"].get("RestartPolicy") or {}).get("Name") != "no": + intent = record_migration_intent(container, state, intent, restart_disabled=True) + run(SOURCE, "update", "--restart=no", container["Id"]) + disabled = inspect(SOURCE, "container", container["Id"]) + validator(disabled) + if (stopped_identity(disabled["State"]) != stopped_identity(state) or + snapshot_digest(disabled, ignore_restart=True) != snapshot_digest(planned, ignore_restart=True) or + (disabled["HostConfig"].get("RestartPolicy") or {}).get("Name") != "no"): + raise RuntimeError(f'{container["Name"].lstrip("/")}: source changed while being quiesced') + print(f'{container["Name"].lstrip("/")}: quiesced before rootful Docker access revocation') + + +def verify_resumable_migration(container, target, intent): + name = container["Name"].lstrip("/") + planned = planned_source(container, intent) + destination = intent.get("destination") + if (not isinstance(destination, dict) or destination.get("id") != target.get("Id") or + destination.get("snapshot") != snapshot_digest(target) or + not target_owned(container, target, intent)): + raise ValueError(f"{name}: interrupted rootless destination changed; inspect both engines") + if target["State"]["Running"]: + if not (intent["target_running"] and intent["start_attempted"]): + raise ValueError(f"{name}: interrupted rootless destination has an unexpected lifecycle") + verify_runtime(planned, intent["target_ownership"]) + + expected_volumes = {destination_volume(planned, mount): mount + for mount in planned.get("Mounts", [])} + if set(intent["volumes"]) != set(expected_volumes): + raise ValueError(f"{name}: interrupted destination volume inventory changed") + for target_name, mount in expected_volumes.items(): + record = intent["volumes"][target_name] + ownership = validate_volume_record(planned, mount, record) + if not re.fullmatch(r"[a-f0-9]{64}", record.get("digest") or ""): + raise ValueError(f"{name}: interrupted destination volume record is incomplete") + source_volume = inspect(SOURCE, "volume", mount["Name"]) + validate_source_volume(planned, source_volume) + verify_volume_definition(source_volume, target_name, ownership) + verify_volume(target_name, record["digest"]) + if source_volume_digest(source_volume) != record["digest"]: + raise RuntimeError(f"{name}: source volume changed after interruption; inspect both engines") + + state = container["State"] + if (stopped_identity(state) != intent.get("stopped") or + snapshot_digest(container, ignore_restart=True) != snapshot_digest(planned, ignore_restart=True)): + raise RuntimeError(f"{name}: rootful source changed after interruption; inspect both engines") + return planned, state + + +def resume_verified_migration(container, target, intent): + name = container["Name"].lstrip("/") + planned, state = verify_resumable_migration(container, target, intent) + if (container["HostConfig"].get("RestartPolicy") or {}).get("Name") != "no": + intent = record_migration_intent(container, state, intent, restart_disabled=True) + run(SOURCE, "update", "--restart=no", container["Id"]) + source_after = inspect(SOURCE, "container", container["Id"]) + if (stopped_identity(source_after["State"]) != stopped_identity(state) or + snapshot_digest(source_after, ignore_restart=True) != snapshot_digest(planned, ignore_restart=True) or + (source_after["HostConfig"].get("RestartPolicy") or {}).get("Name") != "no"): + raise RuntimeError(f"{name}: rootful source changed during resumed finalization") + + if intent["target_running"] and not target["State"]["Running"]: + intent["start_attempted"] = True + persist_migration_intent(source_after, intent) + run(TARGET, "start", name) + target = inspect(TARGET, "container", name) + if bool(target["State"]["Running"]) != intent["target_running"]: + raise RuntimeError(f"{name}: resumed destination lifecycle differs from the source") + verify_runtime(planned, intent["target_ownership"]) + record_completion(source_after, state, intent["target_running"]) + clear_migration_intent(container["Id"]) + print(f"{name}: completed the interrupted rootless Docker migration") + + def migrate(container): container = refresh_source(container) name = container["Name"].lstrip("/") @@ -697,7 +885,17 @@ def migrate(container): clear_migration_intent(identity) print(f"{name}: already migrated") return - raise ValueError(f"{name}: an existing rootless Docker container needs review; no completed transfer matches it") + if intent is None or not target_owned(container, target, intent): + raise ValueError(f"{name}: an existing rootless Docker container needs review; no owned transfer matches it") + if intent.get("destination") is not None: + resume_verified_migration(container, target, intent) + return + if target["State"]["Running"] or intent["start_attempted"]: + raise ValueError(f"{name}: an incomplete rootless destination may have run; inspect both engines") + owned_id = target["Id"] + run(TARGET, "rm", "--force", owned_id) + if exists("container", name): + raise ValueError(f"{name}: rootless destination name was replaced during recovery") if completion_path(identity).exists(): raise ValueError(f"{name}: a previously migrated destination is missing; inspect retained data before retrying") @@ -705,24 +903,22 @@ def migrate(container): intent = migration_intent(container) planned = planned_source(container, intent) running = intent["target_running"] if intent is not None else bool(container["State"]["Running"]) - created = False + created_id = None image = None image_committed = False image_loaded = False start_attempted = False restart_changed = False - new_volumes = [] verified_volumes = {} restart = planned["HostConfig"].get("RestartPolicy") or {} - policy = restart.get("Name") or "no" - if policy == "on-failure" and restart.get("MaximumRetryCount"): - policy += f':{restart["MaximumRetryCount"]}' + policy = restart_policy_argument(planned) try: if intent is None: intent = record_migration_intent(container) - configured_timeout = planned["Config"].get("StopTimeout") - stop_timeout = -1 if configured_timeout == -1 else max(120, configured_timeout or 0) - run(SOURCE, "stop", "-t", str(stop_timeout), identity) + expected_volume_names = {destination_volume(planned, mount) for mount in planned.get("Mounts", [])} + if set(intent["volumes"]) - expected_volume_names: + raise ValueError(f"{name}: interrupted destination volume inventory changed") + run(SOURCE, "stop", "-t", str(configured_stop_timeout(planned)), identity) stopped_source = inspect(SOURCE, "container", identity) state = stopped_source["State"] if state["Running"] or (running and state["ExitCode"] in (137, 139)): @@ -744,7 +940,8 @@ def migrate(container): run(SOURCE, "image", "rm", image) image_committed = False arguments = [TARGET, "create", "--pull=never", "--name", name, - "--label", f"{LABEL}={identity}", "--privileged=false", + "--label", f"{LABEL}={identity}", + "--label", f'{OWNERSHIP_LABEL}={intent["target_ownership"]}', "--privileged=false", "--ipc=private", "--cgroupns=private", "--network=bridge"] arguments += runtime_arguments(planned) config = planned["Config"] @@ -767,27 +964,41 @@ def migrate(container): volume = inspect(SOURCE, "volume", mount["Name"]) validate_source_volume(container, volume) target = destination_volume(planned, mount) - if exists("volume", target): - raise ValueError(f"{name}: destination volume already exists; retained it for inspection") + record = intent["volumes"].get(target) + if record is None: + if exists("volume", target): + raise ValueError(f"{name}: destination volume already exists; retained it for inspection") + ownership = volume_identity(planned, mount) + record = {"source": mount["Name"], "ownership": ownership} + intent["volumes"][target] = record + persist_migration_intent(container, intent) + else: + ownership = validate_volume_record(planned, mount, record) volume_arguments = [TARGET, "volume", "create"] for key, value in (volume.get("Labels") or {}).items(): volume_arguments += ["--label", f"{key}={value}"] - ownership = volume_identity(planned, mount) volume_arguments += ["--label", f"{VOLUME_LABEL}={ownership}"] - run(*volume_arguments, target) + if not exists("volume", target): + run(*volume_arguments, target) verify_volume_definition(volume, target, ownership) - new_volumes.append(target) - verified_volumes[target] = (volume, ownership, transfer_volume(volume, target)) + digest = transfer_volume(volume, target) + record["digest"] = digest + persist_migration_intent(container, intent) + verified_volumes[target] = (volume, ownership, digest) mount_arg = f'type=volume,src={target},dst={mount["Destination"]},volume-nocopy' if not mount.get("RW"): mount_arg += ",readonly" arguments += ["--mount", mount_arg] arguments.append(image) run(*arguments) - created = True + created_target = inspect(TARGET, "container", name) + if (not re.fullmatch(r"[a-f0-9]{64}", created_target.get("Id") or "") or + created_target["State"]["Running"] or not target_owned(planned, created_target, intent)): + raise RuntimeError(f"{name}: rootless destination ownership could not be proven") + created_id = created_target["Id"] # The container has not started, and volume-nocopy prevents image data # from replacing the restored volume contents. - verify_runtime(planned) + verify_runtime(planned, intent["target_ownership"]) for target, expected in verified_volumes.items(): volume, ownership, digest = expected verify_volume_definition(volume, target, ownership) @@ -798,6 +1009,11 @@ def migrate(container): if (stopped_identity(latest_source["State"]) != stopped_identity(state) or snapshot_digest(latest_source) != snapshot_digest(container)): raise RuntimeError(f"{name}: Docker source changed during transfer; inspect both engines") + target = inspect(TARGET, "container", created_id) + if not target_owned(planned, target, intent): + raise RuntimeError(f"{name}: rootless destination ownership changed during transfer") + intent["destination"] = {"id": created_id, "snapshot": snapshot_digest(target)} + persist_migration_intent(container, intent) # A later workload may fail, leaving Docker installed. Prevent a daemon # restart from reviving this stale source alongside its migrated copy. intent = record_migration_intent(container, state, intent, restart_disabled=True) @@ -812,27 +1028,37 @@ def migrate(container): # Even a failed start command may have launched an application that # accepted writes. From this point the destination is recovery data. start_attempted = True + intent["start_attempted"] = True + persist_migration_intent(source_after, intent) run(TARGET, "start", name) # A crash before this receipt leaves the destination for review. Its # label alone must never turn a partial transfer into a successful retry. target_state = inspect(TARGET, "container", name)["State"] if bool(target_state["Running"]) != bool(running): raise RuntimeError(f"{name}: destination lifecycle differs from the source") - verify_runtime(planned) + verify_runtime(planned, intent["target_ownership"]) record_completion(source_after, state, bool(running)) clear_migration_intent(identity) print(f"{name}: migrated to rootless Docker; rootful copy retained for recovery") except BaseException: + if intent is None: + raise if start_attempted: print(f"{name}: destination start was attempted; both copies were retained for recovery. " "Inspect rootless Docker before resuming the rootful copy or retrying migration.", file=sys.stderr) raise - recovery = [] recovery_failed = False - if created: - recovery.append((TARGET, "rm", "--force", name)) - for volume in new_volumes: - recovery.append((TARGET, "volume", "rm", volume)) + try: + owned_target = inspect(TARGET, "container", created_id or name) + if not target_owned(planned, owned_target, intent): + raise RuntimeError("rootless destination ownership changed") + run(TARGET, "rm", "--force", owned_target["Id"]) + except subprocess.CalledProcessError: + pass + except Exception: + recovery_failed = True + print(f"{name}: destination cleanup was not ownership-safe; retained it for inspection", file=sys.stderr) + recovery = [] if image_loaded: recovery.append((TARGET, "image", "rm", image)) if image_committed: @@ -840,6 +1066,12 @@ def migrate(container): if restart_changed or (container["HostConfig"].get("RestartPolicy") or {}) != restart: recovery.append((SOURCE, "update", f"--restart={policy}", identity)) if running: + try: + intent["restore_started"] = True + persist_migration_intent(container, intent) + except Exception: + recovery_failed = True + print(f"{name}: source recovery intent could not be saved", file=sys.stderr) recovery.append((SOURCE, "start", identity)) for command in recovery: try: @@ -848,7 +1080,14 @@ def migrate(container): # A failed cleanup must not prevent trying to restart Docker. recovery_failed = True print(f"{name}: a recovery step failed; inspect both engines before retrying", file=sys.stderr) - if not recovery_failed: + retained_volume = False + for target in intent["volumes"]: + try: + retained_volume = retained_volume or exists("volume", target) + except Exception: + recovery_failed = True + retained_volume = True + if not recovery_failed and not retained_volume: try: restored = inspect(SOURCE, "container", identity) if (bool(restored["State"]["Running"]) == bool(running) and @@ -863,6 +1102,66 @@ def main(): if os.geteuid() == 0: raise ValueError("Run the migration as the desktop user; the destination is always rootless") os.environ.setdefault("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}") + quiesce_all_mode = sys.argv[1:2] == ["--quiesce-all"] + if quiesce_all_mode: + if len(sys.argv) < 3: + raise ValueError("Expected a Windows identity placeholder before container names") + windows_identity = sys.argv[2] + names = sys.argv[3:] + validate_source_daemon(daemon_security(SOURCE)) + containers = [inspect(SOURCE, "container", name) for name in names] + volumes = set() + blockers = [] + for container in containers: + try: + validate(container) + except ValueError as error: + blockers.append(str(error)) + continue + for mount in container.get("Mounts", []): + volume = inspect(SOURCE, "volume", mount["Name"]) + try: + validate_source_volume(container, volume) + except ValueError as error: + blockers.append(str(error)) + if mount["Name"] in volumes: + blockers.append(f'{container["Name"].lstrip("/")}: custom or shared volumes require an explicit transfer') + volumes.add(mount["Name"]) + windows = None + if windows_identity != "-": + windows = inspect(SOURCE, "container", windows_identity) + try: + validate_windows_exception(windows) + except ValueError as error: + blockers.append(str(error)) + if blockers: + raise ValueError("\n".join(blockers)) + if volumes: + validate_trusted_manifest() + quiesced = [] + try: + for container in containers: + quiesced.append((container["Id"], validate)) + quiesce(container) + if windows is not None: + quiesced.append((windows["Id"], validate_windows_exception)) + quiesce(windows, validate_windows_exception) + except BaseException: + for identity, validator in reversed(quiesced): + try: + restore_source(identity, validator) + except Exception: + print("A quiesced rootful workload could not be restored; inspect Docker before retrying", file=sys.stderr) + raise + return + restore_windows = sys.argv[1:2] == ["--restore-windows"] + if restore_windows: + if len(sys.argv) != 3: + raise ValueError("Expected one Windows container identity") + validate_source_daemon(daemon_security(SOURCE)) + restore_source(sys.argv[2], validate_windows_exception) + print("omarchy-windows: restored after rootful Docker access revocation") + return check_windows = sys.argv[1:2] == ["--check-windows"] if check_windows: if len(sys.argv) != 3: @@ -907,20 +1206,32 @@ def main(): (container["HostConfig"].get("RestartPolicy") or {}).get("Name") != "no"): raise ValueError(f"{name}: completed transfer changed; Docker must remain available for recovery") return - if not check_only: + if not check_completed: # Check all destination names before stopping the first source. for container in containers: name = container["Name"].lstrip("/") + intent = migration_intent(container) if exists("container", name): target = inspect(TARGET, "container", name) if not completed(container, target): - raise ValueError(f"{name}: an existing rootless Docker container needs review; no completed transfer matches it") + if intent is None or not target_owned(container, target, intent): + raise ValueError(f"{name}: an existing rootless Docker container needs review; no owned transfer matches it") + if intent.get("destination") is not None: + verify_resumable_migration(container, target, intent) + elif target["State"]["Running"] or intent["start_attempted"]: + raise ValueError(f"{name}: an incomplete rootless destination may have run; inspect both engines") continue if completion_path(container["Id"]).exists(): raise ValueError(f"{name}: a previously migrated destination is missing; inspect retained data before retrying") for mount in container.get("Mounts", []): - if exists("volume", destination_volume(container, mount)): - raise ValueError(f"{name}: destination volume already exists; retained it for inspection") + target = destination_volume(container, mount) + if exists("volume", target): + record = intent["volumes"].get(target) if intent is not None else None + source_volume = inspect(SOURCE, "volume", mount["Name"]) + if record is None: + raise ValueError(f"{name}: destination volume already exists; retained it for inspection") + ownership = validate_volume_record(container, mount, record) + verify_volume_definition(source_volume, target, ownership) if check_only: for container in containers: print(f'{container["Name"].lstrip("/")}: ready for rootless Docker migration') diff --git a/docs/rootless-docker.md b/docs/rootless-docker.md index 21ff6d13e059..5f2609dbc545 100644 --- a/docs/rootless-docker.md +++ b/docs/rootless-docker.md @@ -18,8 +18,8 @@ The migration's machine-wide enabled marker is written only after the shared roo `migrations/1789164756.sh` installs the rootless runtime, allocates subordinate IDs, starts and proves the rootless daemon, claims the machine-wide source inventory for one account, restricts the old API socket to root, and preflights every rootful development container. A container named `omarchy-windows` is exempt only when its image, Compose identity, devices, capabilities, ports, and mounts match Omarchy's managed VM. A blocker in any source prevents the batch from stopping its first container. -The automatic path accepts stock bridge networking with localhost-only unprivileged published ports, private local named volumes, supported resource limits, numeric container users, the stock runtime and namespace boundaries, and Docker's default capability ceiling or stricter settings. It rejects privileged containers, added capabilities, devices, host or shared mounts, named image users whose effective UID is ambiguous, custom networks, namespace sharing, custom runtimes, altered confinement, custom logging, reserved migration labels, and unknown nondefault host settings. +The automatic path accepts stock bridge networking with localhost-only unprivileged published ports, private local named volumes, supported resource limits, containers that run as root with Docker's default capability ceiling or stricter settings, numeric non-root image users that already drop every capability, and the stock runtime and namespace boundaries. It rejects privileged containers, added capabilities, devices, host or shared mounts, named image users whose effective UID is ambiguous, numeric non-root image users whose capability ceiling cannot be reproduced exactly, custom networks, namespace sharing, custom runtimes, altered confinement, custom logging, reserved migration labels, and unknown nondefault host settings. For each accepted container, the migrator stops the source cleanly, commits its writable layer, transfers that image through Docker's native save/load format, copies named-volume contents and metadata inside the RootlessKit user and mount namespace, and recreates the container with explicit private and restrictive settings. It verifies environment, application config, limits, capabilities, mounts, ports, restart policy, logging, volume fingerprints, and lifecycle before writing a receipt bound to full source and destination snapshots. -Before the destination is first started, an error removes newly created destination objects and restores the source. Once a destination start has been attempted, both copies remain stopped or in their observed state for manual recovery because either side may contain new writes. Successful sources remain stopped with their restart policy disabled; they are retained in the rootful engine as recovery copies. +Before the destination is first started, an error removes only the exact journal-owned destination container and restores the source. Journal-owned volumes remain available for fingerprint verification and safe reuse on retry, avoiding destructive cleanup when another client could have claimed a predictable volume name. Once a destination start has been attempted, both copies remain stopped or in their observed state for manual recovery because either side may contain new writes. Successful sources remain stopped with their restart policy disabled; they are retained in the rootful engine as recovery copies. diff --git a/migrations/1789164756.sh b/migrations/1789164756.sh index f70fff9ffd3c..e66e8118dce4 100644 --- a/migrations/1789164756.sh +++ b/migrations/1789164756.sh @@ -115,19 +115,24 @@ sudo /usr/bin/systemctl daemon-reload sudo /usr/bin/systemctl start docker.socket source_host="unix:///run/docker.sock" -# Load the packaged socket policy and revoke the legacy docker group's access -# before inspecting or stopping workloads. This also closes the interval where -# an ordinary new Docker client could restart a source after verification. -if sudo /usr/bin/test -S /run/docker.sock; then - sudo /usr/bin/setfacl -b /run/docker.sock - sudo /usr/bin/chown root:root /run/docker.sock - sudo /usr/bin/chmod 0600 /run/docker.sock -fi -socket_owner=$(sudo /usr/bin/stat -Lc '%u:%g:%a' /run/docker.sock) -if [[ $socket_owner != "0:0:600" ]]; then - echo "The rootful Docker socket could not be restricted to root. This migration remains pending." >&2 - exit 1 -fi +restrict_rootful_socket() { + local socket_owner + if sudo /usr/bin/test -S /run/docker.sock; then + sudo /usr/bin/setfacl -b /run/docker.sock + sudo /usr/bin/chown root:root /run/docker.sock + sudo /usr/bin/chmod 0600 /run/docker.sock + fi + socket_owner=$(sudo /usr/bin/stat -Lc '%u:%g:%a' /run/docker.sock) + if [[ $socket_owner != "0:0:600" ]]; then + echo "The rootful Docker socket could not be restricted to root. This migration remains pending." >&2 + return 1 + fi +} + +# Load the packaged socket policy and prevent new unprivileged rootful clients +# before taking the source inventory. Existing accepted connections are closed +# by the daemon restart after every workload has been safely quiesced below. +restrict_rootful_socket remove_legacy_docker_group docker_inventory=$(sudo /usr/bin/docker --host "$source_host" ps -a --no-trunc --format '{{.ID}} {{.Names}}' | sort) @@ -154,6 +159,35 @@ if (( ${#container_names[@]} )); then echo "Rootful Docker and its data have been retained. This migration remains pending." >&2 exit 1 fi +fi + +if [[ -n $windows_id ]]; then + windows_arg=$windows_id +else + windows_arg="-" +fi +/usr/bin/python3 "$migrator" --quiesce-all "$windows_arg" "${container_names[@]}" + +# All source restart policies and lifecycle intent are durable before this +# restart. Stopping the daemon closes rootful connections accepted before the +# socket became root-only; those clients cannot reconnect afterward. +sudo /usr/bin/systemctl restart docker.service +sudo /usr/bin/systemctl start docker.socket +restrict_rootful_socket + +revoked_inventory=$(sudo /usr/bin/docker --host "$source_host" ps -a --no-trunc --format '{{.ID}} {{.Names}}' | sort) +if [[ $revoked_inventory != "$docker_inventory" ]]; then + echo "Rootful Docker containers changed while access was being revoked. Workloads remain journaled for recovery." >&2 + exit 1 +fi + +if [[ -n $windows_id ]]; then + /usr/bin/python3 "$migrator" --check-windows "$windows_id" + /usr/bin/python3 "$migrator" --restore-windows "$windows_id" +fi + +if (( ${#container_names[@]} )); then + /usr/bin/python3 "$migrator" --check "${container_names[@]}" /usr/bin/python3 "$migrator" "${container_names[@]}" /usr/bin/python3 "$migrator" --check-completed "${container_names[@]}" fi diff --git a/test/shell.d/rootless-docker-migration-test.sh b/test/shell.d/rootless-docker-migration-test.sh index e5fd187a7acb..b4c3d699b622 100755 --- a/test/shell.d/rootless-docker-migration-test.sh +++ b/test/shell.d/rootless-docker-migration-test.sh @@ -96,6 +96,14 @@ numeric_root = copy.deepcopy(container) numeric_root["Config"]["User"] = "00:1000" numeric_root["HostConfig"]["CapDrop"] = [] assert migration.allowed_capabilities(numeric_root) == migration.DOCKER_CAPABILITIES +non_root_default_caps = copy.deepcopy(container) +non_root_default_caps["HostConfig"]["CapDrop"] = [] +try: + migration.validate(non_root_default_caps) +except ValueError: + pass +else: + raise AssertionError("non-root image user with an unreproducible capability ceiling passed") for named_user in ("root", "daemon", "root:root", "\u0660"): changed = copy.deepcopy(container) changed["Config"]["User"] = named_user @@ -107,6 +115,16 @@ for named_user in ("root", "daemon", "root:root", "\u0660"): raise AssertionError(f"ambiguous named user passed preflight: {named_user}") print("ok - numeric UID zero keeps its capabilities and ambiguous named users fail closed") +paused = copy.deepcopy(container) +paused["State"]["Paused"] = True +try: + migration.validate(paused) +except ValueError: + pass +else: + raise AssertionError("a paused source passed automatic lifecycle migration") +print("ok - paused workloads and non-root capability ceilings that cannot be recreated fail closed") + for stop_timeout in (None, -1, 0, 300): changed = copy.deepcopy(container) changed["Config"]["StopTimeout"] = stop_timeout @@ -353,22 +371,80 @@ with tempfile.TemporaryDirectory() as directory: assert migration.intent_path(intent_source["Id"]).stat().st_mode & 0o777 == 0o600 print("ok - durable migration intent restores lifecycle and restart policy after interruption") +quiesce_source = copy.deepcopy(intent_source) +quiesce_calls = [] + +def quiesce_inspect(engine, kind, name): + return copy.deepcopy(quiesce_source) + +def quiesce_run(*args, **kwargs): + quiesce_calls.append(args) + if args[:2] == (migration.SOURCE, "stop"): + quiesce_source["State"] = { + "Running": False, "StartedAt": "start", "FinishedAt": "quiesced", "ExitCode": 0, + } + elif args[:2] == (migration.SOURCE, "update"): + value = args[2].split("=", 1)[1] + quiesce_source["HostConfig"]["RestartPolicy"] = { + "Name": value, "MaximumRetryCount": 0, + } + elif args[:2] == (migration.SOURCE, "start"): + quiesce_source["State"]["Running"] = True + quiesce_source["State"]["StartedAt"] = "restored" + +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + migration.inspect = quiesce_inspect + migration.run = quiesce_run + migration.quiesce(quiesce_source) + quiesced_intent = migration.migration_intent(quiesce_source) + assert quiesced_intent["target_running"] is True + assert quiesced_intent["restart_disabled"] is True + assert (migration.SOURCE, "stop", "-t", "300", quiesce_source["Id"]) in quiesce_calls + assert (migration.SOURCE, "update", "--restart=no", quiesce_source["Id"]) in quiesce_calls + migration.restore_source(quiesce_source["Id"]) + assert quiesce_source["State"]["Running"] is True + assert quiesce_source["HostConfig"]["RestartPolicy"]["Name"] == "unless-stopped" + assert not migration.intent_path(quiesce_source["Id"]).exists() +print("ok - batch quiesce durably disables restart and restores the exact source lifecycle") + +quiesce_source = copy.deepcopy(intent_source) +quiesce_calls = [] +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + migration.quiesce(quiesce_source) + artifact_intent = migration.migration_intent(quiesce_source) + artifact_intent["volumes"]["retained-data"] = { + "source": "source-data", "ownership": f'{quiesce_source["Id"]}:source-data:{"e" * 64}', + } + migration.persist_migration_intent(quiesce_source, artifact_intent) + migration.restore_source(quiesce_source["Id"]) + assert quiesce_source["State"]["Running"] is True + assert migration.intent_path(quiesce_source["Id"]).exists() + assert migration.migration_intent(quiesce_source)["volumes"] == artifact_intent["volumes"] +print("ok - batch recovery retains ownership journals for interrupted destination artifacts") -def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image=False): + +def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image=False, replace_target=False): source = copy.deepcopy(container) source["Id"] = ("d" if after_start else "c") * 64 source["Name"] = "/post-start" if after_start else "/pre-start" source["Mounts"] = [] source["HostConfig"]["Binds"] = [] current_source = copy.deepcopy(source) - current_target = {"State": {"Running": False}} + current_target = None calls = [] pipes = [] def fake_inspect(engine, kind, name): - return copy.deepcopy(current_source if engine == migration.SOURCE else current_target) + if engine == migration.SOURCE: + return copy.deepcopy(current_source) + if current_target is None: + raise migration.subprocess.CalledProcessError(1, ["docker", "inspect"]) + return copy.deepcopy(current_target) def fake_run(*args, **kwargs): + nonlocal current_target calls.append(args) if args[:2] == (migration.SOURCE, "stop"): current_source["State"] = { @@ -382,15 +458,35 @@ def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image current_source["State"]["Running"] = True elif args[:2] == (migration.SOURCE, "commit"): return "sha256:" + ("f" if after_start else "e") * 64 + elif args[:2] == (migration.TARGET, "create"): + labels = {} + for index, argument in enumerate(args): + if argument == "--label": + key, value = args[index + 1].split("=", 1) + labels[key] = value + current_target = {"Id": "b" * 64, "Config": {"Labels": labels}, + "State": {"Running": False}} + elif args[:3] == (migration.TARGET, "rm", "--force"): + current_target = None + elif args[:2] == (migration.TARGET, "start"): + current_target["State"]["Running"] = True migration.inspect = fake_inspect migration.run = fake_run - migration.exists = lambda kind, name: preexisting_image and kind == "image" + migration.exists = lambda kind, name: ((kind == "container" and current_target is not None) or + (preexisting_image and kind == "image")) migration.pipe = lambda producer, consumer: pipes.append((producer, consumer)) if after_start: - migration.verify_runtime = lambda value: None + migration.verify_runtime = lambda value, ownership=None: None else: - migration.verify_runtime = lambda value: (_ for _ in ()).throw(RuntimeError("verification failed")) + def fail_verification(value, ownership=None): + nonlocal current_target + if replace_target: + current_target = {"Id": "6" * 64, "Config": {"Labels": {}}, + "State": {"Running": False}} + raise RuntimeError("verification failed") + migration.verify_runtime = fail_verification + migration.record_completion = lambda source, state, running: (_ for _ in ()).throw(RuntimeError("receipt failed")) with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory @@ -405,7 +501,7 @@ def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image calls, source, pipes, intent_retained = exercise_failed_transfer(False) -assert (migration.TARGET, "rm", "--force", "pre-start") in calls +assert (migration.TARGET, "rm", "--force", "b" * 64) in calls assert (migration.TARGET, "image", "rm", "sha256:" + "e" * 64) in calls assert (migration.SOURCE, "stop", "-t", "300", "c" * 64) in calls assert (migration.SOURCE, "start", "c" * 64) in calls @@ -436,6 +532,12 @@ assert not any(call[:3] == (migration.TARGET, "image", "rm") for call in calls) assert (migration.SOURCE, "image", "rm", "sha256:" + "e" * 64) in calls print("ok - a preexisting target image digest is reused without claiming or deleting it") +calls, source, pipes, intent_retained = exercise_failed_transfer(False, replace_target=True) +assert not any(call[:3] == (migration.TARGET, "rm", "--force") for call in calls) +assert source["State"]["Running"] +assert intent_retained +print("ok - rollback never deletes a concurrently replaced destination container") + retry_original = copy.deepcopy(container) retry_original["Id"] = "9" * 64 retry_original["Name"] = "/interrupted-retry" @@ -446,7 +548,7 @@ retry_source["State"] = { "Running": False, "StartedAt": "start", "FinishedAt": "power-loss-stop", "ExitCode": 0, } retry_source["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} -retry_target = {"State": {"Running": False}} +retry_state = {"target": None} retry_calls = [] with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory @@ -455,20 +557,28 @@ with tempfile.TemporaryDirectory() as directory: restart_disabled=True) def retry_inspect(engine, kind, name): - return copy.deepcopy(retry_source if engine == migration.SOURCE else retry_target) + return copy.deepcopy(retry_source if engine == migration.SOURCE else retry_state["target"]) def retry_run(*args, **kwargs): retry_calls.append(args) if args[:2] == (migration.SOURCE, "commit"): return "sha256:" + "8" * 64 + if args[:2] == (migration.TARGET, "create"): + labels = {} + for index, argument in enumerate(args): + if argument == "--label": + key, value = args[index + 1].split("=", 1) + labels[key] = value + retry_state["target"] = {"Id": "7" * 64, "Config": {"Labels": labels}, + "State": {"Running": False}} if args[:2] == (migration.TARGET, "start"): - retry_target["State"]["Running"] = True + retry_state["target"]["State"]["Running"] = True migration.inspect = retry_inspect migration.run = retry_run migration.exists = lambda kind, name: False migration.pipe = lambda producer, consumer: None - migration.verify_runtime = lambda value: None + migration.verify_runtime = lambda value, ownership=None: None migration.record_completion = lambda source, state, running: None migration.migrate(retry_source) create_call = next(call for call in retry_calls if call[:2] == (migration.TARGET, "create")) @@ -476,4 +586,45 @@ with tempfile.TemporaryDirectory() as directory: assert (migration.TARGET, "start", "interrupted-retry") in retry_calls assert not migration.intent_path(retry_source["Id"]).exists() print("ok - a fresh process resumes a stopped migration with the original running and restart intent") + +resume_original = copy.deepcopy(retry_original) +resume_source = copy.deepcopy(retry_source) +resume_target = copy.deepcopy(retry_state["target"]) +resume_target["State"]["Running"] = False +resume_calls = [] +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + resume_intent = migration.record_migration_intent(resume_original) + resume_intent = migration.record_migration_intent(resume_source, resume_source["State"], resume_intent, + restart_disabled=True) + resume_target["Config"]["Labels"][migration.OWNERSHIP_LABEL] = resume_intent["target_ownership"] + resume_intent["destination"] = { + "id": resume_target["Id"], "snapshot": migration.snapshot_digest(resume_target), + } + migration.persist_migration_intent(resume_source, resume_intent) + + def resume_inspect(engine, kind, name): + return copy.deepcopy(resume_source if engine == migration.SOURCE else resume_target) + + def resume_run(*args, **kwargs): + resume_calls.append(args) + if args[:2] == (migration.TARGET, "start"): + resume_target["State"]["Running"] = True + + migration.inspect = resume_inspect + migration.run = resume_run + migration.verify_runtime = lambda value, ownership=None: None + migration.record_completion = lambda source, state, running: None + unexpected_running = copy.deepcopy(resume_target) + unexpected_running["State"]["Running"] = True + try: + migration.verify_resumable_migration(resume_source, unexpected_running, resume_intent) + except ValueError: + pass + else: + raise AssertionError("an unexpectedly running interrupted destination passed preflight") + migration.resume_verified_migration(resume_source, resume_target, resume_intent) + assert (migration.TARGET, "start", "interrupted-retry") in resume_calls + assert not migration.intent_path(resume_source["Id"]).exists() +print("ok - a verified destination resumes safely across interruption before its first start") PY diff --git a/test/shell.d/rootless-docker-posture-test.sh b/test/shell.d/rootless-docker-posture-test.sh index bfa76441d5e6..33ad72d435ee 100755 --- a/test/shell.d/rootless-docker-posture-test.sh +++ b/test/shell.d/rootless-docker-posture-test.sh @@ -55,7 +55,17 @@ grep -q -- '--check-windows "$windows_id"' "$migration" || windows_secure_line=$(grep -n '^/usr/bin/omarchy-windows-vm __migration-secure$' "$migration" | cut -d: -f1) [[ -n $windows_secure_line && -n $inventory_line ]] && (( windows_secure_line < inventory_line )) || fail "legacy Windows credentials and mounts are not secured before rootful inventory" -pass "migration serializes ownership, restricts the source socket, and validates the Windows exception" +quiesce_line=$(grep -n -- '--quiesce-all "$windows_arg"' "$migration" | cut -d: -f1) +restart_line=$(grep -n 'systemctl restart docker.service' "$migration" | cut -d: -f1) +transfer_line=$(grep -n '^ /usr/bin/python3 "$migrator" "${container_names\[@\]}"' "$migration" | cut -d: -f1) +[[ -n $quiesce_line && -n $restart_line && -n $transfer_line ]] && + (( inventory_line < quiesce_line && quiesce_line < restart_line && restart_line < transfer_line )) || + fail "rootful connections are not revoked between durable quiesce and transfer" +(( $(grep -c '^restrict_rootful_socket$' "$migration") == 2 )) || + fail "rootful socket policy is not rechecked after daemon restart" +grep -q -- '--restore-windows "$windows_id"' "$migration" || + fail "a running Windows VM is not restored after rootful connection revocation" +pass "migration serializes ownership, secures Windows, and revokes existing rootful connections" grep -q "alias d='docker'" "$ROOT/default/bash/aliases" || fail "the d alias remains Docker" ! rg -q 'sudo[[:space:]]+docker' "$ROOT/bin/omarchy-install-docker-dbs" || From 650da2fe61e7590a5f24723152eca80936a6f9b7 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Sat, 12 Sep 2026 03:29:54 -0600 Subject: [PATCH 05/31] Harden rootless Docker retry safety --- default/docker/rootless/migrate.py | 107 +++++++++++++++--- default/docker/rootless/volume-manifest.py | 28 ++++- docs/rootless-docker.md | 6 +- manual/18-development-tools.md | 2 +- migrations/1789164756.sh | 72 ++++++------ .../shell.d/rootless-docker-migration-test.sh | 106 ++++++++++++++++- test/shell.d/rootless-docker-posture-test.sh | 4 + 7 files changed, 265 insertions(+), 60 deletions(-) diff --git a/default/docker/rootless/migrate.py b/default/docker/rootless/migrate.py index a673279b07c4..071ea2c19354 100644 --- a/default/docker/rootless/migrate.py +++ b/default/docker/rootless/migrate.py @@ -367,6 +367,7 @@ def record_migration_intent(container, stopped_state=None, saved=None, restart_d "started_at": state["StartedAt"], "target_running": bool(state["Running"]), "restart_disabled": False, + "quiesce_started": False, "restore_started": False, "start_attempted": False, "target_ownership": secrets.token_hex(32), @@ -378,6 +379,7 @@ def record_migration_intent(container, stopped_state=None, saved=None, restart_d payload = deepcopy(saved) if stopped_state is not None: payload["stopped"] = stopped_identity(stopped_state) + payload["quiesce_started"] = False payload["restore_started"] = False if restart_disabled: payload["restart_disabled"] = True @@ -395,6 +397,7 @@ def migration_intent(container): if (saved["source"] != container["Id"] or not isinstance(saved["target_running"], bool) or not isinstance(saved["restart_disabled"], bool) or + not isinstance(saved["quiesce_started"], bool) or not isinstance(saved["restore_started"], bool) or not isinstance(saved["start_attempted"], bool) or not re.fullmatch(r"[a-f0-9]{64}", saved["target_ownership"]) or @@ -411,11 +414,15 @@ def migration_intent(container): if not exact_snapshot and not disabled_snapshot: raise ValueError if container["State"]["Running"]: + quiescing = (saved["quiesce_started"] is True and + saved.get("destination") is None and + saved["start_attempted"] is False) resumed_restore = (saved["restore_started"] is True and saved["target_running"] is True and exact_snapshot) - if (saved["target_running"] is not True or - ("stopped" in saved and not resumed_restore) or - (saved["started_at"] != container["State"]["StartedAt"] and not resumed_restore)): + if (saved["target_running"] is not True and not quiescing) or ( + "stopped" in saved and not resumed_restore and not quiescing) or ( + saved["started_at"] != container["State"]["StartedAt"] and + not resumed_restore and not quiescing): raise ValueError else: if saved["started_at"] != container["State"]["StartedAt"]: @@ -515,6 +522,11 @@ def validate(container): if (state.get("Paused") or state.get("Restarting") or state.get("Dead") or state.get("RemovalInProgress")): raise ValueError(f"{name}: paused or transitional lifecycle state requires an explicit migration") + if not state["Running"] and state.get("Status") != "created": + intent = migration_intent(container) + if ((intent is None or intent["target_running"] is not True) and + not completion_path(container["Id"]).is_file()): + raise ValueError(f"{name}: an exited container needs an explicit migration to preserve its exit state") allowed_capabilities(container) stop_timeout = container["Config"].get("StopTimeout") if (stop_timeout is not None and @@ -643,6 +655,20 @@ def transfer_volume(volume, target): return source_digest +def clear_volume(target): + destination = inspect(TARGET, "volume", target)["Mountpoint"] + run("target-namespace", "/usr/bin/python3", TRUSTED_MANIFEST, "--clear", destination) + + +def volume_users(target): + output = run(TARGET, "container", "ls", "--all", "--no-trunc", "--filter", + f"volume={target}", "--format", "{{.ID}}", capture=True) + users = output.splitlines() if output else [] + if any(not re.fullmatch(r"[a-f0-9]{64}", identity) for identity in users): + raise RuntimeError("Cannot verify destination volume users") + return users + + def source_volume_digest(volume): return run("/usr/bin/sudo", "/usr/bin/python3", TRUSTED_MANIFEST, volume["Mountpoint"], capture=True) @@ -751,12 +777,44 @@ def restart_policy_argument(container): return policy +def disable_source_restart(container, intent, planned, validator=validate): + restart = container["HostConfig"].get("RestartPolicy") or {} + if restart.get("Name") == "no": + return container, intent + intent = record_migration_intent(container, saved=intent, restart_disabled=True) + running = bool(container["State"]["Running"]) + started_at = container["State"]["StartedAt"] + stopped = None if running else stopped_identity(container["State"]) + run(SOURCE, "update", "--restart=no", container["Id"]) + disabled = inspect(SOURCE, "container", container["Id"]) + validator(disabled) + lifecycle_changed = (bool(disabled["State"]["Running"]) != running or + (running and disabled["State"]["StartedAt"] != started_at) or + (not running and stopped_identity(disabled["State"]) != stopped)) + if (lifecycle_changed or + snapshot_digest(disabled, ignore_restart=True) != snapshot_digest(planned, ignore_restart=True) or + (disabled["HostConfig"].get("RestartPolicy") or {}).get("Name") != "no"): + raise RuntimeError(f'{container["Name"].lstrip("/")}: source changed while restart was being disabled') + return disabled, intent + + +def begin_quiesce(container, intent): + intent = deepcopy(intent) + intent["quiesce_started"] = True + if container["State"]["Running"]: + intent["started_at"] = container["State"]["StartedAt"] + intent.pop("stopped", None) + return persist_migration_intent(container, intent) + + def restore_source(identity, validator=validate): current = inspect(SOURCE, "container", identity) validator(current) intent = migration_intent(current) if intent is None: return + if intent["start_attempted"]: + raise RuntimeError(f'{current["Name"].lstrip("/")}: destination start was attempted; source recovery needs review') planned = planned_source(current, intent) desired_restart = planned["HostConfig"].get("RestartPolicy") or {} if (current["HostConfig"].get("RestartPolicy") or {}) != desired_restart: @@ -765,6 +823,7 @@ def restore_source(identity, validator=validate): if intent["target_running"]: if not current["State"]["Running"]: intent["restore_started"] = True + intent["quiesce_started"] = False persist_migration_intent(current, intent) run(SOURCE, "start", identity) elif current["State"]["Running"]: @@ -788,6 +847,12 @@ def quiesce(container, validator=validate): planned = planned_source(container, intent) if intent is None: intent = record_migration_intent(container) + if intent["start_attempted"]: + raise ValueError(f'{container["Name"].lstrip("/")}: destination start was attempted; inspect both engines') + if intent.get("destination") is not None and intent["restore_started"]: + raise ValueError(f'{container["Name"].lstrip("/")}: source ran after destination creation; inspect both engines') + intent = begin_quiesce(container, intent) + container, intent = disable_source_restart(container, intent, planned, validator) if container["State"]["Running"]: run(SOURCE, "stop", "-t", str(configured_stop_timeout(planned)), container["Id"]) stopped = inspect(SOURCE, "container", container["Id"]) @@ -800,9 +865,6 @@ def quiesce(container, validator=validate): state = container["State"] stopped_identity(state) intent = record_migration_intent(container, state, intent) - if (container["HostConfig"].get("RestartPolicy") or {}).get("Name") != "no": - intent = record_migration_intent(container, state, intent, restart_disabled=True) - run(SOURCE, "update", "--restart=no", container["Id"]) disabled = inspect(SOURCE, "container", container["Id"]) validator(disabled) if (stopped_identity(disabled["State"]) != stopped_identity(state) or @@ -814,6 +876,10 @@ def quiesce(container, validator=validate): def verify_resumable_migration(container, target, intent): name = container["Name"].lstrip("/") + if intent["start_attempted"]: + raise ValueError(f"{name}: destination start was attempted; inspect both engines") + if intent["restore_started"]: + raise ValueError(f"{name}: source ran after destination creation; inspect both engines") planned = planned_source(container, intent) destination = intent.get("destination") if (not isinstance(destination, dict) or destination.get("id") != target.get("Id") or @@ -821,8 +887,7 @@ def verify_resumable_migration(container, target, intent): not target_owned(container, target, intent)): raise ValueError(f"{name}: interrupted rootless destination changed; inspect both engines") if target["State"]["Running"]: - if not (intent["target_running"] and intent["start_attempted"]): - raise ValueError(f"{name}: interrupted rootless destination has an unexpected lifecycle") + raise ValueError(f"{name}: interrupted rootless destination has an unexpected lifecycle") verify_runtime(planned, intent["target_ownership"]) expected_volumes = {destination_volume(planned, mount): mount @@ -878,6 +943,8 @@ def migrate(container): name = container["Name"].lstrip("/") identity = container["Id"] intent = migration_intent(container) + if intent is not None and intent["start_attempted"]: + raise ValueError(f"{name}: destination start was attempted; inspect both engines") if exists("container", name): target = inspect(TARGET, "container", name) container = refresh_source(container) @@ -908,7 +975,6 @@ def migrate(container): image_committed = False image_loaded = False start_attempted = False - restart_changed = False verified_volumes = {} restart = planned["HostConfig"].get("RestartPolicy") or {} policy = restart_policy_argument(planned) @@ -918,6 +984,12 @@ def migrate(container): expected_volume_names = {destination_volume(planned, mount) for mount in planned.get("Mounts", [])} if set(intent["volumes"]) - expected_volume_names: raise ValueError(f"{name}: interrupted destination volume inventory changed") + if intent.get("destination") is not None: + intent = deepcopy(intent) + intent.pop("destination") + persist_migration_intent(container, intent) + intent = begin_quiesce(container, intent) + container, intent = disable_source_restart(container, intent, planned) run(SOURCE, "stop", "-t", str(configured_stop_timeout(planned)), identity) stopped_source = inspect(SOURCE, "container", identity) state = stopped_source["State"] @@ -978,9 +1050,15 @@ def migrate(container): for key, value in (volume.get("Labels") or {}).items(): volume_arguments += ["--label", f"{key}={value}"] volume_arguments += ["--label", f"{VOLUME_LABEL}={ownership}"] - if not exists("volume", target): + retained = exists("volume", target) + if not retained: run(*volume_arguments, target) verify_volume_definition(volume, target, ownership) + if retained: + if volume_users(target): + raise RuntimeError(f"{name}: retained destination volume is attached; retained it for inspection") + clear_volume(target) + verify_volume_definition(volume, target, ownership) digest = transfer_volume(volume, target) record["digest"] = digest persist_migration_intent(container, intent) @@ -1014,11 +1092,6 @@ def migrate(container): raise RuntimeError(f"{name}: rootless destination ownership changed during transfer") intent["destination"] = {"id": created_id, "snapshot": snapshot_digest(target)} persist_migration_intent(container, intent) - # A later workload may fail, leaving Docker installed. Prevent a daemon - # restart from reviving this stale source alongside its migrated copy. - intent = record_migration_intent(container, state, intent, restart_disabled=True) - restart_changed = True - run(SOURCE, "update", "--restart=no", identity) source_after = inspect(SOURCE, "container", identity) if (stopped_identity(source_after["State"]) != stopped_identity(state) or snapshot_digest(source_after, ignore_restart=True) != snapshot_digest(planned, ignore_restart=True) or @@ -1063,7 +1136,7 @@ def migrate(container): recovery.append((TARGET, "image", "rm", image)) if image_committed: recovery.append((SOURCE, "image", "rm", image)) - if restart_changed or (container["HostConfig"].get("RestartPolicy") or {}) != restart: + if intent["restart_disabled"] and restart.get("Name") != "no": recovery.append((SOURCE, "update", f"--restart={policy}", identity)) if running: try: @@ -1211,6 +1284,8 @@ def main(): for container in containers: name = container["Name"].lstrip("/") intent = migration_intent(container) + if intent is not None and intent["start_attempted"]: + raise ValueError(f"{name}: destination start was attempted; inspect both engines") if exists("container", name): target = inspect(TARGET, "container", name) if not completed(container, target): diff --git a/default/docker/rootless/volume-manifest.py b/default/docker/rootless/volume-manifest.py index f39b3cb058ac..e74f7ae82ccb 100644 --- a/default/docker/rootless/volume-manifest.py +++ b/default/docker/rootless/volume-manifest.py @@ -41,5 +41,31 @@ def visit(path, relative): return digest.hexdigest() +def clear(root): + root = Path(root) + root_info = root.lstat() + if not stat.S_ISDIR(root_info.st_mode): + raise RuntimeError("volume root is not a directory") + + def remove(path): + info = path.lstat() + if info.st_dev != root_info.st_dev: + raise RuntimeError("volume contains a nested filesystem") + if stat.S_ISDIR(info.st_mode): + for child in path.iterdir(): + remove(child) + path.rmdir() + else: + path.unlink() + + for child in root.iterdir(): + remove(child) + + if __name__ == '__main__': - print(fingerprint(sys.argv[1])) + if sys.argv[1:2] == ["--clear"] and len(sys.argv) == 3: + clear(sys.argv[2]) + elif len(sys.argv) == 2: + print(fingerprint(sys.argv[1])) + else: + raise SystemExit("usage: volume-manifest.py [--clear] ROOT") diff --git a/docs/rootless-docker.md b/docs/rootless-docker.md index 5f2609dbc545..6eaca68c977d 100644 --- a/docs/rootless-docker.md +++ b/docs/rootless-docker.md @@ -16,10 +16,10 @@ The migration's machine-wide enabled marker is written only after the shared roo ## Existing-install migration -`migrations/1789164756.sh` installs the rootless runtime, allocates subordinate IDs, starts and proves the rootless daemon, claims the machine-wide source inventory for one account, restricts the old API socket to root, and preflights every rootful development container. A container named `omarchy-windows` is exempt only when its image, Compose identity, devices, capabilities, ports, and mounts match Omarchy's managed VM. A blocker in any source prevents the batch from stopping its first container. +`migrations/1789164756.sh` installs the rootless runtime, allocates subordinate IDs, starts and proves the rootless daemon, secures any current account's Windows definition, restricts the old API socket to root, and preflights every rootful container. Only after those checks does it claim the machine-wide source inventory for that account. A container named `omarchy-windows` is exempt only when its image, Compose identity, devices, capabilities, ports, and UID-bound mounts match Omarchy's managed VM. A blocker in any source prevents the batch from stopping its first container or assigning the migration owner. -The automatic path accepts stock bridge networking with localhost-only unprivileged published ports, private local named volumes, supported resource limits, containers that run as root with Docker's default capability ceiling or stricter settings, numeric non-root image users that already drop every capability, and the stock runtime and namespace boundaries. It rejects privileged containers, added capabilities, devices, host or shared mounts, named image users whose effective UID is ambiguous, numeric non-root image users whose capability ceiling cannot be reproduced exactly, custom networks, namespace sharing, custom runtimes, altered confinement, custom logging, reserved migration labels, and unknown nondefault host settings. +The automatic path accepts running or never-started containers with stock bridge networking, localhost-only unprivileged published ports, private local named volumes, supported resource limits, root users with Docker's default capability ceiling or stricter settings, numeric non-root image users that already drop every capability, and the stock runtime and namespace boundaries. It rejects already-exited containers whose historical exit state cannot be recreated without rerunning them, privileged containers, added capabilities, devices, host or shared mounts, named image users whose effective UID is ambiguous, numeric non-root image users whose capability ceiling cannot be reproduced exactly, custom networks, namespace sharing, custom runtimes, altered confinement, custom logging, reserved migration labels, and unknown nondefault host settings. For each accepted container, the migrator stops the source cleanly, commits its writable layer, transfers that image through Docker's native save/load format, copies named-volume contents and metadata inside the RootlessKit user and mount namespace, and recreates the container with explicit private and restrictive settings. It verifies environment, application config, limits, capabilities, mounts, ports, restart policy, logging, volume fingerprints, and lifecycle before writing a receipt bound to full source and destination snapshots. -Before the destination is first started, an error removes only the exact journal-owned destination container and restores the source. Journal-owned volumes remain available for fingerprint verification and safe reuse on retry, avoiding destructive cleanup when another client could have claimed a predictable volume name. Once a destination start has been attempted, both copies remain stopped or in their observed state for manual recovery because either side may contain new writes. Successful sources remain stopped with their restart policy disabled; they are retained in the rootful engine as recovery copies. +Before the destination is first started, an error removes only the exact journal-owned destination container and restores the source. Journal-owned volumes remain available for ownership verification; a retry empties the verified volume before copying the current stopped source again, so a partial transfer or later source deletion cannot leave stale entries. Once a destination start has been attempted, automatic retry and source restoration stop for manual recovery because either side may contain new writes. Successful sources remain stopped with their restart policy disabled; they are retained in the rootful engine as recovery copies. diff --git a/manual/18-development-tools.md b/manual/18-development-tools.md index 740dc4ec06f0..786f766a1497 100644 --- a/manual/18-development-tools.md +++ b/manual/18-development-tools.md @@ -24,7 +24,7 @@ To install, say, Ruby, you'd run `mise use -g ruby`, which will both install Rub The daemon for development containers runs as your user and keeps its data in your home directory. Plain `docker`, `docker compose`, `docker buildx`, and the `d` alias use it directly, without `sudo` and without membership in the root-equivalent `docker` group. A container that escapes this daemon reaches only your user privileges rather than root privileges on the host. -Existing installs automatically move compatible development containers and private named volumes into the rootless Docker store during update. The old rootful containers remain stopped as recovery copies. Containers that depend on elevated privileges, host directories, devices, custom runtimes, or custom networks stay untouched and stop the migration with an explanation so Omarchy never silently weakens or changes their access. +Existing installs automatically move compatible running or never-started development containers and private named volumes into the rootless Docker store during update. The old rootful containers remain stopped as recovery copies. Already-exited containers and containers that depend on elevated privileges, host directories, devices, custom runtimes, or custom networks stay untouched and stop the migration with an explanation so Omarchy never reruns an exited workload or silently weakens or changes its access. Remember to check out Lazydocker to manage your development containers in a cool TUI using `Super + Shift + D`. It connects to the same rootless daemon and does not need an authorization prompt. diff --git a/migrations/1789164756.sh b/migrations/1789164756.sh index e66e8118dce4..a19735ec167e 100644 --- a/migrations/1789164756.sh +++ b/migrations/1789164756.sh @@ -70,42 +70,6 @@ if sudo /usr/bin/test -f "$machine_state/enabled"; then exit 0 fi -# The rootful store is machine-wide. The first user to begin its transfer owns -# the recovery copies until the migration completes, so another account cannot -# split one source inventory across two private stores. -sudo /usr/bin/python3 - "$migration_uid" "$migration_user" <<'PY' -import fcntl -import os -from pathlib import Path -import stat -import sys - - -uid, name = int(sys.argv[1]), sys.argv[2] -root = Path("/var/lib/omarchy/rootless-docker") -root.mkdir(mode=0o755, parents=True, exist_ok=True) -lock_fd = os.open("/run/lock/omarchy-rootless-docker-owner.lock", - os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) -with os.fdopen(lock_fd, "w") as lock: - metadata = os.fstat(lock.fileno()) - if not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != 0 or metadata.st_mode & 0o022: - raise SystemExit("unsafe rootless Docker owner lock") - fcntl.flock(lock, fcntl.LOCK_EX) - owner = root / "migration-owner" - expected = f"{uid}:{name}\n" - if owner.exists(): - if owner.is_symlink() or owner.read_text() != expected: - raise SystemExit("another user owns the rootful Docker migration; finish it from that account") - else: - temporary = root / f".migration-owner.{os.getpid()}" - fd = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) - with os.fdopen(fd, "w") as output: - output.write(expected) - output.flush() - os.fsync(output.fileno()) - temporary.replace(owner) -PY - # Migrate any legacy user-side definition, pin its data into the protected root # anchors, and rewrite the credential-bearing Compose file to root:root 0600. # This performs no Docker lifecycle action. @@ -161,6 +125,42 @@ if (( ${#container_names[@]} )); then fi fi +# The rootful store is machine-wide. Claim it only after this account proves it +# can secure any existing UID-bound Windows VM and migrate the complete source +# inventory. The root lock serializes users that finish preflight together. +sudo /usr/bin/python3 - "$migration_uid" "$migration_user" <<'PY' +import fcntl +import os +from pathlib import Path +import stat +import sys + + +uid, name = int(sys.argv[1]), sys.argv[2] +root = Path("/var/lib/omarchy/rootless-docker") +root.mkdir(mode=0o755, parents=True, exist_ok=True) +lock_fd = os.open("/run/lock/omarchy-rootless-docker-owner.lock", + os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) +with os.fdopen(lock_fd, "w") as lock: + metadata = os.fstat(lock.fileno()) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != 0 or metadata.st_mode & 0o022: + raise SystemExit("unsafe rootless Docker owner lock") + fcntl.flock(lock, fcntl.LOCK_EX) + owner = root / "migration-owner" + expected = f"{uid}:{name}\n" + if owner.exists(): + if owner.is_symlink() or owner.read_text() != expected: + raise SystemExit("another user owns the rootful Docker migration; finish it from that account") + else: + temporary = root / f".migration-owner.{os.getpid()}" + fd = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, "w") as output: + output.write(expected) + output.flush() + os.fsync(output.fileno()) + temporary.replace(owner) +PY + if [[ -n $windows_id ]]; then windows_arg=$windows_id else diff --git a/test/shell.d/rootless-docker-migration-test.sh b/test/shell.d/rootless-docker-migration-test.sh index b4c3d699b622..4536938cfb04 100755 --- a/test/shell.d/rootless-docker-migration-test.sh +++ b/test/shell.d/rootless-docker-migration-test.sh @@ -16,10 +16,31 @@ path = os.path.join(os.environ["ROOT"], "default/docker/rootless/migrate.py") spec = importlib.util.spec_from_file_location("rootless_docker_migration", path) migration = importlib.util.module_from_spec(spec) spec.loader.exec_module(migration) +manifest_path = os.path.join(os.environ["ROOT"], "default/docker/rootless/volume-manifest.py") +manifest_spec = importlib.util.spec_from_file_location("rootless_docker_volume_manifest", manifest_path) +manifest = importlib.util.module_from_spec(manifest_spec) +manifest_spec.loader.exec_module(manifest) assert migration.TRUSTED_MANIFEST == "/usr/share/omarchy/default/docker/rootless/volume-manifest.py" assert migration.local_command([migration.SOURCE, "info"])[:2] == ["/usr/bin/sudo", "/usr/bin/docker"] print("ok - privileged migration helpers resolve only through packaged absolute paths") +with tempfile.TemporaryDirectory() as directory: + volume = os.path.join(directory, "volume") + outside = os.path.join(directory, "outside") + os.makedirs(os.path.join(volume, "nested")) + os.makedirs(outside) + with open(os.path.join(volume, "stale"), "w") as output: + output.write("old") + with open(os.path.join(volume, "nested", "old"), "w") as output: + output.write("old") + with open(os.path.join(outside, "keep"), "w") as output: + output.write("safe") + os.symlink(outside, os.path.join(volume, "outside-link")) + manifest.clear(volume) + assert not os.listdir(volume) + assert open(os.path.join(outside, "keep")).read() == "safe" +print("ok - retained-volume reset removes stale entries without following symlinks") + source_security = ["name=seccomp,profile=builtin", "name=cgroupns"] target_security = ["name=seccomp,profile=builtin", "name=rootless", "name=cgroupns"] migration.validate_source_daemon(source_security) @@ -123,7 +144,25 @@ except ValueError: pass else: raise AssertionError("a paused source passed automatic lifecycle migration") -print("ok - paused workloads and non-root capability ceilings that cannot be recreated fail closed") +exited = copy.deepcopy(container) +exited["State"] = { + "Status": "exited", "Running": False, "StartedAt": "start", "FinishedAt": "finish", "ExitCode": 7, +} +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + try: + migration.validate(exited) + except ValueError: + pass + else: + raise AssertionError("an exited source with unreproducible state passed automatic migration") +created = copy.deepcopy(exited) +created["State"] = { + "Status": "created", "Running": False, "StartedAt": "0001-01-01T00:00:00Z", + "FinishedAt": "0001-01-01T00:00:00Z", "ExitCode": 0, +} +assert migration.validate(created) == "project-worker" +print("ok - paused, exited, and unreproducible non-root capability states fail closed") for stop_timeout in (None, -1, 0, 300): changed = copy.deepcopy(container) @@ -243,6 +282,17 @@ owned_volume = copy.deepcopy(source_volume) owned_volume["Labels"][migration.VOLUME_LABEL] = ownership migration.inspect = lambda engine, kind, name: copy.deepcopy(owned_volume) migration.verify_volume_definition(source_volume, "project-data", ownership) +real_run = migration.run +migration.run = lambda *args, **kwargs: "f" * 64 +assert migration.volume_users("project-data") == ["f" * 64] +migration.run = lambda *args, **kwargs: "short-id" +try: + migration.volume_users("project-data") +except RuntimeError: + pass +else: + raise AssertionError("an ambiguous destination-volume attachment passed validation") +migration.run = real_run reserved_source = copy.deepcopy(source_volume) reserved_source["Labels"][migration.VOLUME_LABEL] = "foreign" try: @@ -251,7 +301,7 @@ except ValueError: pass else: raise AssertionError("a source volume with the migration ownership label was accepted") -print("ok - destination volumes require an unpredictable ownership label before copy or cleanup") +print("ok - destination volumes require unpredictable ownership and no attachments before cleanup") blocked = ( ("Privileged", True), ("CapAdd", ["SYS_ADMIN"]), @@ -315,6 +365,7 @@ with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory migration.inspect = lambda engine, kind, name: copy.deepcopy(stopped if engine == migration.SOURCE else target) migration.record_completion(stopped, stopped["State"], False) + assert migration.validate(stopped) == "project-worker" assert migration.completed(stopped, target) stopped["RestartCount"] = 4 stopped["NetworkSettings"]["SandboxID"] = "changed-by-daemon-restart" @@ -402,12 +453,26 @@ with tempfile.TemporaryDirectory() as directory: assert quiesced_intent["restart_disabled"] is True assert (migration.SOURCE, "stop", "-t", "300", quiesce_source["Id"]) in quiesce_calls assert (migration.SOURCE, "update", "--restart=no", quiesce_source["Id"]) in quiesce_calls + assert quiesce_calls.index((migration.SOURCE, "update", "--restart=no", quiesce_source["Id"])) < \ + quiesce_calls.index((migration.SOURCE, "stop", "-t", "300", quiesce_source["Id"])) migration.restore_source(quiesce_source["Id"]) assert quiesce_source["State"]["Running"] is True assert quiesce_source["HostConfig"]["RestartPolicy"]["Name"] == "unless-stopped" assert not migration.intent_path(quiesce_source["Id"]).exists() print("ok - batch quiesce durably disables restart and restores the exact source lifecycle") +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + power_intent = migration.record_migration_intent(intent_source) + power_intent = migration.record_migration_intent(intent_source, saved=power_intent, + restart_disabled=True) + power_intent["quiesce_started"] = True + migration.persist_migration_intent(intent_source, power_intent) + restarted_before_update = copy.deepcopy(intent_source) + restarted_before_update["State"]["StartedAt"] = "restarted-after-power-loss" + assert migration.migration_intent(restarted_before_update) == power_intent +print("ok - restart-disable intent recovers a daemon restart before Docker applies the update") + quiesce_source = copy.deepcopy(intent_source) quiesce_calls = [] with tempfile.TemporaryDirectory() as directory: @@ -453,7 +518,11 @@ def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image if mutate_source: current_source["HostConfig"]["Memory"] += 4096 elif args[:2] == (migration.SOURCE, "update"): - current_source["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} + value = args[2].split("=", 1)[1] + policy, _, retry_count = value.partition(":") + current_source["HostConfig"]["RestartPolicy"] = { + "Name": policy, "MaximumRetryCount": int(retry_count or 0), + } elif args[:2] == (migration.SOURCE, "start"): current_source["State"]["Running"] = True elif args[:2] == (migration.SOURCE, "commit"): @@ -623,6 +692,37 @@ with tempfile.TemporaryDirectory() as directory: pass else: raise AssertionError("an unexpectedly running interrupted destination passed preflight") + post_start_intent = copy.deepcopy(resume_intent) + post_start_intent["start_attempted"] = True + try: + migration.verify_resumable_migration(resume_source, resume_target, post_start_intent) + except ValueError: + pass + else: + raise AssertionError("a stopped destination that already ran passed automatic retry") + restored_source_intent = copy.deepcopy(resume_intent) + restored_source_intent["restore_started"] = True + try: + migration.verify_resumable_migration(resume_source, resume_target, restored_source_intent) + except ValueError: + pass + else: + raise AssertionError("a destination older than a restored source passed automatic retry") + migration.persist_migration_intent(resume_source, post_start_intent) + try: + migration.restore_source(resume_source["Id"]) + except RuntimeError: + pass + else: + raise AssertionError("post-start recovery restarted the rootful source") + assert not resume_source["State"]["Running"] + try: + migration.migrate(resume_source) + except ValueError: + pass + else: + raise AssertionError("a missing post-start destination allowed automatic recreation") + migration.persist_migration_intent(resume_source, resume_intent) migration.resume_verified_migration(resume_source, resume_target, resume_intent) assert (migration.TARGET, "start", "interrupted-retry") in resume_calls assert not migration.intent_path(resume_source["Id"]).exists() diff --git a/test/shell.d/rootless-docker-posture-test.sh b/test/shell.d/rootless-docker-posture-test.sh index 33ad72d435ee..51b62f9edaeb 100755 --- a/test/shell.d/rootless-docker-posture-test.sh +++ b/test/shell.d/rootless-docker-posture-test.sh @@ -55,6 +55,10 @@ grep -q -- '--check-windows "$windows_id"' "$migration" || windows_secure_line=$(grep -n '^/usr/bin/omarchy-windows-vm __migration-secure$' "$migration" | cut -d: -f1) [[ -n $windows_secure_line && -n $inventory_line ]] && (( windows_secure_line < inventory_line )) || fail "legacy Windows credentials and mounts are not secured before rootful inventory" +windows_check_line=$(grep -n -- '--check-windows "$windows_id"' "$migration" | head -n1 | cut -d: -f1) +owner_claim_line=$(grep -n 'owner = root / "migration-owner"' "$migration" | cut -d: -f1) +[[ -n $windows_check_line && -n $owner_claim_line ]] && (( windows_check_line < owner_claim_line )) || + fail "the machine migration owner is claimed before proving ownership of an existing Windows VM" quiesce_line=$(grep -n -- '--quiesce-all "$windows_arg"' "$migration" | cut -d: -f1) restart_line=$(grep -n 'systemctl restart docker.service' "$migration" | cut -d: -f1) transfer_line=$(grep -n '^ /usr/bin/python3 "$migrator" "${container_names\[@\]}"' "$migration" | cut -d: -f1) From 5cc6b35da85f83a5511bbee82d442d8b55c817d8 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Sat, 12 Sep 2026 04:37:33 -0600 Subject: [PATCH 06/31] Close rootless Docker recovery gaps --- default/docker/rootless/migrate.py | 103 ++++++--- default/docker/rootless/rootful-listeners.py | 107 +++++++++ docs/rootless-docker.md | 6 +- manual/18-development-tools.md | 2 +- migrations/1789164756.sh | 19 ++ .../shell.d/rootless-docker-migration-test.sh | 213 +++++++++++++++++- test/shell.d/rootless-docker-posture-test.sh | 48 ++++ 7 files changed, 460 insertions(+), 38 deletions(-) create mode 100644 default/docker/rootless/rootful-listeners.py diff --git a/default/docker/rootless/migrate.py b/default/docker/rootless/migrate.py index 071ea2c19354..3b21652db798 100644 --- a/default/docker/rootless/migrate.py +++ b/default/docker/rootless/migrate.py @@ -211,6 +211,8 @@ def verify_runtime(container, ownership=None): } if any(target_host.get(key, "") != value for key, value in private_modes.items()): raise RuntimeError(f"{name}: rootless Docker changed a private namespace boundary") + if target_host.get("Runtime") != "runc": + raise RuntimeError(f"{name}: rootless Docker changed the OCI runtime") expected_mounts = sorted((mount["Destination"], destination_volume(container, mount), bool(mount.get("RW"))) for mount in container.get("Mounts", [])) actual_mounts = target.get("Mounts") or [] @@ -494,6 +496,15 @@ def stopped_identity(state): return {key: state[key] for key in ("StartedAt", "FinishedAt")} +def target_never_started(container): + state = container.get("State") or {} + never = "0001-01-01T00:00:00Z" + return (state.get("Status") == "created" and state.get("Running") is False and + state.get("Paused") is not True and state.get("Restarting") is not True and + state.get("Dead") is not True and state.get("StartedAt") == never and + state.get("FinishedAt") == never) + + def record_completion(container, source_state, target_running): latest_source = inspect(SOURCE, "container", container["Id"]) if (stopped_identity(latest_source["State"]) != stopped_identity(source_state) or @@ -817,14 +828,18 @@ def restore_source(identity, validator=validate): raise RuntimeError(f'{current["Name"].lstrip("/")}: destination start was attempted; source recovery needs review') planned = planned_source(current, intent) desired_restart = planned["HostConfig"].get("RestartPolicy") or {} + if intent["target_running"] and not intent["restore_started"]: + # Re-enabling `always` can make Docker start the container after a daemon + # restart. Record that lifecycle restoration has begun before changing + # the policy so a fresh process can recognize that exact transition. + intent["restore_started"] = True + intent["quiesce_started"] = False + persist_migration_intent(current, intent) if (current["HostConfig"].get("RestartPolicy") or {}) != desired_restart: run(SOURCE, "update", f"--restart={restart_policy_argument(planned)}", identity) current = inspect(SOURCE, "container", identity) if intent["target_running"]: if not current["State"]["Running"]: - intent["restore_started"] = True - intent["quiesce_started"] = False - persist_migration_intent(current, intent) run(SOURCE, "start", identity) elif current["State"]["Running"]: raise RuntimeError(f'{current["Name"].lstrip("/")}: stopped source restarted during recovery') @@ -886,8 +901,8 @@ def verify_resumable_migration(container, target, intent): destination.get("snapshot") != snapshot_digest(target) or not target_owned(container, target, intent)): raise ValueError(f"{name}: interrupted rootless destination changed; inspect both engines") - if target["State"]["Running"]: - raise ValueError(f"{name}: interrupted rootless destination has an unexpected lifecycle") + if not target_never_started(target): + raise ValueError(f"{name}: interrupted rootless destination may have run; inspect both engines") verify_runtime(planned, intent["target_ownership"]) expected_volumes = {destination_volume(planned, mount): mount @@ -943,8 +958,6 @@ def migrate(container): name = container["Name"].lstrip("/") identity = container["Id"] intent = migration_intent(container) - if intent is not None and intent["start_attempted"]: - raise ValueError(f"{name}: destination start was attempted; inspect both engines") if exists("container", name): target = inspect(TARGET, "container", name) container = refresh_source(container) @@ -952,17 +965,21 @@ def migrate(container): clear_migration_intent(identity) print(f"{name}: already migrated") return + if intent is not None and intent["start_attempted"]: + raise ValueError(f"{name}: destination start was attempted; inspect both engines") if intent is None or not target_owned(container, target, intent): raise ValueError(f"{name}: an existing rootless Docker container needs review; no owned transfer matches it") if intent.get("destination") is not None: resume_verified_migration(container, target, intent) return - if target["State"]["Running"] or intent["start_attempted"]: + if not target_never_started(target): raise ValueError(f"{name}: an incomplete rootless destination may have run; inspect both engines") owned_id = target["Id"] run(TARGET, "rm", "--force", owned_id) if exists("container", name): raise ValueError(f"{name}: rootless destination name was replaced during recovery") + if intent is not None and intent["start_attempted"]: + raise ValueError(f"{name}: destination start was attempted; inspect both engines") if completion_path(identity).exists(): raise ValueError(f"{name}: a previously migrated destination is missing; inspect retained data before retrying") @@ -1014,7 +1031,7 @@ def migrate(container): arguments = [TARGET, "create", "--pull=never", "--name", name, "--label", f"{LABEL}={identity}", "--label", f'{OWNERSHIP_LABEL}={intent["target_ownership"]}', "--privileged=false", - "--ipc=private", "--cgroupns=private", "--network=bridge"] + "--ipc=private", "--cgroupns=private", "--network=bridge", "--runtime", "runc"] arguments += runtime_arguments(planned) config = planned["Config"] if config.get("Hostname"): @@ -1032,6 +1049,7 @@ def migrate(container): for port, bindings in (planned["HostConfig"].get("PortBindings") or {}).items(): for binding in bindings or []: arguments += ["--publish", f'127.0.0.1:{binding["HostPort"]}:{port}'] + pending_volumes = {} for mount in planned.get("Mounts", []): volume = inspect(SOURCE, "volume", mount["Name"]) validate_source_volume(container, volume) @@ -1054,15 +1072,9 @@ def migrate(container): if not retained: run(*volume_arguments, target) verify_volume_definition(volume, target, ownership) - if retained: - if volume_users(target): - raise RuntimeError(f"{name}: retained destination volume is attached; retained it for inspection") - clear_volume(target) - verify_volume_definition(volume, target, ownership) - digest = transfer_volume(volume, target) - record["digest"] = digest - persist_migration_intent(container, intent) - verified_volumes[target] = (volume, ownership, digest) + if volume_users(target): + raise RuntimeError(f"{name}: destination volume is attached; retained it for inspection") + pending_volumes[target] = (volume, ownership, record) mount_arg = f'type=volume,src={target},dst={mount["Destination"]},volume-nocopy' if not mount.get("RW"): mount_arg += ",readonly" @@ -1071,12 +1083,27 @@ def migrate(container): run(*arguments) created_target = inspect(TARGET, "container", name) if (not re.fullmatch(r"[a-f0-9]{64}", created_target.get("Id") or "") or - created_target["State"]["Running"] or not target_owned(planned, created_target, intent)): + not target_never_started(created_target) or not target_owned(planned, created_target, intent)): raise RuntimeError(f"{name}: rootless destination ownership could not be proven") created_id = created_target["Id"] - # The container has not started, and volume-nocopy prevents image data - # from replacing the restored volume contents. + # The stopped destination pins every volume before mutation, so another + # Docker client cannot remove and replace its predictable name between + # ownership verification and clearing or transfer. volume-nocopy keeps + # the committed image from changing the restored contents. verify_runtime(planned, intent["target_ownership"]) + for target, pending in pending_volumes.items(): + volume, ownership, record = pending + verify_volume_definition(volume, target, ownership) + if volume_users(target) != [created_id]: + raise RuntimeError(f"{name}: destination volume pin changed; retained it for inspection") + clear_volume(target) + verify_volume_definition(volume, target, ownership) + if volume_users(target) != [created_id]: + raise RuntimeError(f"{name}: destination volume pin changed; retained it for inspection") + digest = transfer_volume(volume, target) + record["digest"] = digest + persist_migration_intent(container, intent) + verified_volumes[target] = (volume, ownership, digest) for target, expected in verified_volumes.items(): volume, ownership, digest = expected verify_volume_definition(volume, target, ownership) @@ -1284,18 +1311,21 @@ def main(): for container in containers: name = container["Name"].lstrip("/") intent = migration_intent(container) - if intent is not None and intent["start_attempted"]: - raise ValueError(f"{name}: destination start was attempted; inspect both engines") if exists("container", name): target = inspect(TARGET, "container", name) - if not completed(container, target): - if intent is None or not target_owned(container, target, intent): - raise ValueError(f"{name}: an existing rootless Docker container needs review; no owned transfer matches it") - if intent.get("destination") is not None: - verify_resumable_migration(container, target, intent) - elif target["State"]["Running"] or intent["start_attempted"]: - raise ValueError(f"{name}: an incomplete rootless destination may have run; inspect both engines") + if completed(container, target): + continue + if intent is not None and intent["start_attempted"]: + raise ValueError(f"{name}: destination start was attempted; inspect both engines") + if intent is None or not target_owned(container, target, intent): + raise ValueError(f"{name}: an existing rootless Docker container needs review; no owned transfer matches it") + if intent.get("destination") is not None: + verify_resumable_migration(container, target, intent) + elif not target_never_started(target): + raise ValueError(f"{name}: an incomplete rootless destination may have run; inspect both engines") continue + if intent is not None and intent["start_attempted"]: + raise ValueError(f"{name}: destination start was attempted; inspect both engines") if completion_path(container["Id"]).exists(): raise ValueError(f"{name}: a previously migrated destination is missing; inspect retained data before retrying") for mount in container.get("Mounts", []): @@ -1311,8 +1341,17 @@ def main(): for container in containers: print(f'{container["Name"].lstrip("/")}: ready for rootless Docker migration') if not check_only: - for container in containers: - migrate(container) + try: + for container in containers: + migrate(container) + except BaseException: + for container in reversed(containers): + try: + restore_source(container["Id"]) + except Exception: + print(f'{container["Name"].lstrip("/")}: a quiesced source could not be restored; inspect both engines', + file=sys.stderr) + raise if __name__ == "__main__": diff --git a/default/docker/rootless/rootful-listeners.py b/default/docker/rootless/rootful-listeners.py new file mode 100644 index 000000000000..9c52e07d6bad --- /dev/null +++ b/default/docker/rootless/rootful-listeners.py @@ -0,0 +1,107 @@ +"""Verify that rootful Docker accepts API connections only through its protected Unix socket.""" + +import json +import os +from pathlib import Path +import re +import sys + + +EXPECTED_SOCKET = "/run/docker.sock" +INTERNAL_UNIX_SOCKETS = re.compile( + r"/(?:var/)?run/docker/(?:metrics\.sock|libnetwork/[a-f0-9]+\.sock)" +) + + +def process_socket_inodes(pid, proc=Path("/proc")): + if not isinstance(pid, int) or pid <= 1: + raise RuntimeError("rootful Docker has no valid main process") + inodes = set() + try: + descriptors = (proc / str(pid) / "fd").iterdir() + for descriptor in descriptors: + try: + target = os.readlink(descriptor) + except FileNotFoundError: + continue + match = re.fullmatch(r"socket:\[(\d+)]", target) + if match: + inodes.add(match.group(1)) + except FileNotFoundError as error: + raise RuntimeError("rootful Docker process disappeared while its listeners were checked") from error + return inodes + + +def unix_listeners(inodes, proc=Path("/proc")): + listeners = [] + for line in (proc / "net/unix").read_text().splitlines()[1:]: + fields = line.split(maxsplit=7) + if (len(fields) >= 7 and fields[3] == "00010000" and fields[4] == "0001" and + fields[6] in inodes): + listeners.append(fields[7] if len(fields) == 8 else "") + return listeners + + +def has_tcp_listener(inodes, proc=Path("/proc")): + for table in ("net/tcp", "net/tcp6"): + for line in (proc / table).read_text().splitlines()[1:]: + fields = line.split() + if len(fields) > 9 and fields[3] == "0A" and fields[9] in inodes: + return True + return False + + +def configured_hosts(pid, proc=Path("/proc"), filesystem=Path("/")): + arguments = (proc / str(pid) / "cmdline").read_bytes().split(b"\0") + arguments = [argument.decode() for argument in arguments if argument] + hosts = [] + config_path = "/etc/docker/daemon.json" + index = 1 + while index < len(arguments): + argument = arguments[index] + if argument in ("-H", "--host"): + index += 1 + if index >= len(arguments): + raise RuntimeError("rootful Docker has an incomplete host option") + hosts.append(arguments[index]) + elif argument.startswith("-H=") or argument.startswith("--host="): + hosts.append(argument.split("=", 1)[1]) + elif argument in ("--config-file",): + index += 1 + if index >= len(arguments): + raise RuntimeError("rootful Docker has an incomplete config-file option") + config_path = arguments[index] + elif argument.startswith("--config-file="): + config_path = argument.split("=", 1)[1] + index += 1 + + path = filesystem / config_path.lstrip("/") + configured = json.loads(path.read_text()) if path.exists() else {} + file_hosts = configured.get("hosts") or [] + if not isinstance(file_hosts, list) or any(not isinstance(host, str) for host in file_hosts): + raise RuntimeError("rootful Docker has an invalid hosts configuration") + if hosts and file_hosts: + raise RuntimeError("rootful Docker has conflicting host configuration") + return hosts or file_hosts or ["unix:///var/run/docker.sock"] + + +def verify(pid, proc=Path("/proc"), filesystem=Path("/")): + inodes = process_socket_inodes(pid, proc) + listeners = unix_listeners(inodes, proc) + hosts = configured_hosts(pid, proc, filesystem) + safe_hosts = (["fd://"], ["unix:///run/docker.sock"], ["unix:///var/run/docker.sock"]) + if (hosts not in safe_hosts or has_tcp_listener(inodes, proc) or + listeners.count(EXPECTED_SOCKET) != 1 or + any(path != EXPECTED_SOCKET and not INTERNAL_UNIX_SOCKETS.fullmatch(path) + for path in listeners)): + raise RuntimeError("rootful Docker has a custom API listener; remove it before automatic migration") + + +if __name__ == "__main__": + if len(sys.argv) != 2 or not sys.argv[1].isdigit(): + raise SystemExit("usage: rootful-listeners.py DOCKER_PID") + try: + verify(int(sys.argv[1])) + except (OSError, RuntimeError) as error: + print(f"Rootful Docker listener verification failed: {error}", file=sys.stderr) + raise SystemExit(1) from error diff --git a/docs/rootless-docker.md b/docs/rootless-docker.md index 6eaca68c977d..2312cc5b4b77 100644 --- a/docs/rootless-docker.md +++ b/docs/rootless-docker.md @@ -6,7 +6,7 @@ Omarchy runs ordinary development containers in a per-user rootless Docker daemo The user daemon is `docker.service` from `docker-rootless-extras`. It listens on `$XDG_RUNTIME_DIR/docker.sock`, stores engine data below `~/.local/share/docker`, and reads daemon configuration from `~/.config/docker/daemon.json`. `default/systemd/user-environment-generators/60-omarchy-rootless-docker` and `default/bash/env-bootstrap` export `DOCKER_HOST` only after `~/.local/state/omarchy/rootless-docker/enabled` exists. -The system daemon remains socket-activated for `omarchy-windows-vm`. Its vendor drop-in makes `/run/docker.sock` root-owned with mode `0600`, and the Windows command always selects that socket explicitly after authenticating with `sudo` or `pkexec`. User Docker settings and `DOCKER_HOST` cannot redirect the privileged VM command. +The system daemon remains socket-activated for `omarchy-windows-vm`. Its vendor drop-in makes `/run/docker.sock` root-owned with mode `0600`, and migration verifies from the daemon process's open sockets that this is its only API listener. Custom Unix or TCP listeners stop automatic migration. The Windows command always selects the protected socket explicitly after authenticating with `sudo` or `pkexec`; user Docker settings and `DOCKER_HOST` cannot redirect the privileged VM command. ## Fresh installs and additional users @@ -20,6 +20,6 @@ The migration's machine-wide enabled marker is written only after the shared roo The automatic path accepts running or never-started containers with stock bridge networking, localhost-only unprivileged published ports, private local named volumes, supported resource limits, root users with Docker's default capability ceiling or stricter settings, numeric non-root image users that already drop every capability, and the stock runtime and namespace boundaries. It rejects already-exited containers whose historical exit state cannot be recreated without rerunning them, privileged containers, added capabilities, devices, host or shared mounts, named image users whose effective UID is ambiguous, numeric non-root image users whose capability ceiling cannot be reproduced exactly, custom networks, namespace sharing, custom runtimes, altered confinement, custom logging, reserved migration labels, and unknown nondefault host settings. -For each accepted container, the migrator stops the source cleanly, commits its writable layer, transfers that image through Docker's native save/load format, copies named-volume contents and metadata inside the RootlessKit user and mount namespace, and recreates the container with explicit private and restrictive settings. It verifies environment, application config, limits, capabilities, mounts, ports, restart policy, logging, volume fingerprints, and lifecycle before writing a receipt bound to full source and destination snapshots. +For each accepted container, the migrator stops the source cleanly, commits its writable layer, transfers that image through Docker's native save/load format, creates a stopped `runc` destination to pin every owned volume, and copies volume contents and metadata inside the RootlessKit user and mount namespace. It verifies environment, application config, runtime, limits, capabilities, mounts, ports, restart policy, logging, volume fingerprints, and lifecycle before writing a receipt bound to full source and destination snapshots. If one transfer fails, every later source that the batch already quiesced is restored in reverse order. -Before the destination is first started, an error removes only the exact journal-owned destination container and restores the source. Journal-owned volumes remain available for ownership verification; a retry empties the verified volume before copying the current stopped source again, so a partial transfer or later source deletion cannot leave stale entries. Once a destination start has been attempted, automatic retry and source restoration stop for manual recovery because either side may contain new writes. Successful sources remain stopped with their restart policy disabled; they are retained in the rootful engine as recovery copies. +Before the destination is first started, an error removes only the exact journal-owned destination container and restores the source. Journal-owned volumes remain available for ownership verification; a retry attaches each verified volume to the stopped destination before emptying and copying the current stopped source again, so a concurrent name replacement, partial transfer, or later source deletion cannot damage unrelated data or leave stale entries. Resume requires Docker to prove that the destination has never started. Once a destination start has been attempted, automatic retry and source restoration stop for manual recovery because either side may contain new writes. A durable completion receipt takes precedence over a leftover journal if power fails between those two writes. Successful sources remain stopped with their restart policy disabled; they are retained in the rootful engine as recovery copies. diff --git a/manual/18-development-tools.md b/manual/18-development-tools.md index 786f766a1497..1853ce3c4a11 100644 --- a/manual/18-development-tools.md +++ b/manual/18-development-tools.md @@ -24,7 +24,7 @@ To install, say, Ruby, you'd run `mise use -g ruby`, which will both install Rub The daemon for development containers runs as your user and keeps its data in your home directory. Plain `docker`, `docker compose`, `docker buildx`, and the `d` alias use it directly, without `sudo` and without membership in the root-equivalent `docker` group. A container that escapes this daemon reaches only your user privileges rather than root privileges on the host. -Existing installs automatically move compatible running or never-started development containers and private named volumes into the rootless Docker store during update. The old rootful containers remain stopped as recovery copies. Already-exited containers and containers that depend on elevated privileges, host directories, devices, custom runtimes, or custom networks stay untouched and stop the migration with an explanation so Omarchy never reruns an exited workload or silently weakens or changes its access. +Existing installs automatically move compatible running or never-started development containers and private named volumes into the rootless Docker store during update. The old rootful containers remain stopped as recovery copies. Already-exited containers, custom rootful Docker API listeners, and containers that depend on elevated privileges, host directories, devices, custom runtimes, or custom networks stay untouched and stop the migration with an explanation so Omarchy never reruns an exited workload or silently weakens or changes its access. Remember to check out Lazydocker to manage your development containers in a cool TUI using `Super + Shift + D`. It connects to the same rootless daemon and does not need an authorization prompt. diff --git a/migrations/1789164756.sh b/migrations/1789164756.sh index a19735ec167e..e81b72b9d1ba 100644 --- a/migrations/1789164756.sh +++ b/migrations/1789164756.sh @@ -78,6 +78,7 @@ fi sudo /usr/bin/systemctl daemon-reload sudo /usr/bin/systemctl start docker.socket source_host="unix:///run/docker.sock" +listener_verifier=/usr/share/omarchy/default/docker/rootless/rootful-listeners.py restrict_rootful_socket() { local socket_owner @@ -93,10 +94,27 @@ restrict_rootful_socket() { fi } +verify_rootful_listeners() { + local main_pid verifier_mode + if sudo /usr/bin/test -L "$listener_verifier" || ! sudo /usr/bin/test -f "$listener_verifier"; then + echo "The packaged rootful Docker listener verifier is not trusted. This migration remains pending." >&2 + return 1 + fi + verifier_mode=$(sudo /usr/bin/stat -Lc '%u:%g:%a' "$listener_verifier") + if [[ $verifier_mode != "0:0:644" ]]; then + echo "The packaged rootful Docker listener verifier is not trusted. This migration remains pending." >&2 + return 1 + fi + main_pid=$(sudo /usr/bin/systemctl show docker.service --property MainPID --value) + sudo /usr/bin/python3 "$listener_verifier" "$main_pid" +} + # Load the packaged socket policy and prevent new unprivileged rootful clients # before taking the source inventory. Existing accepted connections are closed # by the daemon restart after every workload has been safely quiesced below. restrict_rootful_socket +sudo /usr/bin/docker --host "$source_host" info >/dev/null +verify_rootful_listeners remove_legacy_docker_group docker_inventory=$(sudo /usr/bin/docker --host "$source_host" ps -a --no-trunc --format '{{.ID}} {{.Names}}' | sort) @@ -174,6 +192,7 @@ fi sudo /usr/bin/systemctl restart docker.service sudo /usr/bin/systemctl start docker.socket restrict_rootful_socket +verify_rootful_listeners revoked_inventory=$(sudo /usr/bin/docker --host "$source_host" ps -a --no-trunc --format '{{.ID}} {{.Names}}' | sort) if [[ $revoked_inventory != "$docker_inventory" ]]; then diff --git a/test/shell.d/rootless-docker-migration-test.sh b/test/shell.d/rootless-docker-migration-test.sh index 4536938cfb04..84cf189bb1ee 100755 --- a/test/shell.d/rootless-docker-migration-test.sh +++ b/test/shell.d/rootless-docker-migration-test.sh @@ -162,6 +162,13 @@ created["State"] = { "FinishedAt": "0001-01-01T00:00:00Z", "ExitCode": 0, } assert migration.validate(created) == "project-worker" +assert migration.target_never_started(created) +ran_target = copy.deepcopy(created) +ran_target["State"] = { + "Status": "exited", "Running": False, "StartedAt": "target-start", + "FinishedAt": "target-stop", "ExitCode": 0, +} +assert not migration.target_never_started(ran_target) print("ok - paused, exited, and unreproducible non-root capability states fail closed") for stop_timeout in (None, -1, 0, 300): @@ -380,6 +387,45 @@ with tempfile.TemporaryDirectory() as directory: assert not migration.completed(stopped, target) print("ok - completion receipts bind both immutable workload snapshots and lifecycle state") +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + overlap_original = copy.deepcopy(container) + overlap_original["Mounts"] = [] + overlap_original["HostConfig"]["Binds"] = [] + overlap_source = copy.deepcopy(overlap_original) + overlap_source["State"] = { + "Status": "exited", "Running": False, "StartedAt": "start", + "FinishedAt": "completed-stop", "ExitCode": 0, + } + overlap_source["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} + overlap_target = copy.deepcopy(overlap_original) + overlap_target["Id"] = "b" * 64 + overlap_target["Config"]["Labels"][migration.LABEL] = overlap_source["Id"] + overlap_target["State"] = { + "Status": "running", "Running": True, "StartedAt": "target-start", + "FinishedAt": "0001-01-01T00:00:00Z", "ExitCode": 0, + } + overlap_intent = migration.record_migration_intent(overlap_original) + overlap_intent = migration.record_migration_intent( + overlap_source, overlap_source["State"], overlap_intent, restart_disabled=True, + ) + overlap_intent["start_attempted"] = True + migration.persist_migration_intent(overlap_source, overlap_intent) + migration.inspect = lambda engine, kind, name: copy.deepcopy( + overlap_source if engine == migration.SOURCE else overlap_target + ) + migration.record_completion(overlap_source, overlap_source["State"], True) + migration.exists = lambda kind, name: kind == "container" + migration.migrate(overlap_source) + assert not migration.intent_path(overlap_source["Id"]).exists() + + migration.persist_migration_intent(overlap_source, overlap_intent) + migration.daemon_security = lambda engine: source_security if engine == migration.SOURCE else target_security + sys.argv = ["migrate.py", "--check", overlap_source["Name"].lstrip("/")] + migration.main() + assert migration.intent_path(overlap_source["Id"]).exists() +print("ok - a valid completion receipt wins over its stale post-start journal") + restarted = copy.deepcopy(stopped) restarted["State"]["Running"] = True migration.inspect = lambda engine, kind, name: copy.deepcopy(restarted if engine == migration.SOURCE else target) @@ -424,6 +470,7 @@ print("ok - durable migration intent restores lifecycle and restart policy after quiesce_source = copy.deepcopy(intent_source) quiesce_calls = [] +restore_markers = [] def quiesce_inspect(engine, kind, name): return copy.deepcopy(quiesce_source) @@ -436,6 +483,8 @@ def quiesce_run(*args, **kwargs): } elif args[:2] == (migration.SOURCE, "update"): value = args[2].split("=", 1)[1] + if value != "no": + restore_markers.append(migration.migration_intent(quiesce_source)["restore_started"]) quiesce_source["HostConfig"]["RestartPolicy"] = { "Name": value, "MaximumRetryCount": 0, } @@ -458,6 +507,7 @@ with tempfile.TemporaryDirectory() as directory: migration.restore_source(quiesce_source["Id"]) assert quiesce_source["State"]["Running"] is True assert quiesce_source["HostConfig"]["RestartPolicy"]["Name"] == "unless-stopped" + assert restore_markers == [True] assert not migration.intent_path(quiesce_source["Id"]).exists() print("ok - batch quiesce durably disables restart and restores the exact source lifecycle") @@ -473,6 +523,25 @@ with tempfile.TemporaryDirectory() as directory: assert migration.migration_intent(restarted_before_update) == power_intent print("ok - restart-disable intent recovers a daemon restart before Docker applies the update") +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + always_source = copy.deepcopy(intent_source) + always_source["HostConfig"]["RestartPolicy"] = {"Name": "always", "MaximumRetryCount": 0} + always_intent = migration.record_migration_intent(always_source) + always_stopped = copy.deepcopy(always_source) + always_stopped["State"] = { + "Running": False, "StartedAt": "start", "FinishedAt": "restore-window", "ExitCode": 0, + } + always_stopped["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} + always_intent = migration.record_migration_intent(always_stopped, always_stopped["State"], + always_intent, restart_disabled=True) + always_intent["restore_started"] = True + migration.persist_migration_intent(always_stopped, always_intent) + restarted_during_restore = copy.deepcopy(always_source) + restarted_during_restore["State"]["StartedAt"] = "daemon-restart-during-restore" + assert migration.migration_intent(restarted_during_restore) == always_intent +print("ok - durable restore intent recognizes an always source restarted after policy restoration") + quiesce_source = copy.deepcopy(intent_source) quiesce_calls = [] with tempfile.TemporaryDirectory() as directory: @@ -534,7 +603,9 @@ def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image key, value = args[index + 1].split("=", 1) labels[key] = value current_target = {"Id": "b" * 64, "Config": {"Labels": labels}, - "State": {"Running": False}} + "State": {"Status": "created", "Running": False, + "StartedAt": "0001-01-01T00:00:00Z", + "FinishedAt": "0001-01-01T00:00:00Z"}} elif args[:3] == (migration.TARGET, "rm", "--force"): current_target = None elif args[:2] == (migration.TARGET, "start"): @@ -570,6 +641,8 @@ def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image calls, source, pipes, intent_retained = exercise_failed_transfer(False) +create_call = next(call for call in calls if call[:2] == (migration.TARGET, "create")) +assert create_call[create_call.index("--runtime") + 1] == "runc" assert (migration.TARGET, "rm", "--force", "b" * 64) in calls assert (migration.TARGET, "image", "rm", "sha256:" + "e" * 64) in calls assert (migration.SOURCE, "stop", "-t", "300", "c" * 64) in calls @@ -639,7 +712,9 @@ with tempfile.TemporaryDirectory() as directory: key, value = args[index + 1].split("=", 1) labels[key] = value retry_state["target"] = {"Id": "7" * 64, "Config": {"Labels": labels}, - "State": {"Running": False}} + "State": {"Status": "created", "Running": False, + "StartedAt": "0001-01-01T00:00:00Z", + "FinishedAt": "0001-01-01T00:00:00Z"}} if args[:2] == (migration.TARGET, "start"): retry_state["target"]["State"]["Running"] = True @@ -692,6 +767,17 @@ with tempfile.TemporaryDirectory() as directory: pass else: raise AssertionError("an unexpectedly running interrupted destination passed preflight") + ran_and_stopped = copy.deepcopy(resume_target) + ran_and_stopped["State"] = { + "Status": "exited", "Running": False, "StartedAt": "outside-start", + "FinishedAt": "outside-stop", "ExitCode": 0, + } + try: + migration.verify_resumable_migration(resume_source, ran_and_stopped, resume_intent) + except ValueError: + pass + else: + raise AssertionError("an externally started and stopped destination passed automatic retry") post_start_intent = copy.deepcopy(resume_intent) post_start_intent["start_attempted"] = True try: @@ -727,4 +813,127 @@ with tempfile.TemporaryDirectory() as directory: assert (migration.TARGET, "start", "interrupted-retry") in resume_calls assert not migration.intent_path(resume_source["Id"]).exists() print("ok - a verified destination resumes safely across interruption before its first start") + +pinned_source = copy.deepcopy(container) +pinned_source["Name"] = "/pinned-volume" +pinned_source["Id"] = "5" * 64 +current_pinned_source = copy.deepcopy(pinned_source) +source_volume = { + "Name": "project-data", "Driver": "local", "Options": None, + "Labels": {"project": "fixture"}, "Mountpoint": "/source-volume", +} +target_volume = None +pinned_target = None +pin_events = [] + + +def pin_inspect(engine, kind, name): + if engine == migration.SOURCE and kind == "container": + return copy.deepcopy(current_pinned_source) + if engine == migration.SOURCE and kind == "volume": + return copy.deepcopy(source_volume) + if engine == migration.TARGET and kind == "volume": + if target_volume is None: + raise migration.subprocess.CalledProcessError(1, ["docker", "inspect"]) + return copy.deepcopy(target_volume) + if pinned_target is None: + raise migration.subprocess.CalledProcessError(1, ["docker", "inspect"]) + return copy.deepcopy(pinned_target) + + +def pin_run(*args, **kwargs): + global target_volume, pinned_target + pin_events.append(args) + if args[:2] == (migration.SOURCE, "update"): + current_pinned_source["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} + elif args[:2] == (migration.SOURCE, "stop"): + current_pinned_source["State"] = { + "Status": "exited", "Running": False, "StartedAt": "start", + "FinishedAt": "pinned-stop", "ExitCode": 0, + } + elif args[:2] == (migration.SOURCE, "commit"): + return "sha256:" + "4" * 64 + elif args[:3] == (migration.TARGET, "volume", "create"): + labels = {} + for index, argument in enumerate(args): + if argument == "--label": + key, value = args[index + 1].split("=", 1) + labels[key] = value + target_volume = { + "Name": args[-1], "Driver": "local", "Options": None, + "Labels": labels, "Mountpoint": "/target-volume", + } + elif args[:2] == (migration.TARGET, "create"): + labels = {} + for index, argument in enumerate(args): + if argument == "--label": + key, value = args[index + 1].split("=", 1) + labels[key] = value + pinned_target = { + "Id": "6" * 64, "Config": {"Labels": labels}, + "State": {"Status": "created", "Running": False, + "StartedAt": "0001-01-01T00:00:00Z", + "FinishedAt": "0001-01-01T00:00:00Z"}, + } + elif args[:3] == (migration.TARGET, "container", "ls"): + return pinned_target["Id"] if pinned_target is not None else "" + elif args[:2] == (migration.TARGET, "start"): + pinned_target["State"]["Status"] = "running" + pinned_target["State"]["Running"] = True + + +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + migration.inspect = pin_inspect + migration.run = pin_run + migration.exists = lambda kind, name: ( + (kind == "container" and pinned_target is not None) or + (kind == "volume" and target_volume is not None) + ) + migration.pipe = lambda producer, consumer: pin_events.append(("pipe",)) + migration.verify_runtime = lambda value, ownership=None: None + migration.verify_volume = lambda target, digest: None + migration.source_volume_digest = lambda volume: "7" * 64 + migration.clear_volume = lambda target: pin_events.append(("clear", target)) + migration.transfer_volume = lambda volume, target: (pin_events.append(("transfer", target)) or "7" * 64) + migration.record_completion = lambda source, state, running: None + migration.migrate(pinned_source) + +create_index = next(index for index, event in enumerate(pin_events) + if event[:2] == (migration.TARGET, "create")) +clear_index = pin_events.index(("clear", "project-data")) +transfer_index = pin_events.index(("transfer", "project-data")) +assert create_index < clear_index < transfer_index +create_call = pin_events[create_index] +assert create_call[create_call.index("--runtime") + 1] == "runc" +assert any(event[:3] == (migration.TARGET, "container", "ls") + for event in pin_events[create_index + 1:clear_index]) +print("ok - the stopped destination pins each owned volume before clearing or transfer") + +batch = [] +for index in (1, 2): + member = copy.deepcopy(container) + member["Name"] = f"/batch-{index}" + member["Id"] = str(index) * 64 + member["Mounts"] = [] + member["HostConfig"]["Binds"] = [] + batch.append(member) +batch_by_name = {member["Name"].lstrip("/"): member for member in batch} +restored_batch = [] +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + migration.daemon_security = lambda engine: source_security if engine == migration.SOURCE else target_security + migration.inspect = lambda engine, kind, name: copy.deepcopy(batch_by_name[name]) + migration.exists = lambda kind, name: False + migration.migrate = lambda member: (_ for _ in ()).throw(RuntimeError("first transfer failed")) + migration.restore_source = lambda identity, validator=migration.validate: restored_batch.append(identity) + sys.argv = ["migrate.py", *batch_by_name] + try: + migration.main() + except RuntimeError: + pass + else: + raise AssertionError("a failed batch transfer was reported as complete") +assert restored_batch == [batch[1]["Id"], batch[0]["Id"]] +print("ok - transfer failure restores every remaining quiesced workload in reverse order") PY diff --git a/test/shell.d/rootless-docker-posture-test.sh b/test/shell.d/rootless-docker-posture-test.sh index 51b62f9edaeb..95e7aad00d7f 100755 --- a/test/shell.d/rootless-docker-posture-test.sh +++ b/test/shell.d/rootless-docker-posture-test.sh @@ -50,6 +50,9 @@ later_group_drop=$(sed -n "${completion_line},${completion_return}p" "$migration socket_line=$(grep -n "socket_owner=" "$migration" | cut -d: -f1) [[ -n $socket_line && -n $inventory_line ]] && (( socket_line < inventory_line )) || fail "the legacy group socket remains writable during source migration" +listener_line=$(grep -n '^verify_rootful_listeners$' "$migration" | head -n1 | cut -d: -f1) +[[ -n $listener_line ]] && (( socket_line < listener_line && listener_line < inventory_line )) || + fail "custom rootful Docker listeners are not rejected before source migration" grep -q -- '--check-windows "$windows_id"' "$migration" || fail "the name-based Windows exception is not authenticated against its managed runtime" windows_secure_line=$(grep -n '^/usr/bin/omarchy-windows-vm __migration-secure$' "$migration" | cut -d: -f1) @@ -67,10 +70,55 @@ transfer_line=$(grep -n '^ /usr/bin/python3 "$migrator" "${container_names\[@\] fail "rootful connections are not revoked between durable quiesce and transfer" (( $(grep -c '^restrict_rootful_socket$' "$migration") == 2 )) || fail "rootful socket policy is not rechecked after daemon restart" +(( $(grep -c '^verify_rootful_listeners$' "$migration") == 2 )) || + fail "rootful Docker listeners are not rechecked after daemon restart" grep -q -- '--restore-windows "$windows_id"' "$migration" || fail "a running Windows VM is not restored after rootful connection revocation" pass "migration serializes ownership, secures Windows, and revokes existing rootful connections" +listener_verifier="$ROOT/default/docker/rootless/rootful-listeners.py" +python3 - "$listener_verifier" <<'PY' +import importlib.util +import os +from pathlib import Path +import sys +import tempfile + +spec = importlib.util.spec_from_file_location("rootful_listeners", sys.argv[1]) +listeners = importlib.util.module_from_spec(spec) +spec.loader.exec_module(listeners) + +with tempfile.TemporaryDirectory() as directory: + proc = Path(directory) + descriptors = proc / "4242/fd" + descriptors.mkdir(parents=True) + (proc / "net").mkdir() + (proc / "4242/cmdline").write_bytes(b"/usr/bin/dockerd\0-H\0fd://\0") + os.symlink("socket:[101]", descriptors / "3") + (proc / "net/unix").write_text( + "Num RefCount Protocol Flags Type St Inode Path\n" + "00000000: 00000002 00000000 00010000 0001 01 101 /run/docker.sock\n" + ) + tcp_header = "sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n" + (proc / "net/tcp").write_text(tcp_header) + (proc / "net/tcp6").write_text(tcp_header) + listeners.verify(4242, proc, proc) + + os.symlink("socket:[102]", descriptors / "4") + (proc / "net/tcp").write_text( + tcp_header + + "0: 0100007F:0947 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 102\n" + ) + try: + listeners.verify(4242, proc, proc) + except RuntimeError: + pass + else: + raise AssertionError("a rootful TCP API listener was accepted") +print("ok - listener verification accepts only the protected rootful Unix socket") +PY +pass "rootful Docker listener verification rejects extra API endpoints" + grep -q "alias d='docker'" "$ROOT/default/bash/aliases" || fail "the d alias remains Docker" ! rg -q 'sudo[[:space:]]+docker' "$ROOT/bin/omarchy-install-docker-dbs" || fail "development database installs still use rootful Docker" From bdc8d1a820b2f3d1173b49be289cb5f844def8c8 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Sat, 12 Sep 2026 05:26:49 -0600 Subject: [PATCH 07/31] Harden rootless Docker finalization --- bin/omarchy-windows-vm | 66 ++++++- default/docker/rootless/migrate.py | 176 +++++++++++++++--- docs/rootless-docker.md | 6 +- migrations/1789164756.sh | 18 +- .../shell.d/rootless-docker-migration-test.sh | 100 +++++++--- test/shell.d/rootless-docker-posture-test.sh | 6 + test/shell.d/windows-vm-auth-test.sh | 3 + test/shell.d/windows-vm-compose-test.sh | 29 ++- 8 files changed, 338 insertions(+), 66 deletions(-) diff --git a/bin/omarchy-windows-vm b/bin/omarchy-windows-vm index 5a2ed9b63162..bf494f6ca4a3 100755 --- a/bin/omarchy-windows-vm +++ b/bin/omarchy-windows-vm @@ -650,6 +650,37 @@ rollback_new_caller_mounts() { return "$failed" } +fsync_regular_file() { + /usr/bin/python3 - "$1" <<'PY' +import os +import stat +import sys + + +descriptor = os.open(sys.argv[1], os.O_RDONLY | os.O_NOFOLLOW) +try: + if not stat.S_ISREG(os.fstat(descriptor).st_mode): + raise SystemExit("refusing to sync a non-regular file") + os.fsync(descriptor) +finally: + os.close(descriptor) +PY +} + +fsync_directory() { + /usr/bin/python3 - "$1" <<'PY' +import os +import sys + + +descriptor = os.open(sys.argv[1], os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) +try: + os.fsync(descriptor) +finally: + os.close(descriptor) +PY +} + write_compose_atomically() ( local ram="$1" cores="$2" disk="$3" username="$4" password="$5" tz="$6" local tmp="" rc esc_password @@ -712,8 +743,10 @@ EOF if ((EUID == 0)); then chown root:root "$tmp" || exit 1 fi + fsync_regular_file "$tmp" || exit 1 mv -fT -- "$tmp" "$COMPOSE_FILE" || exit 1 tmp="" + fsync_directory "$RUNTIME_DIR" || exit 1 trap - EXIT ) @@ -815,7 +848,9 @@ rewrite_compose_security() { return 1 } fi + fsync_regular_file "$tmp" || { rm -f "$tmp"; return 1; } mv -fT -- "$tmp" "$COMPOSE_FILE" || { rm -f "$tmp"; return 1; } + fsync_directory "$RUNTIME_DIR" } assert_compose_trusted() { @@ -893,7 +928,26 @@ assert_mounts_safe() { __priv_up() { assert_mounts_safe && dc up -d; } -__priv_secure() { assert_mounts_safe; } +__priv_secure() { + local status + if [[ ! -f $COMPOSE_FILE ]]; then + if docker inspect "$CONTAINER" >/dev/null 2>&1; then + echo "omarchy-windows-vm: an existing Windows container has no trusted Compose definition" >&2 + return 1 + fi + return 0 + fi + assert_mounts_safe || return 1 + status=$(docker inspect --format='{{.State.Status}}' "$CONTAINER" 2>/dev/null) || return 0 + if [[ $status == "running" ]]; then + dc up -d --force-recreate + elif [[ $status == "created" || $status == "exited" ]]; then + dc up --no-start --force-recreate + else + echo "omarchy-windows-vm: transitional Windows lifecycle needs manual review" >&2 + return 1 + fi +} __priv_down() { dc down; } @@ -1063,7 +1117,8 @@ write_credentials() { umask 077 tmp=$(mktemp "$dir/.credentials.XXXXXX") || { umask "$old_umask"; return 1; } if ! printf 'USERNAME=%s\nPASSWORD=%s\n' "$username" "$password" >"$tmp" || - ! chmod 0600 "$tmp" || ! mv -fT -- "$tmp" "$CREDENTIALS_FILE"; then + ! chmod 0600 "$tmp" || ! fsync_regular_file "$tmp" || + ! mv -fT -- "$tmp" "$CREDENTIALS_FILE" || ! fsync_directory "$dir"; then rm -f -- "$tmp" umask "$old_umask" return 1 @@ -1118,16 +1173,15 @@ migrate_legacy_compose() { echo "Re-run: omarchy-windows-vm install" >&2 return 1 fi - rm -f "$LEGACY_COMPOSE_FILE" + rm -f "$LEGACY_COMPOSE_FILE" || return 1 + fsync_directory "$(dirname -- "$LEGACY_COMPOSE_FILE")" } secure_windows_migration() { if [[ ! -f $COMPOSE_FILE && -f $LEGACY_COMPOSE_FILE ]]; then migrate_legacy_compose || return 1 fi - if [[ -f $COMPOSE_FILE ]]; then - priv secure || return 1 - fi + priv secure } # --- prerequisites ----------------------------------------------------------- diff --git a/default/docker/rootless/migrate.py b/default/docker/rootless/migrate.py index 3b21652db798..ae0b7dd1606b 100644 --- a/default/docker/rootless/migrate.py +++ b/default/docker/rootless/migrate.py @@ -3,7 +3,6 @@ import hashlib import json import os -import pwd import re import secrets import stat @@ -471,6 +470,33 @@ def target_owned(container, target, intent): labels.get(OWNERSHIP_LABEL) == intent["target_ownership"]) +def volume_guard_name(intent): + ownership = intent.get("target_ownership") + if not re.fullmatch(r"[a-f0-9]{64}", ownership or ""): + raise ValueError("Interrupted rootless Docker ownership is invalid") + return f"omarchy-volume-guard-{ownership}" + + +def volume_guard_owned(container, guard, intent): + name = volume_guard_name(intent) + return (guard.get("Name") == f"/{name}" and + target_owned(container, guard, intent) and + target_never_started(guard)) + + +def remove_volume_guard(container, intent): + name = volume_guard_name(intent) + if not exists("container", name): + return + guard = inspect(TARGET, "container", name) + if (not re.fullmatch(r"[a-f0-9]{64}", guard.get("Id") or "") or + not volume_guard_owned(container, guard, intent)): + raise ValueError(f'{container["Name"].lstrip("/")}: rootless volume guard changed or ran; inspect both engines') + run(TARGET, "rm", "--force", guard["Id"]) + if exists("container", name): + raise RuntimeError(f'{container["Name"].lstrip("/")}: rootless volume guard name was replaced during cleanup') + + def completed(container, target): if (target["Config"].get("Labels") or {}).get(LABEL) != container["Id"]: return False @@ -512,6 +538,11 @@ def record_completion(container, source_state, target_running): raise RuntimeError(f'{container["Name"].lstrip("/")}: Docker source changed before completion; inspect both engines') container = latest_source target = inspect(TARGET, "container", container["Name"].lstrip("/")) + if target_running: + if target["State"].get("Running") is not True: + raise RuntimeError(f'{container["Name"].lstrip("/")}: destination stopped before completion') + elif not target_never_started(target): + raise RuntimeError(f'{container["Name"].lstrip("/")}: stopped destination ran before completion') write_private_json(completion_path(container["Id"]), { "target": target["Id"], "source": stopped_identity(source_state), "target_running": target_running, @@ -603,15 +634,12 @@ def validate_windows_exception(container): mounts_by_destination = {mount.get("Destination"): mount for mount in mounts} storage = mounts_by_destination.get("/storage") or {} shared = mounts_by_destination.get("/shared") or {} - account = pwd.getpwuid(os.getuid()) - protected = f"/var/lib/omarchy/windows/mounts/users/{account.pw_uid}" - legacy = account.pw_dir - previous = f'{Path(account.pw_dir).parent}/.omarchy-windows/users/{account.pw_uid}' - allowed_mounts = { - (f"{protected}/storage", f"{protected}/shared"), - (f"{legacy}/.windows", f"{legacy}/Windows"), - (f"{previous}/storage", f"{previous}/shared"), - } + protected = f"/var/lib/omarchy/windows/mounts/users/{os.getuid()}" + environment = config.get("Env") or [] + valid_environment = (isinstance(environment, list) and + all(isinstance(entry, str) and "=" in entry for entry in environment) and + len({entry.split("=", 1)[0] for entry in environment}) == len(environment)) + environment_map = dict(entry.split("=", 1) for entry in environment) if valid_environment else {} networks = container.get("NetworkSettings", {}).get("Networks") or {} if (name != "omarchy-windows" or not re.fullmatch(r"[a-f0-9]{64}", container["Id"]) or @@ -633,7 +661,9 @@ def validate_windows_exception(container): (host.get("RestartPolicy") or {}).get("Name") != "no" or len(mounts) != 2 or any(mount.get("Type") != "bind" for mount in mounts) or any(mount.get("RW") is not True for mount in mounts) or - (storage.get("Source"), shared.get("Source")) not in allowed_mounts or + (storage.get("Source"), shared.get("Source")) != + (f"{protected}/storage", f"{protected}/shared") or + environment_map.get("PROTECT") != "Y" or set(networks) != {"windows_default"}): raise ValueError("omarchy-windows: the rootful exception does not match Omarchy's managed Windows VM") return name @@ -962,6 +992,8 @@ def migrate(container): target = inspect(TARGET, "container", name) container = refresh_source(container) if completed(container, target): + if intent is not None: + remove_volume_guard(container, intent) clear_migration_intent(identity) print(f"{name}: already migrated") return @@ -970,6 +1002,8 @@ def migrate(container): if intent is None or not target_owned(container, target, intent): raise ValueError(f"{name}: an existing rootless Docker container needs review; no owned transfer matches it") if intent.get("destination") is not None: + if exists("container", volume_guard_name(intent)): + raise ValueError(f"{name}: completed volume transfer still has a guard; inspect both engines") resume_verified_migration(container, target, intent) return if not target_never_started(target): @@ -978,6 +1012,8 @@ def migrate(container): run(TARGET, "rm", "--force", owned_id) if exists("container", name): raise ValueError(f"{name}: rootless destination name was replaced during recovery") + if intent is not None: + remove_volume_guard(container, intent) if intent is not None and intent["start_attempted"]: raise ValueError(f"{name}: destination start was attempted; inspect both engines") if completion_path(identity).exists(): @@ -988,6 +1024,7 @@ def migrate(container): planned = planned_source(container, intent) running = intent["target_running"] if intent is not None else bool(container["State"]["Running"]) created_id = None + guard_id = None image = None image_committed = False image_loaded = False @@ -1080,26 +1117,44 @@ def migrate(container): mount_arg += ",readonly" arguments += ["--mount", mount_arg] arguments.append(image) - run(*arguments) - created_target = inspect(TARGET, "container", name) - if (not re.fullmatch(r"[a-f0-9]{64}", created_target.get("Id") or "") or - not target_never_started(created_target) or not target_owned(planned, created_target, intent)): - raise RuntimeError(f"{name}: rootless destination ownership could not be proven") - created_id = created_target["Id"] - # The stopped destination pins every volume before mutation, so another - # Docker client cannot remove and replace its predictable name between - # ownership verification and clearing or transfer. volume-nocopy keeps - # the committed image from changing the restored contents. - verify_runtime(planned, intent["target_ownership"]) + if pending_volumes: + guard_name = volume_guard_name(intent) + guard_arguments = [ + TARGET, "create", "--pull=never", "--name", guard_name, + "--label", f"{LABEL}={identity}", + "--label", f'{OWNERSHIP_LABEL}={intent["target_ownership"]}', + "--privileged=false", "--read-only", "--cap-drop", "ALL", + "--security-opt", "no-new-privileges", "--ipc=private", + "--cgroupns=private", "--network=none", "--runtime", "runc", + "--restart", "no", "--entrypoint", f"/.{guard_name}", + ] + for mount in planned.get("Mounts", []): + target = destination_volume(planned, mount) + mount_arg = f'type=volume,src={target},dst={mount["Destination"]},volume-nocopy' + if not mount.get("RW"): + mount_arg += ",readonly" + guard_arguments += ["--mount", mount_arg] + guard_arguments.append(image) + run(*guard_arguments) + guard = inspect(TARGET, "container", guard_name) + if (not re.fullmatch(r"[a-f0-9]{64}", guard.get("Id") or "") or + not volume_guard_owned(planned, guard, intent)): + raise RuntimeError(f"{name}: rootless volume guard ownership could not be proven") + guard_id = guard["Id"] + for target, pending in pending_volumes.items(): + volume, ownership, _record = pending + verify_volume_definition(volume, target, ownership) + if set(volume_users(target)) != {guard_id}: + raise RuntimeError(f"{name}: destination volume guard changed; retained it for inspection") for target, pending in pending_volumes.items(): volume, ownership, record = pending verify_volume_definition(volume, target, ownership) - if volume_users(target) != [created_id]: - raise RuntimeError(f"{name}: destination volume pin changed; retained it for inspection") + if set(volume_users(target)) != {guard_id}: + raise RuntimeError(f"{name}: destination volume guard changed; retained it for inspection") clear_volume(target) verify_volume_definition(volume, target, ownership) - if volume_users(target) != [created_id]: - raise RuntimeError(f"{name}: destination volume pin changed; retained it for inspection") + if set(volume_users(target)) != {guard_id}: + raise RuntimeError(f"{name}: destination volume guard changed; retained it for inspection") digest = transfer_volume(volume, target) record["digest"] = digest persist_migration_intent(container, intent) @@ -1114,9 +1169,36 @@ def migrate(container): if (stopped_identity(latest_source["State"]) != stopped_identity(state) or snapshot_digest(latest_source) != snapshot_digest(container)): raise RuntimeError(f"{name}: Docker source changed during transfer; inspect both engines") + if guard_id is not None: + guard = inspect(TARGET, "container", guard_id) + if not volume_guard_owned(planned, guard, intent): + raise RuntimeError(f"{name}: rootless volume guard changed or ran during transfer") + run(*arguments) + target = inspect(TARGET, "container", name) + if (not re.fullmatch(r"[a-f0-9]{64}", target.get("Id") or "") or + not target_never_started(target) or not target_owned(planned, target, intent)): + raise RuntimeError(f"{name}: rootless destination ownership could not be proven") + created_id = target["Id"] + verify_runtime(planned, intent["target_ownership"]) + for target_name, pending in pending_volumes.items(): + volume, ownership, _record = pending + verify_volume_definition(volume, target_name, ownership) + if set(volume_users(target_name)) != {guard_id, created_id}: + raise RuntimeError(f"{name}: destination volume references changed; retained it for inspection") + if guard_id is not None: + guard = inspect(TARGET, "container", guard_id) + if not volume_guard_owned(planned, guard, intent): + raise RuntimeError(f"{name}: rootless volume guard changed or ran during finalization") + run(TARGET, "rm", "--force", guard_id) + guard_id = None + if exists("container", volume_guard_name(intent)): + raise RuntimeError(f"{name}: rootless volume guard name was replaced during finalization") + for target_name in pending_volumes: + if set(volume_users(target_name)) != {created_id}: + raise RuntimeError(f"{name}: final destination volume references changed; retained it for inspection") target = inspect(TARGET, "container", created_id) - if not target_owned(planned, target, intent): - raise RuntimeError(f"{name}: rootless destination ownership changed during transfer") + if not target_never_started(target) or not target_owned(planned, target, intent): + raise RuntimeError(f"{name}: rootless destination changed or ran during finalization") intent["destination"] = {"id": created_id, "snapshot": snapshot_digest(target)} persist_migration_intent(container, intent) source_after = inspect(SOURCE, "container", identity) @@ -1148,16 +1230,52 @@ def migrate(container): "Inspect rootless Docker before resuming the rootful copy or retrying migration.", file=sys.stderr) raise recovery_failed = False + destination_may_have_run = False try: owned_target = inspect(TARGET, "container", created_id or name) if not target_owned(planned, owned_target, intent): + destination_may_have_run = True raise RuntimeError("rootless destination ownership changed") + if not target_never_started(owned_target): + destination_may_have_run = True + raise RuntimeError("rootless destination may have run") run(TARGET, "rm", "--force", owned_target["Id"]) + if exists("container", name): + destination_may_have_run = True + raise RuntimeError("rootless destination name was replaced") except subprocess.CalledProcessError: - pass + if exists("container", name): + destination_may_have_run = True + recovery_failed = True + print(f"{name}: destination identity was replaced; retained both stores for review", file=sys.stderr) except Exception: recovery_failed = True print(f"{name}: destination cleanup was not ownership-safe; retained it for inspection", file=sys.stderr) + try: + guard_name = volume_guard_name(intent) + if exists("container", guard_name): + guard = inspect(TARGET, "container", guard_name) + if ((guard_id is not None and guard.get("Id") != guard_id) or + not volume_guard_owned(planned, guard, intent)): + destination_may_have_run = True + raise RuntimeError("rootless volume guard changed or ran") + run(TARGET, "rm", "--force", guard["Id"]) + if exists("container", guard_name): + destination_may_have_run = True + raise RuntimeError("rootless volume guard name was replaced") + except subprocess.CalledProcessError: + pass + except Exception: + recovery_failed = True + print(f"{name}: volume guard cleanup was not ownership-safe; retained it for inspection", file=sys.stderr) + if destination_may_have_run: + try: + intent["start_attempted"] = True + persist_migration_intent(container, intent) + except Exception: + pass + print(f"{name}: a rootless migration container may have run; both stores were retained for review", file=sys.stderr) + raise recovery = [] if image_loaded: recovery.append((TARGET, "image", "rm", image)) diff --git a/docs/rootless-docker.md b/docs/rootless-docker.md index 2312cc5b4b77..92cd61d00e73 100644 --- a/docs/rootless-docker.md +++ b/docs/rootless-docker.md @@ -6,7 +6,7 @@ Omarchy runs ordinary development containers in a per-user rootless Docker daemo The user daemon is `docker.service` from `docker-rootless-extras`. It listens on `$XDG_RUNTIME_DIR/docker.sock`, stores engine data below `~/.local/share/docker`, and reads daemon configuration from `~/.config/docker/daemon.json`. `default/systemd/user-environment-generators/60-omarchy-rootless-docker` and `default/bash/env-bootstrap` export `DOCKER_HOST` only after `~/.local/state/omarchy/rootless-docker/enabled` exists. -The system daemon remains socket-activated for `omarchy-windows-vm`. Its vendor drop-in makes `/run/docker.sock` root-owned with mode `0600`, and migration verifies from the daemon process's open sockets that this is its only API listener. Custom Unix or TCP listeners stop automatic migration. The Windows command always selects the protected socket explicitly after authenticating with `sudo` or `pkexec`; user Docker settings and `DOCKER_HOST` cannot redirect the privileged VM command. +The system daemon remains socket-activated for `omarchy-windows-vm`. Its vendor drop-in makes `/run/docker.sock` root-owned with mode `0600`, and migration verifies both the effective systemd socket properties and the daemon process's open sockets before and after connection revocation. A later administrator override, custom Unix listener, or TCP listener stops automatic migration. The Windows command always selects the protected socket explicitly after authenticating with `sudo` or `pkexec`; user Docker settings and `DOCKER_HOST` cannot redirect the privileged VM command. ## Fresh installs and additional users @@ -16,10 +16,10 @@ The migration's machine-wide enabled marker is written only after the shared roo ## Existing-install migration -`migrations/1789164756.sh` installs the rootless runtime, allocates subordinate IDs, starts and proves the rootless daemon, secures any current account's Windows definition, restricts the old API socket to root, and preflights every rootful container. Only after those checks does it claim the machine-wide source inventory for that account. A container named `omarchy-windows` is exempt only when its image, Compose identity, devices, capabilities, ports, and UID-bound mounts match Omarchy's managed VM. A blocker in any source prevents the batch from stopping its first container or assigning the migration owner. +`migrations/1789164756.sh` installs the rootless runtime, allocates subordinate IDs, starts and proves the rootless daemon, secures any current account's Windows definition, restricts the old API socket to root, and preflights every rootful container. An existing Windows container is recreated from the hardened Compose definition while preserving whether it was running or stopped; the new runtime must use web protection and the current account's protected mount anchors. Only after those checks does the migration claim the machine-wide source inventory for that account. A container named `omarchy-windows` is exempt only when its image, Compose identity, devices, capabilities, ports, environment, and UID-bound mounts match Omarchy's managed VM. A blocker in any source prevents the batch from stopping its first container or assigning the migration owner. Compose, credentials, and legacy-definition removal are synchronized to disk before migration continues. The automatic path accepts running or never-started containers with stock bridge networking, localhost-only unprivileged published ports, private local named volumes, supported resource limits, root users with Docker's default capability ceiling or stricter settings, numeric non-root image users that already drop every capability, and the stock runtime and namespace boundaries. It rejects already-exited containers whose historical exit state cannot be recreated without rerunning them, privileged containers, added capabilities, devices, host or shared mounts, named image users whose effective UID is ambiguous, numeric non-root image users whose capability ceiling cannot be reproduced exactly, custom networks, namespace sharing, custom runtimes, altered confinement, custom logging, reserved migration labels, and unknown nondefault host settings. -For each accepted container, the migrator stops the source cleanly, commits its writable layer, transfers that image through Docker's native save/load format, creates a stopped `runc` destination to pin every owned volume, and copies volume contents and metadata inside the RootlessKit user and mount namespace. It verifies environment, application config, runtime, limits, capabilities, mounts, ports, restart policy, logging, volume fingerprints, and lifecycle before writing a receipt bound to full source and destination snapshots. If one transfer fails, every later source that the batch already quiesced is restored in reverse order. +For each accepted container, the migrator stops the source cleanly, commits its writable layer, transfers that image through Docker's native save/load format, and creates an unpredictable inert guard that pins every owned volume while contents and metadata are copied inside the RootlessKit user and mount namespace. The application container does not exist during that long copy. After transfer, a stopped `runc` application container joins the guard on the verified volumes; the guard is removed only after Docker proves both references, and the application container must still be never-started before finalization. The migrator verifies environment, application config, runtime, limits, capabilities, mounts, ports, restart policy, logging, volume fingerprints, and lifecycle before writing a receipt bound to full source and destination snapshots. If one transfer fails, every later source that the batch already quiesced is restored in reverse order. Before the destination is first started, an error removes only the exact journal-owned destination container and restores the source. Journal-owned volumes remain available for ownership verification; a retry attaches each verified volume to the stopped destination before emptying and copying the current stopped source again, so a concurrent name replacement, partial transfer, or later source deletion cannot damage unrelated data or leave stale entries. Resume requires Docker to prove that the destination has never started. Once a destination start has been attempted, automatic retry and source restoration stop for manual recovery because either side may contain new writes. A durable completion receipt takes precedence over a leftover journal if power fails between those two writes. Successful sources remain stopped with their restart policy disabled; they are retained in the rootful engine as recovery copies. diff --git a/migrations/1789164756.sh b/migrations/1789164756.sh index e81b72b9d1ba..95e3948db0f6 100644 --- a/migrations/1789164756.sh +++ b/migrations/1789164756.sh @@ -72,7 +72,8 @@ fi # Migrate any legacy user-side definition, pin its data into the protected root # anchors, and rewrite the credential-bearing Compose file to root:root 0600. -# This performs no Docker lifecycle action. +# An existing managed VM is recreated from that hardened definition while its +# running or stopped lifecycle is preserved. /usr/bin/omarchy-windows-vm __migration-secure sudo /usr/bin/systemctl daemon-reload @@ -109,10 +110,24 @@ verify_rootful_listeners() { sudo /usr/bin/python3 "$listener_verifier" "$main_pid" } +verify_rootful_socket_unit() { + local socket_group socket_listen socket_mode socket_user + socket_user=$(sudo /usr/bin/systemctl show docker.socket --property=SocketUser --value) + socket_group=$(sudo /usr/bin/systemctl show docker.socket --property=SocketGroup --value) + socket_mode=$(sudo /usr/bin/systemctl show docker.socket --property=SocketMode --value) + socket_listen=$(sudo /usr/bin/systemctl show docker.socket --property=Listen --value) + if [[ $socket_user != "root" || $socket_group != "root" || $socket_mode != "0600" || + $socket_listen != "/run/docker.sock (Stream)" ]]; then + echo "The effective rootful Docker socket unit is not root-only. Remove custom overrides before migration." >&2 + return 1 + fi +} + # Load the packaged socket policy and prevent new unprivileged rootful clients # before taking the source inventory. Existing accepted connections are closed # by the daemon restart after every workload has been safely quiesced below. restrict_rootful_socket +verify_rootful_socket_unit sudo /usr/bin/docker --host "$source_host" info >/dev/null verify_rootful_listeners remove_legacy_docker_group @@ -192,6 +207,7 @@ fi sudo /usr/bin/systemctl restart docker.service sudo /usr/bin/systemctl start docker.socket restrict_rootful_socket +verify_rootful_socket_unit verify_rootful_listeners revoked_inventory=$(sudo /usr/bin/docker --host "$source_host" ps -a --no-trunc --format '{{.ID}} {{.Names}}' | sort) diff --git a/test/shell.d/rootless-docker-migration-test.sh b/test/shell.d/rootless-docker-migration-test.sh index 84cf189bb1ee..4e6f413b7a05 100755 --- a/test/shell.d/rootless-docker-migration-test.sh +++ b/test/shell.d/rootless-docker-migration-test.sh @@ -7,8 +7,10 @@ python3 - <<'PY' import copy import importlib.util import os +import re import sys import tempfile +from pathlib import Path sys.dont_write_bytecode = True @@ -202,6 +204,7 @@ windows = copy.deepcopy(container) windows["Name"] = "/omarchy-windows" windows["Id"] = "f" * 64 windows["Config"]["Image"] = "dockurr/windows" +windows["Config"]["Env"] = ["VERSION=11", "PROTECT=Y"] windows["Config"]["Labels"] = { "com.docker.compose.project": "windows", "com.docker.compose.service": "windows", @@ -233,12 +236,11 @@ windows["Mounts"] = [ windows["NetworkSettings"]["Networks"] = {"windows_default": {}} assert migration.validate_windows_exception(windows) == "omarchy-windows" legacy_windows = copy.deepcopy(windows) -account = migration.pwd.getpwuid(uid) -legacy_windows["Mounts"][0]["Source"] = f"{account.pw_dir}/.windows" -legacy_windows["Mounts"][1]["Source"] = f"{account.pw_dir}/Windows" -assert migration.validate_windows_exception(legacy_windows) == "omarchy-windows" +legacy_windows["Mounts"][0]["Source"] = f"{Path.home()}/.windows" +legacy_windows["Mounts"][1]["Source"] = f"{Path.home()}/Windows" for mutation in ("image", "labels", "devices", "extra-device", "device-rules", "security-opt", - "mounts", "mount-source", "restart", "network-mode", "extra-network", "autoremove"): + "mounts", "mount-source", "restart", "network-mode", "extra-network", "autoremove", + "missing-protect", "duplicate-protect"): changed = copy.deepcopy(windows) if mutation == "image": changed["Config"]["Image"] = "example/custom" @@ -262,6 +264,10 @@ for mutation in ("image", "labels", "devices", "extra-device", "device-rules", " changed["HostConfig"]["NetworkMode"] = "host" elif mutation == "extra-network": changed["NetworkSettings"]["Networks"]["unexpected"] = {} + elif mutation == "missing-protect": + changed["Config"]["Env"] = ["VERSION=11"] + elif mutation == "duplicate-protect": + changed["Config"]["Env"] += ["PROTECT=N"] else: changed["HostConfig"]["AutoRemove"] = True try: @@ -270,6 +276,12 @@ for mutation in ("image", "labels", "devices", "extra-device", "device-rules", " pass else: raise AssertionError(f"unmanaged Windows exception passed: {mutation}") +try: + migration.validate_windows_exception(legacy_windows) +except ValueError: + pass +else: + raise AssertionError("legacy home-mounted Windows runtime passed the protected exception") print("ok - only Omarchy's managed Windows runtime qualifies for the rootful exception") source_volume = {"Name": "project-data", "Driver": "local", "Options": None, @@ -368,6 +380,10 @@ stopped["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} target = copy.deepcopy(stopped) target["Id"] = "b" * 64 target["Config"]["Labels"][migration.LABEL] = stopped["Id"] +target["State"] = { + "Status": "created", "Running": False, "StartedAt": "0001-01-01T00:00:00Z", + "FinishedAt": "0001-01-01T00:00:00Z", "ExitCode": 0, +} with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory migration.inspect = lambda engine, kind, name: copy.deepcopy(stopped if engine == migration.SOURCE else target) @@ -415,7 +431,7 @@ with tempfile.TemporaryDirectory() as directory: overlap_source if engine == migration.SOURCE else overlap_target ) migration.record_completion(overlap_source, overlap_source["State"], True) - migration.exists = lambda kind, name: kind == "container" + migration.exists = lambda kind, name: kind == "container" and name == "project-worker" migration.migrate(overlap_source) assert not migration.intent_path(overlap_source["Id"]).exists() @@ -613,8 +629,11 @@ def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image migration.inspect = fake_inspect migration.run = fake_run - migration.exists = lambda kind, name: ((kind == "container" and current_target is not None) or - (preexisting_image and kind == "image")) + migration.exists = lambda kind, name: ( + (kind == "container" and current_target is not None and + name in (current_target.get("Id"), current_target.get("Name", "").lstrip("/"))) or + (preexisting_image and kind == "image") + ) migration.pipe = lambda producer, consumer: pipes.append((producer, consumer)) if after_start: migration.verify_runtime = lambda value, ownership=None: None @@ -676,9 +695,9 @@ print("ok - a preexisting target image digest is reused without claiming or dele calls, source, pipes, intent_retained = exercise_failed_transfer(False, replace_target=True) assert not any(call[:3] == (migration.TARGET, "rm", "--force") for call in calls) -assert source["State"]["Running"] +assert not source["State"]["Running"] assert intent_retained -print("ok - rollback never deletes a concurrently replaced destination container") +print("ok - a concurrently replaced destination is retained without restarting its rootful source") retry_original = copy.deepcopy(container) retry_original["Id"] = "9" * 64 @@ -824,6 +843,7 @@ source_volume = { } target_volume = None pinned_target = None +pinned_guard = None pin_events = [] @@ -836,13 +856,14 @@ def pin_inspect(engine, kind, name): if target_volume is None: raise migration.subprocess.CalledProcessError(1, ["docker", "inspect"]) return copy.deepcopy(target_volume) - if pinned_target is None: - raise migration.subprocess.CalledProcessError(1, ["docker", "inspect"]) - return copy.deepcopy(pinned_target) + for candidate in (pinned_target, pinned_guard): + if candidate is not None and name in (candidate["Id"], candidate["Name"].lstrip("/")): + return copy.deepcopy(candidate) + raise migration.subprocess.CalledProcessError(1, ["docker", "inspect"]) def pin_run(*args, **kwargs): - global target_volume, pinned_target + global target_volume, pinned_target, pinned_guard pin_events.append(args) if args[:2] == (migration.SOURCE, "update"): current_pinned_source["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} @@ -869,27 +890,43 @@ def pin_run(*args, **kwargs): if argument == "--label": key, value = args[index + 1].split("=", 1) labels[key] = value - pinned_target = { - "Id": "6" * 64, "Config": {"Labels": labels}, + created_name = args[args.index("--name") + 1] + created = { + "Id": ("8" if created_name.startswith("omarchy-volume-guard-") else "6") * 64, + "Name": f"/{created_name}", "Config": {"Labels": labels}, "State": {"Status": "created", "Running": False, "StartedAt": "0001-01-01T00:00:00Z", "FinishedAt": "0001-01-01T00:00:00Z"}, } + if created_name.startswith("omarchy-volume-guard-"): + pinned_guard = created + else: + pinned_target = created elif args[:3] == (migration.TARGET, "container", "ls"): - return pinned_target["Id"] if pinned_target is not None else "" + return "\n".join(candidate["Id"] for candidate in (pinned_guard, pinned_target) + if candidate is not None) + elif args[:3] == (migration.TARGET, "rm", "--force"): + if pinned_guard is not None and args[3] == pinned_guard["Id"]: + pinned_guard = None + elif pinned_target is not None and args[3] == pinned_target["Id"]: + pinned_target = None elif args[:2] == (migration.TARGET, "start"): pinned_target["State"]["Status"] = "running" pinned_target["State"]["Running"] = True +def pin_exists(kind, name): + if kind == "volume": + return target_volume is not None + return any(candidate is not None and name in (candidate["Id"], candidate["Name"].lstrip("/")) + for candidate in (pinned_guard, pinned_target)) + + with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory migration.inspect = pin_inspect migration.run = pin_run - migration.exists = lambda kind, name: ( - (kind == "container" and pinned_target is not None) or - (kind == "volume" and target_volume is not None) - ) + migration.exists = pin_exists migration.pipe = lambda producer, consumer: pin_events.append(("pipe",)) migration.verify_runtime = lambda value, ownership=None: None migration.verify_volume = lambda target, digest: None @@ -899,16 +936,27 @@ with tempfile.TemporaryDirectory() as directory: migration.record_completion = lambda source, state, running: None migration.migrate(pinned_source) -create_index = next(index for index, event in enumerate(pin_events) - if event[:2] == (migration.TARGET, "create")) +create_indexes = [index for index, event in enumerate(pin_events) + if event[:2] == (migration.TARGET, "create")] +assert len(create_indexes) == 2 +guard_index, create_index = create_indexes clear_index = pin_events.index(("clear", "project-data")) transfer_index = pin_events.index(("transfer", "project-data")) -assert create_index < clear_index < transfer_index +assert guard_index < clear_index < transfer_index < create_index +guard_call = pin_events[guard_index] create_call = pin_events[create_index] +assert "--network=none" in guard_call +assert "--read-only" in guard_call and "--cap-drop" in guard_call +guard_entrypoint = guard_call[guard_call.index("--entrypoint") + 1] +assert re.fullmatch(r"/\.omarchy-volume-guard-[a-f0-9]{64}", guard_entrypoint) assert create_call[create_call.index("--runtime") + 1] == "runc" assert any(event[:3] == (migration.TARGET, "container", "ls") - for event in pin_events[create_index + 1:clear_index]) -print("ok - the stopped destination pins each owned volume before clearing or transfer") + for event in pin_events[guard_index + 1:clear_index]) +guard_remove_index = next(index for index, event in enumerate(pin_events) + if event[:3] == (migration.TARGET, "rm", "--force") and event[3] == "8" * 64) +start_index = pin_events.index((migration.TARGET, "start", "pinned-volume")) +assert create_index < guard_remove_index < start_index +print("ok - an inert random guard pins volumes while the application container does not yet exist") batch = [] for index in (1, 2): diff --git a/test/shell.d/rootless-docker-posture-test.sh b/test/shell.d/rootless-docker-posture-test.sh index 95e7aad00d7f..156e38e48427 100755 --- a/test/shell.d/rootless-docker-posture-test.sh +++ b/test/shell.d/rootless-docker-posture-test.sh @@ -72,6 +72,12 @@ transfer_line=$(grep -n '^ /usr/bin/python3 "$migrator" "${container_names\[@\] fail "rootful socket policy is not rechecked after daemon restart" (( $(grep -c '^verify_rootful_listeners$' "$migration") == 2 )) || fail "rootful Docker listeners are not rechecked after daemon restart" +(( $(grep -c '^verify_rootful_socket_unit$' "$migration") == 2 )) || + fail "the effective rootful socket unit is not rechecked after daemon restart" +for property in SocketUser SocketGroup SocketMode Listen; do + grep -q -- "--property=$property" "$migration" || + fail "migration does not verify effective docker.socket $property" +done grep -q -- '--restore-windows "$windows_id"' "$migration" || fail "a running Windows VM is not restored after rootful connection revocation" pass "migration serializes ownership, secures Windows, and revokes existing rootful connections" diff --git a/test/shell.d/windows-vm-auth-test.sh b/test/shell.d/windows-vm-auth-test.sh index 6f58c9e2ba1d..be2ae83e1827 100644 --- a/test/shell.d/windows-vm-auth-test.sh +++ b/test/shell.d/windows-vm-auth-test.sh @@ -58,6 +58,9 @@ MODE_LOG="$test_dir/mode" OMARCHY_WINDOWS_DIR="$test_dir" ROOT="$ROOT" bash -c ' [[ $(<"$MODE_LOG") == "secure" ]] valid_priv_action secure rm "$OMARCHY_WINDOWS_DIR/docker-compose.yml" + : >"$MODE_LOG" + secure_windows_migration + [[ $(<"$MODE_LOG") == "secure" ]] mkdir -p "$HOME/.config/windows" touch "$HOME/.config/windows/docker-compose.yml" migrate_legacy_compose() { return 23; } diff --git a/test/shell.d/windows-vm-compose-test.sh b/test/shell.d/windows-vm-compose-test.sh index 189536f4f2be..5db632ab4310 100644 --- a/test/shell.d/windows-vm-compose-test.sh +++ b/test/shell.d/windows-vm-compose-test.sh @@ -85,7 +85,7 @@ grep -q 'PASSWORD: ".*\$\$.*"' "$COMPOSE" || fail "dollar not escaped" [[ $(unescape "$(read_compose_value PASSWORD "$COMPOSE")") == "$tricky" ]] || fail "password did not round-trip" pass "password with quote, backslash, and dollar round-trips" -for action in write_compose up up_wait down status remove; do +for action in write_compose up up_wait down status remove secure; do valid_priv_action "$action" || fail "known action rejected: $action" done for action in '/../evil/x' bogus 'up;rm' '' '__priv_up'; do @@ -162,6 +162,33 @@ assert_mounts_safe 2>/dev/null && fail "writable compose accepted" chmod 0640 "$COMPOSE" pass "bring-up rejects tampered, duplicate, unprotected, and writable compose inputs" +# The one-time security migration replaces the live container from the trusted +# hardened definition and preserves whether it was running or stopped. +reset_case +prepare_user_mount_sources +write 8G 4 64G secure-user secure-pass UTC +secure_log="$TMPDIR/secure-compose" +windows_status=running +docker() { + if [[ $1 == inspect && ${2:-} == --format=* ]]; then + printf '%s' "$windows_status" + return 0 + fi + [[ $1 == inspect ]] +} +dc() { printf '%s\n' "$*" >>"$secure_log"; } +__priv_secure +[[ $(tail -n1 "$secure_log") == "up -d --force-recreate" ]] || fail "running VM was not recreated running" +windows_status=exited +__priv_secure +[[ $(tail -n1 "$secure_log") == "up --no-start --force-recreate" ]] || fail "stopped VM was not recreated stopped" +rm -f "$COMPOSE" +__priv_secure 2>/dev/null && fail "live Windows container without trusted Compose passed migration" +docker() { [[ $1 == inspect ]] && return 1; } +__priv_secure || fail "an absent Windows VM required a Compose definition" +unset -f docker dc +pass "security migration recreates hardened Windows while preserving its lifecycle" + # Both sources are pinned before a bind; bad symlinks stay untouched. reset_case mkdir -p "$HOME/.windows" From 5b596e8e6168eb5030ae4cc2659c40eb7f35847e Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Sat, 12 Sep 2026 06:14:09 -0600 Subject: [PATCH 08/31] Make rootless Docker recovery durable --- bin/omarchy-windows-vm | 83 +++++++++++++++++-- default/docker/rootless/migrate.py | 24 +++++- docs/rootless-docker.md | 4 +- install/config/enable-services.sh | 4 +- migrations/1789164756.sh | 41 ++++++++- .../shell.d/rootless-docker-migration-test.sh | 57 ++++++++++++- test/shell.d/rootless-docker-posture-test.sh | 15 +++- test/shell.d/windows-vm-compose-test.sh | 25 +++++- 8 files changed, 229 insertions(+), 24 deletions(-) diff --git a/bin/omarchy-windows-vm b/bin/omarchy-windows-vm index bf494f6ca4a3..4fe5a9128c32 100755 --- a/bin/omarchy-windows-vm +++ b/bin/omarchy-windows-vm @@ -26,6 +26,7 @@ CREDENTIALS_FILE="$HOME/.config/windows/credentials" IMAGE="dockurr/windows" CONTAINER="omarchy-windows" VM_LOCK_DIR=/run/lock/omarchy-windows-vm +SECURITY_MIGRATION_STATE="$RUNTIME_DIR/.security-migration-state" # Removal is the only path that recursively proves there are no bind aliases. # Bound every metadata walk so a large or hostile caller tree fails closed # instead of hanging a privileged action indefinitely. @@ -681,6 +682,44 @@ finally: PY } +write_security_migration_state() ( + local lifecycle="$1" old_umask tmp="" + [[ $lifecycle == "running" || $lifecycle == "stopped" ]] || exit 1 + old_umask=$(umask) + umask 077 + tmp=$(mktemp "$RUNTIME_DIR/.security-migration-state.XXXXXX") || exit 1 + trap 'rm -f -- "$tmp"; umask "$old_umask"' EXIT + printf '%s\n' "$lifecycle" >"$tmp" || exit 1 + chmod 0600 "$tmp" || exit 1 + if ((EUID == 0)); then + chown root:root "$tmp" || exit 1 + fi + fsync_regular_file "$tmp" || exit 1 + mv -fT -- "$tmp" "$SECURITY_MIGRATION_STATE" || exit 1 + tmp="" + fsync_directory "$RUNTIME_DIR" || exit 1 + trap - EXIT + umask "$old_umask" +) + +read_security_migration_state() { + local expected lifecycle metadata + [[ -f $SECURITY_MIGRATION_STATE && ! -L $SECURITY_MIGRATION_STATE ]] || return 1 + expected=$(boundary_owner) + metadata=$(stat -Lc '%u:%a' "$SECURITY_MIGRATION_STATE") || return 1 + [[ $metadata == "$expected:600" ]] || return 1 + IFS= read -r lifecycle <"$SECURITY_MIGRATION_STATE" || return 1 + [[ $lifecycle == "running" || $lifecycle == "stopped" ]] || return 1 + [[ $(wc -l <"$SECURITY_MIGRATION_STATE") == 1 ]] || return 1 + [[ $(<"$SECURITY_MIGRATION_STATE") == "$lifecycle" ]] || return 1 + printf '%s' "$lifecycle" +} + +clear_security_migration_state() { + rm -f -- "$SECURITY_MIGRATION_STATE" || return 1 + fsync_directory "$RUNTIME_DIR" +} + write_compose_atomically() ( local ram="$1" cores="$2" disk="$3" username="$4" password="$5" tz="$6" local tmp="" rc esc_password @@ -929,24 +968,49 @@ assert_mounts_safe() { __priv_up() { assert_mounts_safe && dc up -d; } __priv_secure() { - local status + local desired status if [[ ! -f $COMPOSE_FILE ]]; then if docker inspect "$CONTAINER" >/dev/null 2>&1; then echo "omarchy-windows-vm: an existing Windows container has no trusted Compose definition" >&2 return 1 fi + if [[ -e $SECURITY_MIGRATION_STATE || -L $SECURITY_MIGRATION_STATE ]]; then + read_security_migration_state >/dev/null || { + echo "omarchy-windows-vm: refusing an untrusted Windows security-migration state" >&2 + return 1 + } + clear_security_migration_state || return 1 + fi return 0 fi assert_mounts_safe || return 1 - status=$(docker inspect --format='{{.State.Status}}' "$CONTAINER" 2>/dev/null) || return 0 - if [[ $status == "running" ]]; then - dc up -d --force-recreate - elif [[ $status == "created" || $status == "exited" ]]; then - dc up --no-start --force-recreate + if [[ -e $SECURITY_MIGRATION_STATE || -L $SECURITY_MIGRATION_STATE ]]; then + desired=$(read_security_migration_state) || { + echo "omarchy-windows-vm: refusing an untrusted Windows security-migration state" >&2 + return 1 + } else - echo "omarchy-windows-vm: transitional Windows lifecycle needs manual review" >&2 - return 1 + status=$(docker inspect --format='{{.State.Status}}' "$CONTAINER" 2>/dev/null) || return 0 + if [[ $status == "running" ]]; then + desired=running + elif [[ $status == "created" || $status == "exited" ]]; then + desired=stopped + else + echo "omarchy-windows-vm: transitional Windows lifecycle needs manual review" >&2 + return 1 + fi + write_security_migration_state "$desired" || return 1 + fi + if [[ $desired == "running" ]]; then + dc up -d || return 1 + status=$(docker inspect --format='{{.State.Status}}' "$CONTAINER" 2>/dev/null) || return 1 + [[ $status == "running" ]] || return 1 + else + dc up --no-start || return 1 + status=$(docker inspect --format='{{.State.Status}}' "$CONTAINER" 2>/dev/null) || return 1 + [[ $status == "created" || $status == "exited" ]] || return 1 fi + clear_security_migration_state } __priv_down() { dc down; } @@ -1025,7 +1089,8 @@ __priv_remove() { umount -- "$EXPECTED_SHARED" || return 1 umount -- "$EXPECTED_STORAGE" || return 1 docker rmi "$IMAGE" 2>/dev/null || true - rm -f "$COMPOSE_FILE" + rm -f "$COMPOSE_FILE" "$SECURITY_MIGRATION_STATE" + fsync_directory "$RUNTIME_DIR" || return 1 rmdir -- "$EXPECTED_STORAGE" "$EXPECTED_SHARED" "$CALLER_DATA_ROOT" 2>/dev/null || true } diff --git a/default/docker/rootless/migrate.py b/default/docker/rootless/migrate.py index ae0b7dd1606b..bb1fcda06901 100644 --- a/default/docker/rootless/migrate.py +++ b/default/docker/rootless/migrate.py @@ -464,6 +464,12 @@ def persist_migration_intent(container, intent): return intent +def record_destination_may_have_run(container, intent): + saved = deepcopy(intent) + saved["start_attempted"] = True + return persist_migration_intent(container, saved) + + def target_owned(container, target, intent): labels = target["Config"].get("Labels") or {} return (labels.get(LABEL) == container["Id"] and @@ -888,6 +894,11 @@ def restore_source(identity, validator=validate): def quiesce(container, validator=validate): container = refresh_source(container, validator) + name = container["Name"].lstrip("/") + if exists("container", name) and completed(container, inspect(TARGET, "container", name)): + clear_migration_intent(container["Id"]) + print(f"{name}: already migrated") + return intent = migration_intent(container) planned = planned_source(container, intent) if intent is None: @@ -999,7 +1010,10 @@ def migrate(container): return if intent is not None and intent["start_attempted"]: raise ValueError(f"{name}: destination start was attempted; inspect both engines") - if intent is None or not target_owned(container, target, intent): + if intent is None: + raise ValueError(f"{name}: an existing rootless Docker container needs review; no owned transfer matches it") + if not target_owned(container, target, intent): + intent = record_destination_may_have_run(container, intent) raise ValueError(f"{name}: an existing rootless Docker container needs review; no owned transfer matches it") if intent.get("destination") is not None: if exists("container", volume_guard_name(intent)): @@ -1007,13 +1021,19 @@ def migrate(container): resume_verified_migration(container, target, intent) return if not target_never_started(target): + intent = record_destination_may_have_run(container, intent) raise ValueError(f"{name}: an incomplete rootless destination may have run; inspect both engines") owned_id = target["Id"] run(TARGET, "rm", "--force", owned_id) if exists("container", name): + intent = record_destination_may_have_run(container, intent) raise ValueError(f"{name}: rootless destination name was replaced during recovery") if intent is not None: - remove_volume_guard(container, intent) + try: + remove_volume_guard(container, intent) + except BaseException: + intent = record_destination_may_have_run(container, intent) + raise if intent is not None and intent["start_attempted"]: raise ValueError(f"{name}: destination start was attempted; inspect both engines") if completion_path(identity).exists(): diff --git a/docs/rootless-docker.md b/docs/rootless-docker.md index 92cd61d00e73..075b334bb62d 100644 --- a/docs/rootless-docker.md +++ b/docs/rootless-docker.md @@ -10,13 +10,13 @@ The system daemon remains socket-activated for `omarchy-windows-vm`. Its vendor ## Fresh installs and additional users -The root setup allocates each account a nonoverlapping subordinate UID and GID range of at least 65,536 IDs, enables the rootless service globally, and writes `/var/lib/omarchy/rootless-docker/enabled`. User finalization then creates the private marker and daemon config before first login starts the service. +The root setup allocates each account a nonoverlapping subordinate UID and GID range of at least 65,536 IDs and writes `/var/lib/omarchy/rootless-docker/enabled`. User finalization creates the private marker and daemon config, then first-run setup enables the rootless service only for that initialized account. Existing accounts follow the same order during migration; no global user-unit symlink can start Docker for another account before its subordinate IDs and daemon config exist. The migration's machine-wide enabled marker is written only after the shared rootful inventory has migrated and `/run/docker.sock` has been restricted. When another account later runs the per-user migration, it initializes that account's rootless daemon and returns before inspecting the retained rootful recovery store. ## Existing-install migration -`migrations/1789164756.sh` installs the rootless runtime, allocates subordinate IDs, starts and proves the rootless daemon, secures any current account's Windows definition, restricts the old API socket to root, and preflights every rootful container. An existing Windows container is recreated from the hardened Compose definition while preserving whether it was running or stopped; the new runtime must use web protection and the current account's protected mount anchors. Only after those checks does the migration claim the machine-wide source inventory for that account. A container named `omarchy-windows` is exempt only when its image, Compose identity, devices, capabilities, ports, environment, and UID-bound mounts match Omarchy's managed VM. A blocker in any source prevents the batch from stopping its first container or assigning the migration owner. Compose, credentials, and legacy-definition removal are synchronized to disk before migration continues. +`migrations/1789164756.sh` installs the rootless runtime, allocates subordinate IDs, restarts and proves the rootless daemon with that account's configuration, secures any current account's Windows definition, restricts the old API socket to root, and preflights every rootful container. An existing Windows container is reconciled from the hardened Compose definition while a root-only, synchronized lifecycle record preserves whether it was running or stopped across interruption; the new runtime must use web protection and the current account's protected mount anchors. Only after those checks does the migration durably claim the machine-wide source inventory for that account. A container named `omarchy-windows` is exempt only when its image, Compose identity, devices, capabilities, ports, environment, and UID-bound mounts match Omarchy's managed VM. A blocker in any source prevents the batch from stopping its first container or assigning the migration owner. Compose, credentials, legacy-definition removal, owner selection, and machine completion are synchronized to disk before migration continues. The automatic path accepts running or never-started containers with stock bridge networking, localhost-only unprivileged published ports, private local named volumes, supported resource limits, root users with Docker's default capability ceiling or stricter settings, numeric non-root image users that already drop every capability, and the stock runtime and namespace boundaries. It rejects already-exited containers whose historical exit state cannot be recreated without rerunning them, privileged containers, added capabilities, devices, host or shared mounts, named image users whose effective UID is ambiguous, numeric non-root image users whose capability ceiling cannot be reproduced exactly, custom networks, namespace sharing, custom runtimes, altered confinement, custom logging, reserved migration labels, and unknown nondefault host settings. diff --git a/install/config/enable-services.sh b/install/config/enable-services.sh index d2bc653efd47..129d80dd0767 100644 --- a/install/config/enable-services.sh +++ b/install/config/enable-services.sh @@ -5,8 +5,8 @@ systemctl enable avahi-daemon.service systemctl enable linux-modules-cleanup.service # The root-owned socket is reserved for authenticated Windows VM operations. systemctl enable docker.socket -# Development containers use each desktop user's rootless daemon. -systemctl --global enable docker.service +# Development Docker is enabled per user only after subordinate IDs and that +# account's daemon configuration have been installed. systemctl enable systemd-resolved.service systemctl enable NetworkManager.service # Don't let network-online.target hold up graphical.target waiting for diff --git a/migrations/1789164756.sh b/migrations/1789164756.sh index 95e3948db0f6..eb68c512fa8f 100644 --- a/migrations/1789164756.sh +++ b/migrations/1789164756.sh @@ -47,7 +47,13 @@ if [[ ! -e $HOME/.config/docker/daemon.json ]]; then fi systemctl --user daemon-reload -systemctl --user enable --now docker.service +# A global user-unit enablement would start this daemon for secondary accounts +# before their subordinate IDs and per-user daemon config exist. Enable only +# this initialized account, clear any early start-limit failure, and restart so +# an already-running daemon consumes the just-installed configuration. +systemctl --user reset-failed docker.service +systemctl --user enable docker.service +systemctl --user restart docker.service target_host="unix://$XDG_RUNTIME_DIR/docker.sock" if ! /usr/bin/docker --host "$target_host" info >/dev/null; then echo "Rootless Docker did not start. Rootful Docker has not been changed." >&2 @@ -59,7 +65,6 @@ fi # inspect or claim the retained recovery copies owned by the first account. machine_state=/var/lib/omarchy/rootless-docker if sudo /usr/bin/test -f "$machine_state/enabled"; then - sudo /usr/bin/systemctl --global enable docker.service remove_legacy_docker_group touch "$rootless_state/enabled" chmod 0600 "$rootless_state/enabled" @@ -171,7 +176,17 @@ import sys uid, name = int(sys.argv[1]), sys.argv[2] root = Path("/var/lib/omarchy/rootless-docker") +root_was_missing = not root.exists() root.mkdir(mode=0o755, parents=True, exist_ok=True) +metadata = root.lstat() +if not stat.S_ISDIR(metadata.st_mode) or metadata.st_uid != 0 or metadata.st_mode & 0o022: + raise SystemExit("unsafe rootless Docker machine-state directory") +if root_was_missing: + parent_fd = os.open(root.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(parent_fd) + finally: + os.close(parent_fd) lock_fd = os.open("/run/lock/omarchy-rootless-docker-owner.lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) with os.fdopen(lock_fd, "w") as lock: @@ -192,6 +207,11 @@ with os.fdopen(lock_fd, "w") as lock: output.flush() os.fsync(output.fileno()) temporary.replace(owner) + directory_fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) PY if [[ -n $windows_id ]]; then @@ -233,10 +253,25 @@ if [[ $latest_inventory != "$docker_inventory" ]]; then exit 1 fi -sudo /usr/bin/systemctl --global enable docker.service sudo /usr/bin/touch /var/lib/omarchy/rootless-docker/enabled sudo /usr/bin/chown root:root /var/lib/omarchy/rootless-docker/enabled sudo /usr/bin/chmod 0644 /var/lib/omarchy/rootless-docker/enabled +sudo /usr/bin/python3 - <<'PY' +import os + + +path = "/var/lib/omarchy/rootless-docker/enabled" +descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) +try: + os.fsync(descriptor) +finally: + os.close(descriptor) +directory = os.open(os.path.dirname(path), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) +try: + os.fsync(directory) +finally: + os.close(directory) +PY touch "$rootless_state/enabled" chmod 0600 "$rootless_state/enabled" diff --git a/test/shell.d/rootless-docker-migration-test.sh b/test/shell.d/rootless-docker-migration-test.sh index 4e6f413b7a05..31fda4af7528 100755 --- a/test/shell.d/rootless-docker-migration-test.sh +++ b/test/shell.d/rootless-docker-migration-test.sh @@ -440,7 +440,10 @@ with tempfile.TemporaryDirectory() as directory: sys.argv = ["migrate.py", "--check", overlap_source["Name"].lstrip("/")] migration.main() assert migration.intent_path(overlap_source["Id"]).exists() -print("ok - a valid completion receipt wins over its stale post-start journal") + sys.argv = ["migrate.py", "--quiesce-all", "-", overlap_source["Name"].lstrip("/")] + migration.main() + assert not migration.intent_path(overlap_source["Id"]).exists() +print("ok - a valid completion receipt clears its stale journal in check, transfer, and quiesce phases") restarted = copy.deepcopy(stopped) restarted["State"]["Running"] = True @@ -833,6 +836,58 @@ with tempfile.TemporaryDirectory() as directory: assert not migration.intent_path(resume_source["Id"]).exists() print("ok - a verified destination resumes safely across interruption before its first start") +for unsafe_kind in ("destination", "guard"): + unsafe_original = copy.deepcopy(retry_original) + unsafe_original["Id"] = ("a" if unsafe_kind == "destination" else "b") * 64 + unsafe_original["Name"] = f"/{unsafe_kind}-race" + unsafe_source = copy.deepcopy(unsafe_original) + unsafe_source["State"] = { + "Status": "exited", "Running": False, "StartedAt": unsafe_original["State"]["StartedAt"], + "FinishedAt": "source-stop", "ExitCode": 0, + } + unsafe_source["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} + with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + unsafe_intent = migration.record_migration_intent(unsafe_original) + unsafe_intent = migration.record_migration_intent( + unsafe_source, unsafe_source["State"], unsafe_intent, restart_disabled=True, + ) + unsafe_name = (unsafe_source["Name"].lstrip("/") if unsafe_kind == "destination" + else migration.volume_guard_name(unsafe_intent)) + unsafe_target = { + "Id": "c" * 64, "Name": f"/{unsafe_name}", + "Config": {"Labels": { + migration.LABEL: unsafe_source["Id"], + migration.OWNERSHIP_LABEL: unsafe_intent["target_ownership"], + }}, + "State": {"Status": "exited", "Running": False, "StartedAt": "outside-start", + "FinishedAt": "outside-stop", "ExitCode": 0}, + } + + def unsafe_inspect(engine, kind, name): + if engine == migration.SOURCE: + return copy.deepcopy(unsafe_source) + if name in (unsafe_target["Id"], unsafe_name): + return copy.deepcopy(unsafe_target) + raise migration.subprocess.CalledProcessError(1, ["docker", "inspect"]) + + migration.inspect = unsafe_inspect + migration.exists = lambda kind, name: kind == "container" and name == unsafe_name + try: + migration.migrate(unsafe_source) + except ValueError: + pass + else: + raise AssertionError(f"a raced {unsafe_kind} allowed automatic migration") + assert migration.migration_intent(unsafe_source)["start_attempted"] is True + try: + migration.restore_source(unsafe_source["Id"]) + except RuntimeError: + pass + else: + raise AssertionError(f"a raced {unsafe_kind} allowed rootful source restart") +print("ok - a destination or guard run after preflight durably blocks rootful source restart") + pinned_source = copy.deepcopy(container) pinned_source["Name"] = "/pinned-volume" pinned_source["Id"] = "5" * 64 diff --git a/test/shell.d/rootless-docker-posture-test.sh b/test/shell.d/rootless-docker-posture-test.sh index 156e38e48427..d241171392db 100755 --- a/test/shell.d/rootless-docker-posture-test.sh +++ b/test/shell.d/rootless-docker-posture-test.sh @@ -8,8 +8,8 @@ for package in docker docker-buildx docker-compose docker-rootless-extras rootle done pass "the base install keeps Docker tooling and adds the rootless runtime" -grep -q 'systemctl --global enable docker.service' "$ROOT/install/config/enable-services.sh" || - fail "fresh installs globally enable the rootless Docker user service" +! rg -q 'systemctl --global enable docker.service' "$ROOT/install" "$ROOT/migrations/1789164756.sh" || + fail "rootless Docker starts globally before each account is initialized" grep -q 'docker.service' "$ROOT/install/user/first-run/enable-user-units.sh" || fail "first login starts the rootless Docker user service" grep -q 'rootless_docker_ensure_subids' "$ROOT/install/config/docker.sh" || @@ -33,6 +33,13 @@ rm "$home/.local/state/omarchy/rootless-docker/enabled" pass "the Docker endpoint activates only after rootless setup completes" migration="$ROOT/migrations/1789164756.sh" +reset_line=$(grep -n 'systemctl --user reset-failed docker.service' "$migration" | cut -d: -f1) +user_enable_line=$(grep -n 'systemctl --user enable docker.service' "$migration" | cut -d: -f1) +user_restart_line=$(grep -n 'systemctl --user restart docker.service' "$migration" | cut -d: -f1) +daemon_config_line=$(grep -n 'install -m 0644.*config/docker/daemon.json' "$migration" | cut -d: -f1) +[[ -n $reset_line && -n $user_enable_line && -n $user_restart_line && -n $daemon_config_line ]] && + (( daemon_config_line < reset_line && reset_line < user_enable_line && user_enable_line < user_restart_line )) || + fail "migration does not recover and restart only the initialized user's daemon after writing config" grep -q 'migration_user=$(id -un)' "$migration" || fail "migration trusts the USER environment instead of the current account" lock_line=$(grep -n '/usr/bin/flock -n' "$migration" | cut -d: -f1) package_line=$(grep -n '^omarchy-pkg-add docker-rootless-extras' "$migration" | cut -d: -f1) @@ -62,6 +69,10 @@ windows_check_line=$(grep -n -- '--check-windows "$windows_id"' "$migration" | h owner_claim_line=$(grep -n 'owner = root / "migration-owner"' "$migration" | cut -d: -f1) [[ -n $windows_check_line && -n $owner_claim_line ]] && (( windows_check_line < owner_claim_line )) || fail "the machine migration owner is claimed before proving ownership of an existing Windows VM" +owner_replace_line=$(grep -n 'temporary.replace(owner)' "$migration" | cut -d: -f1) +owner_sync_line=$(grep -n 'os.fsync(directory_fd)' "$migration" | head -n1 | cut -d: -f1) +[[ -n $owner_replace_line && -n $owner_sync_line ]] && (( owner_replace_line < owner_sync_line )) || + fail "the machine migration owner rename is not directory-synced" quiesce_line=$(grep -n -- '--quiesce-all "$windows_arg"' "$migration" | cut -d: -f1) restart_line=$(grep -n 'systemctl restart docker.service' "$migration" | cut -d: -f1) transfer_line=$(grep -n '^ /usr/bin/python3 "$migrator" "${container_names\[@\]}"' "$migration" | cut -d: -f1) diff --git a/test/shell.d/windows-vm-compose-test.sh b/test/shell.d/windows-vm-compose-test.sh index 5db632ab4310..27821a12d5df 100644 --- a/test/shell.d/windows-vm-compose-test.sh +++ b/test/shell.d/windows-vm-compose-test.sh @@ -178,16 +178,35 @@ docker() { } dc() { printf '%s\n' "$*" >>"$secure_log"; } __priv_secure -[[ $(tail -n1 "$secure_log") == "up -d --force-recreate" ]] || fail "running VM was not recreated running" +[[ $(tail -n1 "$secure_log") == "up -d" ]] || fail "running VM was not reconciled running" windows_status=exited __priv_secure -[[ $(tail -n1 "$secure_log") == "up --no-start --force-recreate" ]] || fail "stopped VM was not recreated stopped" +[[ $(tail -n1 "$secure_log") == "up --no-start" ]] || fail "stopped VM was not reconciled stopped" + +# A failed recreation retains the original lifecycle before Docker mutation. A +# retry uses that durable state instead of mistaking the partial replacement's +# created status for the user's original stopped intent. +windows_status=running +fail_secure_once=1 +dc() { + printf '%s\n' "$*" >>"$secure_log" + if ((fail_secure_once)); then + fail_secure_once=0 + windows_status=created + return 1 + fi + [[ $* == "up -d" ]] && windows_status=running +} +__priv_secure 2>/dev/null && fail "interrupted Windows reconciliation succeeded" +[[ $(<"$SECURITY_MIGRATION_STATE") == running ]] || fail "running lifecycle was not durable before recreation" +__priv_secure +[[ $windows_status == running && ! -e $SECURITY_MIGRATION_STATE ]] || fail "retry did not restore and clear running lifecycle" rm -f "$COMPOSE" __priv_secure 2>/dev/null && fail "live Windows container without trusted Compose passed migration" docker() { [[ $1 == inspect ]] && return 1; } __priv_secure || fail "an absent Windows VM required a Compose definition" unset -f docker dc -pass "security migration recreates hardened Windows while preserving its lifecycle" +pass "security migration reconciles hardened Windows while durably preserving its lifecycle" # Both sources are pinned before a bind; bad symlinks stay untouched. reset_case From e1fccc0dc3372cf152d0d83bc868815094c45088 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Sat, 12 Sep 2026 07:21:59 -0600 Subject: [PATCH 09/31] Harden rootless Docker volume cutover --- default/docker/rootless/migrate.py | 214 +++++++++++++++++- default/docker/rootless/volume-manifest.py | 20 +- docs/rootless-docker.md | 4 +- .../shell.d/rootless-docker-migration-test.sh | 173 +++++++++++++- 4 files changed, 401 insertions(+), 10 deletions(-) diff --git a/default/docker/rootless/migrate.py b/default/docker/rootless/migrate.py index bb1fcda06901..80b5ca19fd93 100644 --- a/default/docker/rootless/migrate.py +++ b/default/docker/rootless/migrate.py @@ -9,6 +9,7 @@ import subprocess import sys from copy import deepcopy +from datetime import datetime, timezone from decimal import Decimal from pathlib import Path @@ -16,6 +17,7 @@ LABEL = "io.omarchy.rootless-docker.source-id" OWNERSHIP_LABEL = "io.omarchy.rootless-docker.ownership" VOLUME_LABEL = "io.omarchy.rootless-docker.source-volume" +VOLUME_EVENT_LABEL = "io.omarchy.rootless-docker.event-marker" SOURCE = "source" TARGET = "target" TRUSTED_MANIFEST = "/usr/share/omarchy/default/docker/rootless/volume-manifest.py" @@ -36,6 +38,10 @@ "CpuQuota": "--cpu-quota", "CpuPeriod": "--cpu-period", "CpusetCpus": "--cpuset-cpus", "CpusetMems": "--cpuset-mems", } +DEFAULT_ZERO_HOST_CONFIG = { + "BlkioWeight", "CpuCount", "CpuPercent", "CpuRealtimePeriod", "CpuRealtimeRuntime", + "IOMaximumBandwidth", "IOMaximumIOps", "OomScoreAdj", +} def daemon_security(engine): @@ -129,7 +135,13 @@ def validate_security(container): "SecurityOpt", "CapDrop", "LogConfig", "NanoCpus", "Mounts", *RESOURCE_FLAGS, } for key, value in host.items(): - if key in handled or value in (None, False, "", [], {}): + # bool is an int subclass, so membership in a tuple containing False + # also accepts integer zero. Allow only the stock zero-valued fields + # Docker currently emits; an unknown zero can be meaningful (for + # example MemorySwappiness=0) and must fail closed. + if (key in handled or value is None or value is False or + value == "" or value == [] or value == {} or + (key in DEFAULT_ZERO_HOST_CONFIG and type(value) is int and value == 0)): continue if key == "ConsoleSize" and value == [0, 0]: continue @@ -337,8 +349,26 @@ def intent_path(identity): return receipt.with_name(f"{receipt.name}.in-progress") +def ensure_state_directory(path): + missing = [] + current = path + while not current.exists(): + missing.append(current) + current = current.parent + path.mkdir(parents=True, exist_ok=True, mode=0o700) + # fsync every directory that received a new child entry. This includes the + # first pre-existing ancestor, making a newly created state hierarchy + # durable before its journal can authorize source mutation. + for created in missing: + directory = os.open(created.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(directory) + finally: + os.close(directory) + + def write_private_json(path, payload): - path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + ensure_state_directory(path.parent) temporary = path.with_suffix(f"{path.suffix}.tmp-{os.getpid()}") try: descriptor = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) @@ -372,6 +402,8 @@ def record_migration_intent(container, stopped_state=None, saved=None, restart_d "restore_started": False, "start_attempted": False, "target_ownership": secrets.token_hex(32), + "source_volumes": None, + "volume_event": None, "volumes": {}, } if not state["Running"]: @@ -395,6 +427,8 @@ def migration_intent(container): try: saved = json.loads(path.read_text()) restart_policy = saved["source_restart_policy"] + source_volumes = saved.get("source_volumes") + volume_event = saved.get("volume_event") if (saved["source"] != container["Id"] or not isinstance(saved["target_running"], bool) or not isinstance(saved["restart_disabled"], bool) or @@ -402,10 +436,22 @@ def migration_intent(container): not isinstance(saved["restore_started"], bool) or not isinstance(saved["start_attempted"], bool) or not re.fullmatch(r"[a-f0-9]{64}", saved["target_ownership"]) or + (source_volumes is not None and + (not isinstance(source_volumes, dict) or + any(not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]*", name) or + not re.fullmatch(r"[a-f0-9]{64}", digest) + for name, digest in source_volumes.items()))) or + (volume_event is not None and + (not isinstance(volume_event, dict) or + set(volume_event) != {"name", "since"} or + volume_event.get("name") != f'omarchy-volume-event-marker-{saved["target_ownership"]}' or + not isinstance(volume_event.get("since"), str) or not volume_event["since"])) or not isinstance(saved["volumes"], dict) or not isinstance(restart_policy, dict) or not isinstance(saved["started_at"], str)): raise ValueError + saved.setdefault("source_volumes", None) + saved.setdefault("volume_event", None) exact_snapshot = saved["source_snapshot"] == snapshot_digest(container) disabled_snapshot = ( saved["restart_disabled"] is True and @@ -707,6 +753,11 @@ def clear_volume(target): run("target-namespace", "/usr/bin/python3", TRUSTED_MANIFEST, "--clear", destination) +def sync_volume(target): + destination = inspect(TARGET, "volume", target)["Mountpoint"] + run("target-namespace", "/usr/bin/python3", TRUSTED_MANIFEST, "--sync", destination) + + def volume_users(target): output = run(TARGET, "container", "ls", "--all", "--no-trunc", "--filter", f"volume={target}", "--format", "{{.ID}}", capture=True) @@ -716,11 +767,106 @@ def volume_users(target): return users +def volume_event_marker_name(intent): + ownership = intent.get("target_ownership") + if not re.fullmatch(r"[a-f0-9]{64}", ownership or ""): + raise ValueError("Interrupted rootless Docker ownership is invalid") + return f"omarchy-volume-event-marker-{ownership}" + + +def volume_event_marker_owned(container, marker, intent): + expected_labels = { + LABEL: container["Id"], + OWNERSHIP_LABEL: intent["target_ownership"], + VOLUME_EVENT_LABEL: "1", + } + return (marker.get("Name") == volume_event_marker_name(intent) and + marker.get("Driver") == "local" and marker.get("Options") in (None, {}) and + marker.get("Labels") == expected_labels) + + +def remove_volume_event_marker(container, intent): + name = volume_event_marker_name(intent) + if not exists("volume", name): + return + marker = inspect(TARGET, "volume", name) + if not volume_event_marker_owned(container, marker, intent) or volume_users(name): + raise RuntimeError(f'{container["Name"].lstrip("/")}: volume event marker changed; retained it for inspection') + run(TARGET, "volume", "rm", name) + if exists("volume", name): + raise RuntimeError(f'{container["Name"].lstrip("/")}: volume event marker name was replaced during cleanup') + + +def begin_volume_event_window(container, intent): + remove_volume_event_marker(container, intent) + since = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + name = volume_event_marker_name(intent) + run(TARGET, "volume", "create", + "--label", f"{LABEL}={container['Id']}", + "--label", f"{OWNERSHIP_LABEL}={intent['target_ownership']}", + "--label", f"{VOLUME_EVENT_LABEL}=1", name) + marker = inspect(TARGET, "volume", name) + if not volume_event_marker_owned(container, marker, intent) or volume_users(name): + raise RuntimeError(f'{container["Name"].lstrip("/")}: volume event marker ownership could not be proven') + return {"name": name, "since": since} + + +def verify_volume_event_window(container, intent, window, targets, allowed_container=None): + until = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + output = run(TARGET, "events", "--since", window["since"], "--until", until, + "--filter", "type=volume", "--format", "{{json .}}", capture=True) + try: + events = [json.loads(line) for line in output.splitlines() if line] + except json.JSONDecodeError as error: + raise RuntimeError("Cannot verify destination volume access events") from error + if any(not isinstance(event, dict) for event in events): + raise RuntimeError("Cannot verify destination volume access events") + marker_events = [event for event in events + if event.get("Type") == "volume" and event.get("Action") == "create" and + (event.get("Actor") or {}).get("ID") == window["name"]] + if len(marker_events) != 1: + raise RuntimeError(f'{container["Name"].lstrip("/")}: destination volume event history is incomplete') + expected_mounts = set() + for event in events: + actor = event.get("Actor") or {} + if (event.get("Type") != "volume" or event.get("Action") != "mount" or + actor.get("ID") not in targets): + continue + mounted_by = (actor.get("Attributes") or {}).get("container") + if allowed_container is None or mounted_by != allowed_container: + raise RuntimeError(f'{container["Name"].lstrip("/")}: another container accessed a destination volume during transfer') + expected_mounts.add(actor["ID"]) + if allowed_container is not None and expected_mounts != set(targets): + raise RuntimeError(f'{container["Name"].lstrip("/")}: destination volume mount history is incomplete') + remove_volume_event_marker(container, intent) + + def source_volume_digest(volume): return run("/usr/bin/sudo", "/usr/bin/python3", TRUSTED_MANIFEST, volume["Mountpoint"], capture=True) +def current_source_volume_digests(container): + digests = {} + for mount in container.get("Mounts", []): + volume = inspect(SOURCE, "volume", mount["Name"]) + validate_source_volume(container, volume) + digests[mount["Name"]] = source_volume_digest(volume) + return digests + + +def seal_quiesced_source_volumes(container, intent): + actual = current_source_volume_digests(container) + expected = intent.get("source_volumes") + if expected is None: + saved = deepcopy(intent) + saved["source_volumes"] = actual + return persist_migration_intent(container, saved) + if expected != actual: + raise RuntimeError(f'{container["Name"].lstrip("/")}: source volume changed after quiescing; inspect rootful Docker') + return intent + + def validate_source_volume(container, volume): name = container["Name"].lstrip("/") if (volume.get("Driver") != "local" or volume.get("Options") or @@ -851,6 +997,10 @@ def begin_quiesce(container, intent): if container["State"]["Running"]: intent["started_at"] = container["State"]["StartedAt"] intent.pop("stopped", None) + # A source restored after an earlier pre-transfer failure may have + # changed its volume normally while it ran. Establish the next cutover + # snapshot only after this quiesce stops it again. + intent["source_volumes"] = None return persist_migration_intent(container, intent) @@ -927,6 +1077,7 @@ def quiesce(container, validator=validate): snapshot_digest(disabled, ignore_restart=True) != snapshot_digest(planned, ignore_restart=True) or (disabled["HostConfig"].get("RestartPolicy") or {}).get("Name") != "no"): raise RuntimeError(f'{container["Name"].lstrip("/")}: source changed while being quiesced') + seal_quiesced_source_volumes(disabled, intent) print(f'{container["Name"].lstrip("/")}: quiesced before rootful Docker access revocation') @@ -937,6 +1088,7 @@ def verify_resumable_migration(container, target, intent): if intent["restore_started"]: raise ValueError(f"{name}: source ran after destination creation; inspect both engines") planned = planned_source(container, intent) + seal_quiesced_source_volumes(container, intent) destination = intent.get("destination") if (not isinstance(destination, dict) or destination.get("id") != target.get("Id") or destination.get("snapshot") != snapshot_digest(target) or @@ -988,6 +1140,13 @@ def resume_verified_migration(container, target, intent): target = inspect(TARGET, "container", name) if bool(target["State"]["Running"]) != intent["target_running"]: raise RuntimeError(f"{name}: resumed destination lifecycle differs from the source") + expected_volumes = {destination_volume(planned, mount) for mount in planned.get("Mounts", [])} + event_window = intent.get("volume_event") + if expected_volumes and event_window is None: + raise RuntimeError(f"{name}: interrupted destination volume event history is missing") + if event_window is not None: + verify_volume_event_window(planned, intent, event_window, expected_volumes, + target["Id"] if intent["target_running"] else None) verify_runtime(planned, intent["target_ownership"]) record_completion(source_after, state, intent["target_running"]) clear_migration_intent(container["Id"]) @@ -1045,6 +1204,7 @@ def migrate(container): running = intent["target_running"] if intent is not None else bool(container["State"]["Running"]) created_id = None guard_id = None + event_window = None image = None image_committed = False image_loaded = False @@ -1074,6 +1234,7 @@ def migrate(container): raise RuntimeError(f"{name}: Docker source configuration changed while stopping; rerun after workloads are stable") container = stopped_source intent = record_migration_intent(container, state, intent) + intent = seal_quiesced_source_volumes(container, intent) # Commit includes writable-layer changes and the exact image config. # Volume data is copied separately while the source container is stopped. image = run(SOURCE, "commit", identity, capture=True) @@ -1166,6 +1327,10 @@ def migrate(container): verify_volume_definition(volume, target, ownership) if set(volume_users(target)) != {guard_id}: raise RuntimeError(f"{name}: destination volume guard changed; retained it for inspection") + event_window = begin_volume_event_window(planned, intent) + intent = deepcopy(intent) + intent["volume_event"] = event_window + persist_migration_intent(container, intent) for target, pending in pending_volumes.items(): volume, ownership, record = pending verify_volume_definition(volume, target, ownership) @@ -1182,6 +1347,10 @@ def migrate(container): for target, expected in verified_volumes.items(): volume, ownership, digest = expected verify_volume_definition(volume, target, ownership) + # A digest proves what the page cache currently returns. Flush the + # destination filesystem before any completion metadata can outlive + # the copied volume data across sudden power loss. + sync_volume(target) verify_volume(target, digest) if source_volume_digest(volume) != digest: raise RuntimeError(f"{name}: source volume changed during transfer; inspect both engines") @@ -1238,6 +1407,10 @@ def migrate(container): target_state = inspect(TARGET, "container", name)["State"] if bool(target_state["Running"]) != bool(running): raise RuntimeError(f"{name}: destination lifecycle differs from the source") + if event_window is not None: + verify_volume_event_window(planned, intent, event_window, set(pending_volumes), + created_id if running else None) + event_window = None verify_runtime(planned, intent["target_ownership"]) record_completion(source_after, state, bool(running)) clear_migration_intent(identity) @@ -1288,6 +1461,13 @@ def migrate(container): except Exception: recovery_failed = True print(f"{name}: volume guard cleanup was not ownership-safe; retained it for inspection", file=sys.stderr) + try: + if event_window is not None: + remove_volume_event_marker(planned, intent) + event_window = None + except Exception: + recovery_failed = True + print(f"{name}: volume event marker cleanup was not ownership-safe; retained it for inspection", file=sys.stderr) if destination_may_have_run: try: intent["start_attempted"] = True @@ -1350,10 +1530,13 @@ def main(): containers = [inspect(SOURCE, "container", name) for name in names] volumes = set() blockers = [] + intents = {} for container in containers: try: validate(container) - except ValueError as error: + intent = migration_intent(container) + intents[container["Id"]] = intent + except (ValueError, RuntimeError) as error: blockers.append(str(error)) continue for mount in container.get("Mounts", []): @@ -1376,6 +1559,16 @@ def main(): raise ValueError("\n".join(blockers)) if volumes: validate_trusted_manifest() + for container in containers: + intent = intents[container["Id"]] + if (intent is not None and not container["State"]["Running"] and + intent.get("source_volumes") is not None): + try: + seal_quiesced_source_volumes(container, intent) + except (ValueError, RuntimeError) as error: + blockers.append(str(error)) + if blockers: + raise ValueError("\n".join(blockers)) quiesced = [] try: for container in containers: @@ -1417,10 +1610,13 @@ def main(): containers = [inspect(SOURCE, "container", name) for name in names] volumes = set() blockers = [] + intents = {} for container in containers: try: validate(container) - except ValueError as error: + intent = migration_intent(container) + intents[container["Id"]] = intent + except (ValueError, RuntimeError) as error: blockers.append(str(error)) continue for mount in container.get("Mounts", []): @@ -1436,6 +1632,16 @@ def main(): raise ValueError("\n".join(blockers)) if volumes: validate_trusted_manifest() + for container in containers: + intent = intents[container["Id"]] + if (intent is not None and not container["State"]["Running"] and + intent.get("source_volumes") is not None): + try: + seal_quiesced_source_volumes(container, intent) + except (ValueError, RuntimeError) as error: + blockers.append(str(error)) + if blockers: + raise ValueError("\n".join(blockers)) if check_completed: for container in containers: name = container["Name"].lstrip("/") diff --git a/default/docker/rootless/volume-manifest.py b/default/docker/rootless/volume-manifest.py index e74f7ae82ccb..c6aa614d1e65 100644 --- a/default/docker/rootless/volume-manifest.py +++ b/default/docker/rootless/volume-manifest.py @@ -1,5 +1,6 @@ """Fingerprint a quiesced volume, using the caller's numeric UID/GID namespace.""" +import ctypes import hashlib import json import os @@ -62,10 +63,27 @@ def remove(path): remove(child) +def sync_filesystem(root): + root = Path(root) + info = root.lstat() + if not stat.S_ISDIR(info.st_mode): + raise RuntimeError("volume root is not a directory") + descriptor = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + libc = ctypes.CDLL(None, use_errno=True) + if libc.syncfs(descriptor) != 0: + error = ctypes.get_errno() + raise OSError(error, os.strerror(error), root) + finally: + os.close(descriptor) + + if __name__ == '__main__': if sys.argv[1:2] == ["--clear"] and len(sys.argv) == 3: clear(sys.argv[2]) + elif sys.argv[1:2] == ["--sync"] and len(sys.argv) == 3: + sync_filesystem(sys.argv[2]) elif len(sys.argv) == 2: print(fingerprint(sys.argv[1])) else: - raise SystemExit("usage: volume-manifest.py [--clear] ROOT") + raise SystemExit("usage: volume-manifest.py [--clear|--sync] ROOT") diff --git a/docs/rootless-docker.md b/docs/rootless-docker.md index 075b334bb62d..d36794b30d1f 100644 --- a/docs/rootless-docker.md +++ b/docs/rootless-docker.md @@ -20,6 +20,6 @@ The migration's machine-wide enabled marker is written only after the shared roo The automatic path accepts running or never-started containers with stock bridge networking, localhost-only unprivileged published ports, private local named volumes, supported resource limits, root users with Docker's default capability ceiling or stricter settings, numeric non-root image users that already drop every capability, and the stock runtime and namespace boundaries. It rejects already-exited containers whose historical exit state cannot be recreated without rerunning them, privileged containers, added capabilities, devices, host or shared mounts, named image users whose effective UID is ambiguous, numeric non-root image users whose capability ceiling cannot be reproduced exactly, custom networks, namespace sharing, custom runtimes, altered confinement, custom logging, reserved migration labels, and unknown nondefault host settings. -For each accepted container, the migrator stops the source cleanly, commits its writable layer, transfers that image through Docker's native save/load format, and creates an unpredictable inert guard that pins every owned volume while contents and metadata are copied inside the RootlessKit user and mount namespace. The application container does not exist during that long copy. After transfer, a stopped `runc` application container joins the guard on the verified volumes; the guard is removed only after Docker proves both references, and the application container must still be never-started before finalization. The migrator verifies environment, application config, runtime, limits, capabilities, mounts, ports, restart policy, logging, volume fingerprints, and lifecycle before writing a receipt bound to full source and destination snapshots. If one transfer fails, every later source that the batch already quiesced is restored in reverse order. +For each accepted container, the migrator stops the source cleanly and durably seals its source-volume fingerprints before rootful Docker is restarted to revoke existing clients. Every seal is checked again before the first destination transfer. The migrator commits the writable layer, transfers that image through Docker's native save/load format, and creates an unpredictable inert guard that pins every owned volume while contents and metadata are copied inside the RootlessKit user and mount namespace. The application container does not exist during that long copy. Copied volume filesystems are synchronized before completion metadata is published. After transfer, a stopped `runc` application container joins the guard on the verified volumes; the guard is removed only after Docker proves both references, and the application container must still be never-started before finalization. A unique volume event marker proves the daemon retained the complete transfer window; a transient mount by any other container or missing event history stops automatic finalization. The migrator verifies environment, application config, runtime, limits, capabilities, mounts, ports, restart policy, logging, volume fingerprints, and lifecycle before writing a receipt bound to full source and destination snapshots. If one transfer fails, every later source that the batch already quiesced is restored in reverse order. -Before the destination is first started, an error removes only the exact journal-owned destination container and restores the source. Journal-owned volumes remain available for ownership verification; a retry attaches each verified volume to the stopped destination before emptying and copying the current stopped source again, so a concurrent name replacement, partial transfer, or later source deletion cannot damage unrelated data or leave stale entries. Resume requires Docker to prove that the destination has never started. Once a destination start has been attempted, automatic retry and source restoration stop for manual recovery because either side may contain new writes. A durable completion receipt takes precedence over a leftover journal if power fails between those two writes. Successful sources remain stopped with their restart policy disabled; they are retained in the rootful engine as recovery copies. +Before the destination is first started, an error removes only the exact journal-owned destination container and restores the source. The first journal directory entry, each journal update, and each rename are synchronized before they can authorize mutation. Journal-owned volumes remain available for ownership verification; a retry attaches each verified volume to the stopped destination before emptying and copying the current stopped source again, so a concurrent name replacement, partial transfer, or later source deletion cannot damage unrelated data or leave stale entries. Resume requires Docker to prove that the destination has never started and to replay the persisted event window before starting it. Once a destination start has been attempted, automatic retry and source restoration stop for manual recovery because either side may contain new writes. A durable completion receipt takes precedence over a leftover journal if power fails between those two writes. Successful sources remain stopped with their restart policy disabled; they are retained in the rootful engine as recovery copies. diff --git a/test/shell.d/rootless-docker-migration-test.sh b/test/shell.d/rootless-docker-migration-test.sh index 31fda4af7528..65443fc5ad3d 100755 --- a/test/shell.d/rootless-docker-migration-test.sh +++ b/test/shell.d/rootless-docker-migration-test.sh @@ -6,6 +6,7 @@ source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" python3 - <<'PY' import copy import importlib.util +import json import os import re import sys @@ -41,8 +42,31 @@ with tempfile.TemporaryDirectory() as directory: manifest.clear(volume) assert not os.listdir(volume) assert open(os.path.join(outside, "keep")).read() == "safe" + with open(os.path.join(volume, "durable"), "w") as output: + output.write("new") + manifest.sync_filesystem(volume) print("ok - retained-volume reset removes stale entries without following symlinks") +with tempfile.TemporaryDirectory() as directory: + state_home = Path(directory) / "new-state-home" + observed_syncs = [] + original_fsync = migration.os.fsync + + def tracing_fsync(descriptor): + observed_syncs.append(Path(os.readlink(f"/proc/self/fd/{descriptor}")).resolve()) + original_fsync(descriptor) + + migration.os.fsync = tracing_fsync + try: + migration.write_private_json( + state_home / "omarchy/rootless-docker-migration" / ("a" * 64 + ".in-progress"), + {"state": "durable"}, + ) + finally: + migration.os.fsync = original_fsync + assert Path(directory).resolve() in observed_syncs +print("ok - first journal creation synchronizes the new state hierarchy into its existing parent") + source_security = ["name=seccomp,profile=builtin", "name=cgroupns"] target_security = ["name=seccomp,profile=builtin", "name=rootless", "name=cgroupns"] migration.validate_source_daemon(source_security) @@ -83,6 +107,9 @@ container = { "MaskedPaths": sorted(migration.MASKED_PATHS), "ReadonlyPaths": sorted(migration.READONLY_PATHS), "Runtime": "runc", "CgroupnsMode": "private", "ConsoleSize": [0, 0], + "OomScoreAdj": 0, "BlkioWeight": 0, "CpuRealtimePeriod": 0, + "CpuRealtimeRuntime": 0, "CpuCount": 0, "CpuPercent": 0, + "IOMaximumIOps": 0, "IOMaximumBandwidth": 0, "PortBindings": {"8080/tcp": [{"HostIp": "127.0.0.1", "HostPort": "18080"}]}, "RestartPolicy": {"Name": "unless-stopped", "MaximumRetryCount": 0}, "LogConfig": {"Type": "json-file", "Config": {"max-size": "10m", "max-file": "5"}}, @@ -286,6 +313,52 @@ print("ok - only Omarchy's managed Windows runtime qualifies for the rootful exc source_volume = {"Name": "project-data", "Driver": "local", "Options": None, "Labels": {"project": "fixture"}} +sealed_container = copy.deepcopy(container) +sealed_container["State"] = { + "Status": "created", "Running": False, + "StartedAt": "0001-01-01T00:00:00Z", + "FinishedAt": "0001-01-01T00:00:00Z", "ExitCode": 0, +} +sealed_container["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} +sealed_digest = ["1" * 64] +original_inspect = migration.inspect +original_source_volume_digest = migration.source_volume_digest +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + migration.inspect = lambda engine, kind, name: copy.deepcopy(source_volume) + migration.source_volume_digest = lambda volume: sealed_digest[0] + sealed_intent = migration.record_migration_intent(sealed_container) + sealed_intent = migration.seal_quiesced_source_volumes(sealed_container, sealed_intent) + assert sealed_intent["source_volumes"] == {"project-data": "1" * 64} + sealed_digest[0] = "2" * 64 + try: + migration.seal_quiesced_source_volumes(sealed_container, sealed_intent) + except RuntimeError: + pass + else: + raise AssertionError("a rootful client changed a volume after quiescing without detection") + sealed_digest[0] = "1" * 64 + seal_order = [] + original_validate_trusted_manifest = migration.validate_trusted_manifest + original_daemon_security = migration.daemon_security + original_exists = migration.exists + migration.validate_trusted_manifest = lambda: seal_order.append("trusted-helper") + migration.daemon_security = lambda engine: source_security if engine == migration.SOURCE else target_security + migration.inspect = lambda engine, kind, name: copy.deepcopy( + sealed_container if kind == "container" else source_volume + ) + migration.exists = lambda kind, name: False + migration.source_volume_digest = lambda volume: (seal_order.append("source-digest") or sealed_digest[0]) + sys.argv = ["migrate.py", "--check", sealed_container["Name"].lstrip("/")] + migration.main() + assert seal_order[:2] == ["trusted-helper", "source-digest"] + migration.validate_trusted_manifest = original_validate_trusted_manifest + migration.daemon_security = original_daemon_security + migration.exists = original_exists +migration.inspect = original_inspect +migration.source_volume_digest = original_source_volume_digest +print("ok - trusted helper validation precedes quiesced source-volume seal checks") + ownership = migration.volume_identity(container, container["Mounts"][0]) assert ownership != migration.volume_identity(container, container["Mounts"][0]) raced_volume = copy.deepcopy(source_volume) @@ -311,7 +384,36 @@ except RuntimeError: pass else: raise AssertionError("an ambiguous destination-volume attachment passed validation") +real_remove_event_marker = migration.remove_volume_event_marker +migration.remove_volume_event_marker = lambda source, intent: None +migration.run = lambda *args, **kwargs: "\n".join(( + json.dumps({"Type": "volume", "Action": "create", "Actor": { + "ID": "marker", "Attributes": {"driver": "local"}}}), + json.dumps({"Type": "volume", "Action": "mount", "Actor": { + "ID": "project-data", "Attributes": {"container": "e" * 64}}}), +)) +try: + migration.verify_volume_event_window( + container, {"target_ownership": "d" * 64}, + {"name": "marker", "since": "time"}, {"project-data"}, "f" * 64, + ) +except RuntimeError: + pass +else: + raise AssertionError("a transient destination-volume writer escaped event validation") +migration.run = lambda *args, **kwargs: "\n".join(( + json.dumps({"Type": "volume", "Action": "create", "Actor": { + "ID": "marker", "Attributes": {"driver": "local"}}}), + json.dumps({"Type": "volume", "Action": "mount", "Actor": { + "ID": "project-data", "Attributes": {"container": "f" * 64}}}), +)) +migration.verify_volume_event_window( + container, {"target_ownership": "d" * 64}, + {"name": "marker", "since": "time"}, {"project-data"}, "f" * 64, +) migration.run = real_run +migration.remove_volume_event_marker = real_remove_event_marker +print("ok - volume event windows reject transient writers and require the intended mount") reserved_source = copy.deepcopy(source_volume) reserved_source["Labels"][migration.VOLUME_LABEL] = "foreign" try: @@ -331,6 +433,8 @@ blocked = ( ("SecurityOpt", ["seccomp=unconfined"]), ("Binds", ["/home/example/project:/data:rw"]), ("Mounts", [{"Type": "bind", "Source": "/home/example", "Target": "/data"}]), + ("MemorySwappiness", 0), + ("FutureNumericOption", 0), ("FuturePrivilegeOption", {"enabled": True}), ) for field, value in blocked: @@ -836,6 +940,56 @@ with tempfile.TemporaryDirectory() as directory: assert not migration.intent_path(resume_source["Id"]).exists() print("ok - a verified destination resumes safely across interruption before its first start") +receipt_source = copy.deepcopy(resume_source) +receipt_source["Id"] = "4" * 64 +receipt_source["Name"] = "/receipt-window" +receipt_source["Mounts"] = [copy.deepcopy(container["Mounts"][0])] +receipt_target = copy.deepcopy(resume_target) +receipt_target["Id"] = "3" * 64 +receipt_target["State"]["Running"] = False +receipt_events = [] +original_verify_resumable = migration.verify_resumable_migration +original_verify_event_window = migration.verify_volume_event_window +original_record_completion = migration.record_completion +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + receipt_intent = migration.record_migration_intent(receipt_source) + receipt_intent["volume_event"] = { + "name": migration.volume_event_marker_name(receipt_intent), + "since": "2026-09-12T00:00:00Z", + } + migration.persist_migration_intent(receipt_source, receipt_intent) + migration.verify_resumable_migration = lambda source, target, intent: ( + copy.deepcopy(receipt_source), copy.deepcopy(receipt_source["State"]), + ) + migration.inspect = lambda engine, kind, name: copy.deepcopy( + receipt_source if engine == migration.SOURCE else receipt_target + ) + migration.verify_volume_event_window = lambda source, intent, window, targets, allowed=None: ( + receipt_events.append((copy.deepcopy(window), set(targets), allowed)) + ) + + def interrupt_receipt(source, state, running): + assert migration.migration_intent(source)["volume_event"] == receipt_intent["volume_event"] + raise RuntimeError("power loss before receipt") + + migration.record_completion = interrupt_receipt + try: + migration.resume_verified_migration(receipt_source, receipt_target, receipt_intent) + except RuntimeError as error: + assert str(error) == "power loss before receipt" + else: + raise AssertionError("an interrupted completion unexpectedly removed its event window") + assert migration.migration_intent(receipt_source)["volume_event"] == receipt_intent["volume_event"] + migration.record_completion = lambda source, state, running: None + migration.resume_verified_migration(receipt_source, receipt_target, receipt_intent) + assert len(receipt_events) == 2 + assert not migration.intent_path(receipt_source["Id"]).exists() +migration.verify_resumable_migration = original_verify_resumable +migration.verify_volume_event_window = original_verify_event_window +migration.record_completion = original_record_completion +print("ok - an interrupted receipt retains and replays the destination volume event window") + for unsafe_kind in ("destination", "guard"): unsafe_original = copy.deepcopy(retry_original) unsafe_original["Id"] = ("a" if unsafe_kind == "destination" else "b") * 64 @@ -988,6 +1142,12 @@ with tempfile.TemporaryDirectory() as directory: migration.source_volume_digest = lambda volume: "7" * 64 migration.clear_volume = lambda target: pin_events.append(("clear", target)) migration.transfer_volume = lambda volume, target: (pin_events.append(("transfer", target)) or "7" * 64) + migration.begin_volume_event_window = lambda source, intent: ( + pin_events.append(("event-window-begin",)) or {"name": "marker", "since": "time"} + ) + migration.verify_volume_event_window = lambda source, intent, window, targets, allowed=None: ( + pin_events.append(("event-window-verify", tuple(sorted(targets)), allowed)) + ) migration.record_completion = lambda source, state, running: None migration.migrate(pinned_source) @@ -997,7 +1157,8 @@ assert len(create_indexes) == 2 guard_index, create_index = create_indexes clear_index = pin_events.index(("clear", "project-data")) transfer_index = pin_events.index(("transfer", "project-data")) -assert guard_index < clear_index < transfer_index < create_index +event_begin_index = pin_events.index(("event-window-begin",)) +assert guard_index < event_begin_index < clear_index < transfer_index < create_index guard_call = pin_events[guard_index] create_call = pin_events[create_index] assert "--network=none" in guard_call @@ -1010,8 +1171,14 @@ assert any(event[:3] == (migration.TARGET, "container", "ls") guard_remove_index = next(index for index, event in enumerate(pin_events) if event[:3] == (migration.TARGET, "rm", "--force") and event[3] == "8" * 64) start_index = pin_events.index((migration.TARGET, "start", "pinned-volume")) -assert create_index < guard_remove_index < start_index -print("ok - an inert random guard pins volumes while the application container does not yet exist") +event_verify = next(event for event in pin_events if event[:1] == ("event-window-verify",)) +event_verify_index = pin_events.index(event_verify) +assert create_index < guard_remove_index < start_index < event_verify_index +assert event_verify[1:] == (("project-data",), "6" * 64) +sync_index = next(index for index, event in enumerate(pin_events) + if event[:4] == ("target-namespace", "/usr/bin/python3", migration.TRUSTED_MANIFEST, "--sync")) +assert transfer_index < sync_index < create_index +print("ok - an inert random guard pins and durably verifies volumes before application start") batch = [] for index in (1, 2): From c00141ed8b590718724f62126d8c984789647e52 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Sat, 12 Sep 2026 13:09:28 -0600 Subject: [PATCH 10/31] Harden rootless Docker migration boundaries --- bin/omarchy-windows-vm | 175 ++- default/docker/rootless/migrate.py | 1022 +++++++++++++++-- default/docker/rootless/rootful-listeners.py | 173 ++- default/docker/rootless/volume-manifest.py | 188 ++- docs/rootless-docker.md | 12 +- install/helpers/rootless-docker.sh | 170 ++- migrations/1789164756.sh | 93 +- .../shell.d/rootless-docker-migration-test.sh | 974 ++++++++++++++-- test/shell.d/rootless-docker-posture-test.sh | 349 +++++- test/shell.d/windows-vm-auth-test.sh | 20 +- test/shell.d/windows-vm-compose-test.sh | 144 ++- 11 files changed, 3007 insertions(+), 313 deletions(-) diff --git a/bin/omarchy-windows-vm b/bin/omarchy-windows-vm index 4fe5a9128c32..2642bc3db328 100755 --- a/bin/omarchy-windows-vm +++ b/bin/omarchy-windows-vm @@ -89,10 +89,14 @@ priv() { # rootless DOCKER_HOST. Socket activation keeps that rootful daemon off until an # authenticated VM operation needs it. docker() { + local host="unix:///run/docker.sock" main_pid if ((EUID == 0)); then - /usr/bin/systemctl start docker.socket || return 1 + /usr/bin/systemctl start docker.socket docker.service || return 1 + main_pid=$(/usr/bin/systemctl show docker.service --property=MainPID --value) || return 1 + [[ $main_pid =~ ^[1-9][0-9]*$ ]] || return 1 + host="unix:///proc/$main_pid/root/run/docker.sock" fi - command /usr/bin/docker --host unix:///run/docker.sock "$@" + command /usr/bin/docker --host "$host" "$@" } dc() { docker compose -f "$COMPOSE_FILE" "$@"; } @@ -237,7 +241,7 @@ assert_boundary_dir() { } prepare_boundary_component() { - local path="$1" parent="$2" owner="$3" mode="$4" + local path="$1" parent="$2" owner="$3" mode="$4" keep_existing_mode="${5:-0}" assert_boundary_dir "$parent" "$owner" || return 1 if [[ -e $path || -L $path ]]; then assert_boundary_dir "$path" "$owner" || return 1 @@ -248,9 +252,14 @@ prepare_boundary_component() { install -d -m "$mode" -- "$path" || return 1 fi fi - chmod "$mode" -- "$path" || return 1 - if ((EUID == 0)); then chown root:root -- "$path" || return 1; fi - assert_boundary_dir "$path" "$owner" + if [[ $keep_existing_mode != 1 || ! -e $path ]]; then + chmod "$mode" -- "$path" || return 1 + if ((EUID == 0)); then chown root:root -- "$path" || return 1; fi + fi + assert_boundary_dir "$path" "$owner" || return 1 + # A retry may encounter a directory created by an invocation killed before + # its first fsync. Synchronize both levels even when they already existed. + fsync_directory "$path" && fsync_directory "$parent" } prepare_runtime_tree() { @@ -276,10 +285,11 @@ prepare_runtime_tree() { fi runtime_parent=$(dirname -- "$RUNTIME_DIR") - if ((EUID == 0)) && [[ ! -e $runtime_parent && ! -L $runtime_parent ]]; then + if ((EUID == 0)); then [[ $runtime_parent == /var/lib/omarchy ]] || return 1 - assert_boundary_dir /var/lib 0 || return 1 - install -d -o root -g root -m 0755 -- "$runtime_parent" || return 1 + # This shared parent may have a stricter administrator-selected mode. A + # retry needs to synchronize its directory entry without widening it. + prepare_boundary_component "$runtime_parent" /var/lib 0 0755 1 || return 1 fi prepare_boundary_component "$RUNTIME_DIR" "$runtime_parent" "$owner" 0755 && prepare_boundary_component "$MOUNT_ROOT" "$RUNTIME_DIR" "$owner" 0711 && @@ -984,6 +994,10 @@ __priv_secure() { return 0 fi assert_mounts_safe || return 1 + # A previous process may have completed the Compose rename and died before + # synchronizing it. Prove the replacement durable before the caller removes + # the legacy user-owned definition that still contains credentials. + fsync_regular_file "$COMPOSE_FILE" && fsync_directory "$RUNTIME_DIR" || return 1 if [[ -e $SECURITY_MIGRATION_STATE || -L $SECURITY_MIGRATION_STATE ]]; then desired=$(read_security_migration_state) || { echo "omarchy-windows-vm: refusing an untrusted Windows security-migration state" >&2 @@ -1170,6 +1184,46 @@ unescape() { printf '%s' "$v" } +# Decode the only double-quoted YAML escapes emitted by Omarchy's historical +# writer, then reproduce Compose's $$ interpolation exactly. Other escapes or +# a lone dollar could have produced a different effective value and therefore +# require the user to set the value again explicitly. +decode_legacy_scalar() { + local raw="$1" yaml="" decoded="" char next index length + length=${#raw} + for ((index = 0; index < length; index++)); do + char=${raw:index:1} + if [[ $char == '\' ]]; then + ((++index < length)) || return 1 + next=${raw:index:1} + [[ $next == '\' || $next == '"' ]] || return 1 + yaml+=$next + else + yaml+=$char + fi + done + length=${#yaml} + for ((index = 0; index < length; index++)); do + char=${yaml:index:1} + if [[ $char == '$' ]]; then + ((++index < length)) || return 1 + [[ ${yaml:index:1} == '$' ]] || return 1 + decoded+='$' + else + decoded+=$char + fi + done + printf '%s' "$decoded" +} + +decode_legacy_field() { + decode_legacy_scalar "$1" || { + echo "The legacy Windows settings use unsupported YAML escaping or environment-dependent Compose interpolation." >&2 + echo "Run omarchy-windows-vm install to set them explicitly before migration." >&2 + return 1 + } +} + # Store the RDP credentials privately for the user (0600) so the plaintext # password is not world-readable. The password is one validated printable line # (no newline), so plain KEY=VALUE is safe. @@ -1207,25 +1261,61 @@ read_credential() { read_compose_value() { local key="$1" file="$2" - sed -n "s/.*${key}: \"\(.*\)\"/\1/p" "$file" | head -n1 + sed -n "s/^[[:space:]]*${key}:[[:space:]]*\"\(.*\)\"[[:space:]]*$/\1/p" "$file" | head -n1 +} + +read_legacy_compose_value() { + local key="$1" optional="${2:-0}" values=() + mapfile -t values < <( + sed -n "s/^[[:space:]]*${key}:[[:space:]]*\"\(.*\)\"[[:space:]]*$/\1/p" "$LEGACY_COMPOSE_FILE" + ) + if ((optional == 1 && ${#values[@]} == 0)); then + return 0 + fi + ((${#values[@]} == 1)) || return 1 + printf '%s' "${values[0]}" +} + +read_legacy_field() { + local raw + raw=$(read_legacy_compose_value "$1" "${2:-0}") || { + echo "The legacy Windows definition has missing or duplicate settings." >&2 + echo "Run omarchy-windows-vm install to set them explicitly before migration." >&2 + return 1 + } + decode_legacy_field "$raw" } # Older installs kept the compose under ~/.config/windows. Carry those settings # into the root-owned location (preserving the VM's data via the same volume # paths) so an upgrade does not strand or re-download an existing VM. migrate_legacy_compose() { - [[ -f $COMPOSE_FILE ]] && return 0 + sync_legacy_compose_parent || return 1 + if [[ -f $COMPOSE_FILE ]]; then + if [[ -f $LEGACY_COMPOSE_FILE ]]; then + # This proves a replacement left by an interrupted rename before the + # caller removes the remaining user-readable credential copy. + priv secure || return 1 + remove_legacy_compose || return 1 + fi + return 0 + fi [[ -f $LEGACY_COMPOSE_FILE ]] || return 1 echo "Migrating Windows VM configuration to $COMPOSE_FILE ..." local ram cores disk username password tz - ram=$(read_compose_value RAM_SIZE "$LEGACY_COMPOSE_FILE") - cores=$(read_compose_value CPU_CORES "$LEGACY_COMPOSE_FILE") - disk=$(read_compose_value DISK_SIZE "$LEGACY_COMPOSE_FILE") - username=$(read_compose_value USERNAME "$LEGACY_COMPOSE_FILE") - password=$(read_compose_value PASSWORD "$LEGACY_COMPOSE_FILE") - tz=$(read_compose_value TZ "$LEGACY_COMPOSE_FILE") + ram=$(read_legacy_field RAM_SIZE) || return 1 + cores=$(read_legacy_field CPU_CORES) || return 1 + disk=$(read_legacy_field DISK_SIZE) || return 1 + username=$(read_legacy_field USERNAME) || return 1 + password=$(read_legacy_field PASSWORD) || return 1 + tz=$(read_legacy_field TZ 1) || return 1 [[ -z $tz ]] && tz="UTC" + valid_tz "$tz" || { + echo "The legacy Windows timezone cannot be migrated safely." >&2 + echo "Run omarchy-windows-vm install to set it explicitly before migration." >&2 + return 1 + } prepare_user_mount_sources || { echo "Could not validate the existing Windows VM data directories." >&2 return 1 @@ -1238,15 +1328,33 @@ migrate_legacy_compose() { echo "Re-run: omarchy-windows-vm install" >&2 return 1 fi + # A running legacy container still holds its old unauthenticated ports and + # mounts until Compose recreates it from the hardened definition. + priv secure || return 1 + remove_legacy_compose +} + +remove_legacy_compose() { rm -f "$LEGACY_COMPOSE_FILE" || return 1 fsync_directory "$(dirname -- "$LEGACY_COMPOSE_FILE")" } +sync_legacy_compose_parent() { + local parent + parent=$(dirname -- "$LEGACY_COMPOSE_FILE") + if [[ -e $parent || -L $parent ]]; then + [[ -d $parent && ! -L $parent ]] || return 1 + fsync_directory "$parent" + fi +} + secure_windows_migration() { - if [[ ! -f $COMPOSE_FILE && -f $LEGACY_COMPOSE_FILE ]]; then + sync_legacy_compose_parent || return 1 + if [[ -f $LEGACY_COMPOSE_FILE ]]; then migrate_legacy_compose || return 1 + return 0 fi - priv secure + priv secure || return 1 } # --- prerequisites ----------------------------------------------------------- @@ -1490,11 +1598,14 @@ remove_windows() { echo "Removing Windows VM..." - if [[ ! -f $COMPOSE_FILE && -f $LEGACY_COMPOSE_FILE ]]; then - migrate_legacy_compose || { + if ! migrate_legacy_compose; then + if [[ -f $COMPOSE_FILE ]]; then + echo "❌ Could not securely reconcile the VM definition before removal." >&2 + exit 1 + elif [[ -f $LEGACY_COMPOSE_FILE ]]; then echo "❌ Could not safely migrate the VM before removal." >&2 exit 1 - } + fi fi if [[ -f $COMPOSE_FILE ]]; then priv remove || { @@ -1522,6 +1633,8 @@ launch_windows() { echo "Windows VM not configured. Please run: omarchy-windows-vm install" exit 1 fi + echo "Could not securely reconcile the Windows VM definition." >&2 + exit 1 fi # RDP credentials come from the private per-user file. Older installs may @@ -1606,7 +1719,14 @@ To stop: omarchy-windows-vm stop" } stop_windows() { - migrate_legacy_compose 2>/dev/null || true + if ! migrate_legacy_compose; then + if [[ -f $LEGACY_COMPOSE_FILE ]]; then + exit 1 + elif [[ -f $COMPOSE_FILE ]]; then + echo "Could not securely reconcile the Windows VM definition." >&2 + exit 1 + fi + fi if [[ ! -f $COMPOSE_FILE ]]; then echo "Windows VM not configured." exit 1 @@ -1622,7 +1742,14 @@ stop_windows() { } status_windows() { - migrate_legacy_compose 2>/dev/null || true + if ! migrate_legacy_compose; then + if [[ -f $LEGACY_COMPOSE_FILE ]]; then + exit 1 + elif [[ -f $COMPOSE_FILE ]]; then + echo "Could not securely reconcile the Windows VM definition." >&2 + exit 1 + fi + fi if [[ ! -f $COMPOSE_FILE ]]; then echo "Windows VM not configured." echo "To set up: omarchy-windows-vm install" diff --git a/default/docker/rootless/migrate.py b/default/docker/rootless/migrate.py index 80b5ca19fd93..0047dacc4265 100644 --- a/default/docker/rootless/migrate.py +++ b/default/docker/rootless/migrate.py @@ -1,23 +1,30 @@ """Move compatible rootful containers into the desktop user's rootless Docker store.""" import hashlib +import io import json import os import re import secrets +import socket import stat +import struct import subprocess import sys +import tarfile from copy import deepcopy from datetime import datetime, timezone from decimal import Decimal -from pathlib import Path +from pathlib import Path, PurePosixPath LABEL = "io.omarchy.rootless-docker.source-id" OWNERSHIP_LABEL = "io.omarchy.rootless-docker.ownership" VOLUME_LABEL = "io.omarchy.rootless-docker.source-volume" VOLUME_EVENT_LABEL = "io.omarchy.rootless-docker.event-marker" +NOFILE_PROBE_LABEL = "io.omarchy.rootless-docker.nofile-probe" +NOFILE_PROBE_PREFIX = "omarchy-rootless-docker-nofile-" +NOFILE_PROBE_SECONDS = 30 SOURCE = "source" TARGET = "target" TRUSTED_MANIFEST = "/usr/share/omarchy/default/docker/rootless/volume-manifest.py" @@ -42,12 +49,186 @@ "BlkioWeight", "CpuCount", "CpuPercent", "CpuRealtimePeriod", "CpuRealtimeRuntime", "IOMaximumBandwidth", "IOMaximumIOps", "OomScoreAdj", } +TARGET_DAEMON_CONFIG = { + "log-driver": "json-file", + "log-opts": {"max-size": "10m", "max-file": "5"}, +} +TARGET_ROOTLESSKIT_ARGUMENTS = [ + "--net=slirp4netns", + "--mtu=65520", + "--slirp4netns-sandbox=auto", + "--slirp4netns-seccomp=auto", + "--disable-host-loopback", + "--port-driver=builtin", + "--copy-up=/etc", + "--copy-up=/run", + "--propagation=rslave", + "--detach-netns", + "/usr/bin/dockerd-rootless.sh", +] +TARGET_DAEMON_IDENTITY = None def daemon_security(engine): return json.loads(run(engine, "info", "--format", "{{json .SecurityOptions}}", capture=True)) +def unix_peer_credentials(path): + connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + connection.connect(path) + payload = connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, + struct.calcsize("3i")) + except OSError as error: + raise ValueError("the rootless Docker API socket cannot be identified") from error + finally: + connection.close() + return struct.unpack("3i", payload) + + +def process_start_token(proc, pid): + try: + fields = (proc / str(pid) / "stat").read_text().rsplit(")", 1)[1].split() + token = fields[19] + except (FileNotFoundError, PermissionError, IndexError) as error: + raise ValueError("the rootless Docker daemon process identity cannot be verified") from error + if not token.isdigit(): + raise ValueError("the rootless Docker daemon process identity cannot be verified") + return token + + +def target_config(proc, dockerd_pid, config_home, dockerd_start): + path = proc / str(dockerd_pid) / "root" / config_home.lstrip("/") / "docker/daemon.json" + descriptor = None + try: + descriptor = os.open(path, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW | os.O_NONBLOCK) + before = os.fstat(descriptor) + if (not stat.S_ISREG(before.st_mode) or before.st_uid != os.getuid() or + before.st_mode & 0o022 or before.st_nlink != 1): + raise ValueError("the rootless Docker daemon configuration is not a trusted regular file") + with os.fdopen(os.dup(descriptor), "rb") as source: + payload = source.read(1024 * 1024 + 1) + after = os.fstat(descriptor) + identity = lambda value: ( + value.st_dev, value.st_ino, value.st_mode, value.st_uid, value.st_gid, + value.st_nlink, value.st_size, value.st_mtime_ns, value.st_ctime_ns, + ) + if len(payload) > 1024 * 1024 or identity(before) != identity(after): + raise ValueError("the rootless Docker daemon configuration changed while it was read") + if before.st_ctime > dockerd_start: + raise ValueError("the rootless Docker configuration changed after the daemon started; restart it") + return json.loads(payload) + except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error: + raise ValueError("the rootless Docker daemon configuration cannot be verified") from error + finally: + if descriptor is not None: + os.close(descriptor) + + +def verified_target_daemon(identity, proc=Path("/proc")): + if (not isinstance(identity, dict) or set(identity) != {"pid", "start", "runtime"} or + type(identity["pid"]) is not int or identity["pid"] <= 1 or + not isinstance(identity["start"], str) or not identity["start"].isdigit() or + not isinstance(identity["runtime"], str) or not identity["runtime"].startswith("/")): + raise RuntimeError("the verified rootless Docker daemon identity is unavailable") + pid = identity["pid"] + try: + executable = os.readlink(proc / str(pid) / "exe") + current_start = process_start_token(proc, pid) + except (FileNotFoundError, PermissionError, ValueError) as error: + raise RuntimeError("the verified rootless Docker daemon is no longer running") from error + if executable != "/usr/bin/dockerd" or current_start != identity["start"]: + raise RuntimeError("the verified rootless Docker daemon changed during migration") + endpoint = proc / str(pid) / "root" / identity["runtime"].lstrip("/") / "docker.sock" + try: + peer_pid, peer_uid, _peer_gid = unix_peer_credentials(str(endpoint)) + except ValueError as error: + raise RuntimeError("the verified rootless Docker API socket is unavailable") from error + if peer_pid != pid or peer_uid != os.getuid(): + raise RuntimeError("the verified rootless Docker API socket changed during migration") + return pid, str(endpoint) + + +def target_daemon_policy(proc=Path("/proc")): + try: + main_pid = int(run("/usr/bin/systemctl", "--user", "show", "docker.service", + "--property=MainPID", "--value", capture=True)) + except (OSError, ValueError) as error: + raise ValueError("the rootless Docker daemon configuration cannot be verified") from error + if main_pid <= 1: + raise ValueError("the rootless Docker daemon has no valid service process") + try: + rootlesskit_arguments = [value.decode() for value in (proc / str(main_pid) / "cmdline").read_bytes().split(b"\0") if value] + rootlesskit_environment = [value.decode() for value in (proc / str(main_pid) / "environ").read_bytes().split(b"\0") if value] + rootlesskit_executable = os.readlink(proc / str(main_pid) / "exe") + except (FileNotFoundError, PermissionError, UnicodeDecodeError) as error: + raise ValueError("the rootless Docker service process cannot be inspected") from error + + descendants = {main_pid} + changed = True + while changed: + changed = False + for entry in proc.iterdir(): + if not entry.name.isdigit() or int(entry.name) in descendants: + continue + try: + parent = next(line.split()[1] for line in (entry / "status").read_text().splitlines() + if line.startswith("PPid:")) + except (FileNotFoundError, PermissionError, StopIteration): + continue + if int(parent) in descendants: + descendants.add(int(entry.name)) + changed = True + candidates = [] + slirp_candidates = [] + for pid in descendants - {main_pid}: + try: + arguments = [value.decode() for value in (proc / str(pid) / "cmdline").read_bytes().split(b"\0") if value] + except (FileNotFoundError, PermissionError, UnicodeDecodeError): + continue + if arguments and Path(arguments[0]).name == "dockerd": + try: + executable = os.readlink(proc / str(pid) / "exe") + except (FileNotFoundError, PermissionError): + continue + candidates.append((pid, arguments, executable)) + if arguments and Path(arguments[0]).name == "slirp4netns": + try: + executable = os.readlink(proc / str(pid) / "exe") + except (FileNotFoundError, PermissionError): + continue + slirp_candidates.append(executable) + if len(candidates) != 1 or rootlesskit_executable != "/usr/bin/rootlesskit": + raise ValueError("the rootless Docker daemon process cannot be identified uniquely") + dockerd_pid, arguments, executable = candidates[0] + if executable != "/usr/bin/dockerd": + raise ValueError("the rootless Docker daemon does not use the packaged executable") + if slirp_candidates != ["/usr/bin/slirp4netns"]: + raise ValueError("the rootless Docker network helper cannot be identified uniquely") + service_paths = [value.removeprefix("PATH=") for value in rootlesskit_environment + if value.startswith("PATH=")] + config_homes = [value.removeprefix("XDG_CONFIG_HOME=") for value in rootlesskit_environment + if value.startswith("XDG_CONFIG_HOME=")] + expected_config_home = str(Path.home() / ".config") + if service_paths != ["/usr/bin"]: + raise ValueError("the rootless Docker daemon does not use the packaged service PATH") + if config_homes != [expected_config_home]: + raise ValueError("the rootless Docker daemon does not use the packaged config directory") + try: + dockerd_start = (proc / str(dockerd_pid)).stat().st_ctime + dockerd_start_token = process_start_token(proc, dockerd_pid) + except (OSError, ValueError) as error: + raise ValueError("the rootless Docker daemon configuration cannot be verified") from error + runtime = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}" + configuration = target_config(proc, dockerd_pid, config_homes[0], dockerd_start) + identity = {"pid": dockerd_pid, "start": dockerd_start_token, "runtime": runtime} + try: + verified_target_daemon(identity, proc) + except RuntimeError as error: + raise ValueError("the rootless Docker API socket belongs to a different daemon") from error + return configuration, arguments, rootlesskit_arguments, service_paths[0], config_homes[0], identity + + def validate_source_daemon(options): # Daemon defaults (including no-new-privileges and seccomp profiles) need # not appear in individual HostConfig records. Userns remapping also changes @@ -59,7 +240,8 @@ def validate_source_daemon(options): raise ValueError("rootful Docker daemon confinement or user mapping needs an explicit migration") -def validate_target_daemon(options): +def validate_target_daemon(options, configuration=None, arguments=None, rootlesskit_arguments=None, + service_path=None, config_home=None): allowed = { "name=rootless", "name=cgroupns", "name=seccomp,profile=builtin", "name=seccomp,profile=default", @@ -70,6 +252,349 @@ def validate_target_daemon(options): if (configured - allowed or "name=cgroupns" not in configured or len(configured & SECCOMP_OPTIONS) != 1): raise ValueError("rootless Docker daemon confinement needs an explicit migration") + if configuration is not None and configuration != TARGET_DAEMON_CONFIG: + raise ValueError("rootless Docker has custom daemon defaults; restore Omarchy's daemon.json or migrate containers explicitly") + if arguments is not None and arguments not in (["dockerd"], ["/usr/bin/dockerd"]): + raise ValueError("rootless Docker uses custom daemon options; migrate containers explicitly") + runtime = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}" + expected_rootlesskit = [f"--state-dir={runtime}/dockerd-rootless", *TARGET_ROOTLESSKIT_ARGUMENTS] + if (rootlesskit_arguments is not None and + (not rootlesskit_arguments or Path(rootlesskit_arguments[0]).name != "rootlesskit" or + rootlesskit_arguments[1:] != expected_rootlesskit)): + raise ValueError("rootless Docker uses custom RootlessKit isolation; migrate containers explicitly") + if service_path is not None and service_path != "/usr/bin": + raise ValueError("rootless Docker uses an unsafe service PATH; restart it from the packaged unit") + if config_home is not None and config_home != str(Path.home() / ".config"): + raise ValueError("rootless Docker uses a custom config directory; restart it from the packaged unit") + + +def trusted_probe_file(path): + path = Path(path) + if not path.is_absolute(): + raise ValueError("the source file-limit probe has an invalid executable path") + try: + canonical = path.resolve(strict=True) + metadata = canonical.stat() + except OSError as error: + raise ValueError("the source file-limit probe executable is unavailable") from error + if not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != 0 or metadata.st_mode & 0o022: + raise ValueError("the source file-limit probe executable is not trusted") + parent = canonical.parent + while True: + metadata = parent.stat() + if not stat.S_ISDIR(metadata.st_mode) or metadata.st_uid != 0 or metadata.st_mode & 0o022: + raise ValueError("the source file-limit probe executable has an unsafe parent") + if parent == Path("/"): + break + parent = parent.parent + return canonical + + +def nofile_probe_rootfs(token): + if not re.fullmatch(r"[a-f0-9]{64}", token): + raise ValueError("the source file-limit probe has an invalid identity") + ldd = trusted_probe_file("/usr/bin/ldd") + sleep = trusted_probe_file("/usr/bin/sleep") + result = subprocess.run( + [ldd, sleep], check=True, text=True, capture_output=True, + env={"PATH": "/usr/bin", "LC_ALL": "C"}, + ) + files = {"/usr/bin/sleep": sleep} + for line in result.stdout.splitlines(): + definition = line.split("(", 1)[0].strip() + left, separator, right = definition.partition("=>") + for candidate in ((left.strip(), right.strip()) if separator else (left.strip(),)): + if candidate.startswith("/"): + files[candidate] = trusted_probe_file(candidate) + if len(files) < 3: + raise ValueError("the source file-limit probe dependencies cannot be identified") + + archive = io.BytesIO() + with tarfile.open(fileobj=archive, mode="w") as output: + for destination, source in sorted(files.items()): + payload = source.read_bytes() + entry = tarfile.TarInfo(destination.lstrip("/")) + entry.size = len(payload) + entry.mode = 0o755 + output.addfile(entry, io.BytesIO(payload)) + marker = token.encode() + entry = tarfile.TarInfo(f"omarchy-rootless-docker-probe/{token}") + entry.size = len(marker) + entry.mode = 0o400 + output.addfile(entry, io.BytesIO(marker)) + return archive.getvalue() + + +def parse_nofile_limits(output): + line = next((line for line in output.splitlines() if line.startswith("Max open files ")), None) + if line is None: + raise ValueError("the source container file limit cannot be read") + fields = line.split() + if len(fields) != 6 or fields[:3] != ["Max", "open", "files"] or fields[5] != "files": + raise ValueError("the source container file limit has an unexpected format") + try: + soft = -1 if fields[3] == "unlimited" else int(fields[3]) + hard = -1 if fields[4] == "unlimited" else int(fields[4]) + except ValueError as error: + raise ValueError("the source container file limit is invalid") from error + limits = {"soft": soft, "hard": hard} + validate_nofile(limits) + return limits + + +def nofile_probe_path(): + state = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state") + return state / "omarchy/rootless-docker-migration/.nofile-probe.in-progress" + + +def nofile_probe_record(): + path = nofile_probe_path() + try: + metadata = path.lstat() + except FileNotFoundError: + return None + if path.is_symlink() or not stat.S_ISREG(metadata.st_mode): + raise RuntimeError("the source file-limit probe journal changed unexpectedly") + try: + record = json.loads(path.read_text()) + except (OSError, json.JSONDecodeError) as error: + raise RuntimeError("the source file-limit probe journal cannot be read safely") from error + token = record.get("token") if isinstance(record, dict) else None + engine = record.get("engine") if isinstance(record, dict) else None + expected_name = f"{NOFILE_PROBE_PREFIX}{engine}-{token}" + expected_tag = f"omarchy-rootless-docker-nofile-{engine}:{token}" + image = record.get("image") if isinstance(record, dict) else None + limits = record.get("limits") if isinstance(record, dict) else None + try: + if limits is not None: + validate_nofile(limits) + except ValueError as error: + raise RuntimeError("the source file-limit probe journal changed unexpectedly") from error + if (not isinstance(record, dict) or metadata.st_uid != os.getuid() or + metadata.st_mode & 0o077 or + set(record) != {"engine", "token", "name", "tag", "image", "limits"} or + engine not in (SOURCE, TARGET) or + not re.fullmatch(r"[a-f0-9]{64}", token or "") or + record.get("name") != expected_name or record.get("tag") != expected_tag or + (image is not None and not re.fullmatch(r"sha256:[a-f0-9]{64}", image))): + raise RuntimeError("the source file-limit probe journal changed unexpectedly") + return record + + +def docker_inspect_optional(engine, kind, identity): + result = subprocess.run( + local_command([engine, kind, "inspect", identity]), text=True, capture_output=True, + ) + if result.returncode != 0: + run(engine, "info", capture=True) + return None + try: + inspected = json.loads(result.stdout) + except json.JSONDecodeError as error: + raise RuntimeError(f"the source file-limit probe {kind} cannot be inspected") from error + if not isinstance(inspected, list) or len(inspected) != 1 or not isinstance(inspected[0], dict): + raise RuntimeError(f"the source file-limit probe {kind} has an invalid identity") + return inspected[0] + + +def nofile_probe_container_owned(container, record): + config = container.get("Config") or {} + host = container.get("HostConfig") or {} + restart = host.get("RestartPolicy") or {} + expected_ulimits = None + if record["limits"] is not None: + expected_ulimits = [{ + "Name": "nofile", "Soft": record["limits"]["soft"], + "Hard": record["limits"]["hard"], + }] + return ( + record["image"] is not None and + re.fullmatch(r"[a-f0-9]{64}", container.get("Id") or "") is not None and + container.get("Name") == f'/{record["name"]}' and + container.get("Image") == record["image"] and + container.get("Path") == "/usr/bin/sleep" and + container.get("Args") == [str(NOFILE_PROBE_SECONDS)] and + config.get("Image") == record["image"] and + config.get("Entrypoint") == ["/usr/bin/sleep"] and + config.get("Cmd") == [str(NOFILE_PROBE_SECONDS)] and + config.get("Labels") == {NOFILE_PROBE_LABEL: record["token"]} and + host.get("AutoRemove") is True and host.get("NetworkMode") == "none" and + host.get("ReadonlyRootfs") is True and host.get("Privileged") is False and + host.get("CapDrop") == ["ALL"] and + host.get("SecurityOpt") == ["no-new-privileges"] and + (host.get("Ulimits") == expected_ulimits or + (expected_ulimits is None and host.get("Ulimits") in (None, []))) and + restart.get("Name") == "no" and restart.get("MaximumRetryCount") == 0 and + not (host.get("Binds") or host.get("Mounts")) and not container.get("Mounts") + ) + + +def nofile_probe_image_owned(image, record): + identity = image.get("Id") + repository = record["tag"].rsplit(":", 1)[0] + return ( + re.fullmatch(r"sha256:[a-f0-9]{64}", identity or "") is not None and + (record["image"] is None or identity == record["image"]) and + image.get("RepoTags") == [record["tag"]] and + image.get("RepoDigests") in (None, [], [f"{repository}@{identity}"]) + ) + + +def clear_nofile_probe_record(): + path = nofile_probe_path() + try: + path.unlink() + except FileNotFoundError: + return + directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(directory) + finally: + os.close(directory) + + +def cleanup_nofile_probe(): + record = nofile_probe_record() + if record is None: + return + failures = [] + engine = record["engine"] + try: + container = docker_inspect_optional(engine, "container", record["name"]) + if container is not None: + if not nofile_probe_container_owned(container, record): + raise RuntimeError("the source file-limit probe container changed unexpectedly") + run(engine, "container", "rm", "-f", container["Id"], capture=True) + if docker_inspect_optional(engine, "container", container["Id"]) is not None: + raise RuntimeError("the source file-limit probe container was replaced during cleanup") + except Exception as error: + failures.append(error) + try: + image = docker_inspect_optional(engine, "image", record["tag"]) + if image is not None: + if not nofile_probe_image_owned(image, record): + raise RuntimeError("the source file-limit probe image changed unexpectedly") + run(engine, "image", "rm", record["tag"], capture=True) + if (docker_inspect_optional(engine, "image", image["Id"]) is not None or + docker_inspect_optional(engine, "image", record["tag"]) is not None): + raise RuntimeError("the source file-limit probe image was replaced during cleanup") + except Exception as error: + failures.append(error) + if failures: + raise RuntimeError( + "the source file-limit probe could not be cleaned safely; inspect rootful Docker" + ) from failures[0] + clear_nofile_probe_record() + + +def probe_nofile(engine, expected=None): + if engine not in (SOURCE, TARGET): + raise ValueError("the file-limit probe has an invalid Docker engine") + if expected is not None: + validate_nofile(expected) + cleanup_nofile_probe() + token = secrets.token_hex(32) + record = { + "engine": engine, + "token": token, + "name": f"{NOFILE_PROBE_PREFIX}{engine}-{token}", + "tag": f"omarchy-rootless-docker-nofile-{engine}:{token}", + "image": None, + "limits": deepcopy(expected), + } + write_private_json(nofile_probe_path(), record) + try: + imported = subprocess.run( + local_command([engine, "image", "import", "-", record["tag"]]), + input=nofile_probe_rootfs(token), + check=True, capture_output=True, + ).stdout.decode().strip() + if not re.fullmatch(r"sha256:[a-f0-9]{64}", imported): + raise RuntimeError("the source file-limit probe image has an invalid identity") + record["image"] = imported + write_private_json(nofile_probe_path(), record) + arguments = [ + engine, "run", "-d", "--rm", "--name", record["name"], + "--label", f"{NOFILE_PROBE_LABEL}={token}", "--network=none", "--read-only", + "--cap-drop=ALL", "--security-opt=no-new-privileges", "--entrypoint=/usr/bin/sleep", + ] + if expected is not None: + arguments += ["--ulimit", f'nofile={expected["soft"]}:{expected["hard"]}'] + arguments += [imported, str(NOFILE_PROBE_SECONDS)] + container_id = run(*arguments, capture=True) + if not re.fullmatch(r"[a-f0-9]{64}", container_id): + raise RuntimeError("the source file-limit probe container has an invalid identity") + container = inspect(engine, "container", container_id) + if not nofile_probe_container_owned(container, record): + raise RuntimeError("the source file-limit probe container changed unexpectedly") + state = container["State"] + pid = state.get("Pid") + if not state.get("Running") or type(pid) is not int or pid <= 1: + raise RuntimeError("the source file-limit probe did not start safely") + if engine == SOURCE: + limits_path = source_namespace_path(f"/proc/{pid}/limits") + else: + limits_path = f"/proc/{pid}/limits" + output = run("/usr/bin/sudo", "/usr/bin/cat", limits_path, capture=True) + actual = parse_nofile_limits(output) + if expected is not None and actual != expected: + raise RuntimeError("rootless Docker cannot reproduce the source container file limit") + return actual + finally: + cleanup_nofile_probe() + + +def source_default_nofile(): + return probe_nofile(SOURCE) + + +def validate_target_nofile(limits): + probe_nofile(TARGET, limits) + + +def container_nofile(container, default, intent=None): + if intent is not None: + expected = intent["source_nofile"] + else: + expected = default + if not container["State"]["Running"]: + return deepcopy(expected) + pid = container["State"].get("Pid") + if type(pid) is not int or pid <= 1: + raise ValueError(f'{container["Name"].lstrip("/")}: source process cannot be identified') + limits = parse_nofile_limits(run( + "/usr/bin/sudo", "/usr/bin/cat", + source_namespace_path(f"/proc/{pid}/limits"), capture=True, + )) + latest = inspect(SOURCE, "container", container["Id"]) + if (not latest["State"]["Running"] or latest["State"].get("Pid") != pid or + latest["State"].get("StartedAt") != container["State"].get("StartedAt") or + snapshot_digest(latest) != snapshot_digest(container)): + raise RuntimeError(f'{container["Name"].lstrip("/")}: source changed while its file limit was read') + if intent is not None and limits != expected: + raise ValueError(f'{container["Name"].lstrip("/")}: source file limit changed during migration') + return limits + + +def validate_nofile(limits): + if (not isinstance(limits, dict) or set(limits) != {"soft", "hard"} or + any(type(limits[key]) is not int for key in ("soft", "hard"))): + raise ValueError("the source container file limit is invalid") + soft, hard = limits["soft"], limits["hard"] + if soft == 0 or hard == 0 or soft < -1 or hard < -1 or (hard != -1 and (soft == -1 or soft > hard)): + raise ValueError("the source container file limit is invalid") + + +def validate_target_policy(): + global TARGET_DAEMON_IDENTITY + policy = target_daemon_policy() + identity = policy[-1] + TARGET_DAEMON_IDENTITY = identity + try: + validate_target_daemon(daemon_security(TARGET), *policy[:-1]) + except BaseException: + TARGET_DAEMON_IDENTITY = None + raise def validate_volumes(container): @@ -154,9 +679,10 @@ def validate_security(container): raise ValueError(f"{name}: custom logging needs an explicit migration") -def runtime_arguments(container): +def runtime_arguments(container, source_nofile): host = container["HostConfig"] - arguments = ["--shm-size", str(host["ShmSize"])] + arguments = ["--shm-size", str(host["ShmSize"]), "--init=false", "--ulimit", + f'nofile={source_nofile["soft"]}:{source_nofile["hard"]}'] if host.get("PidsLimit") not in (None, 0, -1): arguments.append(f'--pids-limit={host["PidsLimit"]}') for key, flag in RESOURCE_FLAGS.items(): @@ -207,7 +733,7 @@ def mapping(entries): raise RuntimeError("rootless Docker did not preserve the source environment; application was not started") -def verify_runtime(container, ownership=None): +def verify_runtime(container, ownership=None, source_nofile=None): name = container["Name"].lstrip("/") target = inspect(TARGET, "container", name) verify_environment(container, target["Config"].get("Env")) @@ -224,6 +750,13 @@ def verify_runtime(container, ownership=None): raise RuntimeError(f"{name}: rootless Docker changed a private namespace boundary") if target_host.get("Runtime") != "runc": raise RuntimeError(f"{name}: rootless Docker changed the OCI runtime") + if target_host.get("Init") is not False: + raise RuntimeError(f"{name}: rootless Docker changed the init process policy") + if source_nofile is not None: + expected_ulimits = [{"Name": "nofile", "Soft": source_nofile["soft"], "Hard": source_nofile["hard"]}] + actual_ulimits = target_host.get("Ulimits") or [] + if actual_ulimits != expected_ulimits: + raise RuntimeError(f"{name}: rootless Docker did not preserve the source file limit") expected_mounts = sorted((mount["Destination"], destination_volume(container, mount), bool(mount.get("RW"))) for mount in container.get("Mounts", [])) actual_mounts = target.get("Mounts") or [] @@ -279,23 +812,41 @@ def verify_runtime(container, ownership=None): raise RuntimeError(f"{name}: rootless Docker changed the restart policy") if target_host.get("LogConfig") != source_host.get("LogConfig"): raise RuntimeError(f"{name}: rootless Docker changed the logging policy") + return target def local_command(args): if args[0] == SOURCE: - return ["/usr/bin/sudo", "/usr/bin/docker", "--host", "unix:///run/docker.sock", *args[1:]] + host = os.environ.get("OMARCHY_ROOTFUL_DOCKER_HOST", "") + if not re.fullmatch(r"unix:///proc/[1-9][0-9]*/root/run/docker\.sock", host): + raise RuntimeError("the verified rootful Docker endpoint is unavailable") + return ["/usr/bin/sudo", "/usr/bin/docker", "--host", host, *args[1:]] if args[0] == TARGET: - runtime = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}" - return ["/usr/bin/docker", "--host", f"unix://{runtime}/docker.sock", *args[1:]] + _pid, endpoint = verified_target_daemon(TARGET_DAEMON_IDENTITY) + return ["/usr/bin/docker", "--host", f"unix://{endpoint}", *args[1:]] if args[0] == "target-namespace": - runtime = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") - child_pid = (runtime / "dockerd-rootless/child_pid").read_text().strip() - if not child_pid.isdigit() or int(child_pid) <= 1: - raise RuntimeError("cannot identify the rootless Docker namespace") - return ["/usr/bin/nsenter", "-U", "--preserve-credentials", "-m", "-t", child_pid, *args[1:]] + pid, _endpoint = verified_target_daemon(TARGET_DAEMON_IDENTITY) + return ["/usr/bin/nsenter", "-U", "--preserve-credentials", "-m", "-t", str(pid), *args[1:]] return args +def source_dockerd_pid(): + host = os.environ.get("OMARCHY_ROOTFUL_DOCKER_HOST", "") + match = re.fullmatch(r"unix:///proc/([1-9][0-9]*)/root/run/docker\.sock", host) + if match is None: + raise RuntimeError("the verified rootful Docker endpoint is unavailable") + return int(match.group(1)) + + +def source_namespace_path(path): + if not isinstance(path, str) or not path.startswith("/"): + raise ValueError("rootful Docker returned an invalid host path") + normalized = PurePosixPath(path) + if ".." in normalized.parts or str(normalized) != path: + raise ValueError("rootful Docker returned an invalid host path") + return f"/proc/{source_dockerd_pid()}/root{path}" + + def run(*args, capture=False): environment = os.environ.copy() if args[0] == TARGET: @@ -387,9 +938,11 @@ def write_private_json(path, payload): temporary.unlink(missing_ok=True) -def record_migration_intent(container, stopped_state=None, saved=None, restart_disabled=False): +def record_migration_intent(container, stopped_state=None, saved=None, restart_disabled=False, + source_nofile=None): state = container["State"] if saved is None: + validate_nofile(source_nofile) payload = { "source": container["Id"], "source_snapshot": snapshot_digest(container), @@ -403,6 +956,8 @@ def record_migration_intent(container, stopped_state=None, saved=None, restart_d "start_attempted": False, "target_ownership": secrets.token_hex(32), "source_volumes": None, + "source_nofile": deepcopy(source_nofile), + "image": None, "volume_event": None, "volumes": {}, } @@ -428,7 +983,10 @@ def migration_intent(container): saved = json.loads(path.read_text()) restart_policy = saved["source_restart_policy"] source_volumes = saved.get("source_volumes") + source_nofile = saved["source_nofile"] + image_record = saved.get("image") volume_event = saved.get("volume_event") + validate_nofile(source_nofile) if (saved["source"] != container["Id"] or not isinstance(saved["target_running"], bool) or not isinstance(saved["restart_disabled"], bool) or @@ -436,6 +994,16 @@ def migration_intent(container): not isinstance(saved["restore_started"], bool) or not isinstance(saved["start_attempted"], bool) or not re.fullmatch(r"[a-f0-9]{64}", saved["target_ownership"]) or + (image_record is not None and + (not isinstance(image_record, dict) or + set(image_record) != {"tag", "source", "target", "target_preexisting"} or + image_record.get("tag") != f'omarchy-rootless-docker-transfer:{saved["target_ownership"]}' or + (image_record.get("target_preexisting") is not None and + type(image_record.get("target_preexisting")) is not bool) or + ((image_record.get("target") is None) != + (image_record.get("target_preexisting") is None)) or + any(value is not None and not re.fullmatch(r"sha256:[a-f0-9]{64}", value) + for value in (image_record.get("source"), image_record.get("target"))))) or (source_volumes is not None and (not isinstance(source_volumes, dict) or any(not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]*", name) or @@ -451,6 +1019,7 @@ def migration_intent(container): not isinstance(saved["started_at"], str)): raise ValueError saved.setdefault("source_volumes", None) + saved.setdefault("image", None) saved.setdefault("volume_event", None) exact_snapshot = saved["source_snapshot"] == snapshot_digest(container) disabled_snapshot = ( @@ -510,6 +1079,127 @@ def persist_migration_intent(container, intent): return intent +def transfer_image_record(intent): + record = intent.get("image") + expected_tag = f'omarchy-rootless-docker-transfer:{intent["target_ownership"]}' + if (not isinstance(record, dict) or + set(record) != {"tag", "source", "target", "target_preexisting"} or + record.get("tag") != expected_tag or + (record.get("target_preexisting") is not None and + type(record.get("target_preexisting")) is not bool) or + ((record.get("target") is None) != + (record.get("target_preexisting") is None)) or + any(value is not None and not re.fullmatch(r"sha256:[a-f0-9]{64}", value) + for value in (record.get("source"), record.get("target")))): + raise ValueError("interrupted transfer image ownership is invalid") + return record + + +def transfer_image_owned(image, record, engine): + identity = image.get("Id") + repository = record["tag"].rsplit(":", 1)[0] + expected_identity = record[engine] + return ( + re.fullmatch(r"sha256:[a-f0-9]{64}", identity or "") is not None and + (expected_identity is None or identity == expected_identity) and + image.get("RepoTags") == [record["tag"]] and + image.get("RepoDigests") in (None, [], [f"{repository}@{identity}"]) + ) + + +def update_transfer_image(container, intent, engine, identity): + if engine not in (SOURCE, TARGET): + raise ValueError("invalid transfer image engine") + if identity is not None and not re.fullmatch(r"sha256:[a-f0-9]{64}", identity): + raise ValueError("invalid transfer image identity") + saved = deepcopy(intent) + record = transfer_image_record(saved) + record[engine] = identity + return persist_migration_intent(container, saved) + + +def update_target_transfer_image(container, intent, identity, preexisting): + if not isinstance(preexisting, bool) or not re.fullmatch(r"sha256:[a-f0-9]{64}", identity): + raise ValueError("invalid destination transfer image identity") + saved = deepcopy(intent) + record = transfer_image_record(saved) + record["target"] = identity + record["target_preexisting"] = preexisting + return persist_migration_intent(container, saved) + + +def remove_transfer_image(engine, record, untag_only=False): + image = docker_inspect_optional(engine, "image", record["tag"]) + if image is None: + expected_identity = record[engine] + if expected_identity is not None: + retained = docker_inspect_optional(engine, "image", expected_identity) + if retained is not None and not untag_only: + raise RuntimeError("a migration transfer image lost its ownership tag") + return + if not transfer_image_owned(image, record, engine): + raise RuntimeError("a migration transfer image changed; retained it for inspection") + if untag_only: + run(engine, "image", "rm", record["tag"], capture=True) + if docker_inspect_optional(engine, "image", record["tag"]) is not None: + raise RuntimeError("a migration transfer image tag was replaced during cleanup") + else: + # Docker rejects removing a tagged image by digest without --force. + # Ownership proves this is its only tag, so removing the tag deletes + # the unused transfer image without broadening the removal operation. + run(engine, "image", "rm", record["tag"], capture=True) + if (docker_inspect_optional(engine, "image", image["Id"]) is not None or + docker_inspect_optional(engine, "image", record["tag"]) is not None): + raise RuntimeError("a migration transfer image was replaced during cleanup") + + +def cleanup_transfer_images(container, intent): + if intent.get("image") is None: + return intent + record = transfer_image_record(intent) + failures = [] + engines = [SOURCE] if record["target_preexisting"] is True else [TARGET, SOURCE] + for engine in engines: + try: + remove_transfer_image(engine, record) + except Exception as error: + failures.append(error) + if failures: + raise RuntimeError("migration transfer images could not be cleaned safely") from failures[0] + saved = deepcopy(intent) + saved["image"] = None + return persist_migration_intent(container, saved) + + +def release_transfer_image(container, intent): + if intent.get("image") is None: + return intent + record = transfer_image_record(intent) + failures = [] + try: + remove_transfer_image(SOURCE, record) + except Exception as error: + failures.append(error) + if record["target_preexisting"] is not True: + try: + image = docker_inspect_optional(TARGET, "image", record["tag"]) + destination = intent.get("destination") or {} + target = inspect(TARGET, "container", destination.get("id", "")) + if (image is None or not transfer_image_owned(image, record, TARGET) or + target.get("Id") != destination.get("id") or + target.get("Image") != record["target"] or + (target.get("Config") or {}).get("Image") != record["tag"] or + not target_owned(container, target, intent)): + raise RuntimeError("the migrated container no longer owns its transferred image") + except Exception as error: + failures.append(error) + if failures: + raise RuntimeError("migration transfer image tags could not be released safely") from failures[0] + saved = deepcopy(intent) + saved["image"] = None + return persist_migration_intent(container, saved) + + def record_destination_may_have_run(container, intent): saved = deepcopy(intent) saved["start_attempted"] = True @@ -583,13 +1273,17 @@ def target_never_started(container): state.get("FinishedAt") == never) -def record_completion(container, source_state, target_running): +def record_completion(container, source_state, target_running, verified_target): latest_source = inspect(SOURCE, "container", container["Id"]) if (stopped_identity(latest_source["State"]) != stopped_identity(source_state) or snapshot_digest(latest_source) != snapshot_digest(container)): raise RuntimeError(f'{container["Name"].lstrip("/")}: Docker source changed before completion; inspect both engines') container = latest_source target = inspect(TARGET, "container", container["Name"].lstrip("/")) + verified_snapshot = snapshot_digest(verified_target) + if (target.get("Id") != verified_target.get("Id") or + snapshot_digest(target) != verified_snapshot): + raise RuntimeError(f'{container["Name"].lstrip("/")}: destination changed before completion; inspect both engines') if target_running: if target["State"].get("Running") is not True: raise RuntimeError(f'{container["Name"].lstrip("/")}: destination stopped before completion') @@ -599,7 +1293,7 @@ def record_completion(container, source_state, target_running): "target": target["Id"], "source": stopped_identity(source_state), "target_running": target_running, "source_snapshot": snapshot_digest(container), - "target_snapshot": snapshot_digest(target), + "target_snapshot": verified_snapshot, }) @@ -610,7 +1304,7 @@ def validate(container): if not re.fullmatch(r"[a-f0-9]{64}", container["Id"]): raise ValueError("Unsupported Docker container identity") labels = container["Config"].get("Labels") or {} - if labels.keys() & {LABEL, OWNERSHIP_LABEL}: + if labels.keys() & {LABEL, OWNERSHIP_LABEL, NOFILE_PROBE_LABEL}: raise ValueError(f"{name}: reserved Omarchy migration labels need an explicit migration") state = container["State"] if (state.get("Paused") or state.get("Restarting") or state.get("Dead") or @@ -739,8 +1433,8 @@ def transfer_volume(volume, target): destination = inspect(TARGET, "volume", target)["Mountpoint"] # Native tar inside RootlessKit's user/mount namespace preserves numeric # container ownership, root mode, PAX timestamps, ACLs and xattrs. - pipe(["/usr/bin/sudo", "/usr/bin/tar", "--format=pax", "--numeric-owner", "--sparse", "--acls", "--xattrs", - "--xattrs-include=*", "-C", volume["Mountpoint"], "-cpf", "-", "."], + pipe(["/usr/bin/sudo", "/usr/bin/python3", TRUSTED_MANIFEST, "--archive", + source_namespace_path(volume["Mountpoint"])], ["target-namespace", "/usr/bin/tar", "--numeric-owner", "--same-owner", "--same-permissions", "--sparse", "--acls", "--xattrs", "--xattrs-include=*", "-C", destination, "-xpf", "-"]) source_digest = source_volume_digest(volume) @@ -797,21 +1491,58 @@ def remove_volume_event_marker(container, intent): raise RuntimeError(f'{container["Name"].lstrip("/")}: volume event marker name was replaced during cleanup') -def begin_volume_event_window(container, intent): - remove_volume_event_marker(container, intent) - since = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") +def retire_volume_event_window(container, intent, volumes_absent=False): + retired = deepcopy(intent) + retired["volume_event"] = None + if volumes_absent: + retired["volumes"] = {} + if retired != intent: + retired = persist_migration_intent(container, retired) + remove_volume_event_marker(container, retired) + return retired + + +def verify_volume_event_marker(container, intent): name = volume_event_marker_name(intent) + if not exists("volume", name): + raise RuntimeError(f'{container["Name"].lstrip("/")}: destination volume event history is missing') + marker = inspect(TARGET, "volume", name) + if not volume_event_marker_owned(container, marker, intent) or volume_users(name): + raise RuntimeError(f'{container["Name"].lstrip("/")}: volume event marker changed; retained destination data for inspection') + + +def ensure_volume_event_window(container, intent, targets): + window = intent.get("volume_event") + if window is None: + if intent["volumes"]: + raise RuntimeError(f'{container["Name"].lstrip("/")}: interrupted destination volume event history is missing') + window = { + "name": volume_event_marker_name(intent), + "since": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), + } + intent["volume_event"] = window + intent = persist_migration_intent(container, intent) + name = window["name"] + if exists("volume", name): + verify_volume_event_marker(container, intent) + return intent + if intent["volumes"]: + raise RuntimeError(f'{container["Name"].lstrip("/")}: destination volume event marker disappeared; retained destination data for inspection') + for target in targets: + if exists("volume", target): + raise RuntimeError(f'{container["Name"].lstrip("/")}: destination volume already exists without complete event history') run(TARGET, "volume", "create", "--label", f"{LABEL}={container['Id']}", "--label", f"{OWNERSHIP_LABEL}={intent['target_ownership']}", "--label", f"{VOLUME_EVENT_LABEL}=1", name) - marker = inspect(TARGET, "volume", name) - if not volume_event_marker_owned(container, marker, intent) or volume_users(name): - raise RuntimeError(f'{container["Name"].lstrip("/")}: volume event marker ownership could not be proven') - return {"name": name, "since": since} + verify_volume_event_marker(container, intent) + return intent def verify_volume_event_window(container, intent, window, targets, allowed_container=None): + if window != intent.get("volume_event"): + raise RuntimeError(f'{container["Name"].lstrip("/")}: destination volume event journal changed') + verify_volume_event_marker(container, intent) until = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") output = run(TARGET, "events", "--since", window["since"], "--until", until, "--filter", "type=volume", "--format", "{{json .}}", capture=True) @@ -838,12 +1569,12 @@ def verify_volume_event_window(container, intent, window, targets, allowed_conta expected_mounts.add(actor["ID"]) if allowed_container is not None and expected_mounts != set(targets): raise RuntimeError(f'{container["Name"].lstrip("/")}: destination volume mount history is incomplete') - remove_volume_event_marker(container, intent) + verify_volume_event_marker(container, intent) def source_volume_digest(volume): return run("/usr/bin/sudo", "/usr/bin/python3", TRUSTED_MANIFEST, - volume["Mountpoint"], capture=True) + source_namespace_path(volume["Mountpoint"]), capture=True) def current_source_volume_digests(container): @@ -869,8 +1600,11 @@ def seal_quiesced_source_volumes(container, intent): def validate_source_volume(container, volume): name = container["Name"].lstrip("/") + mountpoint = volume.get("Mountpoint") if (volume.get("Driver") != "local" or volume.get("Options") or - VOLUME_LABEL in (volume.get("Labels") or {})): + VOLUME_LABEL in (volume.get("Labels") or {}) or + not isinstance(mountpoint, str) or not mountpoint.startswith("/") or + ".." in PurePosixPath(mountpoint).parts or str(PurePosixPath(mountpoint)) != mountpoint): raise ValueError(f"{name}: custom volume configuration requires an explicit transfer") @@ -1007,6 +1741,18 @@ def begin_quiesce(container, intent): def restore_source(identity, validator=validate): current = inspect(SOURCE, "container", identity) validator(current) + if completion_path(identity).exists(): + try: + target = inspect(TARGET, "container", current["Name"].lstrip("/")) + except BaseException as error: + raise RuntimeError( + f'{current["Name"].lstrip("/")}: completion is durable; source recovery is disabled while the destination cannot be verified' + ) from error + if completed(current, target): + return + raise RuntimeError( + f'{current["Name"].lstrip("/")}: completion is durable but changed; inspect both engines' + ) intent = migration_intent(current) if intent is None: return @@ -1039,20 +1785,31 @@ def restore_source(identity, validator=validate): # restore this source without discarding the ownership needed to resume or # inspect those artifacts safely. if not intent["volumes"] and intent.get("destination") is None and not intent["start_attempted"]: + intent = retire_volume_event_window(planned, intent) + intent = cleanup_transfer_images(current, intent) clear_migration_intent(identity) -def quiesce(container, validator=validate): +def quiesce(container, source_nofile, validator=validate): container = refresh_source(container, validator) name = container["Name"].lstrip("/") if exists("container", name) and completed(container, inspect(TARGET, "container", name)): + intent = migration_intent(container) + if intent is not None: + if intent.get("volume_event") is not None: + remove_volume_event_marker(container, intent) + intent = release_transfer_image(container, intent) clear_migration_intent(container["Id"]) print(f"{name}: already migrated") return intent = migration_intent(container) planned = planned_source(container, intent) + if intent is not None and intent.get("volume_event") is None and not intent["volumes"]: + remove_volume_event_marker(planned, intent) if intent is None: - intent = record_migration_intent(container) + intent = record_migration_intent(container, source_nofile=source_nofile) + elif intent["source_nofile"] != source_nofile: + raise ValueError(f"{name}: source container file-limit defaults changed during migration") if intent["start_attempted"]: raise ValueError(f'{container["Name"].lstrip("/")}: destination start was attempted; inspect both engines') if intent.get("destination") is not None and intent["restore_started"]: @@ -1096,7 +1853,7 @@ def verify_resumable_migration(container, target, intent): raise ValueError(f"{name}: interrupted rootless destination changed; inspect both engines") if not target_never_started(target): raise ValueError(f"{name}: interrupted rootless destination may have run; inspect both engines") - verify_runtime(planned, intent["target_ownership"]) + verify_runtime(planned, intent["target_ownership"], intent["source_nofile"]) expected_volumes = {destination_volume(planned, mount): mount for mount in planned.get("Mounts", [])} @@ -1147,26 +1904,50 @@ def resume_verified_migration(container, target, intent): if event_window is not None: verify_volume_event_window(planned, intent, event_window, expected_volumes, target["Id"] if intent["target_running"] else None) - verify_runtime(planned, intent["target_ownership"]) - record_completion(source_after, state, intent["target_running"]) - clear_migration_intent(container["Id"]) + verified_target = verify_runtime(planned, intent["target_ownership"], intent["source_nofile"]) + completion_published = False + try: + record_completion(source_after, state, intent["target_running"], verified_target) + completion_published = True + if event_window is not None: + remove_volume_event_marker(planned, intent) + intent = release_transfer_image(source_after, intent) + clear_migration_intent(container["Id"]) + except BaseException: + if completion_published: + print(f"{name}: migration completed; transfer-image journal cleanup remains pending", file=sys.stderr) + raise print(f"{name}: completed the interrupted rootless Docker migration") -def migrate(container): +def migrate(container, source_nofile): container = refresh_source(container) name = container["Name"].lstrip("/") identity = container["Id"] intent = migration_intent(container) + if intent is not None and intent["source_nofile"] != source_nofile: + raise ValueError(f"{name}: source container file-limit defaults changed during migration") + planned_retry = planned_source(container, intent) if intent is not None else container + expected_retry_volumes = { + destination_volume(planned_retry, mount) for mount in planned_retry.get("Mounts", []) + } if exists("container", name): target = inspect(TARGET, "container", name) container = refresh_source(container) if completed(container, target): if intent is not None: + if intent.get("volume_event") is not None: + remove_volume_event_marker(container, intent) remove_volume_guard(container, intent) + intent = release_transfer_image(container, intent) clear_migration_intent(identity) print(f"{name}: already migrated") return + if intent is not None and intent.get("volume_event") is not None: + verify_volume_event_window(planned_retry, intent, intent["volume_event"], + expected_retry_volumes) + elif intent is not None and intent["volumes"]: + raise RuntimeError(f"{name}: interrupted destination volume event history is missing") if intent is not None and intent["start_attempted"]: raise ValueError(f"{name}: destination start was attempted; inspect both engines") if intent is None: @@ -1188,11 +1969,20 @@ def migrate(container): intent = record_destination_may_have_run(container, intent) raise ValueError(f"{name}: rootless destination name was replaced during recovery") if intent is not None: + if intent.get("volume_event") is None and not intent["volumes"]: + remove_volume_event_marker(planned_retry, intent) + if (intent.get("volume_event") is not None and + (exists("volume", intent["volume_event"]["name"]) or intent["volumes"])): + verify_volume_event_window(planned_retry, intent, intent["volume_event"], + expected_retry_volumes) + elif intent["volumes"]: + raise RuntimeError(f"{name}: interrupted destination volume event history is missing") try: remove_volume_guard(container, intent) except BaseException: intent = record_destination_may_have_run(container, intent) raise + intent = cleanup_transfer_images(container, intent) if intent is not None and intent["start_attempted"]: raise ValueError(f"{name}: destination start was attempted; inspect both engines") if completion_path(identity).exists(): @@ -1204,17 +1994,16 @@ def migrate(container): running = intent["target_running"] if intent is not None else bool(container["State"]["Running"]) created_id = None guard_id = None - event_window = None + event_window = intent.get("volume_event") if intent is not None else None image = None - image_committed = False - image_loaded = False start_attempted = False + completion_published = False verified_volumes = {} restart = planned["HostConfig"].get("RestartPolicy") or {} policy = restart_policy_argument(planned) try: if intent is None: - intent = record_migration_intent(container) + intent = record_migration_intent(container, source_nofile=source_nofile) expected_volume_names = {destination_volume(planned, mount) for mount in planned.get("Mounts", [])} if set(intent["volumes"]) - expected_volume_names: raise ValueError(f"{name}: interrupted destination volume inventory changed") @@ -1235,22 +2024,49 @@ def migrate(container): container = stopped_source intent = record_migration_intent(container, state, intent) intent = seal_quiesced_source_volumes(container, intent) + intent = deepcopy(intent) + intent["image"] = { + "tag": f'omarchy-rootless-docker-transfer:{intent["target_ownership"]}', + "source": None, + "target": None, + "target_preexisting": None, + } + intent = persist_migration_intent(container, intent) + image_record = transfer_image_record(intent) # Commit includes writable-layer changes and the exact image config. # Volume data is copied separately while the source container is stopped. - image = run(SOURCE, "commit", identity, capture=True) + image = run(SOURCE, "commit", identity, image_record["tag"], capture=True) if not re.fullmatch(r"sha256:[a-f0-9]{64}", image or ""): raise RuntimeError(f"{name}: Docker did not return a transferable committed image") - image_committed = True - if not exists("image", image): - pipe([SOURCE, "image", "save", image], [TARGET, "image", "load", "--quiet"]) - image_loaded = True - run(SOURCE, "image", "rm", image) - image_committed = False + source_image = inspect(SOURCE, "image", image_record["tag"]) + if source_image.get("Id") != image or not transfer_image_owned(source_image, image_record, SOURCE): + raise RuntimeError(f"{name}: source transfer image ownership could not be proven") + intent = update_transfer_image(container, intent, SOURCE, image) + image_record = transfer_image_record(intent) + target_preexisting = exists("image", image) + if not target_preexisting: + if exists("image", image_record["tag"]): + raise RuntimeError(f"{name}: destination transfer image tag already exists") + # Saving by tag keeps the unpredictable journal-owned identity in + # the archive. Saving by digest produces an untagged load that a + # fresh process cannot distinguish safely from an unrelated image. + pipe([SOURCE, "image", "save", image_record["tag"]], + [TARGET, "image", "load", "--quiet"]) + target_image = inspect(TARGET, "image", image_record["tag"]) + if (target_image.get("Id") != image_record["source"] or + not transfer_image_owned(target_image, image_record, TARGET)): + raise RuntimeError(f"{name}: destination transfer image ownership could not be proven") + image = target_image["Id"] + intent = update_target_transfer_image(container, intent, image, target_preexisting) + image_record = transfer_image_record(intent) + target_reference = image if target_preexisting else image_record["tag"] + remove_transfer_image(SOURCE, image_record) + intent = update_transfer_image(container, intent, SOURCE, None) arguments = [TARGET, "create", "--pull=never", "--name", name, "--label", f"{LABEL}={identity}", "--label", f'{OWNERSHIP_LABEL}={intent["target_ownership"]}', "--privileged=false", "--ipc=private", "--cgroupns=private", "--network=bridge", "--runtime", "runc"] - arguments += runtime_arguments(planned) + arguments += runtime_arguments(planned, intent["source_nofile"]) config = planned["Config"] if config.get("Hostname"): arguments += ["--hostname", config["Hostname"]] @@ -1268,6 +2084,9 @@ def migrate(container): for binding in bindings or []: arguments += ["--publish", f'127.0.0.1:{binding["HostPort"]}:{port}'] pending_volumes = {} + if expected_volume_names: + intent = ensure_volume_event_window(planned, intent, expected_volume_names) + event_window = intent["volume_event"] for mount in planned.get("Mounts", []): volume = inspect(SOURCE, "volume", mount["Name"]) validate_source_volume(container, volume) @@ -1297,7 +2116,7 @@ def migrate(container): if not mount.get("RW"): mount_arg += ",readonly" arguments += ["--mount", mount_arg] - arguments.append(image) + arguments.append(target_reference) if pending_volumes: guard_name = volume_guard_name(intent) guard_arguments = [ @@ -1315,7 +2134,7 @@ def migrate(container): if not mount.get("RW"): mount_arg += ",readonly" guard_arguments += ["--mount", mount_arg] - guard_arguments.append(image) + guard_arguments.append(target_reference) run(*guard_arguments) guard = inspect(TARGET, "container", guard_name) if (not re.fullmatch(r"[a-f0-9]{64}", guard.get("Id") or "") or @@ -1327,10 +2146,7 @@ def migrate(container): verify_volume_definition(volume, target, ownership) if set(volume_users(target)) != {guard_id}: raise RuntimeError(f"{name}: destination volume guard changed; retained it for inspection") - event_window = begin_volume_event_window(planned, intent) - intent = deepcopy(intent) - intent["volume_event"] = event_window - persist_migration_intent(container, intent) + verify_volume_event_window(planned, intent, event_window, set(pending_volumes)) for target, pending in pending_volumes.items(): volume, ownership, record = pending verify_volume_definition(volume, target, ownership) @@ -1362,13 +2178,14 @@ def migrate(container): guard = inspect(TARGET, "container", guard_id) if not volume_guard_owned(planned, guard, intent): raise RuntimeError(f"{name}: rootless volume guard changed or ran during transfer") + validate_target_policy() run(*arguments) target = inspect(TARGET, "container", name) if (not re.fullmatch(r"[a-f0-9]{64}", target.get("Id") or "") or not target_never_started(target) or not target_owned(planned, target, intent)): raise RuntimeError(f"{name}: rootless destination ownership could not be proven") created_id = target["Id"] - verify_runtime(planned, intent["target_ownership"]) + verify_runtime(planned, intent["target_ownership"], intent["source_nofile"]) for target_name, pending in pending_volumes.items(): volume, ownership, _record = pending verify_volume_definition(volume, target_name, ownership) @@ -1410,14 +2227,23 @@ def migrate(container): if event_window is not None: verify_volume_event_window(planned, intent, event_window, set(pending_volumes), created_id if running else None) - event_window = None - verify_runtime(planned, intent["target_ownership"]) - record_completion(source_after, state, bool(running)) + verified_target = verify_runtime(planned, intent["target_ownership"], intent["source_nofile"]) + record_completion(source_after, state, bool(running), verified_target) + completion_published = True + if event_window is not None: + remove_volume_event_marker(planned, intent) + intent = release_transfer_image(source_after, intent) clear_migration_intent(identity) print(f"{name}: migrated to rootless Docker; rootful copy retained for recovery") except BaseException: if intent is None: raise + # The receipt rename and directory fsync happen inside record_completion. + # A signal can arrive after that durable boundary but before the next + # Python assignment, so the file itself is the final authority. + if completion_published or completion_path(identity).exists(): + print(f"{name}: migration completed; transfer-image journal cleanup remains pending", file=sys.stderr) + raise if start_attempted: print(f"{name}: destination start was attempted; both copies were retained for recovery. " "Inspect rootless Docker before resuming the rootful copy or retrying migration.", file=sys.stderr) @@ -1461,13 +2287,6 @@ def migrate(container): except Exception: recovery_failed = True print(f"{name}: volume guard cleanup was not ownership-safe; retained it for inspection", file=sys.stderr) - try: - if event_window is not None: - remove_volume_event_marker(planned, intent) - event_window = None - except Exception: - recovery_failed = True - print(f"{name}: volume event marker cleanup was not ownership-safe; retained it for inspection", file=sys.stderr) if destination_may_have_run: try: intent["start_attempted"] = True @@ -1477,10 +2296,11 @@ def migrate(container): print(f"{name}: a rootless migration container may have run; both stores were retained for review", file=sys.stderr) raise recovery = [] - if image_loaded: - recovery.append((TARGET, "image", "rm", image)) - if image_committed: - recovery.append((SOURCE, "image", "rm", image)) + try: + intent = cleanup_transfer_images(container, intent) + except Exception: + recovery_failed = True + print(f"{name}: transfer image cleanup was not ownership-safe; retained it for inspection", file=sys.stderr) if intent["restart_disabled"] and restart.get("Name") != "no": recovery.append((SOURCE, "update", f"--restart={policy}", identity)) if running: @@ -1510,6 +2330,7 @@ def migrate(container): restored = inspect(SOURCE, "container", identity) if (bool(restored["State"]["Running"]) == bool(running) and snapshot_digest(restored) == snapshot_digest(planned)): + intent = retire_volume_event_window(planned, intent, volumes_absent=True) clear_migration_intent(identity) except Exception: pass @@ -1520,6 +2341,15 @@ def main(): if os.geteuid() == 0: raise ValueError("Run the migration as the desktop user; the destination is always rootless") os.environ.setdefault("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}") + if sys.argv[1:] == ["--check-target-policy"]: + validate_target_policy() + print("rootless Docker target policy verified") + return + if sys.argv[1:] == ["--cleanup-probes"]: + validate_source_daemon(daemon_security(SOURCE)) + validate_target_policy() + cleanup_nofile_probe() + return quiesce_all_mode = sys.argv[1:2] == ["--quiesce-all"] if quiesce_all_mode: if len(sys.argv) < 3: @@ -1527,6 +2357,8 @@ def main(): windows_identity = sys.argv[2] names = sys.argv[3:] validate_source_daemon(daemon_security(SOURCE)) + validate_target_policy() + source_nofile = source_default_nofile() containers = [inspect(SOURCE, "container", name) for name in names] volumes = set() blockers = [] @@ -1557,6 +2389,30 @@ def main(): blockers.append(str(error)) if blockers: raise ValueError("\n".join(blockers)) + source_nofiles = {} + for container in containers: + try: + source_nofiles[container["Id"]] = container_nofile( + container, source_nofile, intents[container["Id"]], + ) + except (ValueError, RuntimeError) as error: + blockers.append(str(error)) + target_limits = {(limits["soft"], limits["hard"]) + for limits in source_nofiles.values()} + for soft, hard in sorted(target_limits): + try: + validate_target_nofile({"soft": soft, "hard": hard}) + except (ValueError, RuntimeError, subprocess.CalledProcessError) as error: + blockers.append(str(error)) + windows_nofile = source_nofile + if windows is not None: + try: + windows_intent = migration_intent(windows) + windows_nofile = container_nofile(windows, source_nofile, windows_intent) + except (ValueError, RuntimeError) as error: + blockers.append(str(error)) + if blockers: + raise ValueError("\n".join(blockers)) if volumes: validate_trusted_manifest() for container in containers: @@ -1573,10 +2429,10 @@ def main(): try: for container in containers: quiesced.append((container["Id"], validate)) - quiesce(container) + quiesce(container, source_nofiles[container["Id"]]) if windows is not None: quiesced.append((windows["Id"], validate_windows_exception)) - quiesce(windows, validate_windows_exception) + quiesce(windows, windows_nofile, validate_windows_exception) except BaseException: for identity, validator in reversed(quiesced): try: @@ -1604,9 +2460,12 @@ def main(): check_completed = sys.argv[1:2] == ["--check-completed"] check_only = check_completed or sys.argv[1:2] == ["--check"] names = sys.argv[2:] if check_only else sys.argv[1:] + source_nofile = None if names: validate_source_daemon(daemon_security(SOURCE)) - validate_target_daemon(daemon_security(TARGET)) + validate_target_policy() + if not check_completed: + source_nofile = source_default_nofile() containers = [inspect(SOURCE, "container", name) for name in names] volumes = set() blockers = [] @@ -1630,6 +2489,23 @@ def main(): volumes.add(mount["Name"]) if blockers: raise ValueError("\n".join(blockers)) + source_nofiles = {} + if not check_completed: + for container in containers: + try: + source_nofiles[container["Id"]] = container_nofile( + container, source_nofile, intents[container["Id"]], + ) + except (ValueError, RuntimeError) as error: + blockers.append(str(error)) + for soft, hard in sorted({(limits["soft"], limits["hard"]) + for limits in source_nofiles.values()}): + try: + validate_target_nofile({"soft": soft, "hard": hard}) + except (ValueError, RuntimeError, subprocess.CalledProcessError) as error: + blockers.append(str(error)) + if blockers: + raise ValueError("\n".join(blockers)) if volumes: validate_trusted_manifest() for container in containers: @@ -1687,7 +2563,7 @@ def main(): if not check_only: try: for container in containers: - migrate(container) + migrate(container, source_nofiles[container["Id"]]) except BaseException: for container in reversed(containers): try: diff --git a/default/docker/rootless/rootful-listeners.py b/default/docker/rootless/rootful-listeners.py index 9c52e07d6bad..43c48206c745 100644 --- a/default/docker/rootless/rootful-listeners.py +++ b/default/docker/rootless/rootful-listeners.py @@ -4,6 +4,9 @@ import os from pathlib import Path import re +import socket +import stat +import struct import sys @@ -11,6 +14,33 @@ INTERNAL_UNIX_SOCKETS = re.compile( r"/(?:var/)?run/docker/(?:metrics\.sock|libnetwork/[a-f0-9]+\.sock)" ) +EXPECTED_DAEMON_CONFIG = { + "log-driver": "json-file", + "log-opts": {"max-size": "10m", "max-file": "5"}, + # The rootful bridge exposes systemd-resolved on its gateway. RootlessKit + # supplies the corresponding resolver inside the user network namespace. + "dns": ["172.17.0.1"], + "bip": "172.17.0.1/16", +} + + +def process_start_time(pid, proc=Path("/proc")): + try: + process_directory_time = (proc / str(pid)).stat().st_ctime + process_fields = (proc / str(pid) / "stat").read_text().rsplit(")", 1)[1].split() + start_ticks = int(process_fields[19]) + boot_line = next(line for line in (proc / "stat").read_text().splitlines() + if line.startswith("btime ")) + boot_time = int(boot_line.split()[1]) + ticks_per_second = os.sysconf("SC_CLK_TCK") + except (IndexError, OSError, StopIteration, ValueError) as error: + raise RuntimeError("rootful Docker process start time cannot be verified") from error + if start_ticks <= 0 or boot_time <= 0 or ticks_per_second <= 0: + raise RuntimeError("rootful Docker process start time is invalid") + # btime is reported at whole-second precision. The proc directory carries + # the kernel's finer process-creation timestamp, while the stat fields keep + # the check tied to the PID's start ticks rather than directory contents. + return max(process_directory_time, boot_time + start_ticks / ticks_per_second) def process_socket_inodes(pid, proc=Path("/proc")): @@ -32,9 +62,9 @@ def process_socket_inodes(pid, proc=Path("/proc")): return inodes -def unix_listeners(inodes, proc=Path("/proc")): +def unix_listeners(pid, inodes, proc=Path("/proc")): listeners = [] - for line in (proc / "net/unix").read_text().splitlines()[1:]: + for line in (proc / str(pid) / "net/unix").read_text().splitlines()[1:]: fields = line.split(maxsplit=7) if (len(fields) >= 7 and fields[3] == "00010000" and fields[4] == "0001" and fields[6] in inodes): @@ -42,18 +72,83 @@ def unix_listeners(inodes, proc=Path("/proc")): return listeners -def has_tcp_listener(inodes, proc=Path("/proc")): +def has_tcp_listener(pid, inodes, proc=Path("/proc")): for table in ("net/tcp", "net/tcp6"): - for line in (proc / table).read_text().splitlines()[1:]: + for line in (proc / str(pid) / table).read_text().splitlines()[1:]: fields = line.split() if len(fields) > 9 and fields[3] == "0A" and fields[9] in inodes: return True return False -def configured_hosts(pid, proc=Path("/proc"), filesystem=Path("/")): - arguments = (proc / str(pid) / "cmdline").read_bytes().split(b"\0") - arguments = [argument.decode() for argument in arguments if argument] +def trusted_configuration(pid, config_path, proc=Path("/proc"), filesystem=None, + trusted_uid=0): + if config_path != "/etc/docker/daemon.json": + raise RuntimeError("rootful Docker uses a custom configuration path") + root = Path(filesystem) if filesystem is not None else proc / str(pid) / "root" + try: + root_flags = os.O_RDONLY | os.O_DIRECTORY + if filesystem is not None: + root_flags |= os.O_NOFOLLOW + root_fd = os.open(root, root_flags) + except OSError as error: + raise RuntimeError("rootful Docker mount namespace cannot be opened safely") from error + descriptors = [root_fd] + try: + root_metadata = os.fstat(root_fd) + if (not stat.S_ISDIR(root_metadata.st_mode) or root_metadata.st_uid != trusted_uid or + root_metadata.st_mode & 0o022): + raise RuntimeError("rootful Docker mount namespace has an unsafe root") + parent_fd = root_fd + for component in ("etc", "docker"): + descriptor = os.open( + component, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=parent_fd, + ) + descriptors.append(descriptor) + metadata = os.fstat(descriptor) + if (not stat.S_ISDIR(metadata.st_mode) or metadata.st_uid != trusted_uid or + metadata.st_mode & 0o022): + raise RuntimeError("rootful Docker configuration has an unsafe parent") + parent_fd = descriptor + descriptor = os.open( + "daemon.json", os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW, dir_fd=parent_fd, + ) + descriptors.append(descriptor) + metadata = os.fstat(descriptor) + if (not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != trusted_uid or + metadata.st_mode & 0o022): + raise RuntimeError("rootful Docker daemon configuration is not trusted") + with os.fdopen(os.dup(descriptor), "r") as source: + configured = json.load(source) + latest = os.fstat(descriptor) + if ((latest.st_dev, latest.st_ino, latest.st_mode, latest.st_uid, + latest.st_gid, latest.st_size, latest.st_mtime_ns, latest.st_ctime_ns) != + (metadata.st_dev, metadata.st_ino, metadata.st_mode, metadata.st_uid, + metadata.st_gid, metadata.st_size, metadata.st_mtime_ns, metadata.st_ctime_ns)): + raise RuntimeError("rootful Docker daemon configuration changed while it was read") + except (OSError, json.JSONDecodeError) as error: + raise RuntimeError("rootful Docker daemon configuration cannot be read safely") from error + finally: + for descriptor in reversed(descriptors): + os.close(descriptor) + if metadata.st_ctime > process_start_time(pid, proc): + raise RuntimeError( + "rootful Docker configuration changed after the daemon started; restart Docker before migration" + ) + return configured + + +def daemon_configuration(pid, proc=Path("/proc"), filesystem=None, trusted_uid=0): + try: + arguments = (proc / str(pid) / "cmdline").read_bytes().split(b"\0") + arguments = [argument.decode() for argument in arguments if argument] + executable = os.readlink(proc / str(pid) / "exe") + except (FileNotFoundError, PermissionError, UnicodeDecodeError) as error: + raise RuntimeError("rootful Docker daemon process cannot be inspected") from error + if (not arguments or arguments[0] != "/usr/bin/dockerd" or + executable != "/usr/bin/dockerd"): + raise RuntimeError("rootful Docker does not use the packaged daemon executable") hosts = [] config_path = "/etc/docker/daemon.json" index = 1 @@ -73,35 +168,85 @@ def configured_hosts(pid, proc=Path("/proc"), filesystem=Path("/")): config_path = arguments[index] elif argument.startswith("--config-file="): config_path = argument.split("=", 1)[1] + elif argument == "--containerd": + index += 1 + if index >= len(arguments) or arguments[index] != "/run/containerd/containerd.sock": + raise RuntimeError("rootful Docker uses a custom containerd service") + elif argument.startswith("--containerd="): + if argument.split("=", 1)[1] != "/run/containerd/containerd.sock": + raise RuntimeError("rootful Docker uses a custom containerd service") + else: + # Daemon flags such as --init, --dns, and --default-ulimit can + # change a container without appearing in docker inspect. + raise RuntimeError(f"rootful Docker uses an unsupported daemon option: {argument}") index += 1 - path = filesystem / config_path.lstrip("/") - configured = json.loads(path.read_text()) if path.exists() else {} + configured = trusted_configuration(pid, config_path, proc, filesystem, trusted_uid) + if not isinstance(configured, dict): + raise RuntimeError("rootful Docker has an invalid daemon configuration") file_hosts = configured.get("hosts") or [] if not isinstance(file_hosts, list) or any(not isinstance(host, str) for host in file_hosts): raise RuntimeError("rootful Docker has an invalid hosts configuration") if hosts and file_hosts: raise RuntimeError("rootful Docker has conflicting host configuration") + workload_config = {key: value for key, value in configured.items() if key != "hosts"} + if workload_config != EXPECTED_DAEMON_CONFIG: + raise RuntimeError( + "rootful Docker has custom workload defaults; restore Omarchy's daemon.json or migrate containers explicitly" + ) return hosts or file_hosts or ["unix:///var/run/docker.sock"] -def verify(pid, proc=Path("/proc"), filesystem=Path("/")): +def configured_hosts(pid, proc=Path("/proc"), filesystem=None, trusted_uid=0): + return daemon_configuration(pid, proc, filesystem, trusted_uid) + + +def unix_peer_credentials(path): + connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + connection.connect(path) + payload = connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, + struct.calcsize("3i")) + except OSError as error: + raise RuntimeError("rootful Docker API endpoint cannot be identified") from error + finally: + connection.close() + return struct.unpack("3i", payload) + + +def verify(pid, proc=Path("/proc"), filesystem=None, trusted_uid=0, + peer_credentials=unix_peer_credentials): inodes = process_socket_inodes(pid, proc) - listeners = unix_listeners(inodes, proc) - hosts = configured_hosts(pid, proc, filesystem) + listeners = unix_listeners(pid, inodes, proc) + hosts = configured_hosts(pid, proc, filesystem, trusted_uid) safe_hosts = (["fd://"], ["unix:///run/docker.sock"], ["unix:///var/run/docker.sock"]) - if (hosts not in safe_hosts or has_tcp_listener(inodes, proc) or + if (hosts not in safe_hosts or has_tcp_listener(pid, inodes, proc) or listeners.count(EXPECTED_SOCKET) != 1 or any(path != EXPECTED_SOCKET and not INTERNAL_UNIX_SOCKETS.fullmatch(path) for path in listeners)): raise RuntimeError("rootful Docker has a custom API listener; remove it before automatic migration") + endpoint = f"/proc/{pid}/root{EXPECTED_SOCKET}" + peer_pid, peer_uid, _peer_gid = peer_credentials(endpoint) + # A daemon-created socket reports dockerd. A systemd-activated socket can + # report PID 1, whose root-owned endpoint is separately pinned to the + # verified docker.socket unit by the migration shell. + if peer_uid != 0 or peer_pid not in (1, pid): + raise RuntimeError("rootful Docker API endpoint belongs to a different process") + if peer_pid == 1: + try: + peer_executable = os.readlink(proc / "1/exe") + except OSError as error: + raise RuntimeError("rootful Docker socket activator cannot be identified") from error + if peer_executable != "/usr/lib/systemd/systemd": + raise RuntimeError("rootful Docker API endpoint has an unexpected socket activator") + return f"unix://{endpoint}" if __name__ == "__main__": if len(sys.argv) != 2 or not sys.argv[1].isdigit(): raise SystemExit("usage: rootful-listeners.py DOCKER_PID") try: - verify(int(sys.argv[1])) + print(verify(int(sys.argv[1]))) except (OSError, RuntimeError) as error: print(f"Rootful Docker listener verification failed: {error}", file=sys.stderr) raise SystemExit(1) from error diff --git a/default/docker/rootless/volume-manifest.py b/default/docker/rootless/volume-manifest.py index c6aa614d1e65..cfa887779ba1 100644 --- a/default/docker/rootless/volume-manifest.py +++ b/default/docker/rootless/volume-manifest.py @@ -1,6 +1,7 @@ """Fingerprint a quiesced volume, using the caller's numeric UID/GID namespace.""" import ctypes +from contextlib import contextmanager import hashlib import json import os @@ -9,81 +10,184 @@ import sys -def fingerprint(root): +@contextmanager +def pinned_root(root): + root = Path(root) + descriptor = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + info = os.fstat(descriptor) + current = root.lstat() + if (not stat.S_ISDIR(info.st_mode) or current.st_dev != info.st_dev or + current.st_ino != info.st_ino): + raise RuntimeError("volume root is not a stable directory") + yield descriptor, Path(f"/proc/self/fd/{descriptor}"), info.st_dev + finally: + os.close(descriptor) + + +def metadata_identity(info): + return ( + info.st_dev, info.st_ino, info.st_mode, info.st_uid, info.st_gid, + info.st_nlink, info.st_size, info.st_mtime_ns, info.st_ctime_ns, info.st_rdev, + ) + + +def object_identity(info): + return info.st_dev, info.st_ino, stat.S_IFMT(info.st_mode) + + +def descriptor_attributes(descriptor): + return [(name, os.getxattr(descriptor, name).hex()) + for name in sorted(os.listxattr(descriptor))] + + +def entry_attributes(parent_descriptor, name): + path = f"/proc/self/fd/{parent_descriptor}/{name}" + return [(attribute, os.getxattr(path, attribute, follow_symlinks=False).hex()) + for attribute in sorted(os.listxattr(path, follow_symlinks=False))] + + +def fingerprint_open(root_descriptor, root_device): digest = hashlib.sha256() hardlinks = {} - def visit(path, relative): - info = path.lstat() + def add_row(info, relative, attributes, contents=None, link=None): + if info.st_dev != root_device: + raise RuntimeError("volume contains a nested filesystem") # Unix sockets are transient process endpoints; tar does not copy them. if stat.S_ISSOCK(info.st_mode): return - attributes = [(name, os.getxattr(path, name, follow_symlinks=False).hex()) - for name in sorted(os.listxattr(path, follow_symlinks=False))] row = [str(relative), stat.S_IFMT(info.st_mode), stat.S_IMODE(info.st_mode), info.st_uid, info.st_gid, info.st_mtime_ns, attributes] if stat.S_ISREG(info.st_mode): - contents = hashlib.sha256() - with path.open('rb') as source: - for block in iter(lambda: source.read(1024 * 1024), b''): - contents.update(block) first_link = hardlinks.setdefault((info.st_dev, info.st_ino), str(relative)) - row += [info.st_size, contents.hexdigest(), first_link] + row += [info.st_size, contents, first_link] elif stat.S_ISLNK(info.st_mode): - row.append(os.readlink(path)) + row.append(link) elif stat.S_ISCHR(info.st_mode) or stat.S_ISBLK(info.st_mode): row.append(info.st_rdev) digest.update(json.dumps(row, ensure_ascii=True, separators=(',', ':')).encode() + b'\n') - if stat.S_ISDIR(info.st_mode): - for child in sorted(path.iterdir(), key=lambda item: item.name): - visit(child, relative / child.name) - visit(Path(root), Path('.')) + def visit_directory(descriptor, relative, info): + add_row(info, relative, descriptor_attributes(descriptor)) + names = sorted(os.listdir(descriptor)) + for name in names: + visit_entry(descriptor, name, relative / name) + if sorted(os.listdir(descriptor)) != names: + raise RuntimeError("volume changed while it was fingerprinted") + + def visit_entry(parent_descriptor, name, relative): + before = os.stat(name, dir_fd=parent_descriptor, follow_symlinks=False) + if before.st_dev != root_device: + raise RuntimeError("volume contains a nested filesystem") + if stat.S_ISDIR(before.st_mode): + descriptor = os.open( + name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, + dir_fd=parent_descriptor, + ) + try: + opened = os.fstat(descriptor) + if metadata_identity(opened) != metadata_identity(before): + raise RuntimeError("volume changed while it was fingerprinted") + visit_directory(descriptor, relative, opened) + finally: + os.close(descriptor) + elif stat.S_ISREG(before.st_mode): + descriptor = os.open( + name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, + dir_fd=parent_descriptor, + ) + try: + opened = os.fstat(descriptor) + if metadata_identity(opened) != metadata_identity(before) or not stat.S_ISREG(opened.st_mode): + raise RuntimeError("volume changed while it was fingerprinted") + contents = hashlib.sha256() + with os.fdopen(os.dup(descriptor), "rb") as source: + for block in iter(lambda: source.read(1024 * 1024), b''): + contents.update(block) + after_read = os.fstat(descriptor) + if metadata_identity(after_read) != metadata_identity(opened): + raise RuntimeError("volume changed while it was fingerprinted") + add_row(opened, relative, descriptor_attributes(descriptor), contents.hexdigest()) + finally: + os.close(descriptor) + else: + link = os.readlink(name, dir_fd=parent_descriptor) if stat.S_ISLNK(before.st_mode) else None + add_row(before, relative, entry_attributes(parent_descriptor, name), link=link) + after = os.stat(name, dir_fd=parent_descriptor, follow_symlinks=False) + if metadata_identity(after) != metadata_identity(before): + raise RuntimeError("volume changed while it was fingerprinted") + + root_info = os.fstat(root_descriptor) + visit_directory(root_descriptor, Path('.'), root_info) return digest.hexdigest() -def clear(root): - root = Path(root) - root_info = root.lstat() - if not stat.S_ISDIR(root_info.st_mode): - raise RuntimeError("volume root is not a directory") +def fingerprint(root): + with pinned_root(root) as (descriptor, _pinned, root_device): + return fingerprint_open(descriptor, root_device) - def remove(path): - info = path.lstat() - if info.st_dev != root_info.st_dev: - raise RuntimeError("volume contains a nested filesystem") - if stat.S_ISDIR(info.st_mode): - for child in path.iterdir(): - remove(child) - path.rmdir() - else: - path.unlink() - for child in root.iterdir(): - remove(child) +def archive(root): + with pinned_root(root) as (descriptor, pinned, root_device): + # Read the full tree through the descriptor before tar and reject any + # nested filesystem. tar keeps the same root pinned and independently + # refuses to cross a mount that appears during the copy. + fingerprint_open(descriptor, root_device) + os.set_inheritable(descriptor, True) + os.execvpe("/usr/bin/tar", [ + "/usr/bin/tar", "--format=pax", "--numeric-owner", "--sparse", + "--acls", "--xattrs", "--xattrs-include=*", "--one-file-system", + "-C", str(pinned), "-cpf", "-", ".", + ], {"PATH": "/usr/bin", "LC_ALL": "C"}) + + +def clear(root): + with pinned_root(root) as (root_descriptor, _pinned, root_device): + def remove(parent_descriptor, name): + info = os.stat(name, dir_fd=parent_descriptor, follow_symlinks=False) + if info.st_dev != root_device: + raise RuntimeError("volume contains a nested filesystem") + if stat.S_ISDIR(info.st_mode): + descriptor = os.open( + name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, + dir_fd=parent_descriptor, + ) + try: + opened = os.fstat(descriptor) + if metadata_identity(opened) != metadata_identity(info): + raise RuntimeError("volume changed while it was cleared") + for child in os.listdir(descriptor): + remove(descriptor, child) + finally: + os.close(descriptor) + current = os.stat(name, dir_fd=parent_descriptor, follow_symlinks=False) + if object_identity(current) != object_identity(info): + raise RuntimeError("volume changed while it was cleared") + os.rmdir(name, dir_fd=parent_descriptor) + else: + os.unlink(name, dir_fd=parent_descriptor) + + for child in os.listdir(root_descriptor): + remove(root_descriptor, child) def sync_filesystem(root): - root = Path(root) - info = root.lstat() - if not stat.S_ISDIR(info.st_mode): - raise RuntimeError("volume root is not a directory") - descriptor = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) - try: + with pinned_root(root) as (descriptor, _pinned, _root_device): libc = ctypes.CDLL(None, use_errno=True) if libc.syncfs(descriptor) != 0: error = ctypes.get_errno() raise OSError(error, os.strerror(error), root) - finally: - os.close(descriptor) if __name__ == '__main__': - if sys.argv[1:2] == ["--clear"] and len(sys.argv) == 3: + if sys.argv[1:2] == ["--archive"] and len(sys.argv) == 3: + archive(sys.argv[2]) + elif sys.argv[1:2] == ["--clear"] and len(sys.argv) == 3: clear(sys.argv[2]) elif sys.argv[1:2] == ["--sync"] and len(sys.argv) == 3: sync_filesystem(sys.argv[2]) elif len(sys.argv) == 2: print(fingerprint(sys.argv[1])) else: - raise SystemExit("usage: volume-manifest.py [--clear|--sync] ROOT") + raise SystemExit("usage: volume-manifest.py [--archive|--clear|--sync] ROOT") diff --git a/docs/rootless-docker.md b/docs/rootless-docker.md index d36794b30d1f..1d3298ec63ee 100644 --- a/docs/rootless-docker.md +++ b/docs/rootless-docker.md @@ -6,20 +6,22 @@ Omarchy runs ordinary development containers in a per-user rootless Docker daemo The user daemon is `docker.service` from `docker-rootless-extras`. It listens on `$XDG_RUNTIME_DIR/docker.sock`, stores engine data below `~/.local/share/docker`, and reads daemon configuration from `~/.config/docker/daemon.json`. `default/systemd/user-environment-generators/60-omarchy-rootless-docker` and `default/bash/env-bootstrap` export `DOCKER_HOST` only after `~/.local/state/omarchy/rootless-docker/enabled` exists. -The system daemon remains socket-activated for `omarchy-windows-vm`. Its vendor drop-in makes `/run/docker.sock` root-owned with mode `0600`, and migration verifies both the effective systemd socket properties and the daemon process's open sockets before and after connection revocation. A later administrator override, custom Unix listener, or TCP listener stops automatic migration. The Windows command always selects the protected socket explicitly after authenticating with `sudo` or `pkexec`; user Docker settings and `DOCKER_HOST` cannot redirect the privileged VM command. +The system daemon remains socket-activated for `omarchy-windows-vm`. Its vendor drop-in makes `/run/docker.sock` root-owned with mode `0600`, and migration verifies both the effective systemd socket properties and the daemon process's open sockets before and after connection revocation. A later administrator override, custom Unix listener, or TCP listener stops automatic migration. The verifier connects through dockerd's `/proc` mount namespace and checks the Unix peer before that exact endpoint is exported for every source command. The Windows command derives the same namespace-bound endpoint after authenticating with `sudo` or `pkexec`; user mounts, Docker settings, and `DOCKER_HOST` cannot redirect the privileged VM command. ## Fresh installs and additional users -The root setup allocates each account a nonoverlapping subordinate UID and GID range of at least 65,536 IDs and writes `/var/lib/omarchy/rootless-docker/enabled`. User finalization creates the private marker and daemon config, then first-run setup enables the rootless service only for that initialized account. Existing accounts follow the same order during migration; no global user-unit symlink can start Docker for another account before its subordinate IDs and daemon config exist. +The root setup allocates each account a nonoverlapping subordinate UID and GID range of at least 65,536 IDs and writes `/var/lib/omarchy/rootless-docker/enabled`. Existing ranges and new allocations must also exclude every UID or GID currently assigned through NSS, including root and high-numbered directory-service identities. The resolved account's own UID, primary GID, and supplementary groups remain reserved even when its NSS provider disables enumeration. The allocator also resolves every username or numeric owner found in either subordinate-ID file, so an owner visible in only one file still constrains both UID and GID allocation. The locked allocator rereads both files and NSS identities after `usermod` before accepting the result. User finalization creates the private marker and daemon config, then first-run setup enables the rootless service only for that initialized account. Existing accounts follow the same order during migration; no global user-unit symlink can start Docker for another account before its subordinate IDs and daemon config exist. The migration's machine-wide enabled marker is written only after the shared rootful inventory has migrated and `/run/docker.sock` has been restricted. When another account later runs the per-user migration, it initializes that account's rootless daemon and returns before inspecting the retained rootful recovery store. ## Existing-install migration -`migrations/1789164756.sh` installs the rootless runtime, allocates subordinate IDs, restarts and proves the rootless daemon with that account's configuration, secures any current account's Windows definition, restricts the old API socket to root, and preflights every rootful container. An existing Windows container is reconciled from the hardened Compose definition while a root-only, synchronized lifecycle record preserves whether it was running or stopped across interruption; the new runtime must use web protection and the current account's protected mount anchors. Only after those checks does the migration durably claim the machine-wide source inventory for that account. A container named `omarchy-windows` is exempt only when its image, Compose identity, devices, capabilities, ports, environment, and UID-bound mounts match Omarchy's managed VM. A blocker in any source prevents the batch from stopping its first container or assigning the migration owner. Compose, credentials, legacy-definition removal, owner selection, and machine completion are synchronized to disk before migration continues. +`migrations/1789164756.sh` installs the rootless runtime, allocates subordinate IDs, starts an inactive user daemon, and proves the daemon with that account's configuration before migrating the shared rootful store. An already active rootless daemon is validated in place and never restarted, so a custom-policy rejection or later destination collision leaves its existing workloads running. The migration then restricts and verifies the old API socket, secures any current account's Windows definition through the verified daemon namespace, and preflights every rootful container. The rootful daemon configuration is opened beneath `/proc/$pid/root` without following symlinks and must be a root-owned, non-writable regular file below trusted parents. It must predate the running process, and the active command line must select the packaged executable and standard config path; the same checks run again immediately before and after the mandatory daemon restart. The rootless daemon configuration is opened without following symlinks through its live dockerd mount namespace, must remain the same account-owned regular file throughout the read, and must predate that exact process. Its API socket must report that dockerd process and desktop UID as its peer. Every later target Docker command reconnects through `/proc/$pid/root`, and privileged volume work enters the same process's user and mount namespaces after rechecking its executable, start identity, and socket peer. The packaged executables, exact RootlessKit and dockerd arguments, fixed `/usr/bin` service `PATH`, and fixed `~/.config` configuration root must match Omarchy's known policies because Docker inspection does not expose defaults such as daemon-managed init, DNS, stop timeouts, or RootlessKit sandbox changes. The legacy rootful bridge resolver is deliberately translated to RootlessKit's namespace resolver; other daemon DNS policies require an explicit migration. An existing Windows container is reconciled from the hardened Compose definition while a root-only, synchronized lifecycle record preserves whether it was running or stopped across interruption; ambiguous Compose interpolation and unsupported legacy YAML escapes require the user to set the values explicitly. The new runtime must use web protection and the current account's protected mount anchors. Only after those checks does the migration durably claim the machine-wide source inventory for that account. A container named `omarchy-windows` is exempt only when its image, Compose identity, devices, capabilities, ports, environment, and UID-bound mounts match Omarchy's managed VM. A blocker in any source prevents the batch from stopping its first container or assigning the migration owner. Compose, credentials, the runtime directory hierarchy, legacy-definition removal, owner selection, and machine completion are synchronized to disk before migration continues. The automatic path accepts running or never-started containers with stock bridge networking, localhost-only unprivileged published ports, private local named volumes, supported resource limits, root users with Docker's default capability ceiling or stricter settings, numeric non-root image users that already drop every capability, and the stock runtime and namespace boundaries. It rejects already-exited containers whose historical exit state cannot be recreated without rerunning them, privileged containers, added capabilities, devices, host or shared mounts, named image users whose effective UID is ambiguous, numeric non-root image users whose capability ceiling cannot be reproduced exactly, custom networks, namespace sharing, custom runtimes, altered confinement, custom logging, reserved migration labels, and unknown nondefault host settings. -For each accepted container, the migrator stops the source cleanly and durably seals its source-volume fingerprints before rootful Docker is restarted to revoke existing clients. Every seal is checked again before the first destination transfer. The migrator commits the writable layer, transfers that image through Docker's native save/load format, and creates an unpredictable inert guard that pins every owned volume while contents and metadata are copied inside the RootlessKit user and mount namespace. The application container does not exist during that long copy. Copied volume filesystems are synchronized before completion metadata is published. After transfer, a stopped `runc` application container joins the guard on the verified volumes; the guard is removed only after Docker proves both references, and the application container must still be never-started before finalization. A unique volume event marker proves the daemon retained the complete transfer window; a transient mount by any other container or missing event history stops automatic finalization. The migrator verifies environment, application config, runtime, limits, capabilities, mounts, ports, restart policy, logging, volume fingerprints, and lifecycle before writing a receipt bound to full source and destination snapshots. If one transfer fails, every later source that the batch already quiesced is restored in reverse order. +For each accepted container, the migrator records the live init process's effective `nofile` limit when the source is running and uses a bounded source probe only for a never-started workload. It proves rootless Docker can reproduce every distinct limit before stopping the first source. The migrator then stops each source cleanly and durably seals its source-volume fingerprints before rootful Docker is restarted to revoke existing clients. Every seal is checked again before the first destination transfer. Source volume roots are resolved through dockerd's mount namespace; a root-owned helper requires a real directory, rejects nested filesystems, pins the directory descriptor, and uses descriptor-relative traversal for fingerprints, cleanup, and archive validation so a raced child symlink cannot escape the volume. The migrator journals an unpredictable image tag before committing the writable layer, records each source and destination image identity around Docker's native save/load transfer, and requires the loaded identity to equal the committed source before it cleans only copies that still prove ownership. A completed destination retains that tag as its exact image reference, while the source transfer copy is removed. Before the first owned destination volume can exist, the migrator durably journals and creates a unique event marker. The same event window remains active across recoverable failures and retained-volume retries, and its complete history is checked before retry cleanup, before retained data is cleared, and again before the completion receipt. A missing marker with retained volumes, a transient mount by another container, or incomplete daemon history stops automatic migration. The migrator creates an unpredictable inert guard that pins every owned volume while contents and metadata are copied inside the RootlessKit user and mount namespace. The application container does not exist during that long copy. Copied volume filesystems are synchronized before completion metadata is published. After transfer, a stopped `runc` application container joins the guard on the verified volumes; the guard is removed only after Docker proves both references, and the application container must still be never-started before finalization. The event marker is removed only after the completion receipt is durable. Temporary read-only, networkless, capability-free containers built only from root-owned host runtime files measure daemon defaults and target compatibility. Each probe is journaled before its image exists, uses an unpredictable reserved label and image tag, exits and auto-removes after a short bound, and is verified and cleared before the next source inventory if the prior process was interrupted. Container and image cleanup are attempted independently. The destination disables daemon-managed init explicitly and carries each workload's recorded limit so rootless Docker cannot silently widen or narrow it. The migrator verifies environment, application config, runtime, limits, capabilities, mounts, ports, restart policy, logging, volume fingerprints, and lifecycle before writing a receipt bound to full source and destination snapshots. If one transfer fails, every later source that the batch already quiesced is restored in reverse order. -Before the destination is first started, an error removes only the exact journal-owned destination container and restores the source. The first journal directory entry, each journal update, and each rename are synchronized before they can authorize mutation. Journal-owned volumes remain available for ownership verification; a retry attaches each verified volume to the stopped destination before emptying and copying the current stopped source again, so a concurrent name replacement, partial transfer, or later source deletion cannot damage unrelated data or leave stale entries. Resume requires Docker to prove that the destination has never started and to replay the persisted event window before starting it. Once a destination start has been attempted, automatic retry and source restoration stop for manual recovery because either side may contain new writes. A durable completion receipt takes precedence over a leftover journal if power fails between those two writes. Successful sources remain stopped with their restart policy disabled; they are retained in the rootful engine as recovery copies. +Immediately before publishing that completion receipt, the migrator re-inspects the exact destination returned by runtime verification and rejects any identity or snapshot change. + +Before the destination is first started, an error removes only the exact journal-owned destination container and restores the source. The first journal directory entry, each journal update, and each rename are synchronized before they can authorize mutation. Journal-owned volumes remain available for ownership verification; a retry attaches each verified volume to the stopped destination before emptying and copying the current stopped source again, so a concurrent name replacement, partial transfer, or later source deletion cannot damage unrelated data or leave stale entries. Resume requires Docker to prove that the destination has never started and to replay the persisted event window before starting it. Once a destination start has been attempted, automatic retry and source restoration stop for manual recovery because either side may contain new writes. Publishing the durable completion receipt is an irreversible phase: any later image-tag or journal cleanup failure retains the valid destination and is completed on retry. Successful sources remain stopped with their restart policy disabled; they are retained in the rootful engine as recovery copies. diff --git a/install/helpers/rootless-docker.sh b/install/helpers/rootless-docker.sh index b0ff2c797b42..4b608f5d4dbb 100644 --- a/install/helpers/rootless-docker.sh +++ b/install/helpers/rootless-docker.sh @@ -3,6 +3,7 @@ rootless_docker_ensure_subids() { /usr/bin/python3 - "$account" <<'PY' import fcntl +import grp import os import pwd import stat @@ -10,51 +11,142 @@ import subprocess import sys -account = pwd.getpwnam(sys.argv[1]) -if account.pw_uid == 0: - raise SystemExit("rootless Docker cannot be configured for root") +MAX_ID = 4294967295 +MIN_RANGE = 65536 -lock_path = "/run/lock/omarchy-rootless-docker-subids.lock" -fd = os.open(lock_path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) -with os.fdopen(fd, "w") as lock: - metadata = os.fstat(lock.fileno()) - if not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != 0 or metadata.st_mode & 0o022: - raise SystemExit(f"unsafe subordinate-ID lock: {lock_path}") - fcntl.flock(lock, fcntl.LOCK_EX) - for path, option in (("/etc/subuid", "--add-subuids"), ("/etc/subgid", "--add-subgids")): - ranges = [] +def read_ranges(path): + ranges = [] + try: + with open(path, encoding="utf-8") as source: + for number, line in enumerate(source, 1): + line = line.strip() + if not line or line.startswith("#"): + continue + try: + name, start, count = line.split(":") + start, count = int(start), int(count) + except ValueError as error: + raise SystemExit(f"cannot parse {path}:{number}") from error + if start < 0 or count <= 0 or start + count - 1 > MAX_ID: + raise SystemExit(f"invalid subordinate-ID range in {path}:{number}") + ranges.append((name, start, count)) + except FileNotFoundError: + pass + return ranges + + +def ranges_overlap(first_start, first_count, second_start, second_count): + return max(first_start, second_start) < min( + first_start + first_count, second_start + second_count + ) + + +def validate_ranges(path, ranges, assigned_ids): + for index, (name, start, count) in enumerate(ranges): + if any(start <= assigned < start + count for assigned in assigned_ids): + raise SystemExit(f"subordinate-ID range for {name} intersects a host identity in {path}") + if any(index != other_index and + ranges_overlap(start, count, other_start, other_count) + for other_index, (_other_name, other_start, other_count) in enumerate(ranges)): + raise SystemExit(f"overlapping subordinate-ID ranges in {path}") + + +def owned_ranges(account, ranges): + identities = {account.pw_name, str(account.pw_uid)} + return [(start, count) for name, start, count in ranges if name in identities] + + +def discovered_accounts(account, ranges): + accounts = {(account.pw_name, account.pw_uid): account} + for entry in pwd.getpwall(): + accounts[(entry.pw_name, entry.pw_uid)] = entry + for owner, _start, _count in ranges: try: - with open(path, encoding="utf-8") as source: - for number, line in enumerate(source, 1): - line = line.strip() - if not line or line.startswith("#"): - continue - try: - name, start, count = line.split(":") - start, count = int(start), int(count) - except ValueError as error: - raise SystemExit(f"cannot parse {path}:{number}") from error - if start < 0 or count <= 0 or start + count - 1 > 4294967295: - raise SystemExit(f"invalid subordinate-ID range in {path}:{number}") - ranges.append((name, start, count)) - except FileNotFoundError: + entry = pwd.getpwnam(owner) + accounts[(entry.pw_name, entry.pw_uid)] = entry + except KeyError: pass + if owner.isdecimal(): + try: + entry = pwd.getpwuid(int(owner)) + accounts[(entry.pw_name, entry.pw_uid)] = entry + except KeyError: + pass + return accounts.values() + + +def assigned_uids(account, ranges): + return {0, *(entry.pw_uid for entry in discovered_accounts(account, ranges))} + + +def assigned_gids(account, ranges): + assigned = {0, *(entry.gr_gid for entry in grp.getgrall())} + for entry in discovered_accounts(account, ranges): + assigned.add(entry.pw_gid) + assigned.update(os.getgrouplist(entry.pw_name, entry.pw_gid)) + return assigned - identities = {account.pw_name, str(account.pw_uid)} - owned = [(start, count) for name, start, count in ranges if name in identities] - for owned_start, owned_count in owned: - if any(other_name not in identities and - max(owned_start, other_start) < min(owned_start + owned_count, other_start + other_count) - for other_name, other_start, other_count in ranges): - raise SystemExit(f"overlapping subordinate-ID range for {account.pw_name} in {path}") - if any(count >= 65536 for _, count in owned): + +def include_ranges_from(ranges, other_path): + return [*ranges, *read_ranges(other_path)] + + +def available_range(ranges, assigned_ids): + blocked = [(start, start + count - 1) for _name, start, count in ranges] + blocked.extend((assigned, assigned) for assigned in assigned_ids if 0 <= assigned <= MAX_ID) + candidate = 100000 + for blocked_start, blocked_end in sorted(blocked): + if blocked_end < candidate: continue + if blocked_start >= candidate + MIN_RANGE: + break + candidate = blocked_end + 1 + if candidate + MIN_RANGE - 1 > MAX_ID: + raise SystemExit("no subordinate-ID range is available") + return candidate, candidate + MIN_RANGE - 1 + + +def ensure_range(account, path, option, assigned_ids, usermod="/usr/bin/usermod"): + ranges = read_ranges(path) + assigned = set(assigned_ids(ranges)) + validate_ranges(path, ranges, assigned) + owned = owned_ranges(account, ranges) + if any(count >= MIN_RANGE for _start, count in owned): + return + + start, end = available_range(ranges, assigned) + subprocess.run([usermod, option, f"{start}-{end}", account.pw_name], check=True) + updated = read_ranges(path) + validate_ranges(path, updated, set(assigned_ids(updated))) + owned = owned_ranges(account, updated) + if not any(count >= MIN_RANGE for _start, count in owned): + raise SystemExit(f"could not verify subordinate-ID allocation for {account.pw_name} in {path}") + + +def main(): + account = pwd.getpwnam(sys.argv[1]) + if account.pw_uid == 0: + raise SystemExit("rootless Docker cannot be configured for root") + + lock_path = "/run/lock/omarchy-rootless-docker-subids.lock" + fd = os.open(lock_path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, "w") as lock: + metadata = os.fstat(lock.fileno()) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != 0 or metadata.st_mode & 0o022: + raise SystemExit(f"unsafe subordinate-ID lock: {lock_path}") + fcntl.flock(lock, fcntl.LOCK_EX) + + ensure_range(account, "/etc/subuid", "--add-subuids", + lambda ranges: assigned_uids( + account, include_ranges_from(ranges, "/etc/subgid") + )) + ensure_range(account, "/etc/subgid", "--add-subgids", + lambda ranges: assigned_gids( + account, include_ranges_from(ranges, "/etc/subuid") + )) + - start = max([100000, *(range_start + count for _, range_start, count in ranges)]) - end = start + 65535 - if end > 4294967295: - raise SystemExit(f"no subordinate-ID range is available in {path}") - subprocess.run(["/usr/bin/usermod", option, f"{start}-{end}", account.pw_name], check=True) +main() PY } diff --git a/migrations/1789164756.sh b/migrations/1789164756.sh index eb68c512fa8f..478124ac0d59 100644 --- a/migrations/1789164756.sh +++ b/migrations/1789164756.sh @@ -29,6 +29,11 @@ if ! /usr/bin/flock -n "$migration_lock_fd"; then exit 1 fi +target_was_active=0 +if systemctl --user is-active --quiet docker.service; then + target_was_active=1 +fi + omarchy-pkg-add docker-rootless-extras rootlesskit slirp4netns fuse-overlayfs # Allocate a nonoverlapping subordinate-ID range before the rootless daemon can @@ -41,21 +46,43 @@ sudo /usr/bin/bash -euo pipefail -c ' ' bash "$migration_user" rootless_state="$HOME/.local/state/omarchy/rootless-docker" +machine_state=/var/lib/omarchy/rootless-docker +migrator="$OMARCHY_PATH/default/docker/rootless/migrate.py" +machine_migration_complete=0 +if sudo /usr/bin/test -f "$machine_state/enabled"; then + machine_migration_complete=1 +fi mkdir -p "$HOME/.config/docker" "$rootless_state" if [[ ! -e $HOME/.config/docker/daemon.json ]]; then install -m 0644 "$OMARCHY_PATH/config/docker/daemon.json" "$HOME/.config/docker/daemon.json" fi +# An active rootless daemon can already host unrelated development workloads. +# Prove its live policy before touching the unit when this account will migrate +# the shared rootful store; a rejected migration must not restart those apps. +if (( target_was_active == 1 && machine_migration_complete == 0 )); then + if ! /usr/bin/python3 "$migrator" --check-target-policy; then + echo "The active rootless Docker daemon is customized or changed. Its workloads were left running." >&2 + echo "Restore Omarchy's rootless daemon policy or migrate the rootful containers explicitly, then rerun." >&2 + exit 1 + fi +fi + systemctl --user daemon-reload # A global user-unit enablement would start this daemon for secondary accounts # before their subordinate IDs and per-user daemon config exist. Enable only -# this initialized account, clear any early start-limit failure, and restart so -# an already-running daemon consumes the just-installed configuration. +# this initialized account and clear any early start-limit failure. Preserve an +# existing daemon and its workloads; only start a daemon that was inactive. systemctl --user reset-failed docker.service systemctl --user enable docker.service -systemctl --user restart docker.service +if (( target_was_active == 0 )); then + systemctl --user start docker.service +fi target_host="unix://$XDG_RUNTIME_DIR/docker.sock" if ! /usr/bin/docker --host "$target_host" info >/dev/null; then + if (( target_was_active == 0 )); then + systemctl --user stop docker.service >/dev/null 2>&1 || true + fi echo "Rootless Docker did not start. Rootful Docker has not been changed." >&2 exit 1 fi @@ -63,8 +90,7 @@ fi # Completion of the shared rootful-store migration is machine-wide. Later # accounts only need their own rootless daemon and marker; they must never # inspect or claim the retained recovery copies owned by the first account. -machine_state=/var/lib/omarchy/rootless-docker -if sudo /usr/bin/test -f "$machine_state/enabled"; then +if (( machine_migration_complete == 1 )); then remove_legacy_docker_group touch "$rootless_state/enabled" chmod 0600 "$rootless_state/enabled" @@ -75,25 +101,32 @@ if sudo /usr/bin/test -f "$machine_state/enabled"; then exit 0 fi -# Migrate any legacy user-side definition, pin its data into the protected root -# anchors, and rewrite the credential-bearing Compose file to root:root 0600. -# An existing managed VM is recreated from that hardened definition while its -# running or stopped lifecycle is preserved. -/usr/bin/omarchy-windows-vm __migration-secure +# Recheck after any start and before the first rootful source operation. If this +# invocation started an incompatible daemon, restore its original inactive +# lifecycle rather than leaving an unexpected user service behind. +if ! /usr/bin/python3 "$migrator" --check-target-policy; then + if (( target_was_active == 0 )); then + systemctl --user stop docker.service >/dev/null 2>&1 || true + fi + echo "Rootless Docker does not match Omarchy's safe migration policy. Rootful Docker has not been changed." >&2 + exit 1 +fi sudo /usr/bin/systemctl daemon-reload -sudo /usr/bin/systemctl start docker.socket -source_host="unix:///run/docker.sock" +sudo /usr/bin/systemctl start docker.socket docker.service listener_verifier=/usr/share/omarchy/default/docker/rootless/rootful-listeners.py restrict_rootful_socket() { - local socket_owner - if sudo /usr/bin/test -S /run/docker.sock; then - sudo /usr/bin/setfacl -b /run/docker.sock - sudo /usr/bin/chown root:root /run/docker.sock - sudo /usr/bin/chmod 0600 /run/docker.sock + local main_pid socket_owner socket_path + main_pid=$(sudo /usr/bin/systemctl show docker.service --property MainPID --value) + [[ $main_pid =~ ^[1-9][0-9]*$ ]] || return 1 + socket_path="/proc/$main_pid/root/run/docker.sock" + if sudo /usr/bin/test -S "$socket_path"; then + sudo /usr/bin/setfacl -b "$socket_path" + sudo /usr/bin/chown root:root "$socket_path" + sudo /usr/bin/chmod 0600 "$socket_path" fi - socket_owner=$(sudo /usr/bin/stat -Lc '%u:%g:%a' /run/docker.sock) + socket_owner=$(sudo /usr/bin/stat -Lc '%u:%g:%a' "$socket_path") if [[ $socket_owner != "0:0:600" ]]; then echo "The rootful Docker socket could not be restricted to root. This migration remains pending." >&2 return 1 @@ -101,7 +134,7 @@ restrict_rootful_socket() { } verify_rootful_listeners() { - local main_pid verifier_mode + local main_pid verifier_mode verified_host if sudo /usr/bin/test -L "$listener_verifier" || ! sudo /usr/bin/test -f "$listener_verifier"; then echo "The packaged rootful Docker listener verifier is not trusted. This migration remains pending." >&2 return 1 @@ -112,7 +145,13 @@ verify_rootful_listeners() { return 1 fi main_pid=$(sudo /usr/bin/systemctl show docker.service --property MainPID --value) - sudo /usr/bin/python3 "$listener_verifier" "$main_pid" + verified_host=$(sudo /usr/bin/python3 "$listener_verifier" "$main_pid") || return 1 + if [[ ! $verified_host =~ ^unix:///proc/[1-9][0-9]*/root/run/docker\.sock$ ]]; then + echo "The packaged rootful Docker listener verifier returned an invalid endpoint." >&2 + return 1 + fi + source_host=$verified_host + export OMARCHY_ROOTFUL_DOCKER_HOST="$source_host" } verify_rootful_socket_unit() { @@ -133,12 +172,21 @@ verify_rootful_socket_unit() { # by the daemon restart after every workload has been safely quiesced below. restrict_rootful_socket verify_rootful_socket_unit -sudo /usr/bin/docker --host "$source_host" info >/dev/null verify_rootful_listeners +sudo /usr/bin/docker --host "$source_host" info >/dev/null remove_legacy_docker_group +# Migrate any legacy user-side definition, pin its data into the protected root +# anchors, and rewrite the credential-bearing Compose file to root:root 0600. +# An existing managed VM is recreated through dockerd's own mount namespace +# while its running or stopped lifecycle is preserved. +/usr/bin/omarchy-windows-vm __migration-secure + +# A killed runtime-limit probe is journaled before it starts and uses a bounded, +# auto-removing container. Clear any such verified probe before taking the +# machine-wide source inventory so it can never be mistaken for a workload. +/usr/bin/python3 "$migrator" --cleanup-probes docker_inventory=$(sudo /usr/bin/docker --host "$source_host" ps -a --no-trunc --format '{{.ID}} {{.Names}}' | sort) -migrator="$OMARCHY_PATH/default/docker/rootless/migrate.py" container_names=() windows_id="" while read -r container_id container_name; do @@ -224,6 +272,7 @@ fi # All source restart policies and lifecycle intent are durable before this # restart. Stopping the daemon closes rootful connections accepted before the # socket became root-only; those clients cannot reconnect afterward. +verify_rootful_listeners sudo /usr/bin/systemctl restart docker.service sudo /usr/bin/systemctl start docker.socket restrict_rootful_socket diff --git a/test/shell.d/rootless-docker-migration-test.sh b/test/shell.d/rootless-docker-migration-test.sh index 65443fc5ad3d..53cb5e75b6e4 100755 --- a/test/shell.d/rootless-docker-migration-test.sh +++ b/test/shell.d/rootless-docker-migration-test.sh @@ -5,11 +5,14 @@ source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" python3 - <<'PY' import copy +import io import importlib.util import json import os import re +import subprocess import sys +import tarfile import tempfile from pathlib import Path @@ -19,6 +22,7 @@ path = os.path.join(os.environ["ROOT"], "default/docker/rootless/migrate.py") spec = importlib.util.spec_from_file_location("rootless_docker_migration", path) migration = importlib.util.module_from_spec(spec) spec.loader.exec_module(migration) +os.environ["OMARCHY_ROOTFUL_DOCKER_HOST"] = "unix:///proc/4242/root/run/docker.sock" manifest_path = os.path.join(os.environ["ROOT"], "default/docker/rootless/volume-manifest.py") manifest_spec = importlib.util.spec_from_file_location("rootless_docker_volume_manifest", manifest_path) manifest = importlib.util.module_from_spec(manifest_spec) @@ -45,7 +49,117 @@ with tempfile.TemporaryDirectory() as directory: with open(os.path.join(volume, "durable"), "w") as output: output.write("new") manifest.sync_filesystem(volume) -print("ok - retained-volume reset removes stale entries without following symlinks") + archived = subprocess.run( + [sys.executable, manifest_path, "--archive", volume], + check=True, stdout=subprocess.PIPE, + ).stdout + with tarfile.open(fileobj=io.BytesIO(archived)) as archive: + assert sorted(archive.getnames()) == [".", "./durable"] + volume_link = os.path.join(directory, "volume-link") + os.symlink(volume, volume_link) + try: + manifest.fingerprint(volume_link) + except OSError: + pass + else: + raise AssertionError("a symlinked privileged volume root was accepted") +print("ok - volume helper pins real roots, stays on one filesystem, and archives through its descriptor") + +for operation in ("fingerprint", "clear"): + with tempfile.TemporaryDirectory() as directory: + volume = Path(directory) / "volume" + child = volume / "child" + displaced = volume / "displaced" + outside = Path(directory) / "outside" + child.mkdir(parents=True) + outside.mkdir() + (child / "inside").write_text("volume") + (outside / "keep").write_text("outside") + original_listdir = manifest.os.listdir + raced = False + + def race_child(descriptor): + global raced + resolved = Path(os.readlink(f"/proc/self/fd/{descriptor}")) if isinstance(descriptor, int) else None + if not raced and resolved == child: + raced = True + child.rename(displaced) + child.symlink_to(outside, target_is_directory=True) + return original_listdir(descriptor) + + manifest.os.listdir = race_child + try: + try: + getattr(manifest, operation)(volume) + except RuntimeError: + pass + else: + raise AssertionError(f"a raced child symlink passed privileged volume {operation}") + finally: + manifest.os.listdir = original_listdir + assert raced + assert (outside / "keep").read_text() == "outside" +print("ok - descriptor-relative volume traversal cannot follow raced child symlinks") + +with tempfile.TemporaryDirectory() as directory: + proc = Path(directory) / "proc" + config_home = "/home/test/.config" + config_dir = proc / "4242/root/home/test/.config/docker" + config_dir.mkdir(parents=True) + config = config_dir / "daemon.json" + config.write_text(json.dumps(migration.TARGET_DAEMON_CONFIG)) + config.chmod(0o600) + assert migration.target_config(proc, 4242, config_home, config.stat().st_ctime + 10) == \ + migration.TARGET_DAEMON_CONFIG + trusted = config.with_name("daemon.trusted.json") + config.rename(trusted) + config.symlink_to(trusted) + try: + migration.target_config(proc, 4242, config_home, trusted.stat().st_ctime + 10) + except ValueError: + pass + else: + raise AssertionError("a symlinked target daemon configuration was accepted") +print("ok - target daemon configuration is read from its mount namespace through a pinned file") + +with tempfile.TemporaryDirectory() as directory: + proc = Path(directory) + process = proc / "4242" + process.mkdir() + (process / "root/run/user/1000").mkdir(parents=True) + (process / "stat").write_text("4242 (dockerd) S " + " ".join(["0"] * 18) + " 98765\n") + (process / "exe").symlink_to("/usr/bin/dockerd") + identity = {"pid": 4242, "start": "98765", "runtime": "/run/user/1000"} + original_peer_credentials = migration.unix_peer_credentials + migration.unix_peer_credentials = lambda endpoint: (4242, os.getuid(), os.getgid()) + try: + pid, endpoint = migration.verified_target_daemon(identity, proc) + assert pid == 4242 + assert endpoint == str(process / "root/run/user/1000/docker.sock") + (process / "stat").write_text("4242 (dockerd) S " + " ".join(["0"] * 18) + " 98766\n") + try: + migration.verified_target_daemon(identity, proc) + except RuntimeError: + pass + else: + raise AssertionError("a restarted target daemon retained the previous migration authority") + finally: + migration.unix_peer_credentials = original_peer_credentials + +original_verified_target_daemon = migration.verified_target_daemon +migration.verified_target_daemon = lambda identity: (4242, "/proc/4242/root/run/user/1000/docker.sock") +try: + migration.TARGET_DAEMON_IDENTITY = {"verified": True} + assert migration.local_command([migration.TARGET, "info"])[1:3] == [ + "--host", "unix:///proc/4242/root/run/user/1000/docker.sock", + ] + assert migration.local_command(["target-namespace", "/usr/bin/true"])[5:] == [ + "4242", "/usr/bin/true", + ] +finally: + migration.verified_target_daemon = original_verified_target_daemon + migration.TARGET_DAEMON_IDENTITY = None +print("ok - every target command and namespace entry uses the verified dockerd identity") with tempfile.TemporaryDirectory() as directory: state_home = Path(directory) / "new-state-home" @@ -69,6 +183,212 @@ print("ok - first journal creation synchronizes the new state hierarchy into its source_security = ["name=seccomp,profile=builtin", "name=cgroupns"] target_security = ["name=seccomp,profile=builtin", "name=rootless", "name=cgroupns"] +source_nofile = {"soft": 65536, "hard": 524288} +assert migration.parse_nofile_limits( + "Limit Soft Limit Hard Limit Units\n" + "Max open files 65536 524288 files\n" +) == source_nofile +for invalid in ("", "Max open files unknown 524288 files", "Max open files 0 524288 files"): + try: + migration.parse_nofile_limits(invalid) + except ValueError: + pass + else: + raise AssertionError("an invalid source file-limit probe result passed") +probe_token = "a" * 64 +with tarfile.open(fileobj=io.BytesIO(migration.nofile_probe_rootfs(probe_token))) as archive: + names = archive.getnames() + assert "usr/bin/sleep" in names + assert f"omarchy-rootless-docker-probe/{probe_token}" in names +original_probe_rootfs = migration.nofile_probe_rootfs +original_subprocess_run = migration.subprocess.run +original_run = migration.run +original_inspect = migration.inspect +original_docker_inspect_optional = migration.docker_inspect_optional +original_token_hex = migration.secrets.token_hex +original_verified_target_daemon = migration.verified_target_daemon +probe_calls = [] +probe_objects = {"container": None, "image": None} + +class ImportResult: + stdout = ("sha256:" + "b" * 64).encode() + +def probe_run(*args, capture=False): + probe_calls.append(args) + if len(args) > 1 and args[0] in (migration.SOURCE, migration.TARGET) and args[1] == "run": + engine = args[0] + limits = source_nofile if engine == migration.TARGET else None + probe_objects["container"] = { + "Id": "c" * 64, + "Name": f"/omarchy-rootless-docker-nofile-{engine}-" + "d" * 64, + "Image": "sha256:" + "b" * 64, + "Path": "/usr/bin/sleep", + "Args": [str(migration.NOFILE_PROBE_SECONDS)], + "Config": { + "Image": "sha256:" + "b" * 64, + "Entrypoint": ["/usr/bin/sleep"], + "Cmd": [str(migration.NOFILE_PROBE_SECONDS)], + "Labels": {migration.NOFILE_PROBE_LABEL: "d" * 64}, + }, + "HostConfig": { + "AutoRemove": True, "NetworkMode": "none", "ReadonlyRootfs": True, + "Privileged": False, "CapDrop": ["ALL"], + "SecurityOpt": ["no-new-privileges"], "Binds": None, "Mounts": None, + "Ulimits": ([{"Name": "nofile", "Soft": limits["soft"], "Hard": limits["hard"]}] + if limits is not None else None), + "RestartPolicy": {"Name": "no", "MaximumRetryCount": 0}, + }, + "Mounts": [], + "State": {"Running": True, "Pid": 4242}, + } + return "c" * 64 + if args[:2] == ("/usr/bin/sudo", "/usr/bin/cat"): + return "Max open files 65536 524288 files" + if len(args) > 3 and args[0] in (migration.SOURCE, migration.TARGET) and args[1:4] == ("container", "rm", "-f"): + probe_objects["container"] = None + if len(args) > 2 and args[0] in (migration.SOURCE, migration.TARGET) and args[1:3] == ("image", "rm"): + probe_objects["image"] = None + return "" + +migration.nofile_probe_rootfs = lambda token: b"trusted-rootfs" +def probe_subprocess_run(*args, **kwargs): + command = args[0] + tag = command[-1] + probe_objects["image"] = { + "Id": "sha256:" + "b" * 64, + "RepoTags": [tag], + "RepoDigests": [], + } + return ImportResult() + +migration.subprocess.run = probe_subprocess_run +migration.run = probe_run +migration.inspect = lambda *args: probe_objects["container"] +migration.docker_inspect_optional = lambda engine, kind, identity: probe_objects[kind] +migration.secrets.token_hex = lambda length: "d" * (length * 2) +migration.verified_target_daemon = lambda identity: (4242, "/proc/4242/root/run/user/1000/docker.sock") +with tempfile.TemporaryDirectory() as directory: + previous_state_home = os.environ.get("XDG_STATE_HOME") + os.environ["XDG_STATE_HOME"] = directory + try: + assert migration.source_default_nofile() == source_nofile + migration.validate_target_nofile(source_nofile) + assert not migration.nofile_probe_path().exists() + finally: + if previous_state_home is None: + os.environ.pop("XDG_STATE_HOME", None) + else: + os.environ["XDG_STATE_HOME"] = previous_state_home + migration.nofile_probe_rootfs = original_probe_rootfs + migration.subprocess.run = original_subprocess_run + migration.run = original_run + migration.inspect = original_inspect + migration.docker_inspect_optional = original_docker_inspect_optional + migration.secrets.token_hex = original_token_hex + migration.verified_target_daemon = original_verified_target_daemon +probe_command = next(call for call in probe_calls if call[:2] == (migration.SOURCE, "run")) +target_probe_command = next(call for call in probe_calls if call[:2] == (migration.TARGET, "run")) +assert "--rm" in probe_command +assert probe_command[-1] == str(migration.NOFILE_PROBE_SECONDS) +assert target_probe_command[target_probe_command.index("--ulimit") + 1] == "nofile=65536:524288" +assert probe_calls[-2][:4] == (migration.TARGET, "container", "rm", "-f") +assert probe_calls[-1][:3] == (migration.TARGET, "image", "rm") +print("ok - source discovery and target compatibility use bounded, journaled nofile probes") + +with tempfile.TemporaryDirectory() as directory: + previous_state_home = os.environ.get("XDG_STATE_HOME") + os.environ["XDG_STATE_HOME"] = directory + token = "e" * 64 + record = { + "engine": migration.SOURCE, + "token": token, + "name": migration.NOFILE_PROBE_PREFIX + migration.SOURCE + "-" + token, + "tag": "omarchy-rootless-docker-nofile-source:" + token, + "image": "sha256:" + "f" * 64, + "limits": None, + } + migration.write_private_json(migration.nofile_probe_path(), record) + cleanup_calls = [] + owned_container = { + "Id": "1" * 64, "Name": "/" + record["name"], "Image": record["image"], + "Path": "/usr/bin/sleep", "Args": [str(migration.NOFILE_PROBE_SECONDS)], + "Config": { + "Image": record["image"], "Entrypoint": ["/usr/bin/sleep"], + "Cmd": [str(migration.NOFILE_PROBE_SECONDS)], + "Labels": {migration.NOFILE_PROBE_LABEL: token}, + }, + "HostConfig": { + "AutoRemove": True, "NetworkMode": "none", "ReadonlyRootfs": True, + "Privileged": False, "CapDrop": ["ALL"], + "SecurityOpt": ["no-new-privileges"], "Binds": None, "Mounts": None, + "RestartPolicy": {"Name": "no", "MaximumRetryCount": 0}, + }, + "Mounts": [], + } + owned_image = { + "Id": record["image"], "RepoTags": [record["tag"]], + "RepoDigests": [record["tag"].rsplit(":", 1)[0] + "@" + record["image"]], + } + objects = {"container": owned_container, "image": owned_image} + original_run = migration.run + original_docker_inspect_optional = migration.docker_inspect_optional + def interrupted_probe_inspect(engine, kind, identity): + return objects[kind] + def interrupted_probe_run(*args, capture=False): + cleanup_calls.append(args) + if args[:4] == (migration.SOURCE, "container", "rm", "-f"): + objects["container"] = None + elif args[:3] == (migration.SOURCE, "image", "rm"): + objects["image"] = None + return "" + migration.docker_inspect_optional = interrupted_probe_inspect + migration.run = interrupted_probe_run + try: + migration.cleanup_nofile_probe() + assert not migration.nofile_probe_path().exists() + finally: + migration.run = original_run + migration.docker_inspect_optional = original_docker_inspect_optional + if previous_state_home is None: + os.environ.pop("XDG_STATE_HOME", None) + else: + os.environ["XDG_STATE_HOME"] = previous_state_home +assert cleanup_calls[0][:4] == (migration.SOURCE, "container", "rm", "-f") +assert cleanup_calls[1][:3] == (migration.SOURCE, "image", "rm") +print("ok - the next migration safely removes a journaled interrupted nofile probe") + +with tempfile.TemporaryDirectory() as directory: + previous_state_home = os.environ.get("XDG_STATE_HOME") + os.environ["XDG_STATE_HOME"] = directory + migration.write_private_json(migration.nofile_probe_path(), record) + failed_cleanup_calls = [] + original_run = migration.run + original_docker_inspect_optional = migration.docker_inspect_optional + migration.docker_inspect_optional = lambda engine, kind, identity: ( + owned_container if kind == "container" else owned_image + ) + def failed_probe_run(*args, capture=False): + failed_cleanup_calls.append(args) + raise RuntimeError("injected cleanup failure") + migration.run = failed_probe_run + try: + try: + migration.cleanup_nofile_probe() + except RuntimeError: + pass + else: + raise AssertionError("failed probe cleanup was accepted") + assert migration.nofile_probe_path().exists() + finally: + migration.run = original_run + migration.docker_inspect_optional = original_docker_inspect_optional + if previous_state_home is None: + os.environ.pop("XDG_STATE_HOME", None) + else: + os.environ["XDG_STATE_HOME"] = previous_state_home +assert failed_cleanup_calls[0][:4] == (migration.SOURCE, "container", "rm", "-f") +assert failed_cleanup_calls[1][:3] == (migration.SOURCE, "image", "rm") +print("ok - a container cleanup failure cannot suppress the probe image cleanup attempt") migration.validate_source_daemon(source_security) migration.validate_target_daemon(target_security) for options in (None, [], ["name=rootless"], ["name=userns"], ["name=no-new-privileges"], @@ -88,12 +408,62 @@ for options in (None, [], source_security, target_security + ["name=apparmor"], pass else: raise AssertionError(f"destination was not proven rootless: {options}") -print("ok - migration pins known source confinement and proves the destination daemon is rootless") +runtime = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}" +config_home = str(Path.home() / ".config") +rootlesskit_arguments = [ + "rootlesskit", f"--state-dir={runtime}/dockerd-rootless", *migration.TARGET_ROOTLESSKIT_ARGUMENTS, +] +for configuration, daemon_arguments, rootless_arguments in ( + ({**migration.TARGET_DAEMON_CONFIG, "init": True}, ["dockerd"], rootlesskit_arguments), + ({**migration.TARGET_DAEMON_CONFIG, "dns": ["203.0.113.53"]}, ["dockerd"], rootlesskit_arguments), + ({**migration.TARGET_DAEMON_CONFIG, "default-ulimits": {"nofile": {"Soft": 64, "Hard": 64}}}, ["dockerd"], rootlesskit_arguments), + ({**migration.TARGET_DAEMON_CONFIG, "default-stop-timeout": 321}, ["dockerd"], rootlesskit_arguments), + (migration.TARGET_DAEMON_CONFIG, ["dockerd", "--init=true"], rootlesskit_arguments), + (migration.TARGET_DAEMON_CONFIG, ["dockerd"], [*rootlesskit_arguments[:-1], "--ipv6", rootlesskit_arguments[-1]]), +): + try: + migration.validate_target_daemon( + target_security, configuration, daemon_arguments, rootless_arguments, "/usr/bin", + config_home, + ) + except ValueError: + pass + else: + raise AssertionError("a hidden rootless daemon workload default passed preflight") +migration.validate_target_daemon( + target_security, migration.TARGET_DAEMON_CONFIG, ["dockerd"], rootlesskit_arguments, "/usr/bin", + config_home, +) +try: + migration.validate_target_daemon( + target_security, migration.TARGET_DAEMON_CONFIG, ["dockerd"], rootlesskit_arguments, + "/home/user/.local/bin:/usr/bin", + config_home, + ) +except ValueError: + pass +else: + raise AssertionError("a rootless daemon with a user-writable service PATH passed preflight") +try: + migration.validate_target_daemon( + target_security, migration.TARGET_DAEMON_CONFIG, ["dockerd"], rootlesskit_arguments, + "/usr/bin", "/tmp/custom-docker-config", + ) +except ValueError: + pass +else: + raise AssertionError("a rootless daemon with a custom config directory passed preflight") +print("ok - migration pins known daemon confinement and rejects hidden target workload defaults") +# Direct migration unit fixtures replace Docker with an event recorder. The +# daemon-policy parser is covered above and exercised end-to-end in Lab. +migration.validate_target_policy = lambda: None +migration.source_default_nofile = lambda: source_nofile +migration.validate_target_nofile = lambda limits: None container = { "Name": "/project-worker", "Id": "a" * 64, - "State": {"Running": True, "StartedAt": "start", "FinishedAt": "finish"}, + "State": {"Running": True, "Pid": 5151, "StartedAt": "start", "FinishedAt": "finish"}, "Config": { "Image": "local/project-worker:v1", "Hostname": "worker", "Domainname": "", "User": "1000", "Env": ["PRIVATE=not-logged"], "Labels": {"project": "fixture"}, @@ -119,7 +489,20 @@ container = { "Destination": "/data", "RW": True}], } assert migration.validate(container) == "project-worker" -arguments = migration.runtime_arguments(container) +actual_nofile = {"soft": 32768, "hard": 262144} +original_run = migration.run +original_inspect = migration.inspect +migration.run = lambda *args, **kwargs: ( + "Max open files 32768 262144 files" if args[:2] == ("/usr/bin/sudo", "/usr/bin/cat") else None +) +migration.inspect = lambda engine, kind, name: copy.deepcopy(container) +assert migration.container_nofile(container, source_nofile) == actual_nofile +assert migration.source_namespace_path("/proc/5151/limits") == \ + "/proc/4242/root/proc/5151/limits" +migration.run = original_run +migration.inspect = original_inspect +print("ok - running workloads use their live process file limit instead of a new daemon default") +arguments = migration.runtime_arguments(container, source_nofile) for flag, value in (("--pids-limit=64", None), ("--shm-size", "134217728"), ("--memory", "134217728"), ("--memory-swap", "268435456"), ("--cpus", "0.5"), ("--cap-drop", "ALL")): @@ -128,10 +511,12 @@ for flag, value in (("--pids-limit=64", None), ("--shm-size", "134217728"), else: assert arguments[arguments.index(flag) + 1] == value assert "--cap-add" not in arguments +assert "--init=false" in arguments +assert arguments[arguments.index("--ulimit") + 1] == "nofile=65536:524288" assert migration.destination_volume(container, container["Mounts"][0]) == "project-data" unlimited = copy.deepcopy(container) unlimited["HostConfig"]["PidsLimit"] = 0 -assert not any(argument.startswith("--pids-limit=") for argument in migration.runtime_arguments(unlimited)) +assert not any(argument.startswith("--pids-limit=") for argument in migration.runtime_arguments(unlimited, source_nofile)) modern_mount = copy.deepcopy(container) modern_mount["HostConfig"]["Binds"] = [] modern_mount["HostConfig"]["Mounts"] = [{ @@ -312,7 +697,7 @@ else: print("ok - only Omarchy's managed Windows runtime qualifies for the rootful exception") source_volume = {"Name": "project-data", "Driver": "local", "Options": None, - "Labels": {"project": "fixture"}} + "Labels": {"project": "fixture"}, "Mountpoint": "/source-volume"} sealed_container = copy.deepcopy(container) sealed_container["State"] = { "Status": "created", "Running": False, @@ -327,7 +712,7 @@ with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory migration.inspect = lambda engine, kind, name: copy.deepcopy(source_volume) migration.source_volume_digest = lambda volume: sealed_digest[0] - sealed_intent = migration.record_migration_intent(sealed_container) + sealed_intent = migration.record_migration_intent(sealed_container, source_nofile=source_nofile) sealed_intent = migration.seal_quiesced_source_volumes(sealed_container, sealed_intent) assert sealed_intent["source_volumes"] == {"project-data": "1" * 64} sealed_digest[0] = "2" * 64 @@ -384,8 +769,8 @@ except RuntimeError: pass else: raise AssertionError("an ambiguous destination-volume attachment passed validation") -real_remove_event_marker = migration.remove_volume_event_marker -migration.remove_volume_event_marker = lambda source, intent: None +real_verify_event_marker = migration.verify_volume_event_marker +migration.verify_volume_event_marker = lambda source, intent: None migration.run = lambda *args, **kwargs: "\n".join(( json.dumps({"Type": "volume", "Action": "create", "Actor": { "ID": "marker", "Attributes": {"driver": "local"}}}), @@ -394,7 +779,8 @@ migration.run = lambda *args, **kwargs: "\n".join(( )) try: migration.verify_volume_event_window( - container, {"target_ownership": "d" * 64}, + container, {"target_ownership": "d" * 64, + "volume_event": {"name": "marker", "since": "time"}}, {"name": "marker", "since": "time"}, {"project-data"}, "f" * 64, ) except RuntimeError: @@ -408,12 +794,174 @@ migration.run = lambda *args, **kwargs: "\n".join(( "ID": "project-data", "Attributes": {"container": "f" * 64}}}), )) migration.verify_volume_event_window( - container, {"target_ownership": "d" * 64}, + container, {"target_ownership": "d" * 64, + "volume_event": {"name": "marker", "since": "time"}}, {"name": "marker", "since": "time"}, {"project-data"}, "f" * 64, ) migration.run = real_run -migration.remove_volume_event_marker = real_remove_event_marker +migration.verify_volume_event_marker = real_verify_event_marker print("ok - volume event windows reject transient writers and require the intended mount") + +journal_event_source = {"Id": "b" * 64, "Name": "/journal-event-window"} +journal_event_intent = {"target_ownership": "a" * 64, "volume_event": None, "volumes": {}} +original_event_exists = migration.exists +original_event_run = migration.run +original_event_verify_marker = migration.verify_volume_event_marker +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + migration.exists = lambda kind, name: False + migration.verify_volume_event_marker = lambda source, intent: None + + def create_journaled_marker(*args, **kwargs): + saved = json.loads(migration.intent_path(journal_event_source["Id"]).read_text()) + assert saved["volume_event"]["name"] == migration.volume_event_marker_name(saved) + assert saved["volumes"] == {} + + migration.run = create_journaled_marker + journal_event_intent = migration.ensure_volume_event_window( + journal_event_source, journal_event_intent, {"journal-event-data"}, + ) + saved_event_intent = json.loads(migration.intent_path(journal_event_source["Id"]).read_text()) + assert saved_event_intent["volume_event"] == journal_event_intent["volume_event"] + missing_marker_intent = copy.deepcopy(journal_event_intent) + missing_marker_intent["volumes"]["journal-event-data"] = { + "source": "source-data", "ownership": "owned", + } + try: + migration.ensure_volume_event_window( + journal_event_source, missing_marker_intent, {"journal-event-data"}, + ) + except RuntimeError as error: + assert "marker disappeared" in str(error) + else: + raise AssertionError("a missing marker with a retained destination volume was recreated") +migration.exists = original_event_exists +migration.run = original_event_run +migration.verify_volume_event_marker = original_event_verify_marker +print("ok - event windows are durable before volume creation and missing retained markers fail closed") + +retry_event_source = copy.deepcopy(container) +retry_event_source["Id"] = "c" * 64 +retry_event_source["Name"] = "/retained-event-window" +retry_order = [] +original_retry_inspect = migration.inspect +original_retry_exists = migration.exists +original_retry_verify_window = migration.verify_volume_event_window +original_retry_remove_guard = migration.remove_volume_guard +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + retry_event_intent = migration.record_migration_intent( + retry_event_source, source_nofile={"soft": 1024, "hard": 4096}, + ) + retry_target = migration.destination_volume(retry_event_source, retry_event_source["Mounts"][0]) + retry_event_intent["volumes"][retry_target] = { + "source": retry_event_source["Mounts"][0]["Name"], + "ownership": migration.volume_identity(retry_event_source, retry_event_source["Mounts"][0]), + } + retry_event_intent["volume_event"] = { + "name": migration.volume_event_marker_name(retry_event_intent), + "since": "2026-09-12T00:00:00Z", + } + migration.persist_migration_intent(retry_event_source, retry_event_intent) + migration.inspect = lambda engine, kind, name: copy.deepcopy(retry_event_source) + migration.exists = lambda kind, name: False + + def reject_retry_event(source, intent, window, targets, allowed=None): + retry_order.append("verify-history") + raise RuntimeError("another container accessed a retained destination volume") + + migration.verify_volume_event_window = reject_retry_event + migration.remove_volume_guard = lambda source, intent: retry_order.append("remove-guard") + try: + migration.migrate(retry_event_source, {"soft": 1024, "hard": 4096}) + except RuntimeError as error: + assert "another container accessed" in str(error) + else: + raise AssertionError("a retained destination volume mount between retries was missed") + assert retry_order == ["verify-history"] +migration.inspect = original_retry_inspect +migration.exists = original_retry_exists +migration.verify_volume_event_window = original_retry_verify_window +migration.remove_volume_guard = original_retry_remove_guard +print("ok - retained volume event history is checked before retry cleanup") + +retire_source = copy.deepcopy(container) +retire_source["Id"] = "1" * 64 +retire_source["Name"] = "/retire-event-window" +original_retire_marker = migration.remove_volume_event_marker +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + retire_intent = migration.record_migration_intent( + retire_source, source_nofile={"soft": 1024, "hard": 4096}, + ) + retire_intent["volume_event"] = { + "name": migration.volume_event_marker_name(retire_intent), + "since": "2026-09-12T00:00:00Z", + } + retire_intent["volumes"]["retired-data"] = { + "source": "source-data", "ownership": "owned", + } + migration.persist_migration_intent(retire_source, retire_intent) + + def interrupt_after_marker_removal(source, intent): + raise KeyboardInterrupt + + migration.remove_volume_event_marker = interrupt_after_marker_removal + try: + migration.retire_volume_event_window(retire_source, retire_intent, volumes_absent=True) + except KeyboardInterrupt: + pass + else: + raise AssertionError("event retirement interruption was not injected") + retired = migration.migration_intent(retire_source) + assert retired["volume_event"] is None and retired["volumes"] == {} + migration.remove_volume_event_marker = lambda source, intent: None + retired = migration.retire_volume_event_window(retire_source, retired, volumes_absent=True) + migration.clear_migration_intent(retire_source["Id"]) + assert not migration.intent_path(retire_source["Id"]).exists() +migration.remove_volume_event_marker = original_retire_marker +print("ok - absent retained volumes are durably retired before event-marker removal") + +restore_retire_source = copy.deepcopy(container) +restore_retire_source["Id"] = "2" * 64 +restore_retire_source["Name"] = "/restore-retire-event-window" +original_restore_inspect = migration.inspect +original_restore_remove_marker = migration.remove_volume_event_marker +original_restore_clear_intent = migration.clear_migration_intent +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + restore_retire_intent = migration.record_migration_intent( + restore_retire_source, source_nofile={"soft": 1024, "hard": 4096}, + ) + restore_retire_intent["volume_event"] = { + "name": migration.volume_event_marker_name(restore_retire_intent), + "since": "2026-09-12T00:00:00Z", + } + migration.persist_migration_intent(restore_retire_source, restore_retire_intent) + migration.inspect = lambda engine, kind, name: copy.deepcopy(restore_retire_source) + marker_removals = [] + migration.remove_volume_event_marker = lambda source, intent: marker_removals.append(intent["volume_event"]) + + def interrupt_intent_clear(identity): + raise KeyboardInterrupt + + migration.clear_migration_intent = interrupt_intent_clear + try: + migration.restore_source(restore_retire_source["Id"]) + except KeyboardInterrupt: + pass + else: + raise AssertionError("restored-source cleanup interruption was not injected") + restored_retired = migration.migration_intent(restore_retire_source) + assert restored_retired["volume_event"] is None and restored_retired["volumes"] == {} + migration.clear_migration_intent = original_restore_clear_intent + migration.restore_source(restore_retire_source["Id"]) + assert not migration.intent_path(restore_retire_source["Id"]).exists() + assert marker_removals == [None, None] +migration.inspect = original_restore_inspect +migration.remove_volume_event_marker = original_restore_remove_marker +migration.clear_migration_intent = original_restore_clear_intent +print("ok - restored-source event cleanup resumes after marker removal interruption") reserved_source = copy.deepcopy(source_volume) reserved_source["Labels"][migration.VOLUME_LABEL] = "foreign" try: @@ -491,7 +1039,7 @@ target["State"] = { with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory migration.inspect = lambda engine, kind, name: copy.deepcopy(stopped if engine == migration.SOURCE else target) - migration.record_completion(stopped, stopped["State"], False) + migration.record_completion(stopped, stopped["State"], False, target) assert migration.validate(stopped) == "project-worker" assert migration.completed(stopped, target) stopped["RestartCount"] = 4 @@ -507,6 +1055,30 @@ with tempfile.TemporaryDirectory() as directory: assert not migration.completed(stopped, target) print("ok - completion receipts bind both immutable workload snapshots and lifecycle state") +receipt_source = copy.deepcopy(stopped) +receipt_target = copy.deepcopy(target) +receipt_target["State"] = { + "Status": "created", "Running": False, "StartedAt": "0001-01-01T00:00:00Z", + "FinishedAt": "0001-01-01T00:00:00Z", "ExitCode": 0, +} +verified_receipt_target = copy.deepcopy(receipt_target) +receipt_target["HostConfig"]["RestartPolicy"] = {"Name": "always", "MaximumRetryCount": 0} +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + migration.inspect = lambda engine, kind, name: copy.deepcopy( + receipt_source if engine == migration.SOURCE else receipt_target + ) + try: + migration.record_completion( + receipt_source, receipt_source["State"], False, verified_receipt_target, + ) + except RuntimeError as error: + assert "destination changed before completion" in str(error) + else: + raise AssertionError("a destination changed after runtime verification received a completion receipt") + assert not migration.completion_path(receipt_source["Id"]).exists() +print("ok - completion re-inspects the exact verified destination before publishing its receipt") + with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory overlap_original = copy.deepcopy(container) @@ -525,7 +1097,7 @@ with tempfile.TemporaryDirectory() as directory: "Status": "running", "Running": True, "StartedAt": "target-start", "FinishedAt": "0001-01-01T00:00:00Z", "ExitCode": 0, } - overlap_intent = migration.record_migration_intent(overlap_original) + overlap_intent = migration.record_migration_intent(overlap_original, source_nofile=source_nofile) overlap_intent = migration.record_migration_intent( overlap_source, overlap_source["State"], overlap_intent, restart_disabled=True, ) @@ -534,9 +1106,9 @@ with tempfile.TemporaryDirectory() as directory: migration.inspect = lambda engine, kind, name: copy.deepcopy( overlap_source if engine == migration.SOURCE else overlap_target ) - migration.record_completion(overlap_source, overlap_source["State"], True) + migration.record_completion(overlap_source, overlap_source["State"], True, overlap_target) migration.exists = lambda kind, name: kind == "container" and name == "project-worker" - migration.migrate(overlap_source) + migration.migrate(overlap_source, source_nofile) assert not migration.intent_path(overlap_source["Id"]).exists() migration.persist_migration_intent(overlap_source, overlap_intent) @@ -553,7 +1125,7 @@ restarted = copy.deepcopy(stopped) restarted["State"]["Running"] = True migration.inspect = lambda engine, kind, name: copy.deepcopy(restarted if engine == migration.SOURCE else target) try: - migration.record_completion(stopped, stopped["State"], False) + migration.record_completion(stopped, stopped["State"], False, target) except ValueError: pass else: @@ -565,7 +1137,7 @@ intent_source["Mounts"] = [] intent_source["HostConfig"]["Binds"] = [] with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory - intent = migration.record_migration_intent(intent_source) + intent = migration.record_migration_intent(intent_source, source_nofile=source_nofile) assert migration.migration_intent(intent_source) == intent stopped_intent_source = copy.deepcopy(intent_source) stopped_intent_source["State"] = { @@ -619,7 +1191,7 @@ with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory migration.inspect = quiesce_inspect migration.run = quiesce_run - migration.quiesce(quiesce_source) + migration.quiesce(quiesce_source, source_nofile) quiesced_intent = migration.migration_intent(quiesce_source) assert quiesced_intent["target_running"] is True assert quiesced_intent["restart_disabled"] is True @@ -636,7 +1208,7 @@ print("ok - batch quiesce durably disables restart and restores the exact source with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory - power_intent = migration.record_migration_intent(intent_source) + power_intent = migration.record_migration_intent(intent_source, source_nofile=source_nofile) power_intent = migration.record_migration_intent(intent_source, saved=power_intent, restart_disabled=True) power_intent["quiesce_started"] = True @@ -650,7 +1222,7 @@ with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory always_source = copy.deepcopy(intent_source) always_source["HostConfig"]["RestartPolicy"] = {"Name": "always", "MaximumRetryCount": 0} - always_intent = migration.record_migration_intent(always_source) + always_intent = migration.record_migration_intent(always_source, source_nofile=source_nofile) always_stopped = copy.deepcopy(always_source) always_stopped["State"] = { "Running": False, "StartedAt": "start", "FinishedAt": "restore-window", "ExitCode": 0, @@ -669,7 +1241,7 @@ quiesce_source = copy.deepcopy(intent_source) quiesce_calls = [] with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory - migration.quiesce(quiesce_source) + migration.quiesce(quiesce_source, source_nofile) artifact_intent = migration.migration_intent(quiesce_source) artifact_intent["volumes"]["retained-data"] = { "source": "source-data", "ownership": f'{quiesce_source["Id"]}:source-data:{"e" * 64}', @@ -681,19 +1253,92 @@ with tempfile.TemporaryDirectory() as directory: assert migration.migration_intent(quiesce_source)["volumes"] == artifact_intent["volumes"] print("ok - batch recovery retains ownership journals for interrupted destination artifacts") +transfer_source = copy.deepcopy(container) +transfer_source["Id"] = "2" * 64 +transfer_source["Name"] = "/interrupted-image-transfer" +transfer_source["Mounts"] = [] +transfer_source["HostConfig"]["Binds"] = [] +transfer_image_id = "sha256:" + "3" * 64 +transfer_cleanup_calls = [] +original_run = migration.run +original_docker_inspect_optional = migration.docker_inspect_optional +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + transfer_intent = migration.record_migration_intent( + transfer_source, source_nofile=source_nofile, + ) + transfer_tag = f'omarchy-rootless-docker-transfer:{transfer_intent["target_ownership"]}' + transfer_intent["image"] = { + "tag": transfer_tag, "source": transfer_image_id, "target": transfer_image_id, + "target_preexisting": False, + } + migration.persist_migration_intent(transfer_source, transfer_intent) + transfer_images = { + migration.SOURCE: { + "Id": transfer_image_id, "RepoTags": [transfer_tag], "RepoDigests": [], + }, + migration.TARGET: { + "Id": transfer_image_id, "RepoTags": [transfer_tag], "RepoDigests": [], + }, + } -def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image=False, replace_target=False): + def transfer_inspect_optional(engine, kind, identity): + image = transfer_images[engine] + if image is None or identity not in (image["Id"], *(image.get("RepoTags") or [])): + return None + return copy.deepcopy(image) + + def transfer_cleanup_run(*args, capture=False): + transfer_cleanup_calls.append(args) + if args[1:3] == ("image", "rm"): + transfer_images[args[0]] = None + return "" + + migration.docker_inspect_optional = transfer_inspect_optional + migration.run = transfer_cleanup_run + recovered_intent = migration.migration_intent(transfer_source) + migration.cleanup_transfer_images(transfer_source, recovered_intent) + assert transfer_cleanup_calls == [ + (migration.TARGET, "image", "rm", transfer_tag), + (migration.SOURCE, "image", "rm", transfer_tag), + ] + assert migration.migration_intent(transfer_source)["image"] is None +migration.run = original_run +migration.docker_inspect_optional = original_docker_inspect_optional +print("ok - a fresh process removes both journal-owned image copies after interrupted load") + + +def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image=False, + replace_target=False, completed_cleanup_failure=False, + wrong_loaded_image=False, completion_signal_window=False): + original_release_transfer_image = migration.release_transfer_image source = copy.deepcopy(container) source["Id"] = ("d" if after_start else "c") * 64 source["Name"] = "/post-start" if after_start else "/pre-start" source["Mounts"] = [] source["HostConfig"]["Binds"] = [] + if completed_cleanup_failure or completion_signal_window: + source["State"] = { + "Status": "created", "Running": False, "Pid": 0, + "StartedAt": "0001-01-01T00:00:00Z", + "FinishedAt": "0001-01-01T00:00:00Z", "ExitCode": 0, + } current_source = copy.deepcopy(source) current_target = None + image_id = "sha256:" + ("f" if after_start else "e") * 64 + transfer_tag = None + source_image = None + target_image = ({"Id": image_id, "RepoTags": ["existing/project:v1"], "RepoDigests": []} + if preexisting_image else None) calls = [] pipes = [] def fake_inspect(engine, kind, name): + if kind == "image": + image = source_image if engine == migration.SOURCE else target_image + if image is None or name not in (image["Id"], *(image.get("RepoTags") or [])): + raise migration.subprocess.CalledProcessError(1, ["docker", "inspect"]) + return copy.deepcopy(image) if engine == migration.SOURCE: return copy.deepcopy(current_source) if current_target is None: @@ -701,12 +1346,13 @@ def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image return copy.deepcopy(current_target) def fake_run(*args, **kwargs): - nonlocal current_target + nonlocal current_target, source_image, target_image, transfer_tag calls.append(args) if args[:2] == (migration.SOURCE, "stop"): - current_source["State"] = { - "Running": False, "StartedAt": "start", "FinishedAt": "finish", "ExitCode": 0, - } + if current_source["State"]["Running"]: + current_source["State"] = { + "Running": False, "StartedAt": "start", "FinishedAt": "finish", "ExitCode": 0, + } if mutate_source: current_source["HostConfig"]["Memory"] += 4096 elif args[:2] == (migration.SOURCE, "update"): @@ -718,14 +1364,30 @@ def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image elif args[:2] == (migration.SOURCE, "start"): current_source["State"]["Running"] = True elif args[:2] == (migration.SOURCE, "commit"): - return "sha256:" + ("f" if after_start else "e") * 64 + pending = migration.migration_intent(current_source)["image"] + transfer_tag = args[3] + assert pending == { + "tag": transfer_tag, "source": None, "target": None, + "target_preexisting": None, + } + source_image = {"Id": image_id, "RepoTags": [transfer_tag], "RepoDigests": []} + return image_id + elif args[:3] == (migration.SOURCE, "image", "rm"): + source_image = None + elif args[:3] == (migration.TARGET, "image", "rm"): + if current_target is not None and target_image is not None and args[3] == transfer_tag: + target_image["RepoTags"] = [] + else: + target_image = None elif args[:2] == (migration.TARGET, "create"): labels = {} for index, argument in enumerate(args): if argument == "--label": key, value = args[index + 1].split("=", 1) labels[key] = value - current_target = {"Id": "b" * 64, "Config": {"Labels": labels}, + current_target = {"Id": "b" * 64, "Image": image_id, + "Config": {"Labels": labels, "Image": ( + image_id if preexisting_image else transfer_tag)}, "State": {"Status": "created", "Running": False, "StartedAt": "0001-01-01T00:00:00Z", "FinishedAt": "0001-01-01T00:00:00Z"}} @@ -739,38 +1401,64 @@ def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image migration.exists = lambda kind, name: ( (kind == "container" and current_target is not None and name in (current_target.get("Id"), current_target.get("Name", "").lstrip("/"))) or - (preexisting_image and kind == "image") + (kind == "image" and target_image is not None and + name in (target_image["Id"], *(target_image.get("RepoTags") or []))) ) - migration.pipe = lambda producer, consumer: pipes.append((producer, consumer)) - if after_start: - migration.verify_runtime = lambda value, ownership=None: None + def fake_pipe(producer, consumer): + nonlocal target_image + pipes.append((producer, consumer)) + loaded_id = "sha256:" + "7" * 64 if wrong_loaded_image else image_id + target_image = {"Id": loaded_id, "RepoTags": [transfer_tag], "RepoDigests": []} + migration.pipe = fake_pipe + def fake_inspect_optional(engine, kind, name): + try: + return fake_inspect(engine, kind, name) + except migration.subprocess.CalledProcessError: + return None + migration.docker_inspect_optional = fake_inspect_optional + if after_start or completed_cleanup_failure or completion_signal_window: + migration.verify_runtime = lambda value, ownership=None, source_nofile=None: copy.deepcopy(current_target) else: - def fail_verification(value, ownership=None): + def fail_verification(value, ownership=None, source_nofile=None): nonlocal current_target if replace_target: current_target = {"Id": "6" * 64, "Config": {"Labels": {}}, "State": {"Running": False}} raise RuntimeError("verification failed") migration.verify_runtime = fail_verification - migration.record_completion = lambda source, state, running: (_ for _ in ()).throw(RuntimeError("receipt failed")) + if completed_cleanup_failure: + migration.record_completion = lambda source, state, running, verified: None + migration.release_transfer_image = lambda source, intent: (_ for _ in ()).throw( + RuntimeError("journal cleanup failed") + ) + elif completion_signal_window: + def publish_then_interrupt(source, state, running, verified): + migration.write_private_json(migration.completion_path(source["Id"]), {"durable": True}) + raise KeyboardInterrupt + migration.record_completion = publish_then_interrupt + else: + migration.record_completion = lambda source, state, running, verified: (_ for _ in ()).throw(RuntimeError("receipt failed")) with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory try: - migration.migrate(source) - except RuntimeError: + migration.migrate(source, source_nofile) + except (RuntimeError, KeyboardInterrupt): pass else: raise AssertionError("failed transfer was reported as complete") intent_retained = migration.intent_path(source["Id"]).exists() + migration.release_transfer_image = original_release_transfer_image return calls, current_source, pipes, intent_retained calls, source, pipes, intent_retained = exercise_failed_transfer(False) create_call = next(call for call in calls if call[:2] == (migration.TARGET, "create")) assert create_call[create_call.index("--runtime") + 1] == "runc" +assert len(pipes) == 1 and pipes[0][0][-1].startswith("omarchy-rootless-docker-transfer:") assert (migration.TARGET, "rm", "--force", "b" * 64) in calls -assert (migration.TARGET, "image", "rm", "sha256:" + "e" * 64) in calls +assert any(call[:3] == (migration.TARGET, "image", "rm") and + call[3].startswith("omarchy-rootless-docker-transfer:") for call in calls) assert (migration.SOURCE, "stop", "-t", "300", "c" * 64) in calls assert (migration.SOURCE, "start", "c" * 64) in calls assert source["State"]["Running"] @@ -797,7 +1485,8 @@ print("ok - any destination start attempt retains both copies and keeps the sour calls, source, pipes, intent_retained = exercise_failed_transfer(False, preexisting_image=True) assert not pipes assert not any(call[:3] == (migration.TARGET, "image", "rm") for call in calls) -assert (migration.SOURCE, "image", "rm", "sha256:" + "e" * 64) in calls +assert any(call[:3] == (migration.SOURCE, "image", "rm") and + call[3].startswith("omarchy-rootless-docker-transfer:") for call in calls) print("ok - a preexisting target image digest is reused without claiming or deleting it") calls, source, pipes, intent_retained = exercise_failed_transfer(False, replace_target=True) @@ -806,6 +1495,28 @@ assert not source["State"]["Running"] assert intent_retained print("ok - a concurrently replaced destination is retained without restarting its rootful source") +calls, source, pipes, intent_retained = exercise_failed_transfer(False, wrong_loaded_image=True) +assert len(pipes) == 1 +assert not any(call[:2] == (migration.TARGET, "create") for call in calls) +assert (migration.SOURCE, "start", "c" * 64) in calls +print("ok - a loaded transfer tag must resolve to the committed source image ID") + +calls, source, pipes, intent_retained = exercise_failed_transfer( + False, completed_cleanup_failure=True, +) +assert not any(call[:3] == (migration.TARGET, "rm", "--force") for call in calls) +assert not any(call[:2] == (migration.SOURCE, "start") for call in calls) +assert intent_retained +print("ok - durable completion makes later journal cleanup non-destructive") + +calls, source, pipes, intent_retained = exercise_failed_transfer( + False, completion_signal_window=True, +) +assert not any(call[:3] == (migration.TARGET, "rm", "--force") for call in calls) +assert not any(call[:2] == (migration.SOURCE, "start") for call in calls) +assert intent_retained +print("ok - a signal after durable receipt publication cannot cross back into rollback") + retry_original = copy.deepcopy(container) retry_original["Id"] = "9" * 64 retry_original["Name"] = "/interrupted-retry" @@ -816,41 +1527,77 @@ retry_source["State"] = { "Running": False, "StartedAt": "start", "FinishedAt": "power-loss-stop", "ExitCode": 0, } retry_source["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} -retry_state = {"target": None} +retry_state = {"target": None, "source_image": None, "target_image": None, "tag": None} retry_calls = [] with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory - retry_intent = migration.record_migration_intent(retry_original) + retry_intent = migration.record_migration_intent(retry_original, source_nofile=source_nofile) retry_intent = migration.record_migration_intent(retry_original, retry_source["State"], retry_intent, restart_disabled=True) def retry_inspect(engine, kind, name): + if kind == "image": + key = "source_image" if engine == migration.SOURCE else "target_image" + image = retry_state[key] + if image is None or name not in (image["Id"], *(image.get("RepoTags") or [])): + raise migration.subprocess.CalledProcessError(1, ["docker", "inspect"]) + return copy.deepcopy(image) return copy.deepcopy(retry_source if engine == migration.SOURCE else retry_state["target"]) def retry_run(*args, **kwargs): retry_calls.append(args) if args[:2] == (migration.SOURCE, "commit"): - return "sha256:" + "8" * 64 + image_id = "sha256:" + "8" * 64 + retry_state["tag"] = args[3] + retry_state["source_image"] = { + "Id": image_id, "RepoTags": [retry_state["tag"]], "RepoDigests": [], + } + return image_id + if args[:3] == (migration.SOURCE, "image", "rm"): + retry_state["source_image"] = None + if args[:3] == (migration.TARGET, "image", "rm"): + if retry_state["target_image"] is not None and args[3] == retry_state["tag"]: + retry_state["target_image"]["RepoTags"] = [] + else: + retry_state["target_image"] = None if args[:2] == (migration.TARGET, "create"): labels = {} for index, argument in enumerate(args): if argument == "--label": key, value = args[index + 1].split("=", 1) labels[key] = value - retry_state["target"] = {"Id": "7" * 64, "Config": {"Labels": labels}, - "State": {"Status": "created", "Running": False, - "StartedAt": "0001-01-01T00:00:00Z", - "FinishedAt": "0001-01-01T00:00:00Z"}} + retry_state["target"] = { + "Id": "7" * 64, "Image": "sha256:" + "8" * 64, + "Config": {"Labels": labels, "Image": retry_state["tag"]}, + "State": {"Status": "created", "Running": False, + "StartedAt": "0001-01-01T00:00:00Z", + "FinishedAt": "0001-01-01T00:00:00Z"}, + } if args[:2] == (migration.TARGET, "start"): retry_state["target"]["State"]["Running"] = True migration.inspect = retry_inspect migration.run = retry_run - migration.exists = lambda kind, name: False - migration.pipe = lambda producer, consumer: None - migration.verify_runtime = lambda value, ownership=None: None - migration.record_completion = lambda source, state, running: None - migration.migrate(retry_source) + migration.exists = lambda kind, name: ( + kind == "image" and retry_state["target_image"] is not None and + name in (retry_state["target_image"]["Id"], + *(retry_state["target_image"].get("RepoTags") or [])) + ) + def retry_pipe(producer, consumer): + retry_state["target_image"] = { + "Id": "sha256:" + "8" * 64, + "RepoTags": [retry_state["tag"]], "RepoDigests": [], + } + def retry_inspect_optional(engine, kind, name): + try: + return retry_inspect(engine, kind, name) + except migration.subprocess.CalledProcessError: + return None + migration.pipe = retry_pipe + migration.docker_inspect_optional = retry_inspect_optional + migration.verify_runtime = lambda value, ownership=None, source_nofile=None: copy.deepcopy(retry_state["target"]) + migration.record_completion = lambda source, state, running, verified: None + migration.migrate(retry_source, source_nofile) create_call = next(call for call in retry_calls if call[:2] == (migration.TARGET, "create")) assert create_call[create_call.index("--restart") + 1] == "unless-stopped" assert (migration.TARGET, "start", "interrupted-retry") in retry_calls @@ -864,7 +1611,7 @@ resume_target["State"]["Running"] = False resume_calls = [] with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory - resume_intent = migration.record_migration_intent(resume_original) + resume_intent = migration.record_migration_intent(resume_original, source_nofile=source_nofile) resume_intent = migration.record_migration_intent(resume_source, resume_source["State"], resume_intent, restart_disabled=True) resume_target["Config"]["Labels"][migration.OWNERSHIP_LABEL] = resume_intent["target_ownership"] @@ -883,8 +1630,8 @@ with tempfile.TemporaryDirectory() as directory: migration.inspect = resume_inspect migration.run = resume_run - migration.verify_runtime = lambda value, ownership=None: None - migration.record_completion = lambda source, state, running: None + migration.verify_runtime = lambda value, ownership=None, source_nofile=None: copy.deepcopy(resume_target) + migration.record_completion = lambda source, state, running, verified: None unexpected_running = copy.deepcopy(resume_target) unexpected_running["State"]["Running"] = True try: @@ -929,7 +1676,7 @@ with tempfile.TemporaryDirectory() as directory: raise AssertionError("post-start recovery restarted the rootful source") assert not resume_source["State"]["Running"] try: - migration.migrate(resume_source) + migration.migrate(resume_source, source_nofile) except ValueError: pass else: @@ -951,9 +1698,10 @@ receipt_events = [] original_verify_resumable = migration.verify_resumable_migration original_verify_event_window = migration.verify_volume_event_window original_record_completion = migration.record_completion +original_remove_event_marker = migration.remove_volume_event_marker with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory - receipt_intent = migration.record_migration_intent(receipt_source) + receipt_intent = migration.record_migration_intent(receipt_source, source_nofile=source_nofile) receipt_intent["volume_event"] = { "name": migration.volume_event_marker_name(receipt_intent), "since": "2026-09-12T00:00:00Z", @@ -968,8 +1716,9 @@ with tempfile.TemporaryDirectory() as directory: migration.verify_volume_event_window = lambda source, intent, window, targets, allowed=None: ( receipt_events.append((copy.deepcopy(window), set(targets), allowed)) ) + migration.remove_volume_event_marker = lambda source, intent: receipt_events.append("marker-removed") - def interrupt_receipt(source, state, running): + def interrupt_receipt(source, state, running, verified): assert migration.migration_intent(source)["volume_event"] == receipt_intent["volume_event"] raise RuntimeError("power loss before receipt") @@ -981,14 +1730,44 @@ with tempfile.TemporaryDirectory() as directory: else: raise AssertionError("an interrupted completion unexpectedly removed its event window") assert migration.migration_intent(receipt_source)["volume_event"] == receipt_intent["volume_event"] - migration.record_completion = lambda source, state, running: None + receipt_target["Config"]["Labels"][migration.LABEL] = receipt_source["Id"] + + def publish_receipt(source, state, running, verified): + migration.write_private_json(migration.completion_path(source["Id"]), { + "target": receipt_target["Id"], + "source": migration.stopped_identity(state), + "target_running": running, + "source_snapshot": migration.snapshot_digest(source), + "target_snapshot": migration.snapshot_digest(receipt_target), + }) + + original_release_transfer_image = migration.release_transfer_image + migration.record_completion = publish_receipt + migration.release_transfer_image = lambda source, intent: (_ for _ in ()).throw( + RuntimeError("cleanup after resumed receipt") + ) + before_recovery_calls = len(resume_calls) + try: + migration.resume_verified_migration(receipt_source, receipt_target, receipt_intent) + except RuntimeError as error: + assert str(error) == "cleanup after resumed receipt" + else: + raise AssertionError("resumed completion cleanup failure was accepted") + assert migration.completion_path(receipt_source["Id"]).exists() + migration.restore_source(receipt_source["Id"]) + assert len(resume_calls) == before_recovery_calls + migration.completion_path(receipt_source["Id"]).unlink() + migration.release_transfer_image = original_release_transfer_image + migration.record_completion = lambda source, state, running, verified: None migration.resume_verified_migration(receipt_source, receipt_target, receipt_intent) - assert len(receipt_events) == 2 + assert receipt_events.count("marker-removed") == 2 + assert len([event for event in receipt_events if event != "marker-removed"]) == 3 assert not migration.intent_path(receipt_source["Id"]).exists() migration.verify_resumable_migration = original_verify_resumable migration.verify_volume_event_window = original_verify_event_window migration.record_completion = original_record_completion -print("ok - an interrupted receipt retains and replays the destination volume event window") +migration.remove_volume_event_marker = original_remove_event_marker +print("ok - interrupted and published resumed receipts retain their safe recovery state") for unsafe_kind in ("destination", "guard"): unsafe_original = copy.deepcopy(retry_original) @@ -1002,7 +1781,7 @@ for unsafe_kind in ("destination", "guard"): unsafe_source["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory - unsafe_intent = migration.record_migration_intent(unsafe_original) + unsafe_intent = migration.record_migration_intent(unsafe_original, source_nofile=source_nofile) unsafe_intent = migration.record_migration_intent( unsafe_source, unsafe_source["State"], unsafe_intent, restart_disabled=True, ) @@ -1028,7 +1807,7 @@ for unsafe_kind in ("destination", "guard"): migration.inspect = unsafe_inspect migration.exists = lambda kind, name: kind == "container" and name == unsafe_name try: - migration.migrate(unsafe_source) + migration.migrate(unsafe_source, source_nofile) except ValueError: pass else: @@ -1053,10 +1832,18 @@ source_volume = { target_volume = None pinned_target = None pinned_guard = None +pin_source_image = None +pin_target_image = None +pin_transfer_tag = None pin_events = [] def pin_inspect(engine, kind, name): + if kind == "image": + image = pin_source_image if engine == migration.SOURCE else pin_target_image + if image is None or name not in (image["Id"], *(image.get("RepoTags") or [])): + raise migration.subprocess.CalledProcessError(1, ["docker", "inspect"]) + return copy.deepcopy(image) if engine == migration.SOURCE and kind == "container": return copy.deepcopy(current_pinned_source) if engine == migration.SOURCE and kind == "volume": @@ -1073,6 +1860,7 @@ def pin_inspect(engine, kind, name): def pin_run(*args, **kwargs): global target_volume, pinned_target, pinned_guard + global pin_source_image, pin_target_image, pin_transfer_tag pin_events.append(args) if args[:2] == (migration.SOURCE, "update"): current_pinned_source["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} @@ -1082,7 +1870,19 @@ def pin_run(*args, **kwargs): "FinishedAt": "pinned-stop", "ExitCode": 0, } elif args[:2] == (migration.SOURCE, "commit"): - return "sha256:" + "4" * 64 + pin_transfer_tag = args[3] + pin_source_image = { + "Id": "sha256:" + "4" * 64, + "RepoTags": [pin_transfer_tag], "RepoDigests": [], + } + return pin_source_image["Id"] + elif args[:3] == (migration.SOURCE, "image", "rm"): + pin_source_image = None + elif args[:3] == (migration.TARGET, "image", "rm"): + if pin_target_image is not None and args[3] == pin_transfer_tag: + pin_target_image["RepoTags"] = [] + else: + pin_target_image = None elif args[:3] == (migration.TARGET, "volume", "create"): labels = {} for index, argument in enumerate(args): @@ -1102,7 +1902,8 @@ def pin_run(*args, **kwargs): created_name = args[args.index("--name") + 1] created = { "Id": ("8" if created_name.startswith("omarchy-volume-guard-") else "6") * 64, - "Name": f"/{created_name}", "Config": {"Labels": labels}, + "Name": f"/{created_name}", "Image": "sha256:" + "4" * 64, + "Config": {"Labels": labels, "Image": pin_transfer_tag}, "State": {"Status": "created", "Running": False, "StartedAt": "0001-01-01T00:00:00Z", "FinishedAt": "0001-01-01T00:00:00Z"}, @@ -1127,29 +1928,51 @@ def pin_run(*args, **kwargs): def pin_exists(kind, name): if kind == "volume": return target_volume is not None + if kind == "image": + return (pin_target_image is not None and + name in (pin_target_image["Id"], *(pin_target_image.get("RepoTags") or []))) return any(candidate is not None and name in (candidate["Id"], candidate["Name"].lstrip("/")) for candidate in (pinned_guard, pinned_target)) +original_pin_remove_event_marker = migration.remove_volume_event_marker with tempfile.TemporaryDirectory() as directory: os.environ["XDG_STATE_HOME"] = directory migration.inspect = pin_inspect migration.run = pin_run migration.exists = pin_exists - migration.pipe = lambda producer, consumer: pin_events.append(("pipe",)) - migration.verify_runtime = lambda value, ownership=None: None + def pin_pipe(producer, consumer): + global pin_target_image + pin_events.append(("pipe",)) + pin_target_image = { + "Id": "sha256:" + "4" * 64, + "RepoTags": [pin_transfer_tag], "RepoDigests": [], + } + def pin_inspect_optional(engine, kind, name): + try: + return pin_inspect(engine, kind, name) + except migration.subprocess.CalledProcessError: + return None + migration.pipe = pin_pipe + migration.docker_inspect_optional = pin_inspect_optional + migration.verify_runtime = lambda value, ownership=None, source_nofile=None: copy.deepcopy(pinned_target) migration.verify_volume = lambda target, digest: None migration.source_volume_digest = lambda volume: "7" * 64 migration.clear_volume = lambda target: pin_events.append(("clear", target)) migration.transfer_volume = lambda volume, target: (pin_events.append(("transfer", target)) or "7" * 64) - migration.begin_volume_event_window = lambda source, intent: ( - pin_events.append(("event-window-begin",)) or {"name": "marker", "since": "time"} - ) + def pin_event_window(source, intent, targets): + pin_events.append(("event-window-begin",)) + intent = copy.deepcopy(intent) + intent["volume_event"] = {"name": "marker", "since": "time"} + return intent + migration.ensure_volume_event_window = pin_event_window migration.verify_volume_event_window = lambda source, intent, window, targets, allowed=None: ( pin_events.append(("event-window-verify", tuple(sorted(targets)), allowed)) ) - migration.record_completion = lambda source, state, running: None - migration.migrate(pinned_source) + migration.remove_volume_event_marker = lambda source, intent: pin_events.append(("event-window-remove",)) + migration.record_completion = lambda source, state, running, verified: None + migration.migrate(pinned_source, source_nofile) +migration.remove_volume_event_marker = original_pin_remove_event_marker create_indexes = [index for index, event in enumerate(pin_events) if event[:2] == (migration.TARGET, "create")] @@ -1158,7 +1981,7 @@ guard_index, create_index = create_indexes clear_index = pin_events.index(("clear", "project-data")) transfer_index = pin_events.index(("transfer", "project-data")) event_begin_index = pin_events.index(("event-window-begin",)) -assert guard_index < event_begin_index < clear_index < transfer_index < create_index +assert event_begin_index < guard_index < clear_index < transfer_index < create_index guard_call = pin_events[guard_index] create_call = pin_events[create_index] assert "--network=none" in guard_call @@ -1171,10 +1994,12 @@ assert any(event[:3] == (migration.TARGET, "container", "ls") guard_remove_index = next(index for index, event in enumerate(pin_events) if event[:3] == (migration.TARGET, "rm", "--force") and event[3] == "8" * 64) start_index = pin_events.index((migration.TARGET, "start", "pinned-volume")) -event_verify = next(event for event in pin_events if event[:1] == ("event-window-verify",)) +event_verify = [event for event in pin_events if event[:1] == ("event-window-verify",)][-1] event_verify_index = pin_events.index(event_verify) assert create_index < guard_remove_index < start_index < event_verify_index assert event_verify[1:] == (("project-data",), "6" * 64) +assert ("event-window-verify", ("project-data",), None) in pin_events[guard_index:create_index] +assert event_verify_index < pin_events.index(("event-window-remove",)) sync_index = next(index for index, event in enumerate(pin_events) if event[:4] == ("target-namespace", "/usr/bin/python3", migration.TRUSTED_MANIFEST, "--sync")) assert transfer_index < sync_index < create_index @@ -1195,7 +2020,8 @@ with tempfile.TemporaryDirectory() as directory: migration.daemon_security = lambda engine: source_security if engine == migration.SOURCE else target_security migration.inspect = lambda engine, kind, name: copy.deepcopy(batch_by_name[name]) migration.exists = lambda kind, name: False - migration.migrate = lambda member: (_ for _ in ()).throw(RuntimeError("first transfer failed")) + migration.container_nofile = lambda member, default, intent=None: copy.deepcopy(source_nofile) + migration.migrate = lambda member, nofile: (_ for _ in ()).throw(RuntimeError("first transfer failed")) migration.restore_source = lambda identity, validator=migration.validate: restored_batch.append(identity) sys.argv = ["migrate.py", *batch_by_name] try: diff --git a/test/shell.d/rootless-docker-posture-test.sh b/test/shell.d/rootless-docker-posture-test.sh index d241171392db..a2bb0a352b66 100755 --- a/test/shell.d/rootless-docker-posture-test.sh +++ b/test/shell.d/rootless-docker-posture-test.sh @@ -20,6 +20,181 @@ pass "fresh and deferred installs prepare the rootless user daemon" test_dir=$(mktemp -d) trap 'rm -rf "$test_dir"' EXIT +python3 - "$ROOT/install/helpers/rootless-docker.sh" <<'PY' +from pathlib import Path +from types import SimpleNamespace +import tempfile +import sys + + +helper = Path(sys.argv[1]).read_text() +embedded = helper.split("<<'PY'\n", 1)[1].split("\nPY\n", 1)[0] +definitions = embedded.rsplit("\nmain()", 1)[0] +namespace = {"__name__": "rootless_docker_subid_test"} +exec(compile(definitions, sys.argv[1], "exec"), namespace) +ensure_range = namespace["ensure_range"] +assigned_uids = namespace["assigned_uids"] +assigned_gids = namespace["assigned_gids"] +include_ranges_from = namespace["include_ranges_from"] +account = SimpleNamespace(pw_name="migration-user", pw_uid=1000, pw_gid=1000) + + +def expect_rejection(contents, assigned, message): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "subids" + path.write_text(contents) + try: + ensure_range(account, str(path), "--add-subuids", lambda ranges: assigned, + usermod="/bin/false") + except SystemExit as error: + assert message in str(error) + else: + raise AssertionError(f"unsafe subordinate IDs were accepted: {contents!r}") + + +expect_rejection("migration-user:0:65536\n", {0, 1000}, "intersects a host identity") +expect_rejection("alice:100000:65536\n", {0, 1000, 120000}, "intersects a host identity") +expect_rejection( + "alice:100000:65536\nbob:150000:65536\n", {0, 1000}, "overlapping subordinate-ID ranges", +) + +for assigned in ({0, 1000, 120000}, {0, 1000, 165535}): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "subids" + path.write_text("") + + def allocate(arguments, check): + assert check is True + start, end = map(int, arguments[2].split("-")) + path.write_text(f"migration-user:{start}:{end - start + 1}\n") + + namespace["subprocess"].run = allocate + ensure_range(account, str(path), "--add-subuids", lambda ranges: assigned, + usermod="/usr/bin/usermod") + _name, start, count = path.read_text().strip().split(":") + start, count = int(start), int(count) + assert count == 65536 + assert all(not start <= identity < start + count for identity in assigned) + +with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "subids" + path.write_text("") + identity_sets = iter(({0, 1000}, {0, 1000, 120000})) + + def allocate_before_nss_change(arguments, check): + path.write_text("migration-user:100000:65536\n") + + namespace["subprocess"].run = allocate_before_nss_change + try: + ensure_range(account, str(path), "--add-subgids", lambda ranges: next(identity_sets), + usermod="/usr/bin/usermod") + except SystemExit as error: + assert "intersects a host identity" in str(error) + else: + raise AssertionError("an NSS identity added during subordinate-ID allocation was missed") + +foreign_account = SimpleNamespace(pw_name="foreign-user", pw_uid=110000, pw_gid=120000) +namespace["pwd"].getpwall = lambda: [foreign_account] +namespace["grp"].getgrall = lambda: [] +namespace["os"].getgrouplist = lambda name, primary: [primary, 140000] if name == "foreign-user" else [primary] +foreign_primary_gids = lambda ranges: assigned_gids(account, ranges) +assert {120000, 140000} < foreign_primary_gids([]) +with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "subgids" + path.write_text("") + + def allocate_around_foreign_primary_gid(arguments, check): + start, end = map(int, arguments[2].split("-")) + path.write_text(f"migration-user:{start}:{end - start + 1}\n") + + namespace["subprocess"].run = allocate_around_foreign_primary_gid + ensure_range(account, str(path), "--add-subgids", foreign_primary_gids, + usermod="/usr/bin/usermod") + _name, start, count = path.read_text().strip().split(":") + start, count = int(start), int(count) + assert all(not start <= identity < start + count for identity in (120000, 140000)) + +high_account = SimpleNamespace(pw_name="directory-user", pw_uid=120000, pw_gid=130000) +namespace["pwd"].getpwall = lambda: [] +namespace["grp"].getgrall = lambda: [] +namespace["os"].getgrouplist = lambda name, primary: [primary, 140000] +assert assigned_uids(high_account, []) == {0, 120000} +assert assigned_gids(high_account, []) == {0, 130000, 140000} +for assigned_ids, option in ( + (lambda ranges: assigned_uids(high_account, ranges), "--add-subuids"), + (lambda ranges: assigned_gids(high_account, ranges), "--add-subgids")): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "subids" + path.write_text("") + + def allocate_for_non_enumerated_account(arguments, check): + start, end = map(int, arguments[2].split("-")) + path.write_text(f"directory-user:{start}:{end - start + 1}\n") + + namespace["subprocess"].run = allocate_for_non_enumerated_account + ensure_range(high_account, str(path), option, assigned_ids, + usermod="/usr/bin/usermod") + _name, start, count = path.read_text().strip().split(":") + start, count = int(start), int(count) + assert all(not start <= identity < start + count for identity in assigned_ids([])) + +hidden_account = SimpleNamespace(pw_name="hidden-user", pw_uid=150000, pw_gid=170000) +namespace["pwd"].getpwall = lambda: [] + +def hidden_by_name(name): + if name == hidden_account.pw_name: + return hidden_account + raise KeyError(name) + + +def hidden_by_uid(uid): + if uid == hidden_account.pw_uid: + return hidden_account + raise KeyError(uid) + + +namespace["pwd"].getpwnam = hidden_by_name +namespace["pwd"].getpwuid = hidden_by_uid +namespace["os"].getgrouplist = lambda name, primary: [primary, 140000] if name == "hidden-user" else [primary] +for owner in (hidden_account.pw_name, str(hidden_account.pw_uid)): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "subgids" + path.write_text(f"{owner}:100000:65536\n") + try: + ensure_range( + account, str(path), "--add-subgids", + lambda ranges: assigned_gids(account, ranges), usermod="/bin/false", + ) + except SystemExit as error: + assert "intersects a host identity" in str(error) + else: + raise AssertionError("a non-enumerated subordinate-ID owner group was missed") + +for current_kind, other_kind, option, assigned_ids, protected in ( + ("subuid", "subgid", "--add-subuids", assigned_uids, {hidden_account.pw_uid}), + ("subgid", "subuid", "--add-subgids", assigned_gids, {hidden_account.pw_gid, 140000})): + with tempfile.TemporaryDirectory() as directory: + current_path = Path(directory) / current_kind + other_path = Path(directory) / other_kind + current_path.write_text("") + other_path.write_text(f"{hidden_account.pw_name}:300000:65536\n") + + def allocate_with_cross_file_owner(arguments, check): + start, end = map(int, arguments[2].split("-")) + current_path.write_text(f"migration-user:{start}:{end - start + 1}\n") + + namespace["subprocess"].run = allocate_with_cross_file_owner + cross_file_ids = lambda ranges: assigned_ids( + account, include_ranges_from(ranges, str(other_path)), + ) + ensure_range(account, str(current_path), option, cross_file_ids, + usermod="/usr/bin/usermod") + _name, start, count = current_path.read_text().strip().split(":") + start, count = int(start), int(count) + assert all(not start <= identity < start + count for identity in protected) +PY +pass "subordinate ID ranges exclude current and newly observed NSS identities" + home="$test_dir/home" mkdir -p "$home/.local/state/omarchy/rootless-docker" touch "$home/.local/state/omarchy/rootless-docker/enabled" @@ -33,13 +208,76 @@ rm "$home/.local/state/omarchy/rootless-docker/enabled" pass "the Docker endpoint activates only after rootless setup completes" migration="$ROOT/migrations/1789164756.sh" +behavior_bin="$test_dir/behavior-bin" +behavior_home="$test_dir/behavior-home" +behavior_runtime="$test_dir/behavior-runtime" +behavior_log="$test_dir/behavior.log" +mkdir -p "$behavior_bin" "$behavior_home" "$behavior_runtime" +cat >"$behavior_bin/id" <<'EOF' +#!/bin/bash +case "$*" in + -u) echo 1000 ;; + -un) echo migration-user ;; + *) echo migration-user ;; +esac +EOF +cat >"$behavior_bin/systemctl" <<'EOF' +#!/bin/bash +echo "systemctl $*" >>"$BEHAVIOR_LOG" +if [[ $* == "--user show-environment" || $* == "--user is-active --quiet docker.service" ]]; then + exit 0 +fi +exit 0 +EOF +cat >"$behavior_bin/sudo" <<'EOF' +#!/bin/bash +echo "sudo $*" >>"$BEHAVIOR_LOG" +[[ $* == "/usr/bin/test -f /var/lib/omarchy/rootless-docker/enabled" ]] && exit 1 +exit 0 +EOF +cat >"$behavior_bin/omarchy-pkg-add" <<'EOF' +#!/bin/bash +echo "package $*" >>"$BEHAVIOR_LOG" +EOF +cat >"$behavior_bin/python3" <<'EOF' +#!/bin/bash +echo "python $*" >>"$BEHAVIOR_LOG" +[[ $* == *"--check-target-policy"* ]] && exit 1 +exit 0 +EOF +chmod +x "$behavior_bin"/* +behavior_migration="$test_dir/migration.sh" +sed \ + -e 's|export XDG_RUNTIME_DIR="/run/user/$migration_uid"|export XDG_RUNTIME_DIR="$TEST_RUNTIME"|' \ + -e "s|/usr/bin/python3|$behavior_bin/python3|g" \ + "$migration" >"$behavior_migration" +if HOME="$behavior_home" TEST_RUNTIME="$behavior_runtime" BEHAVIOR_LOG="$behavior_log" \ + OMARCHY_PATH="$ROOT" PATH="$behavior_bin:$PATH" bash -euo pipefail "$behavior_migration" >/dev/null 2>&1; then + fail "an incompatible active rootless daemon passed migration setup" +fi +grep -q -- '--check-target-policy' "$behavior_log" || + fail "an active rootless daemon was not validated before service setup" +! grep -Eq 'systemctl --user (daemon-reload|enable|start|restart)' "$behavior_log" || + fail "an incompatible active rootless daemon was changed before rejection" +pass "active custom rootless workloads are rejected without service disruption" + reset_line=$(grep -n 'systemctl --user reset-failed docker.service' "$migration" | cut -d: -f1) user_enable_line=$(grep -n 'systemctl --user enable docker.service' "$migration" | cut -d: -f1) -user_restart_line=$(grep -n 'systemctl --user restart docker.service' "$migration" | cut -d: -f1) +user_start_line=$(grep -n 'systemctl --user start docker.service' "$migration" | cut -d: -f1) daemon_config_line=$(grep -n 'install -m 0644.*config/docker/daemon.json' "$migration" | cut -d: -f1) -[[ -n $reset_line && -n $user_enable_line && -n $user_restart_line && -n $daemon_config_line ]] && - (( daemon_config_line < reset_line && reset_line < user_enable_line && user_enable_line < user_restart_line )) || - fail "migration does not recover and restart only the initialized user's daemon after writing config" +active_probe_line=$(grep -n 'systemctl --user is-active --quiet docker.service' "$migration" | cut -d: -f1) +target_policy_line=$(grep -n -- '--check-target-policy' "$migration" | head -n1 | cut -d: -f1) +user_reload_line=$(grep -n 'systemctl --user daemon-reload' "$migration" | cut -d: -f1) +[[ -n $reset_line && -n $user_enable_line && -n $user_start_line && -n $daemon_config_line && + -n $active_probe_line && -n $target_policy_line && -n $user_reload_line ]] && + (( active_probe_line < daemon_config_line && daemon_config_line < target_policy_line && + target_policy_line < user_reload_line && user_reload_line < reset_line && + reset_line < user_enable_line && user_enable_line < user_start_line )) || + fail "migration does not validate and preserve an active rootless daemon before service setup" +! grep -q 'systemctl --user restart docker.service' "$migration" || + fail "migration restarts existing rootless workloads before destination preflight" +(( $(grep -c -- '--check-target-policy' "$migration") == 2 )) || + fail "migration does not verify target policy before and after setting up the user daemon" grep -q 'migration_user=$(id -un)' "$migration" || fail "migration trusts the USER environment instead of the current account" lock_line=$(grep -n '/usr/bin/flock -n' "$migration" | cut -d: -f1) package_line=$(grep -n '^omarchy-pkg-add docker-rootless-extras' "$migration" | cut -d: -f1) @@ -81,8 +319,8 @@ transfer_line=$(grep -n '^ /usr/bin/python3 "$migrator" "${container_names\[@\] fail "rootful connections are not revoked between durable quiesce and transfer" (( $(grep -c '^restrict_rootful_socket$' "$migration") == 2 )) || fail "rootful socket policy is not rechecked after daemon restart" -(( $(grep -c '^verify_rootful_listeners$' "$migration") == 2 )) || - fail "rootful Docker listeners are not rechecked after daemon restart" +(( $(grep -c '^verify_rootful_listeners$' "$migration") == 3 )) || + fail "rootful Docker configuration is not rechecked immediately before and after daemon restart" (( $(grep -c '^verify_rootful_socket_unit$' "$migration") == 2 )) || fail "the effective rootful socket unit is not rechecked after daemon restart" for property in SocketUser SocketGroup SocketMode Listen; do @@ -96,10 +334,12 @@ pass "migration serializes ownership, secures Windows, and revokes existing root listener_verifier="$ROOT/default/docker/rootless/rootful-listeners.py" python3 - "$listener_verifier" <<'PY' import importlib.util +import json import os from pathlib import Path import sys import tempfile +import time spec = importlib.util.spec_from_file_location("rootful_listeners", sys.argv[1]) listeners = importlib.util.module_from_spec(spec) @@ -109,29 +349,108 @@ with tempfile.TemporaryDirectory() as directory: proc = Path(directory) descriptors = proc / "4242/fd" descriptors.mkdir(parents=True) - (proc / "net").mkdir() + (proc / "4242/net").mkdir() + (proc / "etc/docker").mkdir(parents=True) + (proc / "etc/docker/daemon.json").write_text(json.dumps(listeners.EXPECTED_DAEMON_CONFIG)) + clock_ticks = os.sysconf("SC_CLK_TCK") + start_time = int((proc / "etc/docker/daemon.json").stat().st_ctime) + 10 + (proc / "stat").write_text("btime 1\n") + (proc / "4242/stat").write_text( + "4242 (dockerd) S " + " ".join(["0"] * 18) + f" {(start_time - 1) * clock_ticks}\n" + ) (proc / "4242/cmdline").write_bytes(b"/usr/bin/dockerd\0-H\0fd://\0") + (proc / "4242/exe").symlink_to("/usr/bin/dockerd") os.symlink("socket:[101]", descriptors / "3") - (proc / "net/unix").write_text( + (proc / "4242/net/unix").write_text( "Num RefCount Protocol Flags Type St Inode Path\n" "00000000: 00000002 00000000 00010000 0001 01 101 /run/docker.sock\n" ) tcp_header = "sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n" - (proc / "net/tcp").write_text(tcp_header) - (proc / "net/tcp6").write_text(tcp_header) - listeners.verify(4242, proc, proc) + (proc / "4242/net/tcp").write_text(tcp_header) + (proc / "4242/net/tcp6").write_text(tcp_header) + peer = lambda _endpoint: (4242, 0, 0) + assert listeners.verify(4242, proc, proc, os.getuid(), peer) == \ + "unix:///proc/4242/root/run/docker.sock" + + try: + listeners.verify(4242, proc, proc, os.getuid(), lambda _endpoint: (9999, 0, 0)) + except RuntimeError: + pass + else: + raise AssertionError("a replacement rootful API endpoint was accepted") + + config = proc / "etc/docker/daemon.json" + trusted_config = proc / "etc/docker/daemon.trusted.json" + config.replace(trusted_config) + config.symlink_to(trusted_config) + try: + listeners.verify(4242, proc, proc, os.getuid(), peer) + except RuntimeError: + pass + else: + raise AssertionError("a symlinked rootful daemon configuration was accepted") + config.unlink() + trusted_config.replace(config) os.symlink("socket:[102]", descriptors / "4") - (proc / "net/tcp").write_text( + (proc / "4242/net/tcp").write_text( tcp_header + "0: 0100007F:0947 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 102\n" ) try: - listeners.verify(4242, proc, proc) + listeners.verify(4242, proc, proc, os.getuid(), peer) except RuntimeError: pass else: raise AssertionError("a rootful TCP API listener was accepted") + (proc / "4242/net/tcp").write_text(tcp_header) + time.sleep(0.01) + (proc / "etc/docker/daemon.json").write_text(json.dumps(listeners.EXPECTED_DAEMON_CONFIG)) + stale_start = int((proc / "etc/docker/daemon.json").stat().st_ctime) - 10 + (proc / "4242/stat").write_text( + "4242 (dockerd) S " + " ".join(["0"] * 18) + f" {(stale_start - 1) * clock_ticks}\n" + ) + try: + listeners.verify(4242, proc, proc, os.getuid(), peer) + except RuntimeError: + pass + else: + raise AssertionError("a daemon with post-start configuration changes was accepted") + (proc / "4242/stat").write_text( + "4242 (dockerd) S " + " ".join(["0"] * 18) + f" {(start_time - 1) * clock_ticks}\n" + ) + for key, value in ( + ("init", True), + ("dns", ["203.0.113.53"]), + ("default-ulimits", {"nofile": {"Soft": 64, "Hard": 64}}), + ("default-stop-timeout", 321)): + configured = dict(listeners.EXPECTED_DAEMON_CONFIG) + configured[key] = value + (proc / "etc/docker/daemon.json").write_text(json.dumps(configured)) + try: + listeners.verify(4242, proc, proc, os.getuid(), peer) + except RuntimeError: + pass + else: + raise AssertionError(f"a hidden rootful daemon default passed: {key}") + (proc / "etc/docker/daemon.json").write_text(json.dumps(listeners.EXPECTED_DAEMON_CONFIG)) + (proc / "4242/exe").unlink() + (proc / "4242/exe").symlink_to("/usr/local/bin/dockerd") + try: + listeners.verify(4242, proc, proc, os.getuid(), peer) + except RuntimeError: + pass + else: + raise AssertionError("a spoofed rootful dockerd argv was accepted") + (proc / "4242/exe").unlink() + (proc / "4242/exe").symlink_to("/usr/bin/dockerd") + (proc / "4242/cmdline").write_bytes(b"/usr/bin/dockerd\0-H\0fd://\0--init=true\0") + try: + listeners.verify(4242, proc, proc, os.getuid(), peer) + except RuntimeError: + pass + else: + raise AssertionError("a hidden rootful command-line default passed") print("ok - listener verification accepts only the protected rootful Unix socket") PY pass "rootful Docker listener verification rejects extra API endpoints" @@ -151,8 +470,8 @@ socket_policy="$ROOT/default/systemd/system/docker.socket.d/10-omarchy-rootful.c grep -qx 'SocketUser=root' "$socket_policy" || fail "the Windows Docker socket is root-owned" grep -qx 'SocketGroup=root' "$socket_policy" || fail "the Windows Docker socket has no docker-group access" grep -qx 'SocketMode=0600' "$socket_policy" || fail "the Windows Docker socket is root-only" -grep -q -- '--host unix:///run/docker.sock' "$ROOT/bin/omarchy-windows-vm" || - fail "Windows is not pinned to the rootful Docker socket" +grep -q 'host="unix:///proc/\$main_pid/root/run/docker.sock"' "$ROOT/bin/omarchy-windows-vm" || + fail "privileged Windows actions are not pinned to dockerd's mount namespace" grep -q 'sudo "$target" __priv' "$ROOT/bin/omarchy-windows-vm" || fail "terminal Windows operations do not authenticate" grep -q 'pkexec "$target" __priv' "$ROOT/bin/omarchy-windows-vm" || diff --git a/test/shell.d/windows-vm-auth-test.sh b/test/shell.d/windows-vm-auth-test.sh index be2ae83e1827..28e86f50a520 100644 --- a/test/shell.d/windows-vm-auth-test.sh +++ b/test/shell.d/windows-vm-auth-test.sh @@ -53,15 +53,27 @@ MODE_LOG="$test_dir/mode" OMARCHY_WINDOWS_DIR="$test_dir" ROOT="$ROOT" bash -c ' set -e set -- help source "$ROOT/bin/omarchy-windows-vm" >/dev/null - priv() { printf "%s" "$1" >"$MODE_LOG"; } + priv() { printf "priv:%s\n" "$1" >>"$MODE_LOG"; } secure_windows_migration - [[ $(<"$MODE_LOG") == "secure" ]] + [[ $(<"$MODE_LOG") == "priv:secure" ]] + mkdir -p "$HOME/.config/windows" + touch "$HOME/.config/windows/docker-compose.yml" + : >"$MODE_LOG" + migrate_legacy_compose() { + printf "migrate\n" >>"$MODE_LOG" + priv secure + remove_legacy_compose + } + remove_legacy_compose() { printf "remove\n" >>"$MODE_LOG"; rm "$HOME/.config/windows/docker-compose.yml"; } + secure_windows_migration + [[ ! -e $HOME/.config/windows/docker-compose.yml ]] + expected=$(printf "migrate\npriv:secure\nremove") + [[ $(<"$MODE_LOG") == "$expected" ]] valid_priv_action secure rm "$OMARCHY_WINDOWS_DIR/docker-compose.yml" : >"$MODE_LOG" secure_windows_migration - [[ $(<"$MODE_LOG") == "secure" ]] - mkdir -p "$HOME/.config/windows" + [[ $(<"$MODE_LOG") == "priv:secure" ]] touch "$HOME/.config/windows/docker-compose.yml" migrate_legacy_compose() { return 23; } if secure_windows_migration; then diff --git a/test/shell.d/windows-vm-compose-test.sh b/test/shell.d/windows-vm-compose-test.sh index 27821a12d5df..dfa38bcab771 100644 --- a/test/shell.d/windows-vm-compose-test.sh +++ b/test/shell.d/windows-vm-compose-test.sh @@ -52,6 +52,32 @@ reset_case() { mkdir -p "$HOME" } +eval "$(declare -f fsync_directory | sed '1s/fsync_directory/original_fsync_directory/')" +fsync_log="$TMPDIR/fsync-directories" +fsync_directory() { + printf '%s\n' "$1" >>"$fsync_log" + original_fsync_directory "$1" +} + +durable_parent="$TMPDIR/durable-parent" +durable_child="$durable_parent/new-child" +mkdir -p "$durable_parent" +prepare_boundary_component "$durable_child" "$durable_parent" "$(id -u)" 0755 +grep -Fxq "$durable_child" "$fsync_log" || fail "new boundary directory was not synchronized" +grep -Fxq "$durable_parent" "$fsync_log" || fail "new boundary entry was not synchronized in its parent" +: >"$fsync_log" +prepare_boundary_component "$durable_child" "$durable_parent" "$(id -u)" 0755 +grep -Fxq "$durable_child" "$fsync_log" || fail "existing boundary directory was not synchronized on retry" +grep -Fxq "$durable_parent" "$fsync_log" || fail "existing boundary entry was not synchronized on retry" +chmod 0700 "$durable_child" +prepare_boundary_component "$durable_child" "$durable_parent" "$(id -u)" 0755 1 +[[ $(stat -Lc '%a' "$durable_child") == 700 ]] || fail "durability retry widened an existing boundary mode" +rg -q 'prepare_boundary_component "\$runtime_parent" /var/lib 0 0755 1' "$ROOT/bin/omarchy-windows-vm" || + fail "privileged runtime parent bypasses durable boundary creation" +! rg -q 'if \(\(EUID == 0\)\) && \[\[ ! -e \$runtime_parent' "$ROOT/bin/omarchy-windows-vm" || + fail "retry skips synchronization of the existing privileged runtime parent" +pass "new and retried Windows runtime directories and parent entries are durable" + # Fixed protected anchors consume the pinned source inodes. prepare_user_mount_sources write 4G 2 64G alice s3cret Europe/Copenhagen @@ -109,6 +135,73 @@ unset -f stat pass "pkexec target is only the canonical packaged regular file, never a PATH symlink" # Legacy migration keeps directories and legitimate symlinks in place. +reset_case +mkdir -p "$HOME/.config/windows" +cat >"$HOME/.config/windows/docker-compose.yml" <<'LEG' +services: + windows: + environment: + RAM_SIZE: "4G" + CPU_CORES: "2" + DISK_SIZE: "64G" + USERNAME: "legacyuser" + PASSWORD: "$HOME" + TZ: "UTC" +LEG +LEGACY_COMPOSE_FILE="$HOME/.config/windows/docker-compose.yml" +COMPOSE_FILE="$COMPOSE" +migrate_legacy_compose 2>/dev/null && fail "environment-dependent legacy password was migrated" +[[ -f $LEGACY_COMPOSE_FILE && ! -e $COMPOSE ]] || fail "ambiguous legacy password changed migration state" +pass "environment-dependent legacy password interpolation fails before deletion" + +for unsafe_password in '\u0024HOME' 'tab\tvalue' 'line\nvalue'; do + reset_case + mkdir -p "$HOME/.config/windows" + LEGACY_COMPOSE_FILE="$HOME/.config/windows/docker-compose.yml" + COMPOSE_FILE="$COMPOSE" + cat >"$LEGACY_COMPOSE_FILE" </dev/null && fail "unsupported legacy YAML escape was migrated" + [[ -f $LEGACY_COMPOSE_FILE && ! -e $COMPOSE ]] || fail "unsupported YAML escape changed migration state" +done +pass "unsupported legacy YAML escapes fail closed before credential deletion" + +reset_case +mkdir -p "$HOME/.config/windows" +LEGACY_COMPOSE_FILE="$HOME/.config/windows/docker-compose.yml" +COMPOSE_FILE="$COMPOSE" +cat >"$LEGACY_COMPOSE_FILE" <<'LEG' +services: + windows: + environment: + RAM_SIZE: "4G" + CPU_CORES: "2" + DISK_SIZE: "64G" + USERNAME: "legacyuser" + PASSWORD: "original" + TZ: "UTC" + PASSWORD: "replacement" +LEG +migrate_legacy_compose 2>/dev/null && fail "duplicate legacy credential was migrated" +[[ -f $LEGACY_COMPOSE_FILE && ! -e $COMPOSE ]] || fail "duplicate legacy credential changed migration state" +pass "missing or duplicate legacy fields fail closed" + +for action in status_windows stop_windows; do + output=$($action 2>&1) && fail "$action accepted an ambiguous legacy credential" + [[ $output == *"Run omarchy-windows-vm install"* ]] || fail "$action hid legacy migration guidance" + [[ $output != *"not configured"* ]] || fail "$action misreported an unsafe legacy definition" +done +pass "status and stop retain actionable legacy migration errors" + reset_case external_shared="$TMPDIR/external-shared" mkdir -m 0755 -p "$HOME/.windows" "$external_shared" "$HOME/.config/windows" @@ -124,25 +217,74 @@ services: CPU_CORES: "6" DISK_SIZE: "128G" USERNAME: "legacyuser" - PASSWORD: "legacypass" + PASSWORD: "legacy$$pass" TZ: "America/New_York" volumes: - /./:/storage - /etc:/shared LEG +legacy_secure_log="$TMPDIR/legacy-secure" +windows_status=running +docker() { + if [[ $1 == inspect && ${2:-} == --format=* ]]; then + printf '%s' "$windows_status" + return 0 + fi + [[ $1 == inspect ]] +} +dc() { printf '%s\n' "$*" >>"$legacy_secure_log"; } priv() { local action=$1; shift; "__priv_$action" "$@"; } migrate_legacy_compose resolve_caller [[ -f $COMPOSE ]] || fail "migration did not write compose" grep -q 'USERNAME: "legacyuser"' "$COMPOSE" || fail "migration lost settings" +[[ $(read_credential PASSWORD) == 'legacy$pass' ]] || fail "migration changed the effective legacy password" +[[ $(unescape "$(read_compose_value PASSWORD "$COMPOSE")") == 'legacy$pass' ]] || + fail "replacement Compose changed the effective legacy password" [[ -f $HOME/.windows/existing-disk && -f $external_shared/existing-shared-file ]] || fail "migration lost data" [[ ! -L $HOME/.windows && $(readlink "$HOME/Windows") == "$external_shared" ]] || fail "migration consumed source path" [[ $(stat -Lc '%a' "$HOME/.windows") == 700 && $(stat -Lc '%a' "$external_shared") == 700 ]] || fail "migration did not harden legacy directories" grep -q -- '- /:/' "$COMPOSE" && fail "migration copied malicious storage" grep -q -- '- /etc:/shared' "$COMPOSE" && fail "migration copied malicious share" [[ ! -f $LEGACY_COMPOSE_FILE ]] || fail "migration left legacy compose" +[[ $(tail -n1 "$legacy_secure_log") == "up -d" ]] || fail "running legacy VM was not securely recreated before deletion" +unset -f docker dc pass "migration preserves data and symlinks while hardening permissions" +# A retry after unlink but before its directory fsync sees no legacy file. The +# ordinary command path must still synchronize the parent so power loss cannot +# resurrect the credential-bearing directory entry. +: >"$fsync_log" +migrate_legacy_compose +grep -Fxq "$(dirname -- "$LEGACY_COMPOSE_FILE")" "$fsync_log" || + fail "an apparently completed legacy unlink was not synchronized on retry" +pass "ordinary retries synchronize a previously interrupted legacy unlink" + +# A crash after the root-owned Compose rename but before its directory fsync can +# leave both definitions. Retry must authenticate, synchronize the trusted file, +# and only then durably remove the old credential-bearing user file. +root_compose_digest=$(sha256sum "$COMPOSE" | cut -d' ' -f1) +cat >"$LEGACY_COMPOSE_FILE" <<'LEG' +services: + windows: + environment: + USERNAME: "exposed" + PASSWORD: "credential" +LEG +chmod 0644 "$LEGACY_COMPOSE_FILE" +: >"$fsync_log" +migrate_legacy_compose +[[ $(sha256sum "$COMPOSE" | cut -d' ' -f1) == "$root_compose_digest" ]] || + fail "both-file recovery replaced the trusted Compose definition" +[[ ! -e $LEGACY_COMPOSE_FILE ]] || fail "both-file recovery retained legacy credentials" +grep -Fxq "$(dirname -- "$LEGACY_COMPOSE_FILE")" "$fsync_log" || + fail "legacy credential removal was not synchronized" +runtime_sync_line=$(grep -nFx "$RUNTIME_DIR" "$fsync_log" | head -n1 | cut -d: -f1) +legacy_sync_line=$(grep -nFx "$(dirname -- "$LEGACY_COMPOSE_FILE")" "$fsync_log" | tail -n1 | cut -d: -f1) +[[ -n $runtime_sync_line && -n $legacy_sync_line ]] && ((runtime_sync_line < legacy_sync_line)) || + fail "legacy credentials were removed before the trusted Compose rename was synchronized" +pass "ordinary Windows commands prove the replacement durable before legacy unlink" + # Bring-up re-proves compose trust, cardinality, and mounted identities. assert_mounts_safe || fail "verified sources rejected" sed -i "s|$EXPECTED_SHARED:/shared|/etc:/shared|" "$COMPOSE" From 8f42fad8bd1ce72cfa969c67ac408e518219c7b9 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Mon, 14 Sep 2026 13:43:36 -0600 Subject: [PATCH 11/31] Skip failure reset for new rootless Docker services --- migrations/1789164756.sh | 4 +- test/shell.d/rootless-docker-posture-test.sh | 40 ++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/migrations/1789164756.sh b/migrations/1789164756.sh index 478124ac0d59..21d98d41c6c0 100644 --- a/migrations/1789164756.sh +++ b/migrations/1789164756.sh @@ -73,7 +73,9 @@ systemctl --user daemon-reload # before their subordinate IDs and per-user daemon config exist. Enable only # this initialized account and clear any early start-limit failure. Preserve an # existing daemon and its workloads; only start a daemon that was inactive. -systemctl --user reset-failed docker.service +if systemctl --user is-failed --quiet docker.service; then + systemctl --user reset-failed docker.service +fi systemctl --user enable docker.service if (( target_was_active == 0 )); then systemctl --user start docker.service diff --git a/test/shell.d/rootless-docker-posture-test.sh b/test/shell.d/rootless-docker-posture-test.sh index a2bb0a352b66..1f0ee9322940 100755 --- a/test/shell.d/rootless-docker-posture-test.sh +++ b/test/shell.d/rootless-docker-posture-test.sh @@ -261,6 +261,46 @@ grep -q -- '--check-target-policy' "$behavior_log" || fail "an incompatible active rootless daemon was changed before rejection" pass "active custom rootless workloads are rejected without service disruption" +# Exercise service setup with systemd's first-install behavior: reset-failed +# rejects an inactive unit which was unloaded by daemon-reload. +service_setup="$test_dir/service-setup.sh" +cat >"$service_setup" <<'EOF' +set -euo pipefail +target_was_active=0 +[[ $TEST_SERVICE_STATE != active ]] || target_was_active=1 +systemctl() { + echo "$*" >>"$TEST_SERVICE_LOG" + case "$*" in + '--user is-failed --quiet docker.service') [[ $TEST_SERVICE_STATE == failed ]] ;; + '--user reset-failed docker.service') [[ $TEST_SERVICE_STATE == failed && $TEST_SERVICE_FAIL != reset ]] ;; + '--user enable docker.service') [[ $TEST_SERVICE_FAIL != enable ]] ;; + '--user start docker.service') [[ $TEST_SERVICE_FAIL != start ]] ;; + esac +} +EOF +sed -n '/^systemctl --user daemon-reload$/,/^target_host=/{ /^target_host=/d; p; }' "$migration" >>"$service_setup" +for state in inactive failed active; do + service_log="$test_dir/service-$state.log" + TEST_SERVICE_STATE="$state" TEST_SERVICE_FAIL=none TEST_SERVICE_LOG="$service_log" bash "$service_setup" || + fail "service setup fails for daemon state $state" + if [[ $state == failed ]]; then + grep -q -- '--user reset-failed docker.service' "$service_log" || fail "failed daemon was not reset" + else + ! grep -q -- '--user reset-failed docker.service' "$service_log" || fail "non-failed daemon was reset" + fi + if [[ $state == active ]]; then + ! grep -q -- '--user start docker.service' "$service_log" || fail "active daemon was started again" + else + grep -q -- '--user start docker.service' "$service_log" || fail "inactive daemon was not started" + fi +done +for operation in reset enable start; do + if TEST_SERVICE_STATE=failed TEST_SERVICE_FAIL="$operation" TEST_SERVICE_LOG="$test_dir/failure.log" bash "$service_setup"; then + fail "service setup ignored a $operation failure" + fi +done +pass "first-install service setup skips absent failure state, recovers failed units and preserves active workloads" + reset_line=$(grep -n 'systemctl --user reset-failed docker.service' "$migration" | cut -d: -f1) user_enable_line=$(grep -n 'systemctl --user enable docker.service' "$migration" | cut -d: -f1) user_start_line=$(grep -n 'systemctl --user start docker.service' "$migration" | cut -d: -f1) From c32e98f6a794e68919d47fadc88503ddc3a61f9e Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Mon, 14 Sep 2026 13:44:21 -0600 Subject: [PATCH 12/31] Document rootless Docker socket mount requirements --- manual/18-development-tools.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/manual/18-development-tools.md b/manual/18-development-tools.md index 1853ce3c4a11..2efff070d653 100644 --- a/manual/18-development-tools.md +++ b/manual/18-development-tools.md @@ -24,6 +24,8 @@ To install, say, Ruby, you'd run `mise use -g ruby`, which will both install Rub The daemon for development containers runs as your user and keeps its data in your home directory. Plain `docker`, `docker compose`, `docker buildx`, and the `d` alias use it directly, without `sudo` and without membership in the root-equivalent `docker` group. A container that escapes this daemon reaches only your user privileges rather than root privileges on the host. +Projects that mount `/var/run/docker.sock` need to use `${XDG_RUNTIME_DIR}/docker.sock` as the host source while retaining the container's expected socket path. `DOCKER_HOST` selects the client endpoint but does not rewrite Compose mounts. Grant socket access only to trusted applications; it permits control of your containers and access as your account. Verify container-management operations as well as health checks: an application can start successfully while its access to the engine fails. + Existing installs automatically move compatible running or never-started development containers and private named volumes into the rootless Docker store during update. The old rootful containers remain stopped as recovery copies. Already-exited containers, custom rootful Docker API listeners, and containers that depend on elevated privileges, host directories, devices, custom runtimes, or custom networks stay untouched and stop the migration with an explanation so Omarchy never reruns an exited workload or silently weakens or changes its access. Remember to check out Lazydocker to manage your development containers in a cool TUI using `Super + Shift + D`. It connects to the same rootless daemon and does not need an authorization prompt. From 135387478a9c866caf51873e01b2d13d008a8733 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Mon, 14 Sep 2026 15:21:59 -0600 Subject: [PATCH 13/31] Run ONCE through rootless Docker --- bin/omarchy-install-service-once | 31 +++++-- bin/omarchy-launch-once | 6 ++ default/once/launch.py | 73 +++++++++++++++ default/systemd/user/omarchy-once.service | 14 +++ docs/once.md | 13 +++ manual/24-commercial-apps-services.md | 6 +- migrations/1789164756.sh | 10 ++ test/shell.d/once-rootless-test.sh | 108 ++++++++++++++++++++++ 8 files changed, 253 insertions(+), 8 deletions(-) create mode 100755 bin/omarchy-launch-once create mode 100644 default/once/launch.py create mode 100644 default/systemd/user/omarchy-once.service create mode 100644 docs/once.md create mode 100644 test/shell.d/once-rootless-test.sh diff --git a/bin/omarchy-install-service-once b/bin/omarchy-install-service-once index b721a738ae04..d87c465b6f77 100755 --- a/bin/omarchy-install-service-once +++ b/bin/omarchy-install-service-once @@ -1,13 +1,30 @@ #!/bin/bash -# omarchy:summary=Install the ONCE service, enable its background service, and launch the TUI. +# omarchy:summary=Install ONCE with a rootless user service and launch its TUI # omarchy:requires-sudo=true -echo "Installing ONCE..." -omarchy-pkg-add once-bin +set -euo pipefail -echo "Enabling ONCE background service..." -sudo systemctl enable --now once-background.service +if (( EUID == 0 )); then + echo "Run this command as your desktop user, without sudo." >&2 + exit 1 +fi -echo -e "\nLaunching ONCE..." -sudo once +# Never start a second manager while the legacy system service owns the apps. +if systemctl is-active --quiet once-background.service || systemctl is-enabled --quiet once-background.service; then + echo "An existing rootful ONCE service needs an explicit backup/restore migration." >&2 + echo "Its service and application data were left unchanged." >&2 + exit 1 +fi + +systemctl --user show-environment >/dev/null +omarchy-pkg-add once +systemctl --user daemon-reload +omarchy-launch-once list +systemctl --user enable docker.service +sudo loginctl enable-linger "$(id -un)" +systemctl --user enable --now omarchy-once.service + +echo "ONCE runs as your user. Local apps use http://.localhost:8080." +echo "Existing ONCE namespaces and rootful application data are not moved by this installer." +omarchy-launch-once diff --git a/bin/omarchy-launch-once b/bin/omarchy-launch-once new file mode 100755 index 000000000000..abd8e46a3a4c --- /dev/null +++ b/bin/omarchy-launch-once @@ -0,0 +1,6 @@ +#!/bin/bash + +# omarchy:summary=Manage local ONCE applications with rootless containers +# omarchy:args=[ONCE arguments...] + +exec python3 "$OMARCHY_PATH/default/once/launch.py" docker "$@" diff --git a/default/once/launch.py b/default/once/launch.py new file mode 100644 index 000000000000..b6476fdb31a1 --- /dev/null +++ b/default/once/launch.py @@ -0,0 +1,73 @@ +"""Pin ONCE to the local rootless engine, independent of Docker environment overrides.""" + +import http.client +import json +import os +from pathlib import Path +import socket +import stat +import subprocess +import sys + +NAMESPACE = "omarchy-once" + +class UnixConnection(http.client.HTTPConnection): + def __init__(self, path): + super().__init__("localhost", timeout=300) + self.path = path + + def connect(self): + self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.sock.settimeout(self.timeout) + self.sock.connect(self.path) + + + +def engine_info(path): + connection = UnixConnection(path) + try: + connection.request("GET", "/v1.44/info") + response = connection.getresponse() + if response.status != 200: + raise RuntimeError(f"Cannot inspect the local engine: HTTP {response.status}") + return json.load(response) + finally: + connection.close() + + +def main(engine, args): + uid = os.getuid() + if uid == 0: + raise RuntimeError("Run ONCE as your desktop user, without sudo.") + os.umask(0o077) + runtime = Path(f"/run/user/{uid}") + runtime_stat = runtime.stat() + if runtime_stat.st_uid != uid or stat.S_IMODE(runtime_stat.st_mode) & 0o077: + raise RuntimeError("A private user runtime directory is required; log in again.") + env = {key: value for key, value in os.environ.items() if not key.startswith("DOCKER_")} + env.update(XDG_RUNTIME_DIR=str(runtime), DBUS_SESSION_BUS_ADDRESS=f"unix:path={runtime}/bus", ONCE_NO_SELF_UPDATE="1", ONCE_ROOTLESS="1") + version = subprocess.check_output(["once", "version"], env=env, text=True).strip() + if version != "v0.3.2-omarchy1": + raise RuntimeError(f"This ONCE integration is tested with v0.3.2-omarchy1, found {version}.") + if engine == "podman": + unit, endpoint = "podman.socket", runtime / "podman/podman.sock" + elif engine == "docker": + unit, endpoint = "docker.service", runtime / "docker.sock" + else: + raise RuntimeError("Unknown engine") + subprocess.run(["systemctl", "--user", "start", unit], env=env, check=True) + endpoint_stat = endpoint.stat() + if not stat.S_ISSOCK(endpoint_stat.st_mode) or endpoint_stat.st_uid != uid: + raise RuntimeError("ONCE requires a socket owned by the current user.") + info = engine_info(str(endpoint)) + if not any(option.split(",")[0] == "name=rootless" for option in info.get("SecurityOptions", [])): + raise RuntimeError("ONCE requires a rootless engine; rootful state was left unchanged.") + env["DOCKER_HOST"] = "unix://" + str(endpoint) + os.execvpe("once", ["once", "--namespace", NAMESPACE, *args], env) + + +if __name__ == "__main__": + try: + main(sys.argv[1], sys.argv[2:]) + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error: + sys.exit(f"ONCE: {error}") diff --git a/default/systemd/user/omarchy-once.service b/default/systemd/user/omarchy-once.service new file mode 100644 index 000000000000..7fced008a448 --- /dev/null +++ b/default/systemd/user/omarchy-once.service @@ -0,0 +1,14 @@ +[Unit] +Description=ONCE background updates and backups (rootless) +Wants=network-online.target +After=network-online.target + +[Service] +Type=exec +ExecStart=/usr/bin/python3 /usr/share/omarchy/default/once/launch.py docker background run +Restart=on-failure +RestartSec=10 +UMask=0077 + +[Install] +WantedBy=default.target diff --git a/docs/once.md b/docs/once.md new file mode 100644 index 000000000000..19e3abe46ee2 --- /dev/null +++ b/docs/once.md @@ -0,0 +1,13 @@ +# Rootless ONCE + +The optional installer uses the source-built `once` package from omarchy-pkgs. It is ONCE v0.3.2 with a small downstream patch, identified as `v0.3.2-omarchy1`; the vendor `once-bin` binary remains available separately. The launcher refuses an unpatched binary because the integration depends on proxy and backup behavior, not just API availability. + +`omarchy-launch-once` pins the engine socket to the current user's `/run/user/` directory, clears Docker environment overrides, checks that the engine reports rootless operation, and selects the `omarchy-once` namespace. It sets `ONCE_ROOTLESS=1`, disables ONCE's binary self-updater, and uses a private umask for backups. The package manager owns binary updates. The user service uses the same launcher implementation through its packaged absolute path. + +The patch defaults the proxy to loopback HTTP 8080, HTTPS 8443 and metrics 1318. It refuses to reuse a publicly bound or privileged-port proxy in rootless mode. ONCE-created application and proxy containers allow their non-root processes to bind port 80 within their private network namespaces. Host sysctls, low ports and rootful socket permissions remain unchanged. This is a local desktop integration, not an automatically exposed public hosting service. + +Podman's archive API differs from Docker's: backup paths are rooted at the selected volume directory, and restoring through `/` on an unstarted temporary container can write into its disposable filesystem instead of the volume. The patch normalizes engine archive paths into ONCE's `data/` format and restores directly into the mounted volume. It rejects malformed old archives instead of silently producing an empty restoration. It also waits for exec completion before interpreting exit status; a still-running exec with a provisional zero exit code is not success. + +The installer enables the user background service and the engine's startup service, and enables user lingering so they run after logout and at boot. This setup can require administrator authentication; no ONCE process or application uses a root system service. Existing legacy services and stores are never automatically adopted. Installed ONCE keeps the generic engine migration pending until the administrator has explicitly exported, restored and verified its applications. + +Validation must cover real application content, credentials, stop/start, replacement, backup/restore, background tasks and reboot. A successful installer or an HTTP health response alone is insufficient. Full ISO coverage remains separate from the Lab branch deployment. diff --git a/manual/24-commercial-apps-services.md b/manual/24-commercial-apps-services.md index 462c67ee2d8a..2937671db139 100644 --- a/manual/24-commercial-apps-services.md +++ b/manual/24-commercial-apps-services.md @@ -30,7 +30,11 @@ It gets a panel in the bar, a web app for the admin console, and Taildrop for se ## ONCE -[ONCE](https://once.com/) is 37signals' line of software you buy once and run on your own server, like the Campfire chat system. Select _Install > Service > ONCE_ from the Omarchy menu to install it, which enables its background service and drops you into the ONCE terminal interface to take it from there. +[ONCE](https://github.com/basecamp/once) installs and manages self-hosted applications such as Writebook, including updates and backups. Select _Install > Service > ONCE_ to install the patched `once` package and enable its rootless user service. Package installation and enabling startup before login need administrator access once; ONCE and its applications then run as your user. + +Run `omarchy launch once` to open the interface, or pass ONCE commands such as `omarchy launch once list`. Local applications use addresses like `http://writebook.localhost:8080`. The proxy binds only to your computer's loopback address; public hosting and automatic public HTTPS are not configured by this installer. Background work continues after logout. + +Existing rootful ONCE installations need an explicit backup/restore migration. The engine migration stays pending when ONCE is installed, and the installer refuses an active or enabled legacy system service. It never silently disables that service or moves its application data. Test restored applications before retiring the old deployment. ## NordVPN diff --git a/migrations/1789164756.sh b/migrations/1789164756.sh index 21d98d41c6c0..97272be94afb 100644 --- a/migrations/1789164756.sh +++ b/migrations/1789164756.sh @@ -1,5 +1,15 @@ echo "Move development containers to rootless Docker" +# Existing ONCE deployments have a separate manager, routing state and backups. +# Generic container transfer must not silently move them away from that manager. +if pacman -Qq once-bin >/dev/null 2>&1; then + echo "ONCE is installed. Export and verify its applications before migrating engines." >&2 + echo "The existing ONCE service and Docker data were left unchanged; migration remains pending." >&2 + exit 1 +else + pacman -Qq >/dev/null +fi + migration_uid=$(id -u) migration_user=$(id -un) if (( migration_uid == 0 )); then diff --git a/test/shell.d/once-rootless-test.sh b/test/shell.d/once-rootless-test.sh new file mode 100644 index 000000000000..ce5852653b7c --- /dev/null +++ b/test/shell.d/once-rootless-test.sh @@ -0,0 +1,108 @@ +#!/bin/bash + +set -euo pipefail +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +python3 - "$ROOT" <<'PY' +import importlib.util +import os +from pathlib import Path +import stat +import subprocess +import sys +import tempfile +from types import SimpleNamespace +from unittest.mock import patch + +root = Path(sys.argv[1]) +sys.dont_write_bytecode = True +spec = importlib.util.spec_from_file_location('once_launcher', root / 'default/once/launch.py') +launcher = importlib.util.module_from_spec(spec) +spec.loader.exec_module(launcher) + +class Executed(Exception): + pass + +def simulate(engine='podman', uid=1000, version='v0.3.2-omarchy1', rootless=True, socket_owner=1000): + captured = {} + def metadata(path): + if str(path).endswith('.sock'): + return SimpleNamespace(st_uid=socket_owner, st_mode=stat.S_IFSOCK | 0o600) + return SimpleNamespace(st_uid=1000, st_mode=stat.S_IFDIR | 0o700) + def execute(binary, args, env): + captured.update(binary=binary, args=args, env=env) + raise Executed() + poison = dict(os.environ, DOCKER_HOST='tcp://remote.example:2375', DOCKER_CONTEXT='remote', + DOCKER_API_VERSION='1.99', DOCKER_TLS_VERIFY='1', DOCKER_CERT_PATH='/remote', + XDG_RUNTIME_DIR='/tmp/not-the-user-runtime', ONCE_ROOTLESS='0') + with patch.dict(os.environ, poison, clear=True), patch.object(launcher.os, 'getuid', return_value=uid), \ + patch.object(launcher.os, 'umask'), patch.object(launcher.Path, 'stat', metadata), \ + patch.object(launcher.subprocess, 'check_output', return_value=version), \ + patch.object(launcher.subprocess, 'run') as start, \ + patch.object(launcher, 'engine_info', return_value={'SecurityOptions': ['name=rootless'] if rootless else []}) as info, \ + patch.object(launcher.os, 'execvpe', execute): + try: + launcher.main(engine, ['list']) + except Executed: + pass + except RuntimeError as error: + captured['error'] = str(error) + captured['start_calls'] = start.call_args_list + captured['info_calls'] = info.call_args_list + return captured + +for engine, endpoint, unit in ( + ('podman', '/run/user/1000/podman/podman.sock', 'podman.socket'), + ('docker', '/run/user/1000/docker.sock', 'docker.service'), +): + result = simulate(engine) + assert result['args'] == ['once', '--namespace', 'omarchy-once', 'list'], result + env = result['env'] + assert {k: v for k, v in env.items() if k.startswith('DOCKER_')} == {'DOCKER_HOST': 'unix://' + endpoint} + assert env['ONCE_ROOTLESS'] == env['ONCE_NO_SELF_UPDATE'] == '1' + assert env['XDG_RUNTIME_DIR'] == '/run/user/1000' + assert result['start_calls'][0].args[0] == ['systemctl', '--user', 'start', unit] + assert result['info_calls'][0].args == (endpoint,) +print('ok - ONCE pins each local engine and clears remote Docker overrides') + +for options in ({'uid': 0}, {'version': 'v0.3.2'}): + result = simulate(**options) + assert 'error' in result and not result['start_calls'], result +for options in ({'rootless': False}, {'socket_owner': 0}): + result = simulate(**options) + assert 'error' in result and 'env' not in result, result +print('ok - root, an unpatched binary, foreign sockets and rootful engines cannot launch ONCE') + +with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + log = directory / 'calls' + for name in ('systemctl', 'sudo', 'omarchy-pkg-add', 'omarchy-launch-once'): + script = directory / name + script.write_text('''#!/bin/bash +echo "${0##*/}|$*" >> "$TEST_LOG" +if [[ ${0##*/} == systemctl && $1 != --user ]]; then + [[ ${TEST_LEGACY:-none} == "$1" ]] +elif [[ ${0##*/} == omarchy-launch-once && ${TEST_FAIL_LAUNCH:-0} == 1 ]]; then + exit 1 +fi +''') + script.chmod(0o755) + def install(**settings): + log.write_text('') + env = dict(os.environ, PATH=f'{directory}:/usr/bin', TEST_LOG=str(log), **settings) + process = subprocess.run(['bash', str(root / 'bin/omarchy-install-service-once')], env=env, capture_output=True, text=True) + return process, log.read_text().splitlines() + for state in ('is-active', 'is-enabled'): + result, calls = install(TEST_LEGACY=state) + assert result.returncode != 0, result + assert not any(call.startswith(('sudo|', 'omarchy-pkg-add|', 'omarchy-launch-once|')) for call in calls), calls + result, calls = install(TEST_FAIL_LAUNCH='1') + assert result.returncode != 0 + assert not any('enable --now' in call or call.startswith('sudo|') for call in calls), calls + result, calls = install() + assert result.returncode == 0, (result.stderr, calls) + assert 'omarchy-pkg-add|once' in calls + assert calls.index('omarchy-launch-once|list') < calls.index('systemctl|--user enable --now omarchy-once.service') + assert not any('sudo|once' in call or 'docker.socket' in call for call in calls), calls +print('ok - installer preserves legacy services, validates startup, and enables only user background tasks') +PY From 2b0e764d9a754d1a618446bfb8ac457356477409 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Mon, 14 Sep 2026 17:05:20 -0600 Subject: [PATCH 14/31] Allow rootless ONCE providers through engine migration --- migrations/1789164756.sh | 16 +++++--- test/shell.d/once-migration-test.sh | 58 +++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 6 deletions(-) create mode 100755 test/shell.d/once-migration-test.sh diff --git a/migrations/1789164756.sh b/migrations/1789164756.sh index 97272be94afb..1f85b2facd11 100644 --- a/migrations/1789164756.sh +++ b/migrations/1789164756.sh @@ -1,13 +1,17 @@ echo "Move development containers to rootless Docker" -# Existing ONCE deployments have a separate manager, routing state and backups. -# Generic container transfer must not silently move them away from that manager. -if pacman -Qq once-bin >/dev/null 2>&1; then - echo "ONCE is installed. Export and verify its applications before migrating engines." >&2 +# Preserve legacy ONCE managers, including those using a replacement package. +# Pacman resolves provides: the rootless once package also provides once-bin. +if ! once_provider=$(pacman -Qq once-bin 2>/dev/null); then + pacman -Qq >/dev/null + once_provider="" +fi +if [[ -n $once_provider && $once_provider != "once" ]] || + systemctl is-active --quiet once-background.service || + systemctl is-enabled --quiet once-background.service; then + echo "Legacy ONCE is installed or enabled. Export and verify its applications before migrating engines." >&2 echo "The existing ONCE service and Docker data were left unchanged; migration remains pending." >&2 exit 1 -else - pacman -Qq >/dev/null fi migration_uid=$(id -u) diff --git a/test/shell.d/once-migration-test.sh b/test/shell.d/once-migration-test.sh new file mode 100755 index 000000000000..67784114c014 --- /dev/null +++ b/test/shell.d/once-migration-test.sh @@ -0,0 +1,58 @@ +#!/bin/bash + +set -euo pipefail +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +python3 - "$ROOT" <<'PYTEST' +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +root = Path(sys.argv[1]) +migration = root / 'migrations/1789164756.sh' +# Execute the actual migration preflight up to its first mutation/setup step. +text = migration.read_text() +preflight = text.split('migration_uid=$(id -u)', 1)[0] +with tempfile.TemporaryDirectory() as directory: + work = Path(directory) + preflight_path = work / 'preflight' + preflight_path.write_text(preflight + '\necho guard-passed\n') + for name in ('pacman', 'systemctl', 'id'): + command = work / name + command.write_text('''#!/bin/bash +set -eu +case "${0##*/}" in + id) echo 1000 ;; + systemctl) + if [[ $1 == --user ]]; then exit 0; fi + [[ $TEST_LEGACY == "$1" ]] ;; + pacman) + [[ $TEST_DB != broken ]] || exit 2 + if [[ $* == '-Qq once-bin' ]]; then + [[ $TEST_ONCE != missing ]] || exit 1 + echo "$TEST_ONCE" + elif [[ $* == '-Qq docker' ]]; then + echo podman-docker + fi ;; +esac +''') + command.chmod(0o755) + for provider in ('missing', 'once', 'once-bin', 'custom-once'): + for legacy in ('none', 'is-active', 'is-enabled'): + env = dict(os.environ, PATH=f'{work}:/usr/bin', TEST_ONCE=provider, + TEST_LEGACY=legacy, TEST_DB='available') + result = subprocess.run(['bash', '-euo', 'pipefail', str(preflight_path)], + env=env, capture_output=True, text=True) + allowed = provider in ('missing', 'once') and legacy == 'none' + assert (result.returncode == 0) == allowed, (provider, legacy, result) + assert ('guard-passed' in result.stdout) == allowed, (provider, legacy, result) + if not allowed: + assert 'Legacy ONCE' in result.stderr, result + env.update(TEST_ONCE='missing', TEST_LEGACY='none', TEST_DB='broken') + result = subprocess.run(['bash', '-euo', 'pipefail', str(preflight_path)], + env=env, capture_output=True, text=True) + assert result.returncode != 0 and 'guard-passed' not in result.stdout, result +print('ok - rootless ONCE providers pass migration while legacy managers and failed package queries block it') +PYTEST From 850e10e05826120f5f172a0a485c0b30a1e41d9b Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Mon, 14 Sep 2026 17:08:35 -0600 Subject: [PATCH 15/31] Clarify which ONCE installations block engine migration --- docs/once.md | 2 +- manual/24-commercial-apps-services.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/once.md b/docs/once.md index 19e3abe46ee2..bbdc65d82567 100644 --- a/docs/once.md +++ b/docs/once.md @@ -8,6 +8,6 @@ The patch defaults the proxy to loopback HTTP 8080, HTTPS 8443 and metrics 1318. Podman's archive API differs from Docker's: backup paths are rooted at the selected volume directory, and restoring through `/` on an unstarted temporary container can write into its disposable filesystem instead of the volume. The patch normalizes engine archive paths into ONCE's `data/` format and restores directly into the mounted volume. It rejects malformed old archives instead of silently producing an empty restoration. It also waits for exec completion before interpreting exit status; a still-running exec with a provisional zero exit code is not success. -The installer enables the user background service and the engine's startup service, and enables user lingering so they run after logout and at boot. This setup can require administrator authentication; no ONCE process or application uses a root system service. Existing legacy services and stores are never automatically adopted. Installed ONCE keeps the generic engine migration pending until the administrator has explicitly exported, restored and verified its applications. +The installer enables the user background service and the engine's startup service, and enables user lingering so they run after logout and at boot. This setup can require administrator authentication; no ONCE process or application uses a root system service. Existing legacy services and stores are never automatically adopted. A legacy ONCE package or an active or enabled legacy system service keeps the generic engine migration pending for explicit, verified backup/restore. The rootless `once` package alone does not block migration. Validation must cover real application content, credentials, stop/start, replacement, backup/restore, background tasks and reboot. A successful installer or an HTTP health response alone is insufficient. Full ISO coverage remains separate from the Lab branch deployment. diff --git a/manual/24-commercial-apps-services.md b/manual/24-commercial-apps-services.md index 2937671db139..2445f8d91980 100644 --- a/manual/24-commercial-apps-services.md +++ b/manual/24-commercial-apps-services.md @@ -34,7 +34,7 @@ It gets a panel in the bar, a web app for the admin console, and Taildrop for se Run `omarchy launch once` to open the interface, or pass ONCE commands such as `omarchy launch once list`. Local applications use addresses like `http://writebook.localhost:8080`. The proxy binds only to your computer's loopback address; public hosting and automatic public HTTPS are not configured by this installer. Background work continues after logout. -Existing rootful ONCE installations need an explicit backup/restore migration. The engine migration stays pending when ONCE is installed, and the installer refuses an active or enabled legacy system service. It never silently disables that service or moves its application data. Test restored applications before retiring the old deployment. +Existing rootful ONCE installations need an explicit backup/restore migration. The engine migration stays pending for a legacy ONCE package or an active or enabled legacy system service. The rootless `once` package alone does not block migration. The installer also refuses an active or enabled legacy system service. It never silently disables that service or moves its application data. Test restored applications before retiring the old deployment. ## NordVPN From 0f2e361ee2904bdb7118b27146ba9c54f66e26b2 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Mon, 14 Sep 2026 17:28:54 -0600 Subject: [PATCH 16/31] Require initialized rootless Docker before ONCE setup --- bin/omarchy-install-service-once | 21 +++++++++++ default/omarchy/omarchy-menu.jsonc | 2 +- default/once/launch.py | 2 ++ docs/once.md | 2 +- test/shell.d/once-rootless-test.sh | 58 ++++++++++++++++++++++++++---- 5 files changed, 77 insertions(+), 8 deletions(-) diff --git a/bin/omarchy-install-service-once b/bin/omarchy-install-service-once index d87c465b6f77..98d366e5c0c6 100755 --- a/bin/omarchy-install-service-once +++ b/bin/omarchy-install-service-once @@ -17,6 +17,27 @@ if systemctl is-active --quiet once-background.service || systemctl is-enabled - exit 1 fi +# Package queries resolve providers too: once-bin satisfies "once", so the +# package helper would leave the unpatched binary installed. Never replace an +# existing manager implicitly, even when its legacy service is stopped. +if ! once_provider=$(pacman -Qq once 2>/dev/null); then + if ! pacman -Qq >/dev/null; then + echo "Cannot verify the installed ONCE package; no changes were made." >&2 + exit 1 + fi + once_provider="" +fi +if [[ -n $once_provider && $once_provider != "once" ]]; then + echo "An existing ONCE package needs an explicit backup/restore migration to the patched once package." >&2 + echo "Its package, service and application data were left unchanged." >&2 + exit 1 +fi + +if [[ ! -f $HOME/.local/state/omarchy/rootless-docker/enabled ]]; then + echo "Rootless Docker is not initialized for this account. Complete omarchy-migrate before installing ONCE." >&2 + exit 1 +fi + systemctl --user show-environment >/dev/null omarchy-pkg-add once systemctl --user daemon-reload diff --git a/default/omarchy/omarchy-menu.jsonc b/default/omarchy/omarchy-menu.jsonc index 14740ffa1610..f05349c0167a 100644 --- a/default/omarchy/omarchy-menu.jsonc +++ b/default/omarchy/omarchy-menu.jsonc @@ -225,7 +225,7 @@ "install.service.signal": {"icon":"󰭹","label":"Signal","disabled":"omarchy-pkg-present signal-desktop","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-service-signal"}, "install.service.tailscale": {"icon":"","label":"Tailscale","disabled":"omarchy-pkg-present tailscale","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-service-tailscale"}, "install.service.nordvpn": {"icon":"󱇱","label":"NordVPN","disabled":"omarchy-pkg-present nordvpn-bin","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-service-nordvpn"}, - "install.service.once": {"icon":"󰏖","label":"ONCE","disabled":"omarchy-pkg-present once-bin","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-service-once"}, + "install.service.once": {"icon":"󰏖","label":"ONCE","disabled":"systemctl --user is-enabled --quiet omarchy-once.service","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-service-once"}, "install.service.bitwarden": {"icon":"󰟵","label":"Bitwarden","disabled":"omarchy-pkg-present bitwarden","action":"omarchy-install-and-launch Bitwarden 'bitwarden bitwarden-cli' bitwarden"}, "install.service.chromium-account": {"icon":"","label":"Chromium Account","when":"[[ -f ~/.config/chromium-flags.conf ]]","disabled":"grep -q oauth2-client-id ~/.config/chromium-flags.conf","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-chromium-google-account"}, "install.editor.vscode": {"icon":"","label":"VSCode","disabled":"omarchy-pkg-present visual-studio-code-bin","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-editor-vscode"}, diff --git a/default/once/launch.py b/default/once/launch.py index b6476fdb31a1..d1929da3990d 100644 --- a/default/once/launch.py +++ b/default/once/launch.py @@ -44,6 +44,8 @@ def main(engine, args): runtime_stat = runtime.stat() if runtime_stat.st_uid != uid or stat.S_IMODE(runtime_stat.st_mode) & 0o077: raise RuntimeError("A private user runtime directory is required; log in again.") + if engine == "docker" and not (Path.home() / ".local/state/omarchy/rootless-docker/enabled").is_file(): + raise RuntimeError("Rootless Docker is not initialized for this account. Complete omarchy-migrate before launching ONCE.") env = {key: value for key, value in os.environ.items() if not key.startswith("DOCKER_")} env.update(XDG_RUNTIME_DIR=str(runtime), DBUS_SESSION_BUS_ADDRESS=f"unix:path={runtime}/bus", ONCE_NO_SELF_UPDATE="1", ONCE_ROOTLESS="1") version = subprocess.check_output(["once", "version"], env=env, text=True).strip() diff --git a/docs/once.md b/docs/once.md index bbdc65d82567..a718b97bc860 100644 --- a/docs/once.md +++ b/docs/once.md @@ -1,6 +1,6 @@ # Rootless ONCE -The optional installer uses the source-built `once` package from omarchy-pkgs. It is ONCE v0.3.2 with a small downstream patch, identified as `v0.3.2-omarchy1`; the vendor `once-bin` binary remains available separately. The launcher refuses an unpatched binary because the integration depends on proxy and backup behavior, not just API availability. +The optional installer uses the source-built `once` package from omarchy-pkgs. It is ONCE v0.3.2 with a small downstream patch, identified as `v0.3.2-omarchy1`; the vendor `once-bin` binary remains available separately. The launcher refuses an unpatched binary because the integration depends on proxy and backup behavior, not just API availability. The account must complete rootless Docker setup before installing or launching ONCE; run `omarchy-migrate` if setup remains pending. `omarchy-launch-once` pins the engine socket to the current user's `/run/user/` directory, clears Docker environment overrides, checks that the engine reports rootless operation, and selects the `omarchy-once` namespace. It sets `ONCE_ROOTLESS=1`, disables ONCE's binary self-updater, and uses a private umask for backups. The package manager owns binary updates. The user service uses the same launcher implementation through its packaged absolute path. diff --git a/test/shell.d/once-rootless-test.sh b/test/shell.d/once-rootless-test.sh index ce5852653b7c..fac7288dc9f9 100644 --- a/test/shell.d/once-rootless-test.sh +++ b/test/shell.d/once-rootless-test.sh @@ -5,6 +5,7 @@ source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" python3 - "$ROOT" <<'PY' import importlib.util +import json import os from pathlib import Path import stat @@ -23,7 +24,7 @@ spec.loader.exec_module(launcher) class Executed(Exception): pass -def simulate(engine='podman', uid=1000, version='v0.3.2-omarchy1', rootless=True, socket_owner=1000): +def simulate(engine='podman', uid=1000, version='v0.3.2-omarchy1', rootless=True, socket_owner=1000, engine_ready=True): captured = {} def metadata(path): if str(path).endswith('.sock'): @@ -37,6 +38,7 @@ def simulate(engine='podman', uid=1000, version='v0.3.2-omarchy1', rootless=True XDG_RUNTIME_DIR='/tmp/not-the-user-runtime', ONCE_ROOTLESS='0') with patch.dict(os.environ, poison, clear=True), patch.object(launcher.os, 'getuid', return_value=uid), \ patch.object(launcher.os, 'umask'), patch.object(launcher.Path, 'stat', metadata), \ + patch.object(launcher.Path, 'is_file', return_value=engine_ready), \ patch.object(launcher.subprocess, 'check_output', return_value=version), \ patch.object(launcher.subprocess, 'run') as start, \ patch.object(launcher, 'engine_info', return_value={'SecurityOptions': ['name=rootless'] if rootless else []}) as info, \ @@ -71,31 +73,65 @@ for options in ({'uid': 0}, {'version': 'v0.3.2'}): for options in ({'rootless': False}, {'socket_owner': 0}): result = simulate(**options) assert 'error' in result and 'env' not in result, result -print('ok - root, an unpatched binary, foreign sockets and rootful engines cannot launch ONCE') +result = simulate(engine='docker', engine_ready=False) +assert 'not initialized' in result['error'] and not result['start_calls'], result +print('ok - root, an unpatched binary, uninitialized Docker, foreign sockets and rootful engines cannot launch ONCE') with tempfile.TemporaryDirectory() as directory: directory = Path(directory) log = directory / 'calls' - for name in ('systemctl', 'sudo', 'omarchy-pkg-add', 'omarchy-launch-once'): + for name in ('systemctl', 'sudo', 'pacman', 'omarchy-pkg-add', 'omarchy-launch-once'): script = directory / name script.write_text('''#!/bin/bash echo "${0##*/}|$*" >> "$TEST_LOG" -if [[ ${0##*/} == systemctl && $1 != --user ]]; then +if [[ ${0##*/} == pacman ]]; then + [[ ${TEST_ONCE_PROVIDER:-missing} != broken ]] || exit 1 + if [[ $* == "-Qq once" ]]; then + [[ ${TEST_ONCE_PROVIDER:-missing} != missing ]] || exit 1 + echo "$TEST_ONCE_PROVIDER" + elif [[ $* != "-Qq" ]]; then + exit 2 + fi +elif [[ ${0##*/} == systemctl && $* == "--user is-enabled --quiet omarchy-once.service" ]]; then + [[ ${TEST_ONCE_ENABLED:-0} == 1 ]] +elif [[ ${0##*/} == systemctl && $1 != --user ]]; then [[ ${TEST_LEGACY:-none} == "$1" ]] elif [[ ${0##*/} == omarchy-launch-once && ${TEST_FAIL_LAUNCH:-0} == 1 ]]; then exit 1 fi ''') script.chmod(0o755) - def install(**settings): + home = directory / 'home' + marker = home / '.local/state/omarchy/rootless-docker/enabled' + marker.parent.mkdir(parents=True) + def install(engine_ready=True, **settings): + if engine_ready: + marker.touch() + else: + marker.unlink(missing_ok=True) log.write_text('') - env = dict(os.environ, PATH=f'{directory}:/usr/bin', TEST_LOG=str(log), **settings) + env = dict(os.environ, PATH=f'{directory}:/usr/bin', HOME=str(home), TEST_LOG=str(log), **settings) process = subprocess.run(['bash', str(root / 'bin/omarchy-install-service-once')], env=env, capture_output=True, text=True) return process, log.read_text().splitlines() for state in ('is-active', 'is-enabled'): result, calls = install(TEST_LEGACY=state) assert result.returncode != 0, result assert not any(call.startswith(('sudo|', 'omarchy-pkg-add|', 'omarchy-launch-once|')) for call in calls), calls + for provider in ('once-bin', 'once-custom', 'broken'): + result, calls = install(TEST_ONCE_PROVIDER=provider) + assert result.returncode != 0, (provider, result) + assert not any(call.startswith(('sudo|', 'omarchy-pkg-add|', 'omarchy-launch-once|', 'systemctl|--user')) for call in calls), calls + if provider == 'broken': + assert 'Cannot verify' in result.stderr, result.stderr + else: + assert 'backup/restore migration' in result.stderr, result.stderr + for provider in ('once', 'missing'): + result, calls = install(TEST_ONCE_PROVIDER=provider) + assert result.returncode == 0, (provider, result.stderr, calls) + assert calls.index('pacman|-Qq once') < calls.index('omarchy-pkg-add|once'), calls + result, calls = install(engine_ready=False) + assert result.returncode != 0 and 'not initialized' in result.stderr, result + assert not any(call.startswith(('sudo|', 'omarchy-pkg-add|', 'omarchy-launch-once|', 'systemctl|--user')) for call in calls), calls result, calls = install(TEST_FAIL_LAUNCH='1') assert result.returncode != 0 assert not any('enable --now' in call or call.startswith('sudo|') for call in calls), calls @@ -104,5 +140,15 @@ fi assert 'omarchy-pkg-add|once' in calls assert calls.index('omarchy-launch-once|list') < calls.index('systemctl|--user enable --now omarchy-once.service') assert not any('sudo|once' in call or 'docker.socket' in call for call in calls), calls + menu_line = next(line for line in (root / 'default/omarchy/omarchy-menu.jsonc').read_text().splitlines() + if '"install.service.once":' in line) + menu = json.loads('{' + menu_line.strip().rstrip(',') + '}')['install.service.once'] + for enabled in ('0', '1'): + result = subprocess.run(['bash', '-c', menu['disabled']], + env=dict(os.environ, PATH=f'{directory}:/usr/bin', TEST_LOG=str(log), TEST_ONCE_ENABLED=enabled), + capture_output=True, text=True) + assert (result.returncode == 0) == (enabled == '1'), result +print('ok - ONCE setup remains available from the menu until its user service is enabled') print('ok - installer preserves legacy services, validates startup, and enables only user background tasks') +print('ok - installer accepts only the source ONCE package or an absent package, preserving foreign providers and refusing database failures') PY From 9fda8c2b936a46a2368c2d3df794964a2208b4db Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Mon, 14 Sep 2026 17:28:54 -0600 Subject: [PATCH 17/31] Allow Windows commands with unused symlinked user config --- bin/omarchy-windows-vm | 7 +++++- test/shell.d/windows-vm-auth-test.sh | 2 ++ test/shell.d/windows-vm-compose-test.sh | 31 +++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/bin/omarchy-windows-vm b/bin/omarchy-windows-vm index 2642bc3db328..37236da163ed 100755 --- a/bin/omarchy-windows-vm +++ b/bin/omarchy-windows-vm @@ -1342,7 +1342,12 @@ remove_legacy_compose() { sync_legacy_compose_parent() { local parent parent=$(dirname -- "$LEGACY_COMPOSE_FILE") - if [[ -e $parent || -L $parent ]]; then + # A linked user config directory with no legacy definition has nothing to + # synchronize. Existing private root configuration remains authoritative; + # actual legacy removals still require the real directory below. + if [[ -L $parent && ! -e $LEGACY_COMPOSE_FILE && ! -L $LEGACY_COMPOSE_FILE ]]; then + assert_compose_trusted && compose_root_private + elif [[ -e $parent || -L $parent ]]; then [[ -d $parent && ! -L $parent ]] || return 1 fsync_directory "$parent" fi diff --git a/test/shell.d/windows-vm-auth-test.sh b/test/shell.d/windows-vm-auth-test.sh index 28e86f50a520..e39d8ff15d39 100644 --- a/test/shell.d/windows-vm-auth-test.sh +++ b/test/shell.d/windows-vm-auth-test.sh @@ -51,6 +51,8 @@ trap 'rm -rf "$test_dir"' EXIT touch "$test_dir/docker-compose.yml" MODE_LOG="$test_dir/mode" OMARCHY_WINDOWS_DIR="$test_dir" ROOT="$ROOT" bash -c ' set -e + export HOME="$OMARCHY_WINDOWS_DIR/home" + mkdir -p "$HOME" set -- help source "$ROOT/bin/omarchy-windows-vm" >/dev/null priv() { printf "priv:%s\n" "$1" >>"$MODE_LOG"; } diff --git a/test/shell.d/windows-vm-compose-test.sh b/test/shell.d/windows-vm-compose-test.sh index dfa38bcab771..aaa2c2a9c632 100644 --- a/test/shell.d/windows-vm-compose-test.sh +++ b/test/shell.d/windows-vm-compose-test.sh @@ -260,6 +260,37 @@ grep -Fxq "$(dirname -- "$LEGACY_COMPOSE_FILE")" "$fsync_log" || fail "an apparently completed legacy unlink was not synchronized on retry" pass "ordinary retries synchronize a previously interrupted legacy unlink" +# User configuration may be linked elsewhere after the root definition owns +# the VM. It must not block ordinary reconciliation or the migration's secure +# action, and must never make a legacy deletion through that link acceptable. +mv "$HOME/.config/windows" "$TMPDIR/windows-config" +ln -s "$TMPDIR/windows-config" "$HOME/.config/windows" +: >"$fsync_log" +migrate_legacy_compose || fail "linked user config blocked an existing private root definition" +[[ ! -s $fsync_log ]] || fail "empty linked legacy directory was synchronized" +( + priv() { + [[ $1 == secure ]] || fail "unexpected migration action" + assert_compose_trusted && compose_root_private + printf 'secure\n' >"$TMPDIR/linked-config-secure" + } + secure_windows_migration || fail "linked user config blocked root migration security checks" +) +[[ $(<"$TMPDIR/linked-config-secure") == secure ]] || fail "migration skipped its root security action" +printf 'legacy credentials\n' >"$LEGACY_COMPOSE_FILE" +migrate_legacy_compose && fail "legacy removal through a linked config directory was accepted" +[[ $(<"$LEGACY_COMPOSE_FILE") == "legacy credentials" ]] || fail "linked legacy definition was changed" +rm "$LEGACY_COMPOSE_FILE" +ln -s "$TMPDIR/missing-legacy" "$LEGACY_COMPOSE_FILE" +migrate_legacy_compose && fail "dangling legacy symlink bypassed the directory boundary" +rm "$LEGACY_COMPOSE_FILE" +chmod 0644 "$COMPOSE" +migrate_legacy_compose && fail "non-private root definition bypassed the linked config boundary" +chmod 0600 "$COMPOSE" +rm "$HOME/.config/windows" +mv "$TMPDIR/windows-config" "$HOME/.config/windows" +pass "linked user config permits private root operations without authorizing legacy removals" + # A crash after the root-owned Compose rename but before its directory fsync can # leave both definitions. Retry must authenticate, synchronize the trusted file, # and only then durably remove the old credential-bearing user file. From 3a2156b8fd9862648188ce070907e0df71a692c5 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Mon, 14 Sep 2026 17:42:14 -0600 Subject: [PATCH 18/31] Support linked Windows config throughout setup and migration --- bin/omarchy-windows-vm | 10 ++++-- test/shell.d/windows-vm-compose-test.sh | 45 +++++++++++++++++++++---- 2 files changed, 46 insertions(+), 9 deletions(-) diff --git a/bin/omarchy-windows-vm b/bin/omarchy-windows-vm index 37236da163ed..f94471ff7ca7 100755 --- a/bin/omarchy-windows-vm +++ b/bin/omarchy-windows-vm @@ -1231,6 +1231,7 @@ write_credentials() { local username="$1" password="$2" old_umask dir tmp dir=$(dirname -- "$CREDENTIALS_FILE") mkdir -p "$dir" || return 1 + dir=$(realpath -e -- "$dir") || return 1 chmod 0700 "$dir" || return 1 old_umask=$(umask) umask 077 @@ -1343,12 +1344,15 @@ sync_legacy_compose_parent() { local parent parent=$(dirname -- "$LEGACY_COMPOSE_FILE") # A linked user config directory with no legacy definition has nothing to - # synchronize. Existing private root configuration remains authoritative; + # synchronize. The privileged action checks or repairs the root definition; # actual legacy removals still require the real directory below. if [[ -L $parent && ! -e $LEGACY_COMPOSE_FILE && ! -L $LEGACY_COMPOSE_FILE ]]; then - assert_compose_trusted && compose_root_private + return 0 elif [[ -e $parent || -L $parent ]]; then - [[ -d $parent && ! -L $parent ]] || return 1 + [[ -d $parent && ! -L $parent ]] || { + echo "omarchy-windows-vm: legacy configuration requires a real directory: $parent" >&2 + return 1 + } fsync_directory "$parent" fi } diff --git a/test/shell.d/windows-vm-compose-test.sh b/test/shell.d/windows-vm-compose-test.sh index aaa2c2a9c632..89434a5ba6e5 100644 --- a/test/shell.d/windows-vm-compose-test.sh +++ b/test/shell.d/windows-vm-compose-test.sh @@ -260,8 +260,8 @@ grep -Fxq "$(dirname -- "$LEGACY_COMPOSE_FILE")" "$fsync_log" || fail "an apparently completed legacy unlink was not synchronized on retry" pass "ordinary retries synchronize a previously interrupted legacy unlink" -# User configuration may be linked elsewhere after the root definition owns -# the VM. It must not block ordinary reconciliation or the migration's secure +# User configuration may be linked elsewhere independently of VM setup. It +# must not block ordinary reconciliation or the migration's secure # action, and must never make a legacy deletion through that link acceptable. mv "$HOME/.config/windows" "$TMPDIR/windows-config" ln -s "$TMPDIR/windows-config" "$HOME/.config/windows" @@ -271,25 +271,49 @@ migrate_legacy_compose || fail "linked user config blocked an existing private r ( priv() { [[ $1 == secure ]] || fail "unexpected migration action" - assert_compose_trusted && compose_root_private + assert_compose_trusted && compose_root_private || fail "root definition is not trusted and private" printf 'secure\n' >"$TMPDIR/linked-config-secure" } secure_windows_migration || fail "linked user config blocked root migration security checks" ) [[ $(<"$TMPDIR/linked-config-secure") == secure ]] || fail "migration skipped its root security action" printf 'legacy credentials\n' >"$LEGACY_COMPOSE_FILE" -migrate_legacy_compose && fail "legacy removal through a linked config directory was accepted" +legacy_error=$(migrate_legacy_compose 2>&1) && fail "legacy removal through a linked config directory was accepted" +[[ $legacy_error == *"$HOME/.config/windows"* ]] || fail "unsafe legacy directory error omitted its path" [[ $(<"$LEGACY_COMPOSE_FILE") == "legacy credentials" ]] || fail "linked legacy definition was changed" rm "$LEGACY_COMPOSE_FILE" ln -s "$TMPDIR/missing-legacy" "$LEGACY_COMPOSE_FILE" migrate_legacy_compose && fail "dangling legacy symlink bypassed the directory boundary" rm "$LEGACY_COMPOSE_FILE" chmod 0644 "$COMPOSE" -migrate_legacy_compose && fail "non-private root definition bypassed the linked config boundary" +migrate_legacy_compose || fail "linked user config blocked a root definition awaiting repair" +( + priv() { + [[ $1 == secure ]] || fail "unexpected root repair action" + [[ $(stat -c '%a' "$COMPOSE_FILE") == 644 ]] || fail "root permissions changed before authorization" + printf 'repair\n' >"$TMPDIR/linked-config-repair" + } + secure_windows_migration || fail "linked user config blocked authenticated root repair" +) +[[ $(<"$TMPDIR/linked-config-repair") == repair ]] || fail "migration skipped root repair authorization" chmod 0600 "$COMPOSE" +( + COMPOSE_FILE="$TMPDIR/no-vm-compose.yml" + priv() { + [[ $1 == secure ]] || fail "unexpected absent VM action" + __priv_secure + } + docker() { + [[ $1 == inspect && $2 == "$CONTAINER" ]] || fail "unexpected absent VM Docker command" + printf 'inspect\n' >"$TMPDIR/linked-config-no-vm" + return 1 + } + secure_windows_migration || fail "linked user config blocked migration without a VM" +) +[[ $(<"$TMPDIR/linked-config-no-vm") == inspect ]] || fail "migration skipped the privileged absent VM check" rm "$HOME/.config/windows" mv "$TMPDIR/windows-config" "$HOME/.config/windows" -pass "linked user config permits private root operations without authorizing legacy removals" +pass "linked user config permits root operations, repair and absent VMs without authorizing legacy removals" # A crash after the root-owned Compose rename but before its directory fsync can # leave both definitions. Retry must authenticate, synchronize the trusted file, @@ -696,6 +720,15 @@ unset -f mv ! find "$credentials_dir" -name '.credentials.*' -print -quit | grep -q . || fail "failed credentials write left a temporary file" pass "credentials are atomically replaced as a private regular file" +# A linked user config directory is valid; synchronize its actual directory. +mv "$credentials_dir" "$TMPDIR/linked-credentials-target" +ln -s "$TMPDIR/linked-credentials-target" "$credentials_dir" +write_credentials linked 'private=value' || fail "linked credentials directory rejected" +[[ $(read_credential USERNAME) == linked && $(read_credential PASSWORD) == 'private=value' ]] || fail "linked credentials did not round-trip" +[[ $(stat -c '%a' "$TMPDIR/linked-credentials-target") == 700 && $(stat -c '%a' "$CREDENTIALS_FILE") == 600 ]] || fail "linked credentials are not private" +pass "credentials support a linked user configuration directory" + + # Free-space accounting follows the real storage target. reset_case mkdir -p "$external_storage" "$HOME/Windows" From 0a1dce1ef673a333adce9dbf4203b00e6a210006 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Mon, 14 Sep 2026 17:51:33 -0600 Subject: [PATCH 19/31] Preserve private Windows credentials across setup and removal --- bin/omarchy-windows-vm | 71 ++++++--- test/shell.d/windows-vm-compose-test.sh | 1 + test/shell.d/windows-vm-credentials-test.sh | 158 ++++++++++++++++++++ 3 files changed, 213 insertions(+), 17 deletions(-) create mode 100644 test/shell.d/windows-vm-credentials-test.sh diff --git a/bin/omarchy-windows-vm b/bin/omarchy-windows-vm index f94471ff7ca7..286fb3ae6302 100755 --- a/bin/omarchy-windows-vm +++ b/bin/omarchy-windows-vm @@ -1227,12 +1227,22 @@ decode_legacy_field() { # Store the RDP credentials privately for the user (0600) so the plaintext # password is not world-readable. The password is one validated printable line # (no newline), so plain KEY=VALUE is safe. -write_credentials() { - local username="$1" password="$2" old_umask dir tmp +credentials_directory() { + local dir + if [[ -d $CREDENTIALS_FILE && ! -L $CREDENTIALS_FILE ]]; then + echo "omarchy-windows-vm: credentials path is a directory: $CREDENTIALS_FILE" >&2 + return 1 + fi dir=$(dirname -- "$CREDENTIALS_FILE") mkdir -p "$dir" || return 1 dir=$(realpath -e -- "$dir") || return 1 chmod 0700 "$dir" || return 1 + printf '%s\n' "$dir" +} + +write_credentials() { + local username="$1" password="$2" old_umask dir tmp + dir=$(credentials_directory) || return 1 old_umask=$(umask) umask 077 tmp=$(mktemp "$dir/.credentials.XXXXXX") || { umask "$old_umask"; return 1; } @@ -1246,6 +1256,34 @@ write_credentials() { umask "$old_umask" } +# Validate and stage credentials before privileged installation. A failed +# Compose write leaves an existing VM's credentials unchanged. +write_install_configuration() ( + local dir candidate + dir=$(credentials_directory) || { + echo "❌ Could not prepare the private RDP credentials directory." >&2 + exit 1 + } + candidate=$(mktemp "$dir/.credentials-install.XXXXXX") || exit 1 + trap 'rm -f -- "$candidate"' EXIT + CREDENTIALS_FILE="$candidate" write_credentials "$4" "$5" || { + echo "❌ Failed to stage private RDP credentials." >&2 + exit 1 + } + write_compose "$@" || { + echo "❌ Failed to write the Windows VM configuration." >&2 + exit 1 + } + mv -fT -- "$candidate" "$CREDENTIALS_FILE" || { + echo "❌ Failed to publish private RDP credentials. The VM was not started." >&2 + exit 1 + } + fsync_directory "$dir" || { + echo "❌ Failed to synchronize private RDP credentials. The VM was not started." >&2 + exit 1 + } +) + # Read one field from the private credentials file; IFS on the first = keeps a # password that itself contains =. read_credential() { @@ -1341,6 +1379,10 @@ remove_legacy_compose() { } sync_legacy_compose_parent() { + if [[ -L $LEGACY_COMPOSE_FILE ]]; then + echo "omarchy-windows-vm: legacy configuration must not be a symlink: $LEGACY_COMPOSE_FILE" >&2 + return 1 + fi local parent parent=$(dirname -- "$LEGACY_COMPOSE_FILE") # A linked user config directory with no legacy definition has nothing to @@ -1551,18 +1593,8 @@ EOF local tz tz=$(timedatectl show -p Timezone --value 2>/dev/null || echo UTC) - # Write the root-owned compose from the validated settings. The writer pins - # the familiar home directories (or - # their legitimate symlink targets) into root-protected bind anchors. - write_compose "$SELECTED_RAM" "$SELECTED_CORES" "$SELECTED_DISK" \ - "$USERNAME" "$PASSWORD" "$tz" || { - echo "❌ Failed to write the Windows VM configuration." - exit 1 - } - write_credentials "$USERNAME" "$PASSWORD" || { - echo "❌ Failed to store private RDP credentials." >&2 - exit 1 - } + write_install_configuration "$SELECTED_RAM" "$SELECTED_CORES" "$SELECTED_DISK" \ + "$USERNAME" "$PASSWORD" "$tz" || exit 1 echo "" echo "Starting Windows VM installation..." @@ -1623,9 +1655,14 @@ remove_windows() { } fi - rm -f "$HOME/.local/share/applications/windows-vm.desktop" - rm -rf "$HOME/.config/windows" - rm -rf "$HOME/.windows" + # Remove credentials through a linked config directory before removing + # the link itself, and retain the link if that cleanup fails. + if ! rm -f -- "$CREDENTIALS_FILE" || + ! rm -f -- "$HOME/.local/share/applications/windows-vm.desktop" || + ! rm -rf -- "$HOME/.config/windows" "$HOME/.windows"; then + echo "❌ Windows VM user data cleanup failed; inspect the remaining files before retrying." >&2 + exit 1 + fi echo "" echo "Windows VM removal completed!" diff --git a/test/shell.d/windows-vm-compose-test.sh b/test/shell.d/windows-vm-compose-test.sh index 89434a5ba6e5..2e9a5ca0f89e 100644 --- a/test/shell.d/windows-vm-compose-test.sh +++ b/test/shell.d/windows-vm-compose-test.sh @@ -723,6 +723,7 @@ pass "credentials are atomically replaced as a private regular file" # A linked user config directory is valid; synchronize its actual directory. mv "$credentials_dir" "$TMPDIR/linked-credentials-target" ln -s "$TMPDIR/linked-credentials-target" "$credentials_dir" +chmod 0755 "$TMPDIR/linked-credentials-target" write_credentials linked 'private=value' || fail "linked credentials directory rejected" [[ $(read_credential USERNAME) == linked && $(read_credential PASSWORD) == 'private=value' ]] || fail "linked credentials did not round-trip" [[ $(stat -c '%a' "$TMPDIR/linked-credentials-target") == 700 && $(stat -c '%a' "$CREDENTIALS_FILE") == 600 ]] || fail "linked credentials are not private" diff --git a/test/shell.d/windows-vm-credentials-test.sh b/test/shell.d/windows-vm-credentials-test.sh new file mode 100644 index 000000000000..755cdfff4adc --- /dev/null +++ b/test/shell.d/windows-vm-credentials-test.sh @@ -0,0 +1,158 @@ +#!/bin/bash + +set -euo pipefail +source "$(dirname -- "${BASH_SOURCE[0]}")/base-test.sh" + +python3 - <<'PY' +import os +from pathlib import Path +import subprocess +import tempfile + +prefix = r''' +set -euo pipefail +set -- help +source "$ROOT/bin/omarchy-windows-vm" >/dev/null +mkdir -p "$HOME/.config/windows" "$OMARCHY_WINDOWS_DIR" +CREDENTIALS_FILE="$HOME/.config/windows/credentials" +TEST_PUBLISH_PATH=$CREDENTIALS_FILE +prepare_user_mount_sources() { :; } +check_prerequisites() { :; } +omarchy-pkg-add() { :; } +available_storage_gb() { printf 128; } +timedatectl() { printf UTC; } +sleep() { :; } +xdg-open() { :; } +gum() { + case "$1" in + choose) + cat >/dev/null + if [[ $* == *RAM* ]]; then printf 4G; else printf 64G; fi + ;; + input) + if [[ $* == *CPU* ]]; then printf 2 + elif [[ $* == *username* ]]; then printf testuser + else printf testpass + fi + ;; + style | confirm) : ;; + *) return 1 ;; + esac +} +write_compose() { printf 'compose\n' >>"$TEST_LOG"; } +priv() { printf 'priv:%s\n' "$1" >>"$TEST_LOG"; } +''' + + +def run_case(name, body, status=0, setup=None): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + home = root / 'home' + home.mkdir() + env = dict(os.environ, HOME=str(home), OMARCHY_WINDOWS_DIR=str(root / 'runtime'), + TEST_ROOT=str(root), TEST_LOG=str(root / 'calls')) + if setup: + setup(root) + result = subprocess.run(['/bin/bash', '-c', prefix + body], env=env, + capture_output=True, text=True, timeout=20) + assert result.returncode == status, (name, result.returncode, result.stdout, result.stderr) + print('ok - ' + name) + return result + + +for fixture in ('dangling-parent', 'file-parent', 'directory-destination'): + body = r''' +case "$FIXTURE" in + dangling-parent) + rmdir "$HOME/.config/windows" + ln -s "$TEST_ROOT/missing" "$HOME/.config/windows" + ;; + file-parent) + rmdir "$HOME/.config/windows" + touch "$HOME/.config/windows" + ;; + directory-destination) mkdir "$CREDENTIALS_FILE" ;; +esac +if (install_windows); then exit 9; fi +[[ ! -e $TEST_LOG ]] +'''.replace('$FIXTURE', fixture) + run_case('install rejects ' + fixture + ' before privileged configuration', body) + +run_case('failed Compose staging preserves existing credentials and removes private candidates', r''' +write_credentials previous oldpass +before=$(sha256sum "$CREDENTIALS_FILE") +write_compose() { + [[ $(read_credential PASSWORD) == oldpass ]] || exit 9 + candidates=("$HOME/.config/windows"/.credentials-install.*) + [[ ${#candidates[@]} == 1 && -f ${candidates[0]} ]] || exit 9 + [[ $(stat -c '%a' "${candidates[0]}") == 600 ]] || exit 9 + printf 'compose\n' >>"$TEST_LOG" + return 7 +} +if (install_windows); then exit 9; fi +[[ $(sha256sum "$CREDENTIALS_FILE") == "$before" ]] +[[ $(<"$TEST_LOG") == compose ]] +[[ -z $(find "$HOME/.config/windows" -name '.credentials*' -print) ]] +''') + +run_case('publication failure preserves prior credentials, cleans staging and never starts VM', r''' +write_credentials previous oldpass +before=$(sha256sum "$CREDENTIALS_FILE") +mv() { + if [[ ${!#} == "$TEST_PUBLISH_PATH" ]]; then return 1; fi + command mv "$@" +} +if (install_windows); then exit 9; fi +[[ $(sha256sum "$CREDENTIALS_FILE") == "$before" ]] +[[ $(<"$TEST_LOG") == compose ]] +[[ -z $(find "$HOME/.config/windows" -name '.credentials*' -print) ]] +''') + +run_case('install publishes staged credentials before starting VM', r''' +priv() { + [[ $1 == up && $(read_credential PASSWORD) == testpass ]] || exit 9 + printf 'priv:up\n' >>"$TEST_LOG" +} +install_windows +[[ $(<"$TEST_LOG") == $'compose\npriv:up' ]] +[[ $(stat -c '%a' "$CREDENTIALS_FILE") == 600 ]] +[[ -z $(find "$HOME/.config/windows" -name '.credentials*' -print) ]] +''') + +run_case('linked config removal deletes actual credentials and preserves unrelated target files', r''' +mv "$HOME/.config/windows" "$TEST_ROOT/config-target" +ln -s "$TEST_ROOT/config-target" "$HOME/.config/windows" +chmod 0755 "$TEST_ROOT/config-target" +write_credentials linked secret +[[ $(stat -c '%a' "$TEST_ROOT/config-target") == 700 ]] +touch "$TEST_ROOT/config-target/keep" +migrate_legacy_compose() { return 1; } +remove_windows +[[ ! -e $TEST_ROOT/config-target/credentials && -f $TEST_ROOT/config-target/keep ]] +[[ ! -L $HOME/.config/windows && ! -e $HOME/.config/windows ]] +''') + +run_case('credential deletion failure retains the config link and reports removal failure', r''' +mv "$HOME/.config/windows" "$TEST_ROOT/config-target" +ln -s "$TEST_ROOT/config-target" "$HOME/.config/windows" +write_credentials linked secret +migrate_legacy_compose() { return 1; } +rm() { + if [[ ${!#} == "$CREDENTIALS_FILE" ]]; then return 1; fi + command rm "$@" +} +if (remove_windows); then exit 9; fi +[[ -L $HOME/.config/windows && -f $TEST_ROOT/config-target/credentials ]] +''') + +run_case('real and dangling legacy Compose symlinks remain untouched without migration', r''' +printf 'legacy plaintext\n' >"$TEST_ROOT/legacy-target" +for target in "$TEST_ROOT/legacy-target" "$TEST_ROOT/missing-target"; do + ln -s "$target" "$LEGACY_COMPOSE_FILE" + if migrate_legacy_compose; then exit 9; fi + [[ -L $LEGACY_COMPOSE_FILE && ! -e $TEST_LOG ]] + [[ $(<"$TEST_ROOT/legacy-target") == 'legacy plaintext' ]] + rm "$LEGACY_COMPOSE_FILE" +done +''') +PY From 1a909d707520169838e3a1df6130599c14d03421 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Mon, 14 Sep 2026 17:55:06 -0600 Subject: [PATCH 20/31] Remove interrupted Windows credential candidates --- bin/omarchy-windows-vm | 9 ++++++--- test/shell.d/windows-vm-credentials-test.sh | 12 +++++++++++- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/bin/omarchy-windows-vm b/bin/omarchy-windows-vm index 286fb3ae6302..144a6b6a5c2b 100755 --- a/bin/omarchy-windows-vm +++ b/bin/omarchy-windows-vm @@ -1655,9 +1655,12 @@ remove_windows() { } fi - # Remove credentials through a linked config directory before removing - # the link itself, and retain the link if that cleanup fails. - if ! rm -f -- "$CREDENTIALS_FILE" || + # Remove credentials and candidates left by an interrupted install through + # a linked config directory before removing the link itself. + local credentials_dir + credentials_dir=$(dirname -- "$CREDENTIALS_FILE") + if ! rm -f -- "$CREDENTIALS_FILE" \ + "$credentials_dir"/.credentials-install.* "$credentials_dir"/.credentials.* || ! rm -f -- "$HOME/.local/share/applications/windows-vm.desktop" || ! rm -rf -- "$HOME/.config/windows" "$HOME/.windows"; then echo "❌ Windows VM user data cleanup failed; inspect the remaining files before retrying." >&2 diff --git a/test/shell.d/windows-vm-credentials-test.sh b/test/shell.d/windows-vm-credentials-test.sh index 755cdfff4adc..c6fbf75e37d0 100644 --- a/test/shell.d/windows-vm-credentials-test.sh +++ b/test/shell.d/windows-vm-credentials-test.sh @@ -126,8 +126,18 @@ chmod 0755 "$TEST_ROOT/config-target" write_credentials linked secret [[ $(stat -c '%a' "$TEST_ROOT/config-target") == 700 ]] touch "$TEST_ROOT/config-target/keep" +# These private candidates model SIGKILL/power-loss leftovers with no EXIT trap. +for candidate in .credentials-install.ABC123 .credentials.XYZ123; do + printf 'interrupted private credentials\n' >"$TEST_ROOT/config-target/$candidate" + chmod 0600 "$TEST_ROOT/config-target/$candidate" +done +# Cleanup must unlink a planted candidate symlink without following its target. +printf 'external data\n' >"$TEST_ROOT/candidate-victim" +ln -s "$TEST_ROOT/candidate-victim" "$TEST_ROOT/config-target/.credentials.LINK12" migrate_legacy_compose() { return 1; } remove_windows +[[ -z $(find "$TEST_ROOT/config-target" -name '.credentials*' -print) ]] +[[ $(<"$TEST_ROOT/candidate-victim") == 'external data' ]] [[ ! -e $TEST_ROOT/config-target/credentials && -f $TEST_ROOT/config-target/keep ]] [[ ! -L $HOME/.config/windows && ! -e $HOME/.config/windows ]] ''') @@ -138,7 +148,7 @@ ln -s "$TEST_ROOT/config-target" "$HOME/.config/windows" write_credentials linked secret migrate_legacy_compose() { return 1; } rm() { - if [[ ${!#} == "$CREDENTIALS_FILE" ]]; then return 1; fi + if [[ " $* " == *" $CREDENTIALS_FILE "* ]]; then return 1; fi command rm "$@" } if (remove_windows); then exit 9; fi From 1695ad55c2430104662bf669f53da65905e777f1 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Mon, 12 Oct 2026 15:33:29 -0600 Subject: [PATCH 21/31] Recover failed rootless Docker cutovers safely --- default/docker/rootless/migrate.py | 101 ++++++++++++---- migrations/1789164756.sh | 16 +++ .../rootless-docker-failure-recovery-test.sh | 112 ++++++++++++++++++ .../shell.d/rootless-docker-migration-test.sh | 12 ++ 4 files changed, 218 insertions(+), 23 deletions(-) create mode 100644 test/shell.d/rootless-docker-failure-recovery-test.sh diff --git a/default/docker/rootless/migrate.py b/default/docker/rootless/migrate.py index 0047dacc4265..879721f828db 100644 --- a/default/docker/rootless/migrate.py +++ b/default/docker/rootless/migrate.py @@ -1878,6 +1878,29 @@ def verify_resumable_migration(container, target, intent): return planned, state +def stop_unverified_destination(container, intent): + """Retain both stores while fencing only the journal-owned destination.""" + destination = intent.get("destination") or {} + identity = destination.get("id", "") + if not re.fullmatch(r"[a-f0-9]{64}", identity): + raise RuntimeError("the unverified destination identity is not journaled") + target = inspect(TARGET, "container", identity) + if target.get("Id") != identity or not target_owned(container, target, intent): + raise RuntimeError("unverified destination ownership changed; it was left untouched") + failures = [] + for command in ((TARGET, "update", "--restart=no", identity), + (TARGET, "stop", "-t", str(configured_stop_timeout(container)), identity)): + try: + run(*command) + except Exception as error: + failures.append(error) + target = inspect(TARGET, "container", identity) + if (failures or target.get("Id") != identity or not target_owned(container, target, intent) or + target["State"]["Running"] or + (target["HostConfig"].get("RestartPolicy") or {}).get("Name") != "no"): + raise RuntimeError("unverified destination could not be fenced; inspect both engines") + + def resume_verified_migration(container, target, intent): name = container["Name"].lstrip("/") planned, state = verify_resumable_migration(container, target, intent) @@ -1890,34 +1913,42 @@ def resume_verified_migration(container, target, intent): (source_after["HostConfig"].get("RestartPolicy") or {}).get("Name") != "no"): raise RuntimeError(f"{name}: rootful source changed during resumed finalization") - if intent["target_running"] and not target["State"]["Running"]: - intent["start_attempted"] = True - persist_migration_intent(source_after, intent) - run(TARGET, "start", name) - target = inspect(TARGET, "container", name) - if bool(target["State"]["Running"]) != intent["target_running"]: - raise RuntimeError(f"{name}: resumed destination lifecycle differs from the source") - expected_volumes = {destination_volume(planned, mount) for mount in planned.get("Mounts", [])} - event_window = intent.get("volume_event") - if expected_volumes and event_window is None: - raise RuntimeError(f"{name}: interrupted destination volume event history is missing") - if event_window is not None: - verify_volume_event_window(planned, intent, event_window, expected_volumes, - target["Id"] if intent["target_running"] else None) - verified_target = verify_runtime(planned, intent["target_ownership"], intent["source_nofile"]) completion_published = False try: - record_completion(source_after, state, intent["target_running"], verified_target) - completion_published = True + if intent["target_running"] and not target["State"]["Running"]: + intent["start_attempted"] = True + persist_migration_intent(source_after, intent) + run(TARGET, "start", name) + target = inspect(TARGET, "container", name) + if bool(target["State"]["Running"]) != intent["target_running"]: + raise RuntimeError(f"{name}: resumed destination lifecycle differs from the source") + expected_volumes = {destination_volume(planned, mount) for mount in planned.get("Mounts", [])} + event_window = intent.get("volume_event") + if expected_volumes and event_window is None: + raise RuntimeError(f"{name}: interrupted destination volume event history is missing") if event_window is not None: - remove_volume_event_marker(planned, intent) - intent = release_transfer_image(source_after, intent) - clear_migration_intent(container["Id"]) + verify_volume_event_window(planned, intent, event_window, expected_volumes, + target["Id"] if intent["target_running"] else None) + verified_target = verify_runtime(planned, intent["target_ownership"], intent["source_nofile"]) + try: + record_completion(source_after, state, intent["target_running"], verified_target) + completion_published = True + if event_window is not None: + remove_volume_event_marker(planned, intent) + intent = release_transfer_image(source_after, intent) + clear_migration_intent(container["Id"]) + except BaseException: + if completion_published: + print(f"{name}: migration completed; transfer-image journal cleanup remains pending", file=sys.stderr) + raise + print(f"{name}: completed the interrupted rootless Docker migration") except BaseException: - if completion_published: - print(f"{name}: migration completed; transfer-image journal cleanup remains pending", file=sys.stderr) + if not completion_published and not completion_path(container["Id"]).exists() and intent["start_attempted"]: + try: + stop_unverified_destination(planned, intent) + except Exception as error: + print(f"{name}: {error}", file=sys.stderr) raise - print(f"{name}: completed the interrupted rootless Docker migration") def migrate(container, source_nofile): @@ -2245,6 +2276,10 @@ def migrate(container, source_nofile): print(f"{name}: migration completed; transfer-image journal cleanup remains pending", file=sys.stderr) raise if start_attempted: + try: + stop_unverified_destination(planned, intent) + except Exception as error: + print(f"{name}: {error}", file=sys.stderr) print(f"{name}: destination start was attempted; both copies were retained for recovery. " "Inspect rootless Docker before resuming the rootful copy or retrying migration.", file=sys.stderr) raise @@ -2350,6 +2385,26 @@ def main(): validate_target_policy() cleanup_nofile_probe() return + if sys.argv[1:2] == ["--restore-quiesced-all"]: + if len(sys.argv) < 3: + raise ValueError("Expected a Windows identity placeholder before container names") + validate_source_daemon(daemon_security(SOURCE)) + windows_identity = sys.argv[2] + members = [(name, validate) for name in sys.argv[3:]] + if windows_identity != "-": + members.append((windows_identity, validate_windows_exception)) + failures = [] + for name, validator in reversed(members): + try: + current = inspect(SOURCE, "container", name) + intent = migration_intent(current) + if intent is not None and not intent["start_attempted"] and not completion_path(current["Id"]).exists(): + restore_source(current["Id"], validator) + except Exception as error: + failures.append(f"{name}: {error}") + if failures: + raise RuntimeError("\n".join(failures)) + return quiesce_all_mode = sys.argv[1:2] == ["--quiesce-all"] if quiesce_all_mode: if len(sys.argv) < 3: diff --git a/migrations/1789164756.sh b/migrations/1789164756.sh index 1f85b2facd11..e76f9d1c03ba 100644 --- a/migrations/1789164756.sh +++ b/migrations/1789164756.sh @@ -283,6 +283,21 @@ if [[ -n $windows_id ]]; then else windows_arg="-" fi +quiesced_recovery_pending=1 +recover_quiesced_on_failure() { + local status=$? + trap - EXIT + if (( status != 0 && quiesced_recovery_pending == 1 )); then + # The restart itself may fail. Try to make the source API available before + # restoring only workloads whose journals exclude any destination start. + sudo /usr/bin/systemctl start docker.service >/dev/null 2>&1 || true + if ! /usr/bin/python3 "$migrator" --restore-quiesced-all "$windows_arg" "${container_names[@]}"; then + echo "Some rootful workloads could not be restored; their recovery journals were retained." >&2 + fi + fi + exit "$status" +} +trap recover_quiesced_on_failure EXIT /usr/bin/python3 "$migrator" --quiesce-all "$windows_arg" "${container_names[@]}" # All source restart policies and lifecycle intent are durable before this @@ -308,6 +323,7 @@ fi if (( ${#container_names[@]} )); then /usr/bin/python3 "$migrator" --check "${container_names[@]}" + quiesced_recovery_pending=0 /usr/bin/python3 "$migrator" "${container_names[@]}" /usr/bin/python3 "$migrator" --check-completed "${container_names[@]}" fi diff --git a/test/shell.d/rootless-docker-failure-recovery-test.sh b/test/shell.d/rootless-docker-failure-recovery-test.sh new file mode 100644 index 000000000000..3ec90bb81b65 --- /dev/null +++ b/test/shell.d/rootless-docker-failure-recovery-test.sh @@ -0,0 +1,112 @@ +#!/bin/bash +set -euo pipefail +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" +python3 - <<'PY' +import copy +import importlib.util +import os +from pathlib import Path +import subprocess +import tempfile +from unittest.mock import patch + +root = Path(os.environ['ROOT']) +spec = importlib.util.spec_from_file_location('migration', root / 'default/docker/rootless/migrate.py') +m = importlib.util.module_from_spec(spec) +spec.loader.exec_module(m) +source = {'Id': 'a' * 64, 'Name': '/fixture', 'Mounts': [], + 'Config': {'StopTimeout': 12}, 'HostConfig': {'RestartPolicy': {'Name': 'no'}}, + 'State': {'Running': False, 'StartedAt': 'start', 'FinishedAt': 'finish', 'ExitCode': 0}} +for fault in ['events', 'runtime', 'receipt', 'foreign', 'durable-receipt']: + target = {'Id': 'b' * 64, 'Config': {'Labels': {m.LABEL: source['Id'], m.OWNERSHIP_LABEL: 'c' * 64}}, + 'HostConfig': {'RestartPolicy': {'Name': 'unless-stopped'}}, 'State': {'Running': False}} + intent = {'target_running': True, 'start_attempted': False, 'target_ownership': 'c' * 64, + 'source_nofile': {'soft': 1024, 'hard': 1024}, 'volume_event': {'name': 'event'}, + 'destination': {'id': target['Id']}} + calls = [] + with tempfile.TemporaryDirectory() as directory: + receipt = Path(directory) / 'receipt' + def inspect(engine, kind, identity): + return copy.deepcopy(source if engine == m.SOURCE else target) + def run(*args): + calls.append(args) + assert args[0] == m.TARGET, args + if args[1] == 'start': + target['State']['Running'] = True + elif args[1] == 'update': + assert args[2:] == ('--restart=no', target['Id']) + target['HostConfig']['RestartPolicy'] = {'Name': 'no'} + elif args[1] == 'stop': + assert args[-1] == target['Id'] + target['State']['Running'] = False + else: + raise AssertionError(args) + def event(*args): + if fault == 'events': + raise RuntimeError('events') + def runtime(*args): + if fault == 'foreign': + target['Config']['Labels'][m.OWNERSHIP_LABEL] = 'd' * 64 + if fault in ['runtime', 'foreign']: + raise RuntimeError(fault) + return copy.deepcopy(target) + def publish(*args): + if fault == 'durable-receipt': + receipt.touch() + raise RuntimeError(fault) + with patch.object(m, 'verify_resumable_migration', return_value=(copy.deepcopy(source), copy.deepcopy(source['State']))), \ + patch.object(m, 'inspect', inspect), patch.object(m, 'run', run), \ + patch.object(m, 'snapshot_digest', return_value='same'), patch.object(m, 'persist_migration_intent'), \ + patch.object(m, 'verify_volume_event_window', event), patch.object(m, 'verify_runtime', runtime), \ + patch.object(m, 'record_completion', publish), patch.object(m, 'completion_path', return_value=receipt): + try: + m.resume_verified_migration(source, target, intent) + except RuntimeError: + pass + else: + raise AssertionError('fault was reported as success') + assert intent['start_attempted'] and not source['State']['Running'] + if fault in ['foreign', 'durable-receipt']: + assert calls == [(m.TARGET, 'start', 'fixture')], calls + else: + assert not target['State']['Running'] + assert target['HostConfig']['RestartPolicy']['Name'] == 'no' + assert len(calls) == 3, calls +print('ok - resumed event/runtime/receipt faults fence the owned destination, retain both stores and never restore the source; foreign ownership and durable completion remain untouched') + +script = (root / 'migrations/1789164756.sh').read_text() +start = script.index('quiesced_recovery_pending=1\n') +end = script.index(' quiesced_recovery_pending=0\n', start) +phase = script[start:end] + '\nfi\n' +phase = phase.replace('/usr/bin/python3', 'fixture_python').replace('/usr/bin/systemctl', 'systemctl').replace('/usr/bin/docker', 'docker') +prefix = r''' +set -euo pipefail +migrator=/fixture/migrate.py +windows_arg=- +windows_id="" +container_names=(alpha) +source_host=unix:///fixture +docker_inventory=inventory +sudo() { + printf 'sudo %s\n' "$*" >>"$LOG" + [[ $* != 'systemctl restart docker.service' || $FAULT != restart ]] || return 33 + if [[ $1 == docker ]]; then printf '%s\n' inventory; fi +} +fixture_python() { + printf 'python %s\n' "$*" >>"$LOG" + [[ ${2:-} != --check || $FAULT != check ]] || return 33 +} +verify_rootful_listeners() { [[ $FAULT != listeners ]] || return 33; } +restrict_rootful_socket() { [[ $FAULT != socket ]] || return 33; } +verify_rootful_socket_unit() { :; } +''' +with tempfile.TemporaryDirectory() as directory: + for fault in ['restart', 'socket', 'listeners', 'check']: + log = Path(directory) / fault + result = subprocess.run(['bash', '-c', prefix + phase], + env=dict(os.environ, FAULT=fault, LOG=str(log)), capture_output=True, text=True) + assert result.returncode == 33, (fault, result.stderr) + calls = log.read_text() + assert 'python /fixture/migrate.py --restore-quiesced-all - alpha\n' in calls, (fault, calls) +print('ok - failures after quiescing in daemon restart, socket checks, listener checks or second preflight invoke journal-gated source recovery and preserve failure status') +PY diff --git a/test/shell.d/rootless-docker-migration-test.sh b/test/shell.d/rootless-docker-migration-test.sh index 53cb5e75b6e4..5960a84857fb 100755 --- a/test/shell.d/rootless-docker-migration-test.sh +++ b/test/shell.d/rootless-docker-migration-test.sh @@ -1386,6 +1386,7 @@ def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image key, value = args[index + 1].split("=", 1) labels[key] = value current_target = {"Id": "b" * 64, "Image": image_id, + "HostConfig": {"RestartPolicy": {"Name": "unless-stopped", "MaximumRetryCount": 0}}, "Config": {"Labels": labels, "Image": ( image_id if preexisting_image else transfer_tag)}, "State": {"Status": "created", "Running": False, @@ -1395,6 +1396,12 @@ def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image current_target = None elif args[:2] == (migration.TARGET, "start"): current_target["State"]["Running"] = True + elif args[:2] == (migration.TARGET, "update"): + assert args[2:] == ("--restart=no", "b" * 64) + current_target["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0} + elif args[:2] == (migration.TARGET, "stop"): + assert args[-1] == "b" * 64 + current_target["State"]["Running"] = False migration.inspect = fake_inspect migration.run = fake_run @@ -1448,6 +1455,11 @@ def exercise_failed_transfer(after_start, mutate_source=False, preexisting_image else: raise AssertionError("failed transfer was reported as complete") intent_retained = migration.intent_path(source["Id"]).exists() + if after_start and not completed_cleanup_failure and not completion_signal_window: + assert current_target is not None and not current_target["State"]["Running"] + assert current_target["HostConfig"]["RestartPolicy"]["Name"] == "no" + assert (migration.TARGET, "update", "--restart=no", "b" * 64) in calls + assert (migration.TARGET, "stop", "-t", "300", "b" * 64) in calls migration.release_transfer_image = original_release_transfer_image return calls, current_source, pipes, intent_retained From 5f464f6f9c2227240a60bbefde74adaad26dc0fa Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Tue, 20 Oct 2026 23:35:17 -0600 Subject: [PATCH 22/31] Skip Windows hardening on ARM --- migrations/1789164756.sh | 4 +++- test/shell.d/rootless-docker-posture-test.sh | 19 ++++++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/migrations/1789164756.sh b/migrations/1789164756.sh index e76f9d1c03ba..de12766fae7c 100644 --- a/migrations/1789164756.sh +++ b/migrations/1789164756.sh @@ -196,7 +196,9 @@ remove_legacy_docker_group # anchors, and rewrite the credential-bearing Compose file to root:root 0600. # An existing managed VM is recreated through dockerd's own mount namespace # while its running or stopped lifecycle is preserved. -/usr/bin/omarchy-windows-vm __migration-secure +if omarchy-hw-x86; then + /usr/bin/omarchy-windows-vm __migration-secure +fi # A killed runtime-limit probe is journaled before it starts and uses a bounded, # auto-removing container. Clear any such verified probe before taking the diff --git a/test/shell.d/rootless-docker-posture-test.sh b/test/shell.d/rootless-docker-posture-test.sh index 90b3418327ad..ba1f935cdc96 100755 --- a/test/shell.d/rootless-docker-posture-test.sh +++ b/test/shell.d/rootless-docker-posture-test.sh @@ -346,7 +346,7 @@ listener_line=$(grep -n '^verify_rootful_listeners$' "$migration" | head -n1 | c fail "custom rootful Docker listeners are not rejected before source migration" grep -q -- '--check-windows "$windows_id"' "$migration" || fail "the name-based Windows exception is not authenticated against its managed runtime" -windows_secure_line=$(grep -n '^/usr/bin/omarchy-windows-vm __migration-secure$' "$migration" | cut -d: -f1) +windows_secure_line=$(grep -n '^[[:space:]]*/usr/bin/omarchy-windows-vm __migration-secure$' "$migration" | cut -d: -f1) [[ -n $windows_secure_line && -n $inventory_line ]] && (( windows_secure_line < inventory_line )) || fail "legacy Windows credentials and mounts are not secured before rootful inventory" windows_check_line=$(grep -n -- '--check-windows "$windows_id"' "$migration" | head -n1 | cut -d: -f1) @@ -523,3 +523,20 @@ grep -q 'sudo "$target" __priv' "$ROOT/bin/omarchy-windows-vm" || grep -q 'pkexec "$target" __priv' "$ROOT/bin/omarchy-windows-vm" || fail "graphical Windows operations do not authenticate" pass "Windows remains on an authenticated root-only Docker daemon" + +python3 - "$migration" <<'PYARM' +import os, re, subprocess, sys, tempfile +from pathlib import Path +source = Path(sys.argv[1]).read_text() +match = re.search(r"if omarchy-hw-x86; then\n /usr/bin/omarchy-windows-vm __migration-secure\nfi", source) +assert match, "Windows-only hardening must have an architecture gate" +with tempfile.TemporaryDirectory() as directory: + marker = Path(directory) / "secured" + block = match.group().replace("/usr/bin/omarchy-windows-vm", "secure_windows") + for architecture, expected in [("arm", False), ("x86", True)]: + marker.unlink(missing_ok=True) + program = 'omarchy-hw-x86() { [[ $ARCH == x86 ]]; }; secure_windows() { touch "$MARKER"; };\n' + block + result = subprocess.run(["bash", "-euo", "pipefail", "-c", program], env=dict(os.environ, ARCH=architecture, MARKER=str(marker))) + assert result.returncode == 0 and marker.exists() == expected, architecture +print("ok - Windows hardening is a successful no-op on ARM and still executes on x86") +PYARM From 457f5cf80d240d85ece28a59b7152f5017db3509 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Tue, 20 Oct 2026 23:35:17 -0600 Subject: [PATCH 23/31] Keep rootless Docker English catalogs in sync --- default/i18n/en/cli.json | 2 -- default/i18n/en/menu.json | 6 ------ 2 files changed, 8 deletions(-) diff --git a/default/i18n/en/cli.json b/default/i18n/en/cli.json index d9e80076c80b..54a4cda497d9 100644 --- a/default/i18n/en/cli.json +++ b/default/i18n/en/cli.json @@ -79,8 +79,6 @@ "directBoot.disable": "Disable direct boot (remove Omarchy EFI entry)?", "directBoot.setup": "Setup direct boot (so snapshot booting must be done via bios)?", "display.restartFootForFontSize": "Restart Foot to apply the new terminal font size", - "docker.enableSudoless": "Enable sudoless Docker? This gives anything running as you passwordless root.", - "docker.rebootToApply": "Reboot now to apply?", "docker.selectDatabase": "Select database (return to install, esc to cancel)", "done.failed": "Failed (exit code %1)! Press any key to close...", "done.success": "Done! Press any key to close...", diff --git a/default/i18n/en/menu.json b/default/i18n/en/menu.json index b0297c34e3bc..9148108f6289 100644 --- a/default/i18n/en/menu.json +++ b/default/i18n/en/menu.json @@ -656,9 +656,6 @@ "setup.security.ssh-agent": { "label": "SSH Agent" }, - "setup.security.sudoless-docker": { - "label": "Sudoless Docker" - }, "setup.security.passwordless-sudo": { "label": "Passwordless Sudo" }, @@ -1007,9 +1004,6 @@ "remove.security.sshd": { "label": "SSHD" }, - "remove.security.sudoless-docker": { - "label": "Sudoless Docker" - }, "remove.ai.hermes": { "label": "Hermes Desktop" }, From 48aa0012fa7b4de364404ba03da8a2aec460e465 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Tue, 20 Oct 2026 23:35:17 -0600 Subject: [PATCH 24/31] Use Bash for the Docker environment generator --- .../user-environment-generators/60-omarchy-rootless-docker | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/default/systemd/user-environment-generators/60-omarchy-rootless-docker b/default/systemd/user-environment-generators/60-omarchy-rootless-docker index 28bf653f8bed..b854d5fb7e48 100755 --- a/default/systemd/user-environment-generators/60-omarchy-rootless-docker +++ b/default/systemd/user-environment-generators/60-omarchy-rootless-docker @@ -1,6 +1,6 @@ -#!/bin/sh +#!/bin/bash -if [ -f "$HOME/.local/state/omarchy/rootless-docker/enabled" ]; then +if [[ -f $HOME/.local/state/omarchy/rootless-docker/enabled ]]; then runtime_dir=${XDG_RUNTIME_DIR:-/run/user/$(id -u)} printf 'DOCKER_HOST=unix://%s/docker.sock\n' "$runtime_dir" fi From 75d2292c3e4c162d067bcdf00c918bf1f2e42bcc Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Mon, 26 Oct 2026 21:44:56 -0600 Subject: [PATCH 25/31] Drop one-shot migration tests --- test/shell.d/once-migration-test.sh | 58 ------ .../rootless-docker-failure-recovery-test.sh | 37 ---- test/shell.d/rootless-docker-posture-test.sh | 189 +----------------- 3 files changed, 1 insertion(+), 283 deletions(-) delete mode 100755 test/shell.d/once-migration-test.sh diff --git a/test/shell.d/once-migration-test.sh b/test/shell.d/once-migration-test.sh deleted file mode 100755 index 67784114c014..000000000000 --- a/test/shell.d/once-migration-test.sh +++ /dev/null @@ -1,58 +0,0 @@ -#!/bin/bash - -set -euo pipefail -source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" - -python3 - "$ROOT" <<'PYTEST' -import os -from pathlib import Path -import subprocess -import sys -import tempfile - -root = Path(sys.argv[1]) -migration = root / 'migrations/1789164756.sh' -# Execute the actual migration preflight up to its first mutation/setup step. -text = migration.read_text() -preflight = text.split('migration_uid=$(id -u)', 1)[0] -with tempfile.TemporaryDirectory() as directory: - work = Path(directory) - preflight_path = work / 'preflight' - preflight_path.write_text(preflight + '\necho guard-passed\n') - for name in ('pacman', 'systemctl', 'id'): - command = work / name - command.write_text('''#!/bin/bash -set -eu -case "${0##*/}" in - id) echo 1000 ;; - systemctl) - if [[ $1 == --user ]]; then exit 0; fi - [[ $TEST_LEGACY == "$1" ]] ;; - pacman) - [[ $TEST_DB != broken ]] || exit 2 - if [[ $* == '-Qq once-bin' ]]; then - [[ $TEST_ONCE != missing ]] || exit 1 - echo "$TEST_ONCE" - elif [[ $* == '-Qq docker' ]]; then - echo podman-docker - fi ;; -esac -''') - command.chmod(0o755) - for provider in ('missing', 'once', 'once-bin', 'custom-once'): - for legacy in ('none', 'is-active', 'is-enabled'): - env = dict(os.environ, PATH=f'{work}:/usr/bin', TEST_ONCE=provider, - TEST_LEGACY=legacy, TEST_DB='available') - result = subprocess.run(['bash', '-euo', 'pipefail', str(preflight_path)], - env=env, capture_output=True, text=True) - allowed = provider in ('missing', 'once') and legacy == 'none' - assert (result.returncode == 0) == allowed, (provider, legacy, result) - assert ('guard-passed' in result.stdout) == allowed, (provider, legacy, result) - if not allowed: - assert 'Legacy ONCE' in result.stderr, result - env.update(TEST_ONCE='missing', TEST_LEGACY='none', TEST_DB='broken') - result = subprocess.run(['bash', '-euo', 'pipefail', str(preflight_path)], - env=env, capture_output=True, text=True) - assert result.returncode != 0 and 'guard-passed' not in result.stdout, result -print('ok - rootless ONCE providers pass migration while legacy managers and failed package queries block it') -PYTEST diff --git a/test/shell.d/rootless-docker-failure-recovery-test.sh b/test/shell.d/rootless-docker-failure-recovery-test.sh index 3ec90bb81b65..acf147f3ee29 100644 --- a/test/shell.d/rootless-docker-failure-recovery-test.sh +++ b/test/shell.d/rootless-docker-failure-recovery-test.sh @@ -6,7 +6,6 @@ import copy import importlib.util import os from pathlib import Path -import subprocess import tempfile from unittest.mock import patch @@ -73,40 +72,4 @@ for fault in ['events', 'runtime', 'receipt', 'foreign', 'durable-receipt']: assert target['HostConfig']['RestartPolicy']['Name'] == 'no' assert len(calls) == 3, calls print('ok - resumed event/runtime/receipt faults fence the owned destination, retain both stores and never restore the source; foreign ownership and durable completion remain untouched') - -script = (root / 'migrations/1789164756.sh').read_text() -start = script.index('quiesced_recovery_pending=1\n') -end = script.index(' quiesced_recovery_pending=0\n', start) -phase = script[start:end] + '\nfi\n' -phase = phase.replace('/usr/bin/python3', 'fixture_python').replace('/usr/bin/systemctl', 'systemctl').replace('/usr/bin/docker', 'docker') -prefix = r''' -set -euo pipefail -migrator=/fixture/migrate.py -windows_arg=- -windows_id="" -container_names=(alpha) -source_host=unix:///fixture -docker_inventory=inventory -sudo() { - printf 'sudo %s\n' "$*" >>"$LOG" - [[ $* != 'systemctl restart docker.service' || $FAULT != restart ]] || return 33 - if [[ $1 == docker ]]; then printf '%s\n' inventory; fi -} -fixture_python() { - printf 'python %s\n' "$*" >>"$LOG" - [[ ${2:-} != --check || $FAULT != check ]] || return 33 -} -verify_rootful_listeners() { [[ $FAULT != listeners ]] || return 33; } -restrict_rootful_socket() { [[ $FAULT != socket ]] || return 33; } -verify_rootful_socket_unit() { :; } -''' -with tempfile.TemporaryDirectory() as directory: - for fault in ['restart', 'socket', 'listeners', 'check']: - log = Path(directory) / fault - result = subprocess.run(['bash', '-c', prefix + phase], - env=dict(os.environ, FAULT=fault, LOG=str(log)), capture_output=True, text=True) - assert result.returncode == 33, (fault, result.stderr) - calls = log.read_text() - assert 'python /fixture/migrate.py --restore-quiesced-all - alpha\n' in calls, (fault, calls) -print('ok - failures after quiescing in daemon restart, socket checks, listener checks or second preflight invoke journal-gated source recovery and preserve failure status') PY diff --git a/test/shell.d/rootless-docker-posture-test.sh b/test/shell.d/rootless-docker-posture-test.sh index ba1f935cdc96..090401130f2d 100755 --- a/test/shell.d/rootless-docker-posture-test.sh +++ b/test/shell.d/rootless-docker-posture-test.sh @@ -8,7 +8,7 @@ for package in docker docker-buildx docker-compose docker-rootless-extras rootle done pass "the base install keeps Docker tooling and adds the rootless runtime" -! rg -q 'systemctl --global enable docker.service' "$ROOT/install" "$ROOT/migrations/1789164756.sh" || +! rg -q 'systemctl --global enable docker.service' "$ROOT/install" || fail "rootless Docker starts globally before each account is initialized" grep -q 'docker.service' "$ROOT/install/user/first-run/enable-user-units.sh" || fail "first login starts the rootless Docker user service" @@ -207,176 +207,6 @@ rm "$home/.local/state/omarchy/rootless-docker/enabled" fail "the API endpoint stays unchanged before migration completes" pass "the Docker endpoint activates only after rootless setup completes" -migration="$ROOT/migrations/1789164756.sh" -behavior_bin="$test_dir/behavior-bin" -behavior_home="$test_dir/behavior-home" -behavior_runtime="$test_dir/behavior-runtime" -behavior_log="$test_dir/behavior.log" -mkdir -p "$behavior_bin" "$behavior_home" "$behavior_runtime" -cat >"$behavior_bin/id" <<'EOF' -#!/bin/bash -case "$*" in - -u) echo 1000 ;; - -un) echo migration-user ;; - *) echo migration-user ;; -esac -EOF -cat >"$behavior_bin/systemctl" <<'EOF' -#!/bin/bash -echo "systemctl $*" >>"$BEHAVIOR_LOG" -[[ $* == *once-background.service ]] && exit 1 -if [[ $* == "--user show-environment" || $* == "--user is-active --quiet docker.service" ]]; then - exit 0 -fi -exit 0 -EOF -cat >"$behavior_bin/sudo" <<'EOF' -#!/bin/bash -echo "sudo $*" >>"$BEHAVIOR_LOG" -[[ $* == "/usr/bin/test -f /var/lib/omarchy/rootless-docker/enabled" ]] && exit 1 -exit 0 -EOF -cat >"$behavior_bin/omarchy-pkg-add" <<'EOF' -#!/bin/bash -echo "package $*" >>"$BEHAVIOR_LOG" -EOF -cat >"$behavior_bin/python3" <<'EOF' -#!/bin/bash -echo "python $*" >>"$BEHAVIOR_LOG" -[[ $* == *"--check-target-policy"* ]] && exit 1 -exit 0 -EOF -cat >"$behavior_bin/pacman" <<'EOF' -#!/bin/bash -[[ $* == "-Qq once-bin" ]] && exit 1 -exit 0 -EOF -chmod +x "$behavior_bin"/* -behavior_migration="$test_dir/migration.sh" -sed \ - -e 's|export XDG_RUNTIME_DIR="/run/user/$migration_uid"|export XDG_RUNTIME_DIR="$TEST_RUNTIME"|' \ - -e "s|/usr/bin/python3|$behavior_bin/python3|g" \ - "$migration" >"$behavior_migration" -if HOME="$behavior_home" TEST_RUNTIME="$behavior_runtime" BEHAVIOR_LOG="$behavior_log" \ - OMARCHY_PATH="$ROOT" PATH="$behavior_bin:$PATH" bash -euo pipefail "$behavior_migration" >/dev/null 2>&1; then - fail "an incompatible active rootless daemon passed migration setup" -fi -grep -q -- '--check-target-policy' "$behavior_log" || - fail "an active rootless daemon was not validated before service setup" -! grep -Eq 'systemctl --user (daemon-reload|enable|start|restart)' "$behavior_log" || - fail "an incompatible active rootless daemon was changed before rejection" -pass "active custom rootless workloads are rejected without service disruption" - -# Exercise service setup with systemd's first-install behavior: reset-failed -# rejects an inactive unit which was unloaded by daemon-reload. -service_setup="$test_dir/service-setup.sh" -cat >"$service_setup" <<'EOF' -set -euo pipefail -target_was_active=0 -[[ $TEST_SERVICE_STATE != active ]] || target_was_active=1 -systemctl() { - echo "$*" >>"$TEST_SERVICE_LOG" - case "$*" in - '--user is-failed --quiet docker.service') [[ $TEST_SERVICE_STATE == failed ]] ;; - '--user reset-failed docker.service') [[ $TEST_SERVICE_STATE == failed && $TEST_SERVICE_FAIL != reset ]] ;; - '--user enable docker.service') [[ $TEST_SERVICE_FAIL != enable ]] ;; - '--user start docker.service') [[ $TEST_SERVICE_FAIL != start ]] ;; - esac -} -EOF -sed -n '/^systemctl --user daemon-reload$/,/^target_host=/{ /^target_host=/d; p; }' "$migration" >>"$service_setup" -for state in inactive failed active; do - service_log="$test_dir/service-$state.log" - TEST_SERVICE_STATE="$state" TEST_SERVICE_FAIL=none TEST_SERVICE_LOG="$service_log" bash "$service_setup" || - fail "service setup fails for daemon state $state" - if [[ $state == failed ]]; then - grep -q -- '--user reset-failed docker.service' "$service_log" || fail "failed daemon was not reset" - else - ! grep -q -- '--user reset-failed docker.service' "$service_log" || fail "non-failed daemon was reset" - fi - if [[ $state == active ]]; then - ! grep -q -- '--user start docker.service' "$service_log" || fail "active daemon was started again" - else - grep -q -- '--user start docker.service' "$service_log" || fail "inactive daemon was not started" - fi -done -for operation in reset enable start; do - if TEST_SERVICE_STATE=failed TEST_SERVICE_FAIL="$operation" TEST_SERVICE_LOG="$test_dir/failure.log" bash "$service_setup"; then - fail "service setup ignored a $operation failure" - fi -done -pass "first-install service setup skips absent failure state, recovers failed units and preserves active workloads" - -reset_line=$(grep -n 'systemctl --user reset-failed docker.service' "$migration" | cut -d: -f1) -user_enable_line=$(grep -n 'systemctl --user enable docker.service' "$migration" | cut -d: -f1) -user_start_line=$(grep -n 'systemctl --user start docker.service' "$migration" | cut -d: -f1) -daemon_config_line=$(grep -n 'install -m 0644.*config/docker/daemon.json' "$migration" | cut -d: -f1) -active_probe_line=$(grep -n 'systemctl --user is-active --quiet docker.service' "$migration" | cut -d: -f1) -target_policy_line=$(grep -n -- '--check-target-policy' "$migration" | head -n1 | cut -d: -f1) -user_reload_line=$(grep -n 'systemctl --user daemon-reload' "$migration" | cut -d: -f1) -[[ -n $reset_line && -n $user_enable_line && -n $user_start_line && -n $daemon_config_line && - -n $active_probe_line && -n $target_policy_line && -n $user_reload_line ]] && - (( active_probe_line < daemon_config_line && daemon_config_line < target_policy_line && - target_policy_line < user_reload_line && user_reload_line < reset_line && - reset_line < user_enable_line && user_enable_line < user_start_line )) || - fail "migration does not validate and preserve an active rootless daemon before service setup" -! grep -q 'systemctl --user restart docker.service' "$migration" || - fail "migration restarts existing rootless workloads before destination preflight" -(( $(grep -c -- '--check-target-policy' "$migration") == 2 )) || - fail "migration does not verify target policy before and after setting up the user daemon" -grep -q 'migration_user=$(id -un)' "$migration" || fail "migration trusts the USER environment instead of the current account" -lock_line=$(grep -n '/usr/bin/flock -n' "$migration" | cut -d: -f1) -package_line=$(grep -n '^omarchy-pkg-add docker-rootless-extras' "$migration" | cut -d: -f1) -[[ -n $lock_line && -n $package_line ]] && (( lock_line < package_line )) || - fail "same-account migrations are not serialized before any setup or transfer" -completion_line=$(grep -n 'test -f "$machine_state/enabled"' "$migration" | cut -d: -f1) -inventory_line=$(grep -n 'docker_inventory=' "$migration" | cut -d: -f1) -[[ -n $completion_line && -n $inventory_line ]] && (( completion_line < inventory_line )) || - fail "later accounts can reach the machine-wide retained rootful store" -grep -q 'machine-wide rootful recovery store was left untouched' "$migration" || - fail "later accounts do not have an explicit rootful-store no-op path" -completion_return=$(grep -n 'machine-wide rootful recovery store was left untouched' "$migration" | cut -d: -f1) -later_group_drop=$(sed -n "${completion_line},${completion_return}p" "$migration" | grep -n '^ remove_legacy_docker_group' | cut -d: -f1) -[[ -n $later_group_drop ]] || fail "later accounts retain legacy docker-group membership" -socket_line=$(grep -n "socket_owner=" "$migration" | cut -d: -f1) -[[ -n $socket_line && -n $inventory_line ]] && (( socket_line < inventory_line )) || - fail "the legacy group socket remains writable during source migration" -listener_line=$(grep -n '^verify_rootful_listeners$' "$migration" | head -n1 | cut -d: -f1) -[[ -n $listener_line ]] && (( socket_line < listener_line && listener_line < inventory_line )) || - fail "custom rootful Docker listeners are not rejected before source migration" -grep -q -- '--check-windows "$windows_id"' "$migration" || - fail "the name-based Windows exception is not authenticated against its managed runtime" -windows_secure_line=$(grep -n '^[[:space:]]*/usr/bin/omarchy-windows-vm __migration-secure$' "$migration" | cut -d: -f1) -[[ -n $windows_secure_line && -n $inventory_line ]] && (( windows_secure_line < inventory_line )) || - fail "legacy Windows credentials and mounts are not secured before rootful inventory" -windows_check_line=$(grep -n -- '--check-windows "$windows_id"' "$migration" | head -n1 | cut -d: -f1) -owner_claim_line=$(grep -n 'owner = root / "migration-owner"' "$migration" | cut -d: -f1) -[[ -n $windows_check_line && -n $owner_claim_line ]] && (( windows_check_line < owner_claim_line )) || - fail "the machine migration owner is claimed before proving ownership of an existing Windows VM" -owner_replace_line=$(grep -n 'temporary.replace(owner)' "$migration" | cut -d: -f1) -owner_sync_line=$(grep -n 'os.fsync(directory_fd)' "$migration" | head -n1 | cut -d: -f1) -[[ -n $owner_replace_line && -n $owner_sync_line ]] && (( owner_replace_line < owner_sync_line )) || - fail "the machine migration owner rename is not directory-synced" -quiesce_line=$(grep -n -- '--quiesce-all "$windows_arg"' "$migration" | cut -d: -f1) -restart_line=$(grep -n 'systemctl restart docker.service' "$migration" | cut -d: -f1) -transfer_line=$(grep -n '^ /usr/bin/python3 "$migrator" "${container_names\[@\]}"' "$migration" | cut -d: -f1) -[[ -n $quiesce_line && -n $restart_line && -n $transfer_line ]] && - (( inventory_line < quiesce_line && quiesce_line < restart_line && restart_line < transfer_line )) || - fail "rootful connections are not revoked between durable quiesce and transfer" -(( $(grep -c '^restrict_rootful_socket$' "$migration") == 2 )) || - fail "rootful socket policy is not rechecked after daemon restart" -(( $(grep -c '^verify_rootful_listeners$' "$migration") == 3 )) || - fail "rootful Docker configuration is not rechecked immediately before and after daemon restart" -(( $(grep -c '^verify_rootful_socket_unit$' "$migration") == 2 )) || - fail "the effective rootful socket unit is not rechecked after daemon restart" -for property in SocketUser SocketGroup SocketMode Listen; do - grep -q -- "--property=$property" "$migration" || - fail "migration does not verify effective docker.socket $property" -done -grep -q -- '--restore-windows "$windows_id"' "$migration" || - fail "a running Windows VM is not restored after rootful connection revocation" -pass "migration serializes ownership, secures Windows, and revokes existing rootful connections" - listener_verifier="$ROOT/default/docker/rootless/rootful-listeners.py" python3 - "$listener_verifier" <<'PY' import importlib.util @@ -523,20 +353,3 @@ grep -q 'sudo "$target" __priv' "$ROOT/bin/omarchy-windows-vm" || grep -q 'pkexec "$target" __priv' "$ROOT/bin/omarchy-windows-vm" || fail "graphical Windows operations do not authenticate" pass "Windows remains on an authenticated root-only Docker daemon" - -python3 - "$migration" <<'PYARM' -import os, re, subprocess, sys, tempfile -from pathlib import Path -source = Path(sys.argv[1]).read_text() -match = re.search(r"if omarchy-hw-x86; then\n /usr/bin/omarchy-windows-vm __migration-secure\nfi", source) -assert match, "Windows-only hardening must have an architecture gate" -with tempfile.TemporaryDirectory() as directory: - marker = Path(directory) / "secured" - block = match.group().replace("/usr/bin/omarchy-windows-vm", "secure_windows") - for architecture, expected in [("arm", False), ("x86", True)]: - marker.unlink(missing_ok=True) - program = 'omarchy-hw-x86() { [[ $ARCH == x86 ]]; }; secure_windows() { touch "$MARKER"; };\n' + block - result = subprocess.run(["bash", "-euo", "pipefail", "-c", program], env=dict(os.environ, ARCH=architecture, MARKER=str(marker))) - assert result.returncode == 0 and marker.exists() == expected, architecture -print("ok - Windows hardening is a successful no-op on ARM and still executes on x86") -PYARM From 20bdb6f12a3919177bd42e9a8596e522ea1a8fcc Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Mon, 26 Oct 2026 21:53:07 -0600 Subject: [PATCH 26/31] Reject comma-containing Docker volume destinations --- default/docker/rootless/migrate.py | 3 ++- test/shell.d/rootless-docker-migration-test.sh | 9 +++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/default/docker/rootless/migrate.py b/default/docker/rootless/migrate.py index 879721f828db..0db61e28db30 100644 --- a/default/docker/rootless/migrate.py +++ b/default/docker/rootless/migrate.py @@ -606,7 +606,8 @@ def validate_volumes(container): raise ValueError(f"{name}: host mounts or custom storage need an explicit transfer") if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]*", mount["Name"]): raise ValueError(f"{name}: unsupported volume name") - if not mount["Destination"].startswith("/") or ":" in mount["Destination"]: + if (not mount["Destination"].startswith("/") or + any(delimiter in mount["Destination"] for delimiter in (":", ","))): raise ValueError(f"{name}: unsupported volume destination") # -v also records named volumes in Binds. Accept only an exact match to a # local volume; never treat a host directory or socket as a named volume. diff --git a/test/shell.d/rootless-docker-migration-test.sh b/test/shell.d/rootless-docker-migration-test.sh index 5960a84857fb..7892b7408529 100755 --- a/test/shell.d/rootless-docker-migration-test.sh +++ b/test/shell.d/rootless-docker-migration-test.sh @@ -489,6 +489,15 @@ container = { "Destination": "/data", "RW": True}], } assert migration.validate(container) == "project-worker" +comma_mount = copy.deepcopy(container) +comma_mount["Mounts"][0]["Destination"] = "/app,data" +comma_mount["HostConfig"]["Binds"] = ["project-data:/app,data"] +try: + migration.validate(comma_mount) +except ValueError as error: + assert "unsupported volume destination" in str(error), error +else: + raise AssertionError("comma-delimited volume destination passed preflight") actual_nofile = {"soft": 32768, "hard": 262144} original_run = migration.run original_inspect = migration.inspect From 4a04bbd516001236482ad5390dcb6f1e59603973 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Mon, 26 Oct 2026 21:53:07 -0600 Subject: [PATCH 27/31] Keep behavioral rootless Docker posture tests --- test/shell.d/rootless-docker-posture-test.sh | 38 -------------------- 1 file changed, 38 deletions(-) diff --git a/test/shell.d/rootless-docker-posture-test.sh b/test/shell.d/rootless-docker-posture-test.sh index 090401130f2d..f5eba84c5498 100755 --- a/test/shell.d/rootless-docker-posture-test.sh +++ b/test/shell.d/rootless-docker-posture-test.sh @@ -3,21 +3,6 @@ set -euo pipefail source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" -for package in docker docker-buildx docker-compose docker-rootless-extras rootlesskit slirp4netns fuse-overlayfs; do - grep -qx "$package" "$ROOT/install/omarchy-base.packages" || fail "rootless Docker dependency is in the base install: $package" -done -pass "the base install keeps Docker tooling and adds the rootless runtime" - -! rg -q 'systemctl --global enable docker.service' "$ROOT/install" || - fail "rootless Docker starts globally before each account is initialized" -grep -q 'docker.service' "$ROOT/install/user/first-run/enable-user-units.sh" || - fail "first login starts the rootless Docker user service" -grep -q 'rootless_docker_ensure_subids' "$ROOT/install/config/docker.sh" || - fail "fresh installs allocate subordinate IDs before rootless Docker starts" -grep -q 'rootless_docker_ensure_subids' "$ROOT/bin/omarchy-provision-owner" || - fail "deferred provisioning allocates subordinate IDs" -pass "fresh and deferred installs prepare the rootless user daemon" - test_dir=$(mktemp -d) trap 'rm -rf "$test_dir"' EXIT python3 - "$ROOT/install/helpers/rootless-docker.sh" <<'PY' @@ -330,26 +315,3 @@ with tempfile.TemporaryDirectory() as directory: print("ok - listener verification accepts only the protected rootful Unix socket") PY pass "rootful Docker listener verification rejects extra API endpoints" - -grep -q "alias d='docker'" "$ROOT/default/bash/aliases" || fail "the d alias remains Docker" -! rg -q 'sudo[[:space:]]+docker' "$ROOT/bin/omarchy-install-docker-dbs" || - fail "development database installs still use rootful Docker" -! rg -q 'pkexec|omarchy-sudo-docker' "$ROOT/bin/omarchy-launch-docker-tui" || - fail "lazydocker still crosses a root boundary" -[[ ! -e $ROOT/bin/omarchy-sudo-docker && ! -e $ROOT/bin/omarchy-setup-security-sudoless-docker && ! -e $ROOT/bin/omarchy-remove-security-sudoless-docker ]] || - fail "the obsolete docker-group toggle remains installed" -! rg -q 'sudoless-docker|Sudoless Docker' "$ROOT/default/omarchy/omarchy-menu.jsonc" || - fail "the obsolete docker-group toggle remains in the menu" -pass "Docker CLI, Compose, Buildx, databases and lazydocker use the user daemon directly" - -socket_policy="$ROOT/default/systemd/system/docker.socket.d/10-omarchy-rootful.conf" -grep -qx 'SocketUser=root' "$socket_policy" || fail "the Windows Docker socket is root-owned" -grep -qx 'SocketGroup=root' "$socket_policy" || fail "the Windows Docker socket has no docker-group access" -grep -qx 'SocketMode=0600' "$socket_policy" || fail "the Windows Docker socket is root-only" -grep -q 'host="unix:///proc/\$main_pid/root/run/docker.sock"' "$ROOT/bin/omarchy-windows-vm" || - fail "privileged Windows actions are not pinned to dockerd's mount namespace" -grep -q 'sudo "$target" __priv' "$ROOT/bin/omarchy-windows-vm" || - fail "terminal Windows operations do not authenticate" -grep -q 'pkexec "$target" __priv' "$ROOT/bin/omarchy-windows-vm" || - fail "graphical Windows operations do not authenticate" -pass "Windows remains on an authenticated root-only Docker daemon" From b05e433c640988da7427959841da5b4a5e592870 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Thu, 29 Oct 2026 12:54:50 -0600 Subject: [PATCH 28/31] Reject incompatible logging before rootless migration --- default/docker/rootless/migrate.py | 6 +++--- test/shell.d/rootless-docker-migration-test.sh | 9 ++++++--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/default/docker/rootless/migrate.py b/default/docker/rootless/migrate.py index 0db61e28db30..acdbc18eb6b3 100644 --- a/default/docker/rootless/migrate.py +++ b/default/docker/rootless/migrate.py @@ -675,9 +675,9 @@ def validate_security(container): # device, namespace, runtime, mount and resource options. raise ValueError(f"{name}: custom {key} needs an explicit rootless Docker configuration") log = host.get("LogConfig") or {} - if (log.get("Type") not in (None, "", "json-file") or - (log.get("Config") or {}) not in ({}, {"max-size": "10m", "max-file": "5"})): - raise ValueError(f"{name}: custom logging needs an explicit migration") + if (log.get("Type") != TARGET_DAEMON_CONFIG["log-driver"] or + log.get("Config") != TARGET_DAEMON_CONFIG["log-opts"]): + raise ValueError(f"{name}: logging differs from rootless Docker defaults; use an explicit migration") def runtime_arguments(container, source_nofile): diff --git a/test/shell.d/rootless-docker-migration-test.sh b/test/shell.d/rootless-docker-migration-test.sh index 7892b7408529..c4972412f3b5 100755 --- a/test/shell.d/rootless-docker-migration-test.sh +++ b/test/shell.d/rootless-docker-migration-test.sh @@ -987,6 +987,7 @@ blocked = ( ("DeviceRequests", [{"Driver": "nvidia"}]), ("DeviceCgroupRules", ["a *:* rwm"]), ("NetworkMode", "host"), ("Runtime", "nvidia"), ("CgroupnsMode", "host"), + ("LogConfig", {"Type": "json-file", "Config": {}}), ("SecurityOpt", ["seccomp=unconfined"]), ("Binds", ["/home/example/project:/data:rw"]), ("Mounts", [{"Type": "bind", "Source": "/home/example", "Target": "/data"}]), @@ -1012,14 +1013,16 @@ for networks in ({"bridge": {}, "project": {}}, {"project": {}}, {}): pass else: raise AssertionError(f"unsupported networks passed: {networks}") -print("ok - privileged, device, host-path, custom-network and unknown settings fail closed") +print("ok - privileged, device, host-path, logging, custom-network and unknown settings fail closed") records = {} -for index, field in enumerate(("Privileged", "Runtime"), 1): +for index, (field, value) in enumerate(( + ("Privileged", True), ("Runtime", "nvidia"), + ("LogConfig", {"Type": "json-file", "Config": {}})), 1): changed = copy.deepcopy(container) changed["Name"] = f"/blocked-{index}" changed["Id"] = str(index) * 64 - changed["HostConfig"][field] = True if field == "Privileged" else "nvidia" + changed["HostConfig"][field] = value records[changed["Name"].lstrip("/")] = changed migration.daemon_security = lambda engine: source_security if engine == migration.SOURCE else target_security migration.inspect = lambda engine, kind, name: records[name] From c52a6e315824ed123d8b1babbb0049d65bab9d30 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Thu, 29 Oct 2026 12:58:04 -0600 Subject: [PATCH 29/31] Consolidate Windows VM regression coverage --- test/shell.d/windows-vm-auth-test.sh | 85 ------- test/shell.d/windows-vm-compose-test.sh | 251 ++++++++++++++++++++ test/shell.d/windows-vm-credentials-test.sh | 168 ------------- 3 files changed, 251 insertions(+), 253 deletions(-) delete mode 100644 test/shell.d/windows-vm-auth-test.sh delete mode 100644 test/shell.d/windows-vm-credentials-test.sh diff --git a/test/shell.d/windows-vm-auth-test.sh b/test/shell.d/windows-vm-auth-test.sh deleted file mode 100644 index e39d8ff15d39..000000000000 --- a/test/shell.d/windows-vm-auth-test.sh +++ /dev/null @@ -1,85 +0,0 @@ -#!/bin/bash - -set -euo pipefail -source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" - -python3 - <<'PY' -import os -import pty -import subprocess -import tempfile -from pathlib import Path - - -script = r''' -set -e -set -- help -source "$ROOT/bin/omarchy-windows-vm" >/dev/null -priv_target() { printf '/fixture/omarchy-windows-vm\n'; } -sudo() { printf sudo >"$MODE_LOG"; printf exited; } -pkexec() { printf pkexec >"$MODE_LOG"; printf exited; } -migrate_legacy_compose() { :; } -status_windows -''' -with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - (root / "docker-compose.yml").touch() - log = root / "mode" - env = dict(os.environ, OMARCHY_WINDOWS_DIR=str(root), MODE_LOG=str(log), HOME=str(root)) - for name, terminal_input, terminal_error, expected in ( - ("terminal status", True, True, "sudo"), - ("redirected stdin", False, True, "sudo"), - ("graphical caller", False, False, "pkexec")): - master, slave = pty.openpty() - try: - result = subprocess.run(["/bin/bash", "-c", script], env=env, - stdin=slave if terminal_input else subprocess.DEVNULL, - stdout=subprocess.PIPE, - stderr=slave if terminal_error else subprocess.PIPE, - text=True, timeout=10) - assert result.returncode == 0, (name, result.stdout, result.stderr) - assert log.read_text() == expected, (name, log.read_text(), expected) - assert "Windows VM is stopped" in result.stdout - finally: - os.close(slave) - os.close(master) - print(f"ok - {name} uses {expected} while privileged status output is captured") -PY - -test_dir=$(mktemp -d) -trap 'rm -rf "$test_dir"' EXIT -touch "$test_dir/docker-compose.yml" -MODE_LOG="$test_dir/mode" OMARCHY_WINDOWS_DIR="$test_dir" ROOT="$ROOT" bash -c ' - set -e - export HOME="$OMARCHY_WINDOWS_DIR/home" - mkdir -p "$HOME" - set -- help - source "$ROOT/bin/omarchy-windows-vm" >/dev/null - priv() { printf "priv:%s\n" "$1" >>"$MODE_LOG"; } - secure_windows_migration - [[ $(<"$MODE_LOG") == "priv:secure" ]] - mkdir -p "$HOME/.config/windows" - touch "$HOME/.config/windows/docker-compose.yml" - : >"$MODE_LOG" - migrate_legacy_compose() { - printf "migrate\n" >>"$MODE_LOG" - priv secure - remove_legacy_compose - } - remove_legacy_compose() { printf "remove\n" >>"$MODE_LOG"; rm "$HOME/.config/windows/docker-compose.yml"; } - secure_windows_migration - [[ ! -e $HOME/.config/windows/docker-compose.yml ]] - expected=$(printf "migrate\npriv:secure\nremove") - [[ $(<"$MODE_LOG") == "$expected" ]] - valid_priv_action secure - rm "$OMARCHY_WINDOWS_DIR/docker-compose.yml" - : >"$MODE_LOG" - secure_windows_migration - [[ $(<"$MODE_LOG") == "priv:secure" ]] - touch "$HOME/.config/windows/docker-compose.yml" - migrate_legacy_compose() { return 23; } - if secure_windows_migration; then - exit 1 - fi -' -pass "migration security repair authenticates and propagates upgrade failures" diff --git a/test/shell.d/windows-vm-compose-test.sh b/test/shell.d/windows-vm-compose-test.sh index 97610473137b..cdba576b300a 100644 --- a/test/shell.d/windows-vm-compose-test.sh +++ b/test/shell.d/windows-vm-compose-test.sh @@ -7,6 +7,257 @@ source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" # Bind mounts need CAP_SYS_ADMIN in a private mount namespace. Keep the # caller's uid so the non-root development path is exercised. if [[ ${OMARCHY_WINDOWS_TEST_NAMESPACE:-0} != 1 ]]; then + # Auth checks do not require bind mounts. + ( + python3 - <<'PY' +import os +import pty +import subprocess +import tempfile +from pathlib import Path + + +script = r''' +set -e +set -- help +source "$ROOT/bin/omarchy-windows-vm" >/dev/null +priv_target() { printf '/fixture/omarchy-windows-vm\n'; } +sudo() { printf sudo >"$MODE_LOG"; printf exited; } +pkexec() { printf pkexec >"$MODE_LOG"; printf exited; } +migrate_legacy_compose() { :; } +status_windows +''' +with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "docker-compose.yml").touch() + log = root / "mode" + env = dict(os.environ, OMARCHY_WINDOWS_DIR=str(root), MODE_LOG=str(log), HOME=str(root)) + for name, terminal_input, terminal_error, expected in ( + ("terminal status", True, True, "sudo"), + ("redirected stdin", False, True, "sudo"), + ("graphical caller", False, False, "pkexec")): + master, slave = pty.openpty() + try: + result = subprocess.run(["/bin/bash", "-c", script], env=env, + stdin=slave if terminal_input else subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=slave if terminal_error else subprocess.PIPE, + text=True, timeout=10) + assert result.returncode == 0, (name, result.stdout, result.stderr) + assert log.read_text() == expected, (name, log.read_text(), expected) + assert "Windows VM is stopped" in result.stdout + finally: + os.close(slave) + os.close(master) + print(f"ok - {name} uses {expected} while privileged status output is captured") +PY + + test_dir=$(mktemp -d) + trap 'rm -rf "$test_dir"' EXIT + touch "$test_dir/docker-compose.yml" + MODE_LOG="$test_dir/mode" OMARCHY_WINDOWS_DIR="$test_dir" ROOT="$ROOT" bash -c ' + set -e + export HOME="$OMARCHY_WINDOWS_DIR/home" + mkdir -p "$HOME" + set -- help + source "$ROOT/bin/omarchy-windows-vm" >/dev/null + priv() { printf "priv:%s\n" "$1" >>"$MODE_LOG"; } + secure_windows_migration + [[ $(<"$MODE_LOG") == "priv:secure" ]] + mkdir -p "$HOME/.config/windows" + touch "$HOME/.config/windows/docker-compose.yml" + : >"$MODE_LOG" + migrate_legacy_compose() { + printf "migrate\n" >>"$MODE_LOG" + priv secure + remove_legacy_compose + } + remove_legacy_compose() { printf "remove\n" >>"$MODE_LOG"; rm "$HOME/.config/windows/docker-compose.yml"; } + secure_windows_migration + [[ ! -e $HOME/.config/windows/docker-compose.yml ]] + expected=$(printf "migrate\npriv:secure\nremove") + [[ $(<"$MODE_LOG") == "$expected" ]] + valid_priv_action secure + rm "$OMARCHY_WINDOWS_DIR/docker-compose.yml" + : >"$MODE_LOG" + secure_windows_migration + [[ $(<"$MODE_LOG") == "priv:secure" ]] + touch "$HOME/.config/windows/docker-compose.yml" + migrate_legacy_compose() { return 23; } + if secure_windows_migration; then + exit 1 + fi + ' + pass "migration security repair authenticates and propagates upgrade failures" + ) + + # Credentials checks do not require bind mounts. + ( + python3 - <<'PY' +import os +from pathlib import Path +import subprocess +import tempfile + +prefix = r''' +set -euo pipefail +set -- help +source "$ROOT/bin/omarchy-windows-vm" >/dev/null +mkdir -p "$HOME/.config/windows" "$OMARCHY_WINDOWS_DIR" +CREDENTIALS_FILE="$HOME/.config/windows/credentials" +TEST_PUBLISH_PATH=$CREDENTIALS_FILE +prepare_user_mount_sources() { :; } +check_prerequisites() { :; } +omarchy-pkg-add() { :; } +available_storage_gb() { printf 128; } +timedatectl() { printf UTC; } +sleep() { :; } +xdg-open() { :; } +gum() { + case "$1" in + choose) + cat >/dev/null + if [[ $* == *RAM* ]]; then printf 4G; else printf 64G; fi + ;; + input) + if [[ $* == *CPU* ]]; then printf 2 + elif [[ $* == *username* ]]; then printf testuser + else printf testpass + fi + ;; + style | confirm) : ;; + *) return 1 ;; + esac +} +write_compose() { printf 'compose\n' >>"$TEST_LOG"; } +priv() { printf 'priv:%s\n' "$1" >>"$TEST_LOG"; } +''' + + +def run_case(name, body, status=0, setup=None): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + home = root / 'home' + home.mkdir() + env = dict(os.environ, HOME=str(home), OMARCHY_WINDOWS_DIR=str(root / 'runtime'), + TEST_ROOT=str(root), TEST_LOG=str(root / 'calls')) + if setup: + setup(root) + result = subprocess.run(['/bin/bash', '-c', prefix + body], env=env, + capture_output=True, text=True, timeout=20) + assert result.returncode == status, (name, result.returncode, result.stdout, result.stderr) + print('ok - ' + name) + return result + + +for fixture in ('dangling-parent', 'file-parent', 'directory-destination'): + body = r''' +case "$FIXTURE" in + dangling-parent) + rmdir "$HOME/.config/windows" + ln -s "$TEST_ROOT/missing" "$HOME/.config/windows" + ;; + file-parent) + rmdir "$HOME/.config/windows" + touch "$HOME/.config/windows" + ;; + directory-destination) mkdir "$CREDENTIALS_FILE" ;; +esac +if (install_windows); then exit 9; fi +[[ ! -e $TEST_LOG ]] +'''.replace('$FIXTURE', fixture) + run_case('install rejects ' + fixture + ' before privileged configuration', body) + +run_case('failed Compose staging preserves existing credentials and removes private candidates', r''' +write_credentials previous oldpass +before=$(sha256sum "$CREDENTIALS_FILE") +write_compose() { + [[ $(read_credential PASSWORD) == oldpass ]] || exit 9 + candidates=("$HOME/.config/windows"/.credentials-install.*) + [[ ${#candidates[@]} == 1 && -f ${candidates[0]} ]] || exit 9 + [[ $(stat -c '%a' "${candidates[0]}") == 600 ]] || exit 9 + printf 'compose\n' >>"$TEST_LOG" + return 7 +} +if (install_windows); then exit 9; fi +[[ $(sha256sum "$CREDENTIALS_FILE") == "$before" ]] +[[ $(<"$TEST_LOG") == compose ]] +[[ -z $(find "$HOME/.config/windows" -name '.credentials*' -print) ]] +''') + +run_case('publication failure preserves prior credentials, cleans staging and never starts VM', r''' +write_credentials previous oldpass +before=$(sha256sum "$CREDENTIALS_FILE") +mv() { + if [[ ${!#} == "$TEST_PUBLISH_PATH" ]]; then return 1; fi + command mv "$@" +} +if (install_windows); then exit 9; fi +[[ $(sha256sum "$CREDENTIALS_FILE") == "$before" ]] +[[ $(<"$TEST_LOG") == compose ]] +[[ -z $(find "$HOME/.config/windows" -name '.credentials*' -print) ]] +''') + +run_case('install publishes staged credentials before starting VM', r''' +priv() { + [[ $1 == up && $(read_credential PASSWORD) == testpass ]] || exit 9 + printf 'priv:up\n' >>"$TEST_LOG" +} +install_windows +[[ $(<"$TEST_LOG") == $'compose\npriv:up' ]] +[[ $(stat -c '%a' "$CREDENTIALS_FILE") == 600 ]] +[[ -z $(find "$HOME/.config/windows" -name '.credentials*' -print) ]] +''') + +run_case('linked config removal deletes actual credentials and preserves unrelated target files', r''' +mv "$HOME/.config/windows" "$TEST_ROOT/config-target" +ln -s "$TEST_ROOT/config-target" "$HOME/.config/windows" +chmod 0755 "$TEST_ROOT/config-target" +write_credentials linked secret +[[ $(stat -c '%a' "$TEST_ROOT/config-target") == 700 ]] +touch "$TEST_ROOT/config-target/keep" +# These private candidates model SIGKILL/power-loss leftovers with no EXIT trap. +for candidate in .credentials-install.ABC123 .credentials.XYZ123; do + printf 'interrupted private credentials\n' >"$TEST_ROOT/config-target/$candidate" + chmod 0600 "$TEST_ROOT/config-target/$candidate" +done +# Cleanup must unlink a planted candidate symlink without following its target. +printf 'external data\n' >"$TEST_ROOT/candidate-victim" +ln -s "$TEST_ROOT/candidate-victim" "$TEST_ROOT/config-target/.credentials.LINK12" +migrate_legacy_compose() { return 1; } +remove_windows +[[ -z $(find "$TEST_ROOT/config-target" -name '.credentials*' -print) ]] +[[ $(<"$TEST_ROOT/candidate-victim") == 'external data' ]] +[[ ! -e $TEST_ROOT/config-target/credentials && -f $TEST_ROOT/config-target/keep ]] +[[ ! -L $HOME/.config/windows && ! -e $HOME/.config/windows ]] +''') + +run_case('credential deletion failure retains the config link and reports removal failure', r''' +mv "$HOME/.config/windows" "$TEST_ROOT/config-target" +ln -s "$TEST_ROOT/config-target" "$HOME/.config/windows" +write_credentials linked secret +migrate_legacy_compose() { return 1; } +rm() { + if [[ " $* " == *" $CREDENTIALS_FILE "* ]]; then return 1; fi + command rm "$@" +} +if (remove_windows); then exit 9; fi +[[ -L $HOME/.config/windows && -f $TEST_ROOT/config-target/credentials ]] +''') + +run_case('real and dangling legacy Compose symlinks remain untouched without migration', r''' +printf 'legacy plaintext\n' >"$TEST_ROOT/legacy-target" +for target in "$TEST_ROOT/legacy-target" "$TEST_ROOT/missing-target"; do + ln -s "$target" "$LEGACY_COMPOSE_FILE" + if migrate_legacy_compose; then exit 9; fi + [[ -L $LEGACY_COMPOSE_FILE && ! -e $TEST_LOG ]] + [[ $(<"$TEST_ROOT/legacy-target") == 'legacy plaintext' ]] + rm "$LEGACY_COMPOSE_FILE" +done +''') +PY + ) + if unshare --user --map-current-user --keep-caps --mount true 2>/dev/null; then exec env OMARCHY_WINDOWS_TEST_NAMESPACE=1 \ unshare --user --map-current-user --keep-caps --mount --propagation private bash "$0" diff --git a/test/shell.d/windows-vm-credentials-test.sh b/test/shell.d/windows-vm-credentials-test.sh deleted file mode 100644 index c6fbf75e37d0..000000000000 --- a/test/shell.d/windows-vm-credentials-test.sh +++ /dev/null @@ -1,168 +0,0 @@ -#!/bin/bash - -set -euo pipefail -source "$(dirname -- "${BASH_SOURCE[0]}")/base-test.sh" - -python3 - <<'PY' -import os -from pathlib import Path -import subprocess -import tempfile - -prefix = r''' -set -euo pipefail -set -- help -source "$ROOT/bin/omarchy-windows-vm" >/dev/null -mkdir -p "$HOME/.config/windows" "$OMARCHY_WINDOWS_DIR" -CREDENTIALS_FILE="$HOME/.config/windows/credentials" -TEST_PUBLISH_PATH=$CREDENTIALS_FILE -prepare_user_mount_sources() { :; } -check_prerequisites() { :; } -omarchy-pkg-add() { :; } -available_storage_gb() { printf 128; } -timedatectl() { printf UTC; } -sleep() { :; } -xdg-open() { :; } -gum() { - case "$1" in - choose) - cat >/dev/null - if [[ $* == *RAM* ]]; then printf 4G; else printf 64G; fi - ;; - input) - if [[ $* == *CPU* ]]; then printf 2 - elif [[ $* == *username* ]]; then printf testuser - else printf testpass - fi - ;; - style | confirm) : ;; - *) return 1 ;; - esac -} -write_compose() { printf 'compose\n' >>"$TEST_LOG"; } -priv() { printf 'priv:%s\n' "$1" >>"$TEST_LOG"; } -''' - - -def run_case(name, body, status=0, setup=None): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - home = root / 'home' - home.mkdir() - env = dict(os.environ, HOME=str(home), OMARCHY_WINDOWS_DIR=str(root / 'runtime'), - TEST_ROOT=str(root), TEST_LOG=str(root / 'calls')) - if setup: - setup(root) - result = subprocess.run(['/bin/bash', '-c', prefix + body], env=env, - capture_output=True, text=True, timeout=20) - assert result.returncode == status, (name, result.returncode, result.stdout, result.stderr) - print('ok - ' + name) - return result - - -for fixture in ('dangling-parent', 'file-parent', 'directory-destination'): - body = r''' -case "$FIXTURE" in - dangling-parent) - rmdir "$HOME/.config/windows" - ln -s "$TEST_ROOT/missing" "$HOME/.config/windows" - ;; - file-parent) - rmdir "$HOME/.config/windows" - touch "$HOME/.config/windows" - ;; - directory-destination) mkdir "$CREDENTIALS_FILE" ;; -esac -if (install_windows); then exit 9; fi -[[ ! -e $TEST_LOG ]] -'''.replace('$FIXTURE', fixture) - run_case('install rejects ' + fixture + ' before privileged configuration', body) - -run_case('failed Compose staging preserves existing credentials and removes private candidates', r''' -write_credentials previous oldpass -before=$(sha256sum "$CREDENTIALS_FILE") -write_compose() { - [[ $(read_credential PASSWORD) == oldpass ]] || exit 9 - candidates=("$HOME/.config/windows"/.credentials-install.*) - [[ ${#candidates[@]} == 1 && -f ${candidates[0]} ]] || exit 9 - [[ $(stat -c '%a' "${candidates[0]}") == 600 ]] || exit 9 - printf 'compose\n' >>"$TEST_LOG" - return 7 -} -if (install_windows); then exit 9; fi -[[ $(sha256sum "$CREDENTIALS_FILE") == "$before" ]] -[[ $(<"$TEST_LOG") == compose ]] -[[ -z $(find "$HOME/.config/windows" -name '.credentials*' -print) ]] -''') - -run_case('publication failure preserves prior credentials, cleans staging and never starts VM', r''' -write_credentials previous oldpass -before=$(sha256sum "$CREDENTIALS_FILE") -mv() { - if [[ ${!#} == "$TEST_PUBLISH_PATH" ]]; then return 1; fi - command mv "$@" -} -if (install_windows); then exit 9; fi -[[ $(sha256sum "$CREDENTIALS_FILE") == "$before" ]] -[[ $(<"$TEST_LOG") == compose ]] -[[ -z $(find "$HOME/.config/windows" -name '.credentials*' -print) ]] -''') - -run_case('install publishes staged credentials before starting VM', r''' -priv() { - [[ $1 == up && $(read_credential PASSWORD) == testpass ]] || exit 9 - printf 'priv:up\n' >>"$TEST_LOG" -} -install_windows -[[ $(<"$TEST_LOG") == $'compose\npriv:up' ]] -[[ $(stat -c '%a' "$CREDENTIALS_FILE") == 600 ]] -[[ -z $(find "$HOME/.config/windows" -name '.credentials*' -print) ]] -''') - -run_case('linked config removal deletes actual credentials and preserves unrelated target files', r''' -mv "$HOME/.config/windows" "$TEST_ROOT/config-target" -ln -s "$TEST_ROOT/config-target" "$HOME/.config/windows" -chmod 0755 "$TEST_ROOT/config-target" -write_credentials linked secret -[[ $(stat -c '%a' "$TEST_ROOT/config-target") == 700 ]] -touch "$TEST_ROOT/config-target/keep" -# These private candidates model SIGKILL/power-loss leftovers with no EXIT trap. -for candidate in .credentials-install.ABC123 .credentials.XYZ123; do - printf 'interrupted private credentials\n' >"$TEST_ROOT/config-target/$candidate" - chmod 0600 "$TEST_ROOT/config-target/$candidate" -done -# Cleanup must unlink a planted candidate symlink without following its target. -printf 'external data\n' >"$TEST_ROOT/candidate-victim" -ln -s "$TEST_ROOT/candidate-victim" "$TEST_ROOT/config-target/.credentials.LINK12" -migrate_legacy_compose() { return 1; } -remove_windows -[[ -z $(find "$TEST_ROOT/config-target" -name '.credentials*' -print) ]] -[[ $(<"$TEST_ROOT/candidate-victim") == 'external data' ]] -[[ ! -e $TEST_ROOT/config-target/credentials && -f $TEST_ROOT/config-target/keep ]] -[[ ! -L $HOME/.config/windows && ! -e $HOME/.config/windows ]] -''') - -run_case('credential deletion failure retains the config link and reports removal failure', r''' -mv "$HOME/.config/windows" "$TEST_ROOT/config-target" -ln -s "$TEST_ROOT/config-target" "$HOME/.config/windows" -write_credentials linked secret -migrate_legacy_compose() { return 1; } -rm() { - if [[ " $* " == *" $CREDENTIALS_FILE "* ]]; then return 1; fi - command rm "$@" -} -if (remove_windows); then exit 9; fi -[[ -L $HOME/.config/windows && -f $TEST_ROOT/config-target/credentials ]] -''') - -run_case('real and dangling legacy Compose symlinks remain untouched without migration', r''' -printf 'legacy plaintext\n' >"$TEST_ROOT/legacy-target" -for target in "$TEST_ROOT/legacy-target" "$TEST_ROOT/missing-target"; do - ln -s "$target" "$LEGACY_COMPOSE_FILE" - if migrate_legacy_compose; then exit 9; fi - [[ -L $LEGACY_COMPOSE_FILE && ! -e $TEST_LOG ]] - [[ $(<"$TEST_ROOT/legacy-target") == 'legacy plaintext' ]] - rm "$LEGACY_COMPOSE_FILE" -done -''') -PY From 5c33fb6806a46f7275e944247aa626eb056851ec Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Tue, 3 Nov 2026 15:49:54 -0600 Subject: [PATCH 30/31] Run Windows security fixtures on every host architecture --- test/shell.d/windows-vm-compose-test.sh | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/test/shell.d/windows-vm-compose-test.sh b/test/shell.d/windows-vm-compose-test.sh index 861eff37bde7..66d58fcddbd1 100644 --- a/test/shell.d/windows-vm-compose-test.sh +++ b/test/shell.d/windows-vm-compose-test.sh @@ -4,6 +4,13 @@ set -euo pipefail source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" +# Exercise x86 behaviour on every host, including the checks before namespaces. +export OMARCHY_WINDOWS_TEST_BIN=${OMARCHY_WINDOWS_TEST_BIN:-$(mktemp -d)} +trap 'rm -rf "$OMARCHY_WINDOWS_TEST_BIN"' EXIT +printf '#!/bin/bash\nexit 0\n' >"$OMARCHY_WINDOWS_TEST_BIN/omarchy-hw-x86" +chmod +x "$OMARCHY_WINDOWS_TEST_BIN/omarchy-hw-x86" +export PATH="$OMARCHY_WINDOWS_TEST_BIN:$PATH" + # Bind mounts need CAP_SYS_ADMIN in a private mount namespace. Keep the # caller's uid so the non-root development path is exercised. if [[ ${OMARCHY_WINDOWS_TEST_NAMESPACE:-0} != 1 ]]; then @@ -271,14 +278,6 @@ export OMARCHY_WINDOWS_DIR="$TMPDIR/win" export HOME="$TMPDIR/home" mkdir -p "$HOME" -# The command refuses any CPU but x86_64 before defining anything, and sourcing -# it there would exit this test with it. What is under test is the x86_64 path, -# so omarchy-hw-x86 answers as one. -STUB_BIN="$TMPDIR/bin" -mkdir -p "$STUB_BIN" -printf '#!/bin/bash\nexit 0\n' >"$STUB_BIN/omarchy-hw-x86" -chmod +x "$STUB_BIN/omarchy-hw-x86" -PATH="$STUB_BIN:$PATH" set -- help source "$ROOT/bin/omarchy-windows-vm" >/dev/null 2>&1 @@ -295,7 +294,7 @@ unmount_all() { cleanup() { set +e unmount_all - rm -rf "$TMPDIR" + rm -rf "$TMPDIR" "$OMARCHY_WINDOWS_TEST_BIN" } trap cleanup EXIT From 4c3a55f3a1e1c63fe56d66a73f0ac4af0d985471 Mon Sep 17 00:00:00 2001 From: acrogenesis Date: Thu, 19 Nov 2026 22:46:38 -0600 Subject: [PATCH 31/31] Check rootless Docker ID mappings before migration --- default/docker/rootless/migrate.py | 38 +++++++++++++++++++ .../shell.d/rootless-docker-migration-test.sh | 21 ++++++++++ 2 files changed, 59 insertions(+) diff --git a/default/docker/rootless/migrate.py b/default/docker/rootless/migrate.py index acdbc18eb6b3..35c75dd20e01 100644 --- a/default/docker/rootless/migrate.py +++ b/default/docker/rootless/migrate.py @@ -716,6 +716,40 @@ def allowed_capabilities(container): return set() if "ALL" in dropped else DOCKER_CAPABILITIES - dropped +def target_user_maps(proc=Path("/proc")): + pid, _ = verified_target_daemon(TARGET_DAEMON_IDENTITY, proc) + mappings = [] + for kind in ("uid", "gid"): + try: + ranges = [] + for line in (proc / str(pid) / f"{kind}_map").read_text().splitlines(): + first, outside, length = map(int, line.split()) + if first < 0 or outside < 0 or length <= 0: + raise ValueError("invalid mapping range") + ranges.append(range(first, first + length)) + if not ranges: + raise ValueError("empty mapping") + except (OSError, ValueError) as error: + raise ValueError(f"cannot read the rootless Docker daemon's {kind} map") from error + mappings.append(ranges) + # Detect a service restart or PID reuse while reading the maps. + verified_target_daemon(TARGET_DAEMON_IDENTITY, proc) + return mappings + + +def validate_target_user(container, mappings): + user = container["Config"].get("User") or "0" + uid, separator, gid = user.partition(":") + name = container["Name"].lstrip("/") + for kind, value, ranges in (("UID", uid, mappings[0]), ("GID", gid, mappings[1])): + if kind == "GID" and not separator: + continue + if not re.fullmatch(r"[0-9]+", value): + raise ValueError(f"{name}: a named or invalid {kind} needs an explicit migration") + if not any(int(value) in mapped for mapped in ranges): + raise ValueError(f"{name}: {kind} {value} is outside the rootless Docker mapping") + + def verify_environment(container, values): # The committed image contains the source environment exactly. A temporary # empty DOCKER_CONFIG prevents the destination CLI from injecting proxy @@ -2416,12 +2450,14 @@ def main(): validate_target_policy() source_nofile = source_default_nofile() containers = [inspect(SOURCE, "container", name) for name in names] + mappings = target_user_maps() if containers else None volumes = set() blockers = [] intents = {} for container in containers: try: validate(container) + validate_target_user(container, mappings) intent = migration_intent(container) intents[container["Id"]] = intent except (ValueError, RuntimeError) as error: @@ -2523,12 +2559,14 @@ def main(): if not check_completed: source_nofile = source_default_nofile() containers = [inspect(SOURCE, "container", name) for name in names] + mappings = target_user_maps() if containers else None volumes = set() blockers = [] intents = {} for container in containers: try: validate(container) + validate_target_user(container, mappings) intent = migration_intent(container) intents[container["Id"]] = intent except (ValueError, RuntimeError) as error: diff --git a/test/shell.d/rootless-docker-migration-test.sh b/test/shell.d/rootless-docker-migration-test.sh index c4972412f3b5..8330c9e12cd6 100755 --- a/test/shell.d/rootless-docker-migration-test.sh +++ b/test/shell.d/rootless-docker-migration-test.sh @@ -457,6 +457,7 @@ print("ok - migration pins known daemon confinement and rejects hidden target wo # Direct migration unit fixtures replace Docker with an event recorder. The # daemon-policy parser is covered above and exercised end-to-end in Lab. migration.validate_target_policy = lambda: None +migration.target_user_maps = lambda: ([range(65537)], [range(65537)]) migration.source_default_nofile = lambda: source_nofile migration.validate_target_nofile = lambda limits: None @@ -1038,6 +1039,26 @@ else: raise AssertionError("blocked batch passed preflight") print("ok - complete-batch preflight reports every blocker without exposing container secrets") +mapped = copy.deepcopy(container) +unmapped_uid = copy.deepcopy(container) +unmapped_gid = copy.deepcopy(container) +mapped["Name"], mapped["Config"]["User"] = "/mapped", "1000:1001" +unmapped_uid["Name"], unmapped_uid["Config"]["User"] = "/unmapped-uid", "100000:1001" +unmapped_gid["Name"], unmapped_gid["Config"]["User"] = "/unmapped-gid", "0:100000" +mapping_records = {c["Name"][1:]: c for c in (mapped, unmapped_uid, unmapped_gid)} +for flags in (["--check"], ["--quiesce-all", "-"], []): + sys.argv = ["migrate.py", *flags, *mapping_records] + migration.inspect = lambda engine, kind, name: mapping_records[name] if kind == "container" else copy.deepcopy(source_volume) + try: + migration.main() + except ValueError as error: + message = str(error) + assert "unmapped-uid: UID 100000 is outside" in message, message + assert "unmapped-gid: GID 100000 is outside" in message, message + else: + raise AssertionError("unmapped numeric identities passed preflight") +print("ok - both rootless identity mappings are checked before quiescing or transferring the batch") + stopped = copy.deepcopy(container) stopped["State"] = {"Running": False, "StartedAt": "start", "FinishedAt": "finish", "ExitCode": 0} stopped["HostConfig"]["RestartPolicy"] = {"Name": "no", "MaximumRetryCount": 0}