diff --git a/bin/omarchy-install-docker-dbs b/bin/omarchy-install-docker-dbs index 1a21b94857a3..7101c8512e3c 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-install-service-once b/bin/omarchy-install-service-once index b721a738ae04..98d366e5c0c6 100755 --- a/bin/omarchy-install-service-once +++ b/bin/omarchy-install-service-once @@ -1,13 +1,51 @@ #!/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 + +# 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 +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-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-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/bin/omarchy-provision-owner b/bin/omarchy-provision-owner index 53c4aa63dca1..5ae0aa36dc27 100755 --- a/bin/omarchy-provision-owner +++ b/bin/omarchy-provision-owner @@ -876,6 +876,9 @@ create_user() { useradd -m -G "$(user_groups)" -s /bin/bash "$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 0084d9bb4593..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 --affirmative "$(omarchy-i18n common.yes)" --negative "$(omarchy-i18n common.no)" "$(omarchy-i18n docker.rebootToApply)"; 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 0ba0090310de..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 --affirmative "$(omarchy-i18n common.yes)" --negative "$(omarchy-i18n common.no)" "$(omarchy-i18n docker.enableSudoless)"; 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 --affirmative "$(omarchy-i18n common.yes)" --negative "$(omarchy-i18n common.no)" "$(omarchy-i18n docker.rebootToApply)"; 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 794320429b6b..b18b0c7eac72 100755 --- a/bin/omarchy-upgrade-to-quattro +++ b/bin/omarchy-upgrade-to-quattro @@ -1414,9 +1414,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. # A channel's base list may still pick the stock power-profiles-daemon, whose # powerprofilesctl runs mise's python3; the Omarchy build ships it fixed. diff --git a/bin/omarchy-windows-vm b/bin/omarchy-windows-vm index d891965fc020..141dd6a1db37 100755 --- a/bin/omarchy-windows-vm +++ b/bin/omarchy-windows-vm @@ -15,11 +15,8 @@ if ! omarchy-hw-x86; then fi # 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 @@ -32,13 +29,14 @@ fi 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" 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. @@ -58,12 +56,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 @@ -87,47 +79,43 @@ 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 +} + +# 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() { + local host="unix:///run/docker.sock" main_pid + if ((EUID == 0)); then + /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 "$host" "$@" } -dc() { docker-compose -f "$COMPOSE_FILE" "$@"; } +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 @@ -156,25 +144,26 @@ 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 } -# --- 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 @@ -242,8 +231,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' @@ -263,7 +251,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 @@ -274,9 +262,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() { @@ -302,10 +295,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 && @@ -680,6 +674,75 @@ 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_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 @@ -738,12 +801,14 @@ 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 + fsync_regular_file "$tmp" || exit 1 mv -fT -- "$tmp" "$COMPOSE_FILE" || exit 1 tmp="" + fsync_directory "$RUNTIME_DIR" || exit 1 trap - EXIT ) @@ -773,7 +838,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 } @@ -784,7 +849,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 @@ -796,7 +861,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() { @@ -815,6 +882,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 @@ -830,14 +903,16 @@ 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 } 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() { @@ -889,14 +964,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 @@ -908,6 +990,56 @@ assert_mounts_safe() { __priv_up() { assert_mounts_safe && dc up -d; } +__priv_secure() { + 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 + # 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 + return 1 + } + else + 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; } # Bring the VM up and wait until the guest reports it is ready, all under a @@ -984,7 +1116,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 } @@ -1064,19 +1197,71 @@ 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. -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; } 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 @@ -1084,6 +1269,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() { @@ -1100,27 +1313,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") - # Compose decoded the YAML escapes and $$ before the guest saw it, so undo them. - password=$(unescape "$password") - 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 @@ -1133,7 +1380,45 @@ migrate_legacy_compose() { echo "Re-run: omarchy-windows-vm install" >&2 return 1 fi - rm -f "$LEGACY_COMPOSE_FILE" + # 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() { + 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 + # 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 + return 0 + elif [[ -e $parent || -L $parent ]]; then + [[ -d $parent && ! -L $parent ]] || { + echo "omarchy-windows-vm: legacy configuration requires a real directory: $parent" >&2 + return 1 + } + fsync_directory "$parent" + fi +} + +secure_windows_migration() { + sync_legacy_compose_parent || return 1 + if [[ -f $LEGACY_COMPOSE_FILE ]]; then + migrate_legacy_compose || return 1 + return 0 + fi + priv secure || return 1 } # --- prerequisites ----------------------------------------------------------- @@ -1321,18 +1606,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 - # 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..." @@ -1341,11 +1616,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 @@ -1377,11 +1652,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 || { @@ -1390,9 +1668,17 @@ remove_windows() { } fi - rm -f "$HOME/.local/share/applications/windows-vm.desktop" - rm -rf "$HOME/.config/windows" - rm -rf "$HOME/.windows" + # 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 + exit 1 + fi echo "" echo "Windows VM removal completed!" @@ -1409,10 +1695,12 @@ 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. 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 @@ -1516,7 +1804,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 @@ -1532,7 +1827,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" @@ -1589,6 +1891,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/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 81022aaf2568..d31e24f321e4 100644 --- a/default/bash/env-bootstrap +++ b/default/bash/env-bootstrap @@ -60,4 +60,15 @@ 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 + _OMARCHY_ENV_BOOTSTRAPPED=1 diff --git a/default/docker/rootless/migrate.py b/default/docker/rootless/migrate.py new file mode 100644 index 000000000000..35c75dd20e01 --- /dev/null +++ b/default/docker/rootless/migrate.py @@ -0,0 +1,2680 @@ +"""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, 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" +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", + "/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", +} +DEFAULT_ZERO_HOST_CONFIG = { + "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 + # the meaning of numeric volume ownership. Do not guess these policies. + 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, 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", + } + 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") + 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): + 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 + 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. + 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(): + # 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 + # 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") != 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): + host = container["HostConfig"] + 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(): + 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(":", 1)[0] + 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 []} + 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 + # 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, ownership=None, source_nofile=None): + 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") + 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 [] + 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 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"]) + 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") + return target + + +def local_command(args): + if args[0] == SOURCE: + 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: + _pid, endpoint = verified_target_daemon(TARGET_DAEMON_IDENTITY) + return ["/usr/bin/docker", "--host", f"unix://{endpoint}", *args[1:]] + if args[0] == "target-namespace": + 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: + 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 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 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): + 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) + 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, + source_nofile=None): + state = container["State"] + if saved is None: + validate_nofile(source_nofile) + 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, + "quiesce_started": False, + "restore_started": False, + "start_attempted": False, + "target_ownership": secrets.token_hex(32), + "source_volumes": None, + "source_nofile": deepcopy(source_nofile), + "image": None, + "volume_event": None, + "volumes": {}, + } + 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) + payload["quiesce_started"] = False + payload["restore_started"] = False + 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"] + 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 + 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 + (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 + 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("image", None) + saved.setdefault("volume_event", None) + 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"]: + 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 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"]: + raise ValueError + 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 persist_migration_intent(container, intent): + write_private_json(intent_path(container["Id"]), 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 + 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 + 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 + 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 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, 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') + 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, + "source_snapshot": snapshot_digest(container), + "target_snapshot": verified_snapshot, + }) + + +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") + labels = container["Config"].get("Labels") or {} + 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 + 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 + (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 + 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") + 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 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 {} + 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 + 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 + (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 + + +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(["/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) + verify_volume(target, source_digest) + return source_digest + + +def clear_volume(target): + destination = inspect(TARGET, "volume", target)["Mountpoint"] + 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) + 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 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 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) + 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) + 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') + verify_volume_event_marker(container, intent) + + +def source_volume_digest(volume): + return run("/usr/bin/sudo", "/usr/bin/python3", TRUSTED_MANIFEST, + source_namespace_path(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("/") + mountpoint = volume.get("Mountpoint") + if (volume.get("Driver") != "local" or volume.get("Options") 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") + + +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_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: + 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"] + 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") + + +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, 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"].pop("RestartPolicy", None) + 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, 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') + 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 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) + # 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) + + +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 + 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 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"]: + 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"]: + intent = retire_volume_event_window(planned, intent) + intent = cleanup_transfer_images(current, intent) + clear_migration_intent(identity) + + +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, 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"]: + 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"]) + 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) + 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') + seal_quiesced_source_volumes(disabled, intent) + print(f'{container["Name"].lstrip("/")}: quiesced before rootful Docker access revocation') + + +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) + 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 + not target_owned(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"], intent["source_nofile"]) + + 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 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) + 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") + + completion_published = False + try: + 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"]) + 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 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 + + +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: + 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)): + 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): + 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: + 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(): + raise ValueError(f"{name}: a previously migrated destination is missing; inspect retained data before retrying") + + container = refresh_source(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_id = None + guard_id = None + event_window = intent.get("volume_event") if intent is not None else None + image = None + 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, 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") + 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"] + 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) + 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) + 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, 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") + 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, intent["source_nofile"]) + config = planned["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"] + arguments += ["--restart", policy] + 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 = {} + 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) + target = destination_volume(planned, mount) + 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}"] + volume_arguments += ["--label", f"{VOLUME_LABEL}={ownership}"] + retained = exists("volume", target) + if not retained: + run(*volume_arguments, target) + verify_volume_definition(volume, target, ownership) + 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" + arguments += ["--mount", mount_arg] + arguments.append(target_reference) + 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(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 + 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") + 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) + 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 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) + verified_volumes[target] = (volume, ownership, digest) + 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") + 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") + 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") + 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"], intent["source_nofile"]) + 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_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) + 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}: 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. + 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") + if event_window is not None: + verify_volume_event_window(planned, intent, event_window, set(pending_volumes), + created_id if running else None) + 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: + 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 + 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: + 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 = [] + 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: + 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: + 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) + 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 + snapshot_digest(restored) == snapshot_digest(planned)): + intent = retire_volume_event_window(planned, intent, volumes_absent=True) + clear_migration_intent(identity) + except Exception: + pass + 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()}") + 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 + 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: + 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)) + 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: + 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)) + 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: + 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: + quiesced.append((container["Id"], validate)) + quiesce(container, source_nofiles[container["Id"]]) + if windows is not None: + quiesced.append((windows["Id"], validate_windows_exception)) + quiesce(windows, windows_nofile, 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: + 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:] + source_nofile = None + if names: + validate_source_daemon(daemon_security(SOURCE)) + validate_target_policy() + 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: + 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"]) + 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: + 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("/") + 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_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 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", []): + 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') + if not check_only: + try: + for container in containers: + migrate(container, source_nofiles[container["Id"]]) + 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__": + 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/rootful-listeners.py b/default/docker/rootless/rootful-listeners.py new file mode 100644 index 000000000000..43c48206c745 --- /dev/null +++ b/default/docker/rootless/rootful-listeners.py @@ -0,0 +1,252 @@ +"""Verify that rootful Docker accepts API connections only through its protected Unix socket.""" + +import json +import os +from pathlib import Path +import re +import socket +import stat +import struct +import sys + + +EXPECTED_SOCKET = "/run/docker.sock" +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")): + 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(pid, inodes, proc=Path("/proc")): + listeners = [] + 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): + listeners.append(fields[7] if len(fields) == 8 else "") + return listeners + + +def has_tcp_listener(pid, inodes, proc=Path("/proc")): + for table in ("net/tcp", "net/tcp6"): + 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 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 + 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] + 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 + + 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 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(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(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: + 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 new file mode 100644 index 000000000000..cfa887779ba1 --- /dev/null +++ b/default/docker/rootless/volume-manifest.py @@ -0,0 +1,193 @@ +"""Fingerprint a quiesced volume, using the caller's numeric UID/GID namespace.""" + +import ctypes +from contextlib import contextmanager +import hashlib +import json +import os +from pathlib import Path +import stat +import sys + + +@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 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 + 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): + first_link = hardlinks.setdefault((info.st_dev, info.st_ino), str(relative)) + row += [info.st_size, contents, first_link] + elif stat.S_ISLNK(info.st_mode): + 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') + + 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 fingerprint(root): + with pinned_root(root) as (descriptor, _pinned, root_device): + return fingerprint_open(descriptor, root_device) + + +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): + 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) + + +if __name__ == '__main__': + 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 [--archive|--clear|--sync] ROOT") diff --git a/default/i18n/en/cli.json b/default/i18n/en/cli.json index a2dd0d7b97cf..12d8d4f89a93 100644 --- a/default/i18n/en/cli.json +++ b/default/i18n/en/cli.json @@ -128,8 +128,6 @@ "dictation.superwhisperReady": "Superwhisper Dictation Ready", "dictation.voxtypeReady": "Voxtype Dictation Ready", "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 ba03dd15d2cb..8e103de35228 100644 --- a/default/i18n/en/menu.json +++ b/default/i18n/en/menu.json @@ -633,9 +633,6 @@ "setup.security.ssh-agent": { "label": "SSH Agent" }, - "setup.security.sudoless-docker": { - "label": "Sudoless Docker" - }, "setup.security.passwordless-sudo": { "label": "Passwordless Sudo" }, @@ -1011,9 +1008,6 @@ "remove.security.sshd": { "label": "SSHD" }, - "remove.security.sudoless-docker": { - "label": "Sudoless Docker" - }, "remove.ai.hermes": { "label": "Hermes Desktop" }, diff --git a/default/omarchy/omarchy-menu.jsonc b/default/omarchy/omarchy-menu.jsonc index d07f3b238b2e..a9508364cf4a 100644 --- a/default/omarchy/omarchy-menu.jsonc +++ b/default/omarchy/omarchy-menu.jsonc @@ -225,7 +225,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.ssh-agent": {"icon":"󰣀","label":"SSH Agent","when":"! systemctl --user -q is-enabled gcr-ssh-agent.socket","action":"omarchy-launch-floating-terminal-with-presentation omarchy-setup-security-ssh-agent"}, - "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.security.passwordless-sudo": {"icon":"󰟵","label":"Passwordless Sudo","action":"omarchy-launch-floating-terminal-with-presentation omarchy-sudo-passwordless"}, "setup.config.hyprland": {"icon":"","label":"Hyprland","action":"omarchy-launch-editor \"$HOME/.config/hypr/hyprland.lua\""}, "setup.config.hyprsunset": {"icon":"","label":"Hyprsunset","action":"omarchy-launch-editor ~/.config/hypr/hyprsunset.conf && omarchy-restart-hyprsunset"}, @@ -288,7 +287,7 @@ "install.service.microsoft": {"icon":"󰍲","label":"Microsoft","when":"omarchy-region-global","disabled":"[[ -f \"$HOME/.local/share/applications/Microsoft Outlook.desktop\" && -f \"$HOME/.local/share/applications/Microsoft Word.desktop\" && -f \"$HOME/.local/share/applications/Microsoft Excel.desktop\" && -f \"$HOME/.local/share/applications/Microsoft PowerPoint.desktop\" && -f \"$HOME/.local/share/applications/Microsoft Teams.desktop\" && -f \"$HOME/.local/share/applications/Microsoft OneDrive.desktop\" ]]","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-service-microsoft"}, "install.service.nordvpn": {"icon":"󱇱","label":"NordVPN","when":"omarchy-region-global","disabled":"omarchy-pkg-present nordvpn-bin","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-service-nordvpn"}, "install.service.notion": {"icon":"","label":"Notion","disabled":"omarchy-pkg-present notion-desktop","action":"omarchy-install-and-launch Notion notion-desktop com.notion.app.desktop.notion"}, - "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.signal": {"icon":"󰭹","label":"Signal","when":"omarchy-region-global","disabled":"omarchy-pkg-present signal-desktop","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-service-signal"}, "install.service.slack": {"icon":"󰒱","label":"Slack","when":"omarchy-region-global","disabled":"omarchy-pkg-present slack-desktop","action":"omarchy-install-and-launch Slack slack-desktop slack"}, "install.service.tailscale": {"icon":"","iconFont":"omarchy","label":"Tailscale","disabled":"omarchy-pkg-present tailscale","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-service-tailscale"}, @@ -370,7 +369,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.chromium": {"icon":"","label":"Chromium","when":"omarchy-pkg-present chromium","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-browser chromium'"}, "remove.browser.chrome": {"icon":"","label":"Chrome","when":"omarchy-pkg-present google-chrome","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-browser chrome'"}, diff --git a/default/once/launch.py b/default/once/launch.py new file mode 100644 index 000000000000..d1929da3990d --- /dev/null +++ b/default/once/launch.py @@ -0,0 +1,75 @@ +"""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.") + 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() + 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/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..b854d5fb7e48 --- /dev/null +++ b/default/systemd/user-environment-generators/60-omarchy-rootless-docker @@ -0,0 +1,6 @@ +#!/bin/bash + +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/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/file-layout.md b/docs/file-layout.md index 562ffe57e3ff..b9cf11712632 100644 --- a/docs/file-layout.md +++ b/docs/file-layout.md @@ -135,6 +135,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/user/wireplumber.service.d/10-omarchy-camera-access.conf /usr/lib/systemd/user/wireplumber.service.d/ ├─ systemd/system-sleep/unmount-fuse /usr/lib/systemd/system-sleep/ diff --git a/docs/once.md b/docs/once.md new file mode 100644 index 000000000000..a718b97bc860 --- /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. 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. + +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. 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/docs/rootless-docker.md b/docs/rootless-docker.md new file mode 100644 index 000000000000..1d3298ec63ee --- /dev/null +++ b/docs/rootless-docker.md @@ -0,0 +1,27 @@ +# 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 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`. 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, 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 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. + +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/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 f37dd4c8fa2c..6a6e6b1ef75c 100644 --- a/install/config/enable-services.sh +++ b/install/config/enable-services.sh @@ -4,6 +4,8 @@ # thrashing take the whole session down; [Install] pulls in systemd-oomd.socket # via Also=. omarchy-shutdown-ramfs.timer builds /run/initramfs in the # background after boot so shutdown skips mkinitcpio. +# The root-owned Docker socket is reserved for authenticated Windows VM +# operations. Development Docker is initialized separately for each user. systemctl enable \ cups.service \ avahi-daemon.service \ diff --git a/install/helpers/rootless-docker.sh b/install/helpers/rootless-docker.sh new file mode 100644 index 000000000000..4b608f5d4dbb --- /dev/null +++ b/install/helpers/rootless-docker.sh @@ -0,0 +1,152 @@ +rootless_docker_ensure_subids() { + local account="$1" + + /usr/bin/python3 - "$account" <<'PY' +import fcntl +import grp +import os +import pwd +import stat +import subprocess +import sys + + +MAX_ID = 4294967295 +MIN_RANGE = 65536 + + +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: + 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 + + +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") + )) + + +main() +PY +} diff --git a/install/omarchy-base.packages b/install/omarchy-base.packages index d50d9e6abc2e..697c84ab958d 100644 --- a/install/omarchy-base.packages +++ b/install/omarchy-base.packages @@ -25,6 +25,7 @@ disktree-bin docker docker-buildx docker-compose +docker-rootless-extras dosfstools dotnet-runtime exfatprogs @@ -49,6 +50,7 @@ folio fontconfig foot fzf +fuse-overlayfs ghostscript git gliff @@ -137,10 +139,12 @@ qrencode qt6-imageformats quickshell ripgrep +rootlesskit rtkit ruby sddm signed +slirp4netns slurp socat starship diff --git a/install/user/all.sh b/install/user/all.sh index 3e164c703976..26076fcbf02e 100644 --- a/install/user/all.sh +++ b/install/user/all.sh @@ -4,6 +4,7 @@ run_logged "$OMARCHY_INSTALL/user/xcompose.sh" run_logged "$OMARCHY_INSTALL/user/language.sh" run_logged "$OMARCHY_INSTALL/user/region.sh" run_logged "$OMARCHY_INSTALL/user/input-method.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 3e5579caaafd..ec946be8b0c6 100755 --- a/install/user/first-run/enable-user-units.sh +++ b/install/user/first-run/enable-user-units.sh @@ -20,6 +20,7 @@ units=( owed.service omarchy-recover-internal-monitor.service omarchy-sleep-lock.service + docker.service omarchy-migrate-notify.service omarchy-fcitx5.service omarchy-crash-watch.service diff --git a/manual/18-development-tools.md b/manual/18-development-tools.md index 17a6250767bf..cec840a21366 100644 --- a/manual/18-development-tools.md +++ b/manual/18-development-tools.md @@ -51,9 +51,15 @@ _Remove > Preinstalls_ removes Omarchy's preinstalled web apps, TUIs and apps, a ## 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 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. + +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. You can setup the common databases for local development in Docker using _Install > Development > Docker DB_ in the Omarchy menu. diff --git a/manual/24-commercial-apps-services.md b/manual/24-commercial-apps-services.md index 2cc6697dafdf..c1287247bf55 100644 --- a/manual/24-commercial-apps-services.md +++ b/manual/24-commercial-apps-services.md @@ -40,7 +40,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 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 diff --git a/manual/28-windows-vm.md b/manual/28-windows-vm.md index 0f94600b5a63..a0d8d990e56b 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 on x86_64 machines. 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 b3a06504814d..0af407905543 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 (Arch Linux ARM's on ARM machines, plus Asahi ALARM on Apple Silicon) 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*: 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. Setup makes them the same. _Update > Password_ in the Omarchy menu changes both at once, so they stay the same: it asks for the current drive password, then the new one, changes the drive's and then sets your login password to match. Without drive encryption it changes just your login password. If a change is interrupted, run _Update > Password_ again: it asks for the password that unlocks the drive now, finishes the change, and sets your login password to it. To change the password of another encrypted drive, run `omarchy-drive-password` in a terminal. diff --git a/migrations/1787580187.sh b/migrations/1787580187.sh index 1e2697f3d0fb..6957eea054fc 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/default/applications/Docker.desktop ]]; then cp "$OMARCHY_PATH/default/applications/Docker.desktop" "$dest" fi diff --git a/migrations/1789164756.sh b/migrations/1789164756.sh new file mode 100644 index 000000000000..de12766fae7c --- /dev/null +++ b/migrations/1789164756.sh @@ -0,0 +1,365 @@ +echo "Move development containers to rootless Docker" + +# 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 +fi + +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 + +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 + +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 +# 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" +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 and clear any early start-limit failure. Preserve an +# existing daemon and its workloads; only start a daemon that was inactive. +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 +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 + +# 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. +if (( machine_migration_complete == 1 )); then + remove_legacy_docker_group + 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 + +# 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 docker.service +listener_verifier=/usr/share/omarchy/default/docker/rootless/rootful-listeners.py + +restrict_rootful_socket() { + 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' "$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 + fi +} + +verify_rootful_listeners() { + 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 + 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) + 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() { + 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 +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. +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 +# 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) +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 + exit 1 + 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_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: + 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) + 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 + windows_arg=$windows_id +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 +# 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 +verify_rootful_socket_unit +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 + 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[@]}" + quiesced_recovery_pending=0 + /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 + +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" + +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 5fce3ec97204..100a3a35ca14 100644 --- a/test/acceptance.d/system-test.sh +++ b/test/acceptance.d/system-test.sh @@ -81,23 +81,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 83397007bf5a..71e119185940 100755 --- a/test/shell.d/config-test.sh +++ b/test/shell.d/config-test.sh @@ -98,6 +98,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"), @@ -113,6 +114,7 @@ package_defaults = [ ("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/timesyncd.conf.d/10-omarchy.conf", "/usr/lib/systemd/timesyncd.conf.d/10-omarchy.conf", "systemd/timesyncd.conf.d/10-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/once-rootless-test.sh b/test/shell.d/once-rootless-test.sh new file mode 100644 index 000000000000..fac7288dc9f9 --- /dev/null +++ b/test/shell.d/once-rootless-test.sh @@ -0,0 +1,154 @@ +#!/bin/bash + +set -euo pipefail +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 +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, engine_ready=True): + 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.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, \ + 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 +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', 'pacman', 'omarchy-pkg-add', 'omarchy-launch-once'): + script = directory / name + script.write_text('''#!/bin/bash +echo "${0##*/}|$*" >> "$TEST_LOG" +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) + 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', 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 + 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 + 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 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..acf147f3ee29 --- /dev/null +++ b/test/shell.d/rootless-docker-failure-recovery-test.sh @@ -0,0 +1,75 @@ +#!/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 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') +PY 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..8330c9e12cd6 --- /dev/null +++ b/test/shell.d/rootless-docker-migration-test.sh @@ -0,0 +1,2080 @@ +#!/bin/bash + +set -euo pipefail +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 + + +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) +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) +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" + with open(os.path.join(volume, "durable"), "w") as output: + output.write("new") + manifest.sync_filesystem(volume) + 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" + 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"] +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"], + ["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"], + ["name=rootless", "name=cgroupns"], + ["name=rootless", "name=seccomp,profile=builtin"]): + try: + migration.validate_target_daemon(options) + except ValueError: + pass + else: + raise AssertionError(f"destination was not proven rootless: {options}") +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.target_user_maps = lambda: ([range(65537)], [range(65537)]) +migration.source_default_nofile = lambda: source_nofile +migration.validate_target_nofile = lambda limits: None + +container = { + "Name": "/project-worker", + "Id": "a" * 64, + "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"}, + "Tty": False, "OpenStdin": False, "StopTimeout": 300, + }, + "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], + "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"}}, + }, + "NetworkSettings": {"Networks": {"bridge": {}}}, + "Mounts": [{"Type": "volume", "Driver": "local", "Name": "project-data", + "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 +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")): + if value is None: + assert flag in arguments + 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, source_nofile)) +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") + +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 + 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") + +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") +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" +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): + 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) + 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"]["Env"] = ["VERSION=11", "PROTECT=Y"] +windows["Config"]["Labels"] = { + "com.docker.compose.project": "windows", + "com.docker.compose.service": "windows", +} +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"}, +] +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"}], +} +uid = os.getuid() +windows["Mounts"] = [ + {"Type": "bind", "Source": f"/var/lib/omarchy/windows/mounts/users/{uid}/storage", + "Destination": "/storage", "RW": True}, + {"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" +legacy_windows = copy.deepcopy(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", + "missing-protect", "duplicate-protect"): + 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 == "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"] = "/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"] = {} + elif mutation == "missing-protect": + changed["Config"]["Env"] = ["VERSION=11"] + elif mutation == "duplicate-protect": + changed["Config"]["Env"] += ["PROTECT=N"] + else: + changed["HostConfig"]["AutoRemove"] = True + try: + migration.validate_windows_exception(changed) + except ValueError: + 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, + "Labels": {"project": "fixture"}, "Mountpoint": "/source-volume"} +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, 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 + 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) +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) +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") +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"}}}), + 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, + "volume_event": {"name": "marker", "since": "time"}}, + {"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, + "volume_event": {"name": "marker", "since": "time"}}, + {"name": "marker", "since": "time"}, {"project-data"}, "f" * 64, +) +migration.run = real_run +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: + 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 unpredictable ownership and no attachments before cleanup") + +blocked = ( + ("Privileged", True), ("CapAdd", ["SYS_ADMIN"]), + ("Devices", [{"PathOnHost": "/dev/kvm"}]), + ("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"}]), + ("MemorySwappiness", 0), + ("FutureNumericOption", 0), + ("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, logging, custom-network and unknown settings fail closed") + +records = {} +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] = 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] +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") + +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} +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) + migration.record_completion(stopped, stopped["State"], False, target) + assert migration.validate(stopped) == "project-worker" + 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") + +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) + 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, source_nofile=source_nofile) + 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, overlap_target) + migration.exists = lambda kind, name: kind == "container" and name == "project-worker" + migration.migrate(overlap_source, source_nofile) + 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() + 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 +migration.inspect = lambda engine, kind, name: copy.deepcopy(restarted if engine == migration.SOURCE else target) +try: + migration.record_completion(stopped, stopped["State"], False, target) +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") + +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, source_nofile=source_nofile) + 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") + +quiesce_source = copy.deepcopy(intent_source) +quiesce_calls = [] +restore_markers = [] + +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] + if value != "no": + restore_markers.append(migration.migration_intent(quiesce_source)["restore_started"]) + 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, source_nofile) + 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 + 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 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") + +with tempfile.TemporaryDirectory() as directory: + os.environ["XDG_STATE_HOME"] = directory + 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 + 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") + +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, source_nofile=source_nofile) + 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: + os.environ["XDG_STATE_HOME"] = directory + 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}', + } + 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") + +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 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: + raise migration.subprocess.CalledProcessError(1, ["docker", "inspect"]) + return copy.deepcopy(current_target) + + def fake_run(*args, **kwargs): + nonlocal current_target, source_image, target_image, transfer_tag + calls.append(args) + if args[:2] == (migration.SOURCE, "stop"): + 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"): + 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"): + 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, "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, + "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"): + 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 + 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 + (kind == "image" and target_image is not None and + name in (target_image["Id"], *(target_image.get("RepoTags") or []))) + ) + 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, 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 + 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, source_nofile) + except (RuntimeError, KeyboardInterrupt): + pass + 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 + + +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 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"] +assert not intent_retained +print("ok - verification failure before first start removes the destination and restores the source") + +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, 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 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) +assert not any(call[:3] == (migration.TARGET, "rm", "--force") for call in calls) +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" +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_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, 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"): + 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, "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: ( + 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 + 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, 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"] + 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, 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: + migration.verify_resumable_migration(resume_source, unexpected_running, resume_intent) + except ValueError: + 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: + 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, source_nofile) + 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() +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 +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, source_nofile=source_nofile) + 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)) + ) + migration.remove_volume_event_marker = lambda source, intent: receipt_events.append("marker-removed") + + def interrupt_receipt(source, state, running, verified): + 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"] + 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 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 +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) + 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, source_nofile=source_nofile) + 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, source_nofile) + 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 +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 +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": + 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) + 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, 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} + 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"): + 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): + 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 + created_name = args[args.index("--name") + 1] + created = { + "Id": ("8" if created_name.startswith("omarchy-volume-guard-") else "6") * 64, + "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"}, + } + if created_name.startswith("omarchy-volume-guard-"): + pinned_guard = created + else: + pinned_target = created + elif args[:3] == (migration.TARGET, "container", "ls"): + 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 + 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 + 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) + 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.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")] +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")) +event_begin_index = pin_events.index(("event-window-begin",)) +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 +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[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")) +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 +print("ok - an inert random guard pins and durably verifies volumes before application start") + +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.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: + 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 new file mode 100755 index 000000000000..f5eba84c5498 --- /dev/null +++ b/test/shell.d/rootless-docker-posture-test.sh @@ -0,0 +1,317 @@ +#!/bin/bash + +set -euo pipefail +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +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" +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" + +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) +spec.loader.exec_module(listeners) + +with tempfile.TemporaryDirectory() as directory: + proc = Path(directory) + descriptors = proc / "4242/fd" + descriptors.mkdir(parents=True) + (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 / "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 / "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 / "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, 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" 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 0564c59f8715..000000000000 --- a/test/shell.d/sudoless-docker-toggle-test.sh +++ /dev/null @@ -1,94 +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" <<'STUB' -#!/bin/bash -[[ $1 == "reboot" ]] || exit 2 -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-compose-test.sh b/test/shell.d/windows-vm-compose-test.sh index a231dfdf0a99..66d58fcddbd1 100644 --- a/test/shell.d/windows-vm-compose-test.sh +++ b/test/shell.d/windows-vm-compose-test.sh @@ -4,9 +4,267 @@ 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 + # 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" @@ -20,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 @@ -44,7 +294,7 @@ unmount_all() { cleanup() { set +e unmount_all - rm -rf "$TMPDIR" + rm -rf "$TMPDIR" "$OMARCHY_WINDOWS_TEST_BIN" } trap cleanup EXIT @@ -67,6 +317,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 @@ -100,7 +376,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 @@ -124,6 +400,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" @@ -147,6 +490,16 @@ services: - /./:/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 @@ -160,8 +513,99 @@ grep -q 'USERNAME: "legacyuser"' "$COMPOSE" || fail "migration lost settings" 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" + +# 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" +: >"$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 || 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" +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 "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 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, +# 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" @@ -181,6 +625,52 @@ 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" ]] || fail "running VM was not reconciled running" +windows_status=exited +__priv_secure +[[ $(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 reconciles hardened Windows while durably preserving its lifecycle" + # Both sources are pinned before a bind; bad symlinks stay untouched. reset_case mkdir -p "$HOME/.windows" @@ -496,6 +986,16 @@ 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" +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" +pass "credentials support a linked user configuration directory" + + # Free-space accounting follows the real storage target. reset_case mkdir -p "$external_storage" "$HOME/Windows" diff --git a/test/shell.d/windows-vm-mount-boundary-test.sh b/test/shell.d/windows-vm-mount-boundary-test.sh index 6e2a70ccea21..3d986cf61f38 100644 --- a/test/shell.d/windows-vm-mount-boundary-test.sh +++ b/test/shell.d/windows-vm-mount-boundary-test.sh @@ -186,8 +186,8 @@ 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" -with_vm_lock assert_mounts_safe || fail "final root mount/compose assertion rejected the verified pair" +[[ $(command stat -Lc '%u:%g:%a' "$COMPOSE_FILE") == 0:0:600 ]] || fail "root compose ownership/mode is wrong" +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 @@ -196,7 +196,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" @@ -207,7 +207,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"