Initialize system experimental implementation and documentation

This commit is contained in:
Pavel Isaev 2026-11-05 21:27:25 +03:00
commit b2e77f6c56
18 changed files with 1293 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target/

105
Cargo.lock generated Normal file
View file

@ -0,0 +1,105 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "archipelago-system"
version = "0.0.0"
dependencies = [
"serde_json",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "3.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"

9
Cargo.toml Normal file
View file

@ -0,0 +1,9 @@
[package]
name = "archipelago-system"
version = "0.0.0"
edition = "2024"
rust-version = "1.90"
publish = false
[dependencies]
serde_json = "1.0"

76
EXTENSIONS.md Normal file
View file

@ -0,0 +1,76 @@
# Repository-backed Host Extensions (experimental implementation)
The CLI accepts `extension add NAME...`. This implements the D-037 requested-set
model: resolve against the base image's retained sync databases; download exact
packages; compose the entire explicit set against the immutable base and its ALPM
database. Dependencies remain resolved state, not explicit user requests.
Selection starts with the staged deployment when present, otherwise the booted
deployment. Extension metadata identifies the original managed base (including
Managed Overlays), rather than treating the preceding extension image as the base.
Repeated requests are idempotent. Successful additions replace the staged candidate
only after composition and checks succeed. OSTree retains booted/rollback deployments;
each generation has independent refs for its base and result. There is no automatic
reboot, removal of old generation inputs, or package/database refresh (`-Sy/-Syu`).
Prototype storage (not a stable schema):
```
/var/lib/archipelago/host-extensions/generations/<id>/
base, requested, snapshot, base-packages, resolved, plan, inputs/, logs/
package-db/, result, failure
/usr/lib/archipelago/extensions.json # per-image base + explicit requests
```
The base's retained repository databases pin available versions/checksums. The
mirror is only transport: if an exact archive disappears, installation fails; a
rolling sync must not repair it. Monthly snapshot publication remains separate.
An optional `/etc/archipelago/extensions-mirrorlist` changes download transport
without changing the selected database or relaxing signatures/checksums.
Dependencies, signatures and transaction ordering are handled by pacman. Downloads
run in a staging container; the actual `pacman -S` transaction and finalization run
without network, with retained inputs. Base package replacement is rejected.
Package hooks/scriptlets need snapshot-specific classification (RFC-0005). Known
base hooks are captured by checksum when building Core; new unclassified actions
require an adapter before deployment. `/opt` and persistent-file payload adapters
and alternate kernel profiles remain open contracts; these cases must fail
explicitly rather than discard payload or mutate the live system. This is general
name/dependency resolution, not a claim that every Arch package is already adapted.
Acceptance includes multiple additions before reboot, further additions after
activation, duplicate requests, dependencies, failure with an existing pending
deployment, retained inputs/history, and preservation of the managed overlay.
## Experimental DKMS adapter
`extension add v4l2loopback-dkms` uses the same cumulative request path. The adapter
recognizes reviewed exact package archives in `adapters/dkms-policy.tsv`; source
or framework drift requires review, not a wildcard exemption. Initial scope is the
x86_64 Core `linux` profile without Secure Boot; this is not universal DKMS support.
- Resolve `<pkgbase>-headers=<installed kernel package version>` against retained
sync DBs. Generated transaction targets stay separate from explicit requests.
- Review DKMS 3.4.4's package scriptlet (historical informational upgrade message)
and three ALPM hooks. Replace those exact framework hooks with the offline
finalizer: native helper can skip a failed build and still return zero.
- Only reviewed source archives may contribute `/usr/src`; header packages may
contribute kernel build trees and vDSO objects; `linux-headers` may supply its
`/usr/src/linux` link. Unclassified package actions still fail.
- Offline staging explicitly adds/builds/installs each source for each image kernel,
with bounded commands. Validate matching headers, installed status, nonempty
module outputs and vermagic; preserve preexisting modules. Then run depmod and
regenerate initramfs before committing/staging.
- Preserve kernel input hashes, per-module hashes/vermagic and DKMS status/logs/state
under generation `logs/dkms`; publish module provenance at
`/usr/lib/archipelago/dkms-modules.tsv`. Disposable `/var/lib/dkms` and generated
signing keys are not shipped into the deployment or shared with the running host.
- Every recomposition builds from the managed base plus the full requested set.
A required failure prevents staging and retains previous pending/booted state.
Activation and module loading occur only in the target lifecycle after explicit
reboot. Live module loading/building is not part of `extension add`.
VM acceptance (`core_iso_acceptance.py --dkms`) checks build/staging, duplicate and
failed-request preservation, post-reboot modprobe and `/dev/video0`, then another
cumulative addition and reboot. Hardware-driver coverage, module signing for Secure
Boot, updates to another kernel and the stable shared action engine need further work.

16
README.md Normal file
View file

@ -0,0 +1,16 @@
# Archipelago system
Экспериментальная чистая модель первого запуска по D-036/D-064.
Дизайн: `../installer/CONTROL-LAYER.md`.
`onboarding::assess` выбирает следующий шаг по наблюдениям адаптера. Он различает
live/installed контексты, незавершённый аккаунт, завершение frontend и согласованность
аккаунта текущего deployment. Только `Ready` допускает подготовку следующих normal
deployments. Никаких аккаунтов, units или deployment функция сама не изменяет.
Это прототип внутренней политики, не проверка фактической системы и не стабильная
схема. Наблюдение PAM/account/home, disk executor, CLI мастер, блокировки и desktop
адаптеры ещё не реализованы. Frontend выбирается явным профилем, не по наличию бинарника.
Тесты и компиляции — только на superserv1 в `/hdd/archipelago`:
`cargo test --offline --locked`.

54
adapters/dkms-finalize.sh Normal file
View file

@ -0,0 +1,54 @@
# Runs only inside offline extension staging, with generation evidence at /evidence.
set -euo pipefail
shopt -s nullglob
configs=(/usr/src/*/dkms.conf)
((${#configs[@]})) || exit 0
mkdir -p /evidence/dkms
trap 'result=$?; cp -a /var/lib/dkms /evidence/dkms/state 2>/dev/null || true; printf "%s\n" "$result" > /evidence/dkms/exit-status' EXIT
# No live DKMS state or host kernel selection is used. Signing keys are disposable
# staging inputs in this non-Secure-Boot experimental profile.
mkdir -p /var/lib/dkms
printf 'module\tversion\tkernel\tpath\tsha256\tvermagic\n' > /evidence/dkms/modules.tsv
for config in "${configs[@]}"; do
source_dir=${config%/dkms.conf}
# Native DKMS registers the source and evaluates its reviewed configuration.
timeout 120 dkms add "$source_dir"
done
for modules in /usr/lib/modules/*; do
[[ -f $modules/vmlinuz ]] || continue
kernel=${modules##*/}
[[ -f $modules/build/include/config/kernel.release ]] || { echo "Missing headers for $kernel" >&2; exit 1; }
[[ $(cat "$modules/build/include/config/kernel.release") == "$kernel" ]] || { echo "Wrong headers for $kernel" >&2; exit 1; }
sha256sum "$modules/vmlinuz" "$modules/build/Module.symvers" > "/evidence/dkms/kernel-$kernel.sha256"
# Preserve every existing module: package add is not a kernel-module override.
find "$modules" -type f -name '*.ko*' -print0 | sort -z | xargs -0 -r sha256sum > /evidence/dkms/base-modules.sha256
for config in "${configs[@]}"; do
source_dir=${config%/dkms.conf}
# Derive the registered identity, not by sourcing package shell on the host.
identity=''
for link in /var/lib/dkms/*/*/source; do
[[ $(readlink -f "$link") == "$source_dir" ]] || continue
identity=${link#/var/lib/dkms/}; identity=${identity%/source}
done
[[ $identity == */* ]] || { echo "DKMS did not register $source_dir" >&2; exit 1; }
name=${identity%/*}; version=${identity#*/}
timeout 1800 dkms build -m "$name" -v "$version" -k "$kernel" --kernelsourcedir "$modules/build"
timeout 300 dkms install --no-depmod -m "$name" -v "$version" -k "$kernel"
dkms status -m "$name" -v "$version" -k "$kernel" | tee -a /evidence/dkms/status
dkms status -m "$name" -v "$version" -k "$kernel" | grep -Fqx "$name/$version, $kernel, x86_64: installed"
built=(/var/lib/dkms/"$name"/"$version"/"$kernel"/x86_64/module/*.ko*)
((${#built[@]})) || { echo "No DKMS output for $identity/$kernel" >&2; exit 1; }
for module in "${built[@]}"; do
module_name=$(modinfo -F name "$module")
vermagic=$(modinfo -F vermagic "$module")
[[ ${vermagic%% *} == "$kernel" ]] || { echo "Wrong module vermagic: $module" >&2; exit 1; }
# depmod follows all builds; resolve installed files directly here.
installed=$(find "$modules/updates/dkms" -type f -name "${module_name//_/-}.ko*" -o -type f -name "$module_name.ko*" 2>/dev/null)
[[ -n $installed && $installed != *$'\n'* ]] || { echo "Missing/ambiguous installed module: $module_name" >&2; exit 1; }
[[ $(modinfo -F vermagic "$installed") == "$vermagic" ]]
printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$name" "$version" "$kernel" "$installed" "$(sha256sum "$installed" | cut -d' ' -f1)" "$vermagic" >> /evidence/dkms/modules.tsv
done
done
sha256sum --quiet -c /evidence/dkms/base-modules.sha256
done
cp /evidence/dkms/modules.tsv /usr/lib/archipelago/dkms-modules.tsv

4
adapters/dkms-policy.tsv Normal file
View file

@ -0,0 +1,4 @@
# Experimental reviewed package archives; source changes require another review.
# role sha256 package
framework 5881381014e27c1082aa02ebbb66fbc6deae894f7b11016963313f341279075d dkms
source 5e6867f8e6e096afc75c34104d5b66f29e563ad19fafbf177f5f349399aff8a1 v4l2loopback-dkms
1 # Experimental reviewed package archives; source changes require another review.
2 # role sha256 package
3 framework 5881381014e27c1082aa02ebbb66fbc6deae894f7b11016963313f341279075d dkms
4 source 5e6867f8e6e096afc75c34104d5b66f29e563ad19fafbf177f5f349399aff8a1 v4l2loopback-dkms

185
adapters/extensions.sh Normal file
View file

@ -0,0 +1,185 @@
generation=$1
root="$generation/root"
mkdir -p "$generation/inputs" "$generation/logs"
exec > >(tee "$generation/logs/compose.log") 2>&1
export LC_ALL=C
policy="$root/usr/lib/archipelago/hook-policy"
[[ -f $policy/hooks.sha256 && -f $policy/scriptlets.sha256 ]] || {
echo 'Base image lacks the reviewed hook inventory; rebuild the base with repository-backed extension support' >&2
exit 1
}
mv "$root/usr/etc" "$root/etc"
cp -a "$root/etc/resolv.conf" "$generation/resolv.conf"
mkdir -p "$root/var/lib" "$root/run"
if [[ -f /etc/archipelago/extensions-mirrorlist ]]; then
cp /etc/archipelago/extensions-mirrorlist "$root/etc/pacman.d/mirrorlist"
fi
cp "$root/usr/lib/archipelago/packages.txt" "$generation/base-packages"
cp "$generation/requested" "$generation/transaction-targets"
(cd "$root/usr/lib/archipelago/package-db/sync"; sha256sum *.db) > "$generation/sync.sha256"
# The immutable base supplies sync DBs, repository order and transport URLs. No -y.
systemd-nspawn --settings=no --register=no --resolv-conf=replace-host \
-D "$root" --bind="$generation/inputs:/inputs" --bind="$generation/transaction-targets:/requested" \
/bin/bash -euo pipefail -c '
export LC_ALL=C
systemd-sysusers
pacman-key --init
pacman-key --populate archlinux archipelago
mapfile -t requested < /requested
for name in "${requested[@]}"; do pacman -Si -- "$name" >/dev/null; done
pacman -Sp --needed --print-format "%n %v %r %l" -- "${requested[@]}" > /inputs/plan
if grep -q "^dkms " /inputs/plan || pacman -Qq dkms >/dev/null 2>&1; then
count=0
for modules in /usr/lib/modules/*; do
[[ -f $modules/vmlinuz ]] || continue
kernel=${modules##*/}
pkgbase=$(cat "$modules/pkgbase")
[[ $pkgbase =~ ^[a-zA-Z0-9_+-]+$ ]] || exit 1
version=$(pacman -Q "$pkgbase" | cut -d" " -f2)
# Resolve exact headers from the retained sync DB; never refresh.
pacman -Sp --print-format "%n %v %l" "$pkgbase-headers=$version" >> /inputs/headers-plan
printf "%s\n" "$pkgbase-headers=$version" >> /requested
count=$((count + 1))
done
(( count > 0 )) || { echo "No target kernel for DKMS" >&2; exit 1; }
mapfile -t requested < /requested
pacman -Sp --needed --print-format "%n %v %r %l" -- "${requested[@]}" > /inputs/plan
fi
pacman -Sw --needed --noconfirm --cachedir /inputs -- "${requested[@]}"
' 2>&1 | tee "$generation/logs/download.log"
cp "$generation/inputs/plan" "$generation/plan"
(cd "$root/usr/lib/archipelago/package-db/sync"; sha256sum -c "$generation/sync.sha256")
# Inspect exact signed/downloaded inputs before any install script can run.
# New actions and unsupported persistent/boot payloads need explicit adapters.
shopt -s nullglob
dkms_enabled=false
for archive in "$generation/inputs/"*.pkg.tar.*; do
[[ $archive != *.sig ]] || continue
listing="$generation/logs/$(basename "$archive").files"
bsdtar -tf "$archive" > "$listing"
archive_hash=$(sha256sum "$archive" | cut -d' ' -f1)
role=$(awk -v hash="$archive_hash" '$2 == hash {print $1}' "$generation/dkms-policy.tsv")
package=$(bsdtar -xOf "$archive" .PKGINFO | sed -n 's/^pkgname = //p')
if [[ $role == framework ]]; then dkms_enabled=true; fi
while IFS= read -r path; do
path=${path#./}
case "$path" in
.PKGINFO|.BUILDINFO|.MTREE|.INSTALL|''|*/) continue ;;
usr/src/linux)
[[ $package == linux-headers ]] || { echo "Unexpected kernel source link: $package" >&2; exit 1; } ;;
usr/src/*)
[[ $role == source ]] || { echo "Unreviewed DKMS source package: $package ($archive_hash)" >&2; exit 1; } ;;
usr/lib/modules/*/build/*|usr/lib/modules/*/vdso/*.so)
[[ $package == *-headers ]] || { echo "Unexpected kernel build payload: $package" >&2; exit 1; } ;;
usr/local/*|usr/lib/modules/*|boot/*|opt/*|var/*|home/*|root/*|srv/*|mnt/*|etc/pacman.d/hooks/*)
echo "Package needs a persistence/kernel adapter: $(basename "$archive"): $path" >&2; exit 1 ;;
usr/*|etc/*) ;;
*) echo "Unsupported package payload path: $path" >&2; exit 1 ;;
esac
done < "$listing"
if grep -qxE '(\./)?\.INSTALL' "$listing"; then
script=$(grep -xE '(\./)?\.INSTALL' "$listing")
hash=$(bsdtar -xOf "$archive" "$script" | sha256sum | cut -d' ' -f1)
[[ $role == framework ]] || grep -q "^$hash " "$policy/scriptlets.sha256" || {
echo "Unclassified .INSTALL in $(basename "$archive"); hash=$hash" >&2; exit 1;
}
fi
while IFS= read -r hook; do
hash=$(bsdtar -xOf "$archive" "$hook" | sha256sum | cut -d' ' -f1)
[[ $role == framework ]] || grep -Fxq "$hash ${hook#./}" "$policy/hooks.sha256" || {
echo "Unclassified hook in $(basename "$archive"): $hook; hash=$hash" >&2; exit 1;
}
done < <(grep -E '^(\./)?usr/share/libalpm/hooks/[^/]+\.hook$' "$listing" || true)
done
if $dkms_enabled; then
# Exact reviewed framework hooks are replaced by the checked offline finalizer.
# Keep overrides for future staging; no live transaction is allowed on this OS.
mkdir -p "$root/etc/pacman.d/hooks"
for hook in 70-dkms-install.hook 70-dkms-upgrade.hook 71-dkms-remove.hook; do
[[ ! -e $root/etc/pacman.d/hooks/$hook && ! -L $root/etc/pacman.d/hooks/$hook ]] || {
echo "Unexpected DKMS hook override: $hook" >&2; exit 1;
}
ln -s /dev/null "$root/etc/pacman.d/hooks/$hook"
done
fi
(cd "$generation/inputs"; find . -maxdepth 1 -type f ! -name SHA256SUMS -print0 | sort -z | xargs -0 sha256sum) > "$generation/inputs/SHA256SUMS"
systemd-nspawn --settings=no --register=no --private-network --resolv-conf=off \
-D "$root" --bind-ro="$generation/inputs:/inputs" \
--bind-ro="$generation/transaction-targets:/requested" --bind-ro="$generation/base-packages:/base-packages" \
--bind-ro="$generation/requested:/explicit-requested" \
--bind="$generation/logs:/evidence" --bind-ro="$generation/dkms-finalize.sh:/dkms-finalize.sh" \
/bin/bash -euo pipefail -c '
export LC_ALL=C
cd /inputs; sha256sum -c SHA256SUMS; cd /
mapfile -t requested < /requested
pacman -S --needed --noconfirm --cachedir /inputs -- "${requested[@]}"
for target in "${requested[@]}"; do
name=${target%%=*}
if ! grep -Fxq "$name" /explicit-requested; then
pacman -D --asdeps -- "$name"
fi
done
# Add is not an override or base upgrade. Reject any removed/replaced base package.
while read -r name version; do
[[ $(pacman -Q -- "$name") == "$name $version" ]] || {
echo "Base package replacement requires a separate override: $name" >&2; exit 1;
}
done < /base-packages
pacman -Dk
if command -v dkms >/dev/null; then
/bin/bash /dkms-finalize.sh
fi
pacman -Q > /usr/lib/archipelago/packages.txt
ldconfig
systemd-hwdb update --usr
if command -v glib-compile-schemas >/dev/null; then glib-compile-schemas /usr/share/glib-2.0/schemas; fi
if command -v gio-querymodules >/dev/null; then gio-querymodules /usr/lib/gio/modules; fi
if command -v update-desktop-database >/dev/null; then update-desktop-database /usr/share/applications; fi
if command -v update-mime-database >/dev/null; then update-mime-database /usr/share/mime; fi
if command -v gtk-update-icon-cache >/dev/null; then
for theme in /usr/share/icons/*; do
[[ ! -f $theme/index.theme ]] || gtk-update-icon-cache -q -t -f "$theme"
done
fi
update-ca-trust
for modules in /usr/lib/modules/*; do
[[ -f $modules/vmlinuz ]] || continue
kernel=${modules##*/}
depmod "$kernel"
mkinitcpio --nocolor -c /usr/lib/archipelago/mkinitcpio-core.conf -k "$kernel" -g "$modules/initramfs.img"
done
' 2>&1 | tee "$generation/logs/transaction.log"
if grep -Ei 'error:|warning:.*(failed|failure)' "$generation/logs/transaction.log"; then
echo 'Required package action/finalization failed; no deployment prepared' >&2; exit 1
fi
(cd "$root/usr/lib/archipelago/package-db/sync"; sha256sum -c "$generation/sync.sha256")
cp "$root/usr/lib/archipelago/packages.txt" "$generation/resolved"
cp -a "$root/usr/lib/archipelago/package-db" "$generation/package-db"
# Immutable non-root ownership must refer to the same identity on the target.
# New service-owned payloads need an explicit UID/GID adapter; do not guess IDs.
while IFS= read -r -d '' file; do
uid=$(stat -c %u "$file"); gid=$(stat -c %g "$file")
if [[ $uid != 0 ]]; then
target=$(getent passwd "$uid" | cut -d: -f1)
staged=$(awk -F: -v id="$uid" '$3 == id { print $1 }' "$root/etc/passwd")
[[ -n $target && $target == "$staged" ]] || { echo "UID adapter required: $file ($uid)"; exit 1; }
fi
if [[ $gid != 0 ]]; then
target=$(getent group "$gid" | cut -d: -f1)
staged=$(awk -F: -v id="$gid" '$3 == id { print $1 }' "$root/etc/group")
[[ -n $target && $target == "$staged" ]] || { echo "GID adapter required: $file ($gid)"; exit 1; }
fi
done < <(find "$root/usr" \( ! -uid 0 -o ! -gid 0 \) -print0)
for database in passwd shadow group gshadow; do
cp -a "$root/usr/share/factory/etc/$database" "$root/etc/$database"
done
rm -rf "$root/etc/pacman.d/gnupg"
rm -f "$root/etc/resolv.conf" "$root/etc/ssh/ssh_host_"* "$root/etc/.pwd.lock"
cp -a "$generation/resolv.conf" "$root/etc/resolv.conf"
: > "$root/etc/machine-id"
mv "$root/etc" "$root/usr/etc"
rm -rf "$root/var" "$root/run" "$root/tmp"
mkdir -p "$root/var" "$root/run" "$root/tmp"
chmod 1777 "$root/tmp"

51
adapters/firstboot.sh Normal file
View file

@ -0,0 +1,51 @@
[[ $EUID == 0 ]] || { echo 'Run as root' >&2; exit 1; }
[[ -e /run/ostree-booted ]] || { echo 'Not an installed OSTree deployment' >&2; exit 1; }
[[ ! -e /usr/lib/archipelago/gnome-firstboot ]] || { echo 'This deployment uses GNOME Initial Setup through GDM' >&2; exit 1; }
exec 9>/run/archipelago-provision.lock
state=/etc/archipelago
mkdir -p "$state"
echo 'Archipelago Core — first setup'
echo 'Press Enter to begin Core setup on this console.'
# Both console listeners may wait here, but only the selected one mutates accounts.
# Timed reads let the other console yield to getty when setup completes elsewhere.
while [[ ! -f "$state/provisioned" ]]; do
if read -r -t 1; then break; else
result=$?
(( result > 128 )) || exit 1
fi
done
if ! flock -n 9; then
echo 'Setup is active on another console; waiting for it to finish.'
flock 9
fi
if [[ -f "$state/provisioned" ]]; then
user=$(cat "$state/provisioned")
id "$user"
echo 'ARCHIPELAGO_PROVISION_COMPLETE'
exit 0
fi
if [[ -f "$state/provision-user" ]]; then
user=$(cat "$state/provision-user")
echo "Resuming setup for $user"
else
read -r -p 'Username: ' user
[[ $user =~ ^[a-z][a-z0-9_-]{0,30}$ ]] || { echo 'Invalid username'; exit 1; }
! getent passwd "$user" >/dev/null || { echo 'Account already exists'; exit 1; }
[[ ! -e /var/home/$user ]] || { echo 'Home already exists'; exit 1; }
printf '%s\n' "$user" > "$state/provision-user.tmp"
mv "$state/provision-user.tmp" "$state/provision-user"
fi
if ! getent passwd "$user" >/dev/null; then
useradd -m -d "/home/$user" -G wheel -s /bin/bash "$user"
fi
[[ $(getent passwd "$user" | cut -d: -f6) == "/home/$user" ]]
[[ $(stat -c %u "/var/home/$user") == "$(id -u "$user")" ]]
passwd "$user"
install -d -m 0750 /etc/sudoers.d
printf '%%wheel ALL=(ALL:ALL) ALL\n' > /etc/sudoers.d/10-archipelago-wheel
chmod 0440 /etc/sudoers.d/10-archipelago-wheel
visudo -cf /etc/sudoers.d/10-archipelago-wheel
tty > "$state/provision-console"
printf '%s\n' "$user" > "$state/provisioned.tmp"
mv "$state/provisioned.tmp" "$state/provisioned"
echo 'ARCHIPELAGO_PROVISION_COMPLETE'

50
adapters/host.sh Normal file
View file

@ -0,0 +1,50 @@
[[ $EUID == 0 ]] || { echo 'Run as root' >&2; exit 1; }
if [[ $1 == boot-sync ]]; then
[[ ${SERVICE_RESULT:-success} == success ]] || { echo 'OSTree finalization failed; ESP unchanged' >&2; exit 1; }
[[ -e /run/ostree-booted ]]
mountpoint -q /efi
# Copy new artifacts before changing entry selection; retain old artifacts.
cp -a /sysroot/boot/ostree/. /efi/ostree/
mkdir -p /efi/loader/entries
cp -aL /sysroot/boot/loader/entries/. /efi/loader/entries/
sync -f /efi
exit 0
fi
[[ -e /run/ostree-booted ]] || { echo 'Not an installed OSTree deployment' >&2; exit 1; }
if [[ $1 == status ]]; then
ostree admin status
printf 'Experimental Core; public release gates not yet satisfied\n'
if [[ -f /usr/lib/archipelago/host-extensions ]]; then
printf 'Booted support status: unsupported\nHost Extensions: '
cat /usr/lib/archipelago/host-extensions
fi
if [[ -f /usr/lib/archipelago/overlays ]]; then cat /usr/lib/archipelago/overlays; fi
exit 0
fi
[[ -f /etc/archipelago/provisioned ]] || { echo 'Complete firstboot before preparing deployments' >&2; exit 1; }
id "$(cat /etc/archipelago/provisioned)" >/dev/null
exec 9>/run/archipelago-compose.lock
flock -n 9
repo=/sysroot/ostree/repo
[[ ! -e /run/ostree/staged-deployment ]] || { echo 'Activate the pending deployment first'; exit 1; }
booted=$(ostree admin status | sed -n 's/^\* *archipelago \([0-9a-f]*\)\..*/\1/p')
[[ $booted =~ ^[a-f0-9]{64}$ ]]
work=$(mktemp -d /var/tmp/archipelago-compose.XXXXXX)
trap 'rm -rf "$work"' EXIT
ostree --repo="$repo" checkout --force-copy "$booted" "$work/root"
if [[ $1 == overlay ]]; then
[[ ! -f /usr/lib/archipelago/host-extensions ]] || { echo 'Apply managed overlay before Host Extensions in this prototype'; exit 1; }
ostree --repo="$repo" checkout --force-copy test-marker "$work/layer"
cmp "$work/layer/metadata/snapshot" "$work/root/usr/lib/archipelago/snapshot"
target=usr/share/archipelago/test-marker
[[ ! -e $work/root/$target && ! -L $work/root/$target ]]
[[ ! -L $work/root/usr/share/archipelago ]]
install -m644 "$work/layer/payload/$target" "$work/root/$target"
printf 'test-marker\n' > "$work/root/usr/lib/archipelago/overlays"
fi
ref="local/$(date +%s)-$$"
commit=$(ostree --repo="$repo" commit -b "$ref" --tree="dir=$work/root" \
--add-metadata-string="archipelago.base=$booted" \
--add-metadata-string="archipelago.snapshot=$(cat "$work/root/usr/lib/archipelago/snapshot")")
ostree admin deploy --stage --retain --os=archipelago "$commit"
echo "Prepared $commit; activate with an explicit reboot. Current /usr unchanged."

10
hardware-test-ostree.asc Normal file
View file

@ -0,0 +1,10 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEauytARYJKwYBBAHaRw8BAQdAc3YVKsjv+ByFBm+suoudyk/FEI6Ku1ul9lC6
1GBRFca0REFyY2hpcGVsYWdvIEhhcmR3YXJlIFRlc3QgT1NUcmVlIDxoYXJkd2Fy
ZS10ZXN0QGFyY2hpcGVsYWdvLmludmFsaWQ+iJYEExYKAD4WIQTPD+16QS5XAQUn
zWi/ql6A7urMogUCauytAQIbAwUJAeEzgAULCQgHAgYVCgkICwIEFgIDAQIeAQIX
gAAKCRC/ql6A7urMonf+APwIV7Gt3Zib9XjDurkMgVGw9o3FnCdv/SoDNRRlWf2/
8QD7BabVBsHB/BXLogmcgIC/bLhh8dShiWEoE4D0UFZkUQU=
=V1XM
-----END PGP PUBLIC KEY BLOCK-----

3
rust-toolchain.toml Normal file
View file

@ -0,0 +1,3 @@
[toolchain]
channel = "1.90.0"
profile = "minimal"

188
src/desktop.rs Normal file
View file

@ -0,0 +1,188 @@
//! GNOME onboarding observation and first-install Flatpak defaults.
//! Upstream GNOME creates accounts; Flatpak owns application transactions.
use serde_json::Value;
use std::{collections::BTreeMap, fs::{self, File}, os::unix::fs::MetadataExt,
path::Path, process::Command};
type Result<T> = std::result::Result<T, String>;
fn output(program: &str, args: &[&str]) -> Result<String> {
let out = Command::new(program).args(args).env("LC_ALL", "C").output().map_err(|e| e.to_string())?;
if !out.status.success() { return Err(format!("{program} failed: {}", out.status)); }
String::from_utf8(out.stdout).map_err(|e| e.to_string())
}
fn call(program: &str, args: &[&str]) -> Result<()> {
let status = Command::new(program).args(args).status().map_err(|e| e.to_string())?;
if status.success() { Ok(()) } else { Err(format!("{program}: {status}")) }
}
fn target() -> Result<()> {
if output("/usr/bin/id", &["-u"])?.trim() != "0" { return Err("Run as root".into()); }
if !Path::new("/run/ostree-booted").exists() ||
fs::read_to_string("/usr/lib/archipelago/purpose").unwrap_or_default().trim() != "purpose/desktop/gnome" {
return Err("Requires an installed GNOME Purpose deployment".into());
}
Ok(())
}
fn lock(path: &str) -> Result<File> {
let file = File::options().create(true).truncate(false).write(true).open(path).map_err(|e| e.to_string())?;
file.try_lock().map_err(|e| format!("Another desktop operation is running: {e}"))?;
Ok(file)
}
fn atomic(path: &Path, bytes: &[u8]) -> Result<()> {
use std::io::Write;
let temporary = path.with_extension(format!("tmp-{}", std::process::id()));
let mut file = File::options().create_new(true).write(true).open(&temporary).map_err(|e| e.to_string())?;
let result = (|| {
file.write_all(bytes).and_then(|_| file.sync_all()).map_err(|e| e.to_string())?;
fs::rename(&temporary, path).map_err(|e| e.to_string())?;
File::open(path.parent().unwrap()).and_then(|f| f.sync_all()).map_err(|e| e.to_string())
})();
if temporary.exists() { let _ = fs::remove_file(temporary); }
result
}
fn username(name: &str) -> Result<()> {
if name.is_empty() || name.len() > 31 || !name.starts_with(|c: char| c.is_ascii_lowercase()) ||
!name.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"_-".contains(&c)) {
return Err("Unsupported primary username".into());
}
Ok(())
}
fn property(path: &str, key: &str) -> Result<Value> {
let text = output("/usr/bin/busctl", &["--system", "--json=short", "get-property",
"org.freedesktop.Accounts", path, "org.freedesktop.Accounts.User", key])?;
property_value(&text)
}
fn property_value(text: &str) -> Result<Value> {
let data: Value = serde_json::from_str(text).map_err(|e| e.to_string())?;
match (data["type"].as_str(), &data["data"]) {
(Some("b"), Value::Bool(_)) | (Some("s"), Value::String(_)) => Ok(data["data"].clone()),
(Some("t"), value) if value.as_u64().is_some() => Ok(value.clone()),
(Some("i"), value) if value.as_i64().is_some_and(|n| i32::try_from(n).is_ok()) => Ok(value.clone()),
_ => Err("Invalid D-Bus property result".into()),
}
}
pub fn reconcile() -> Result<()> {
target()?;
let _lock = lock("/run/archipelago-provision.lock")?;
if Path::new("/etc/archipelago/provisioned").exists() { return Ok(()); }
let sessions: Value = serde_json::from_str(&output("/usr/bin/loginctl", &["list-sessions", "--json=short"])?).map_err(|e| e.to_string())?;
for session in sessions.as_array().ok_or("Invalid session list")? {
let id = session["session"].as_str().ok_or("Missing session ID")?;
if id.is_empty() || !id.bytes().all(|c| c.is_ascii_alphanumeric()) { return Err("Invalid session ID".into()); }
let text = output("/usr/bin/loginctl", &["show-session", id, "-p", "Name", "-p", "User",
"-p", "Class", "-p", "Type", "-p", "Service", "-p", "Active", "-p", "Remote"])?;
let fields: BTreeMap<_, _> = text.lines().filter_map(|line| line.split_once('=')).collect();
if fields.get("Active") != Some(&"yes") || fields.get("Remote") != Some(&"no") ||
fields.get("Class") != Some(&"user") || fields.get("Service") != Some(&"gdm-password") ||
!matches!(fields.get("Type"), Some(&"wayland") | Some(&"x11")) { continue; }
let name = *fields.get("Name").ok_or("Missing user name")?;
username(name)?;
let uid: u32 = fields.get("User").ok_or("Missing session UID")?.parse().map_err(|_| "Invalid session UID")?;
if uid == 0 { continue; }
let text = output("/usr/bin/busctl", &["--system", "--json=short", "call", "org.freedesktop.Accounts",
"/org/freedesktop/Accounts", "org.freedesktop.Accounts", "FindUserByName", "s", name])?;
let data: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
let path = data["data"][0].as_str().ok_or("Missing AccountsService user")?;
if property(path, "SystemAccount")? != false || property(path, "Locked")? != false ||
property(path, "AccountType")? != 1 || property(path, "Uid")? != uid ||
property(path, "UserName")? != name { return Err("Primary account is not a matching unlocked human administrator".into()); }
let home = format!("/home/{name}");
if property(path, "HomeDirectory")? != home || fs::metadata(&home).map_err(|e| e.to_string())?.uid() != uid {
return Err("Primary home ownership mismatch".into());
}
if !output("/usr/bin/id", &["-nG", name])?.split_whitespace().any(|g| g == "wheel") {
return Err("Primary administrator is not in wheel".into());
}
call("/usr/bin/visudo", &["-c"])?;
fs::create_dir_all("/etc/archipelago").map_err(|e| e.to_string())?;
atomic(Path::new("/etc/archipelago/provisioned"), format!("{name}\n").as_bytes())?;
println!("GNOME onboarding observed after authenticated user login: {name}");
return Ok(());
}
// Pending is normal while GDM's native setup session is active.
Ok(())
}
fn app_ref(value: &str) -> bool {
let parts: Vec<_> = value.split('/').collect();
parts.len() == 4 && parts[0] == "app" && parts[2] == "x86_64" && parts[3] == "stable" &&
parts[1].starts_with("org.gnome.") && parts[1].bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
}
pub fn seed_flatpaks() -> Result<()> {
target()?;
if !Path::new("/etc/archipelago/provisioned").is_file() { return Err("Complete GNOME onboarding first".into()); }
let _lock = lock("/run/archipelago-flatpak-defaults.lock")?;
let state = Path::new("/var/lib/archipelago/flatpak-defaults-v1");
fs::create_dir_all(state.join("completed")).map_err(|e| e.to_string())?;
if state.join("done").is_file() { return Ok(()); }
let initial = state.join("initial-policy.json");
if !initial.exists() {
let override_path = Path::new("/etc/archipelago/flatpak-apps.json");
let bytes = fs::read(if override_path.exists() { override_path } else { Path::new("/usr/share/archipelago/desktop/flatpak-apps.json") }).map_err(|e| e.to_string())?;
atomic(&initial, &bytes)?;
}
let policy: Value = serde_json::from_slice(&fs::read(&initial).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
if policy["enabled"] == false { return Ok(()); }
if policy["version"] != 1 || policy["installation"] != "system" {
return Err("Unsupported Flatpak seed policy".into());
}
let remote = policy["remote"].as_str().filter(|s| !s.is_empty() && !s.starts_with('-') && s.bytes().all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c))).ok_or("invalid Flatpak remote name")?;
let url = policy["remote_url"].as_str().filter(|s| (s.starts_with("https://") || s.starts_with("http://") || s.starts_with("file:///")) && !s.chars().any(char::is_whitespace)).ok_or("invalid Flatpak URL")?;
let remote_file = policy["remote_file"].as_str().filter(|s| s.starts_with('/')).ok_or("absolute Flatpak remote file required")?;
let apps = policy["applications"].as_array().ok_or("Missing default application list")?;
for app in apps {
if !app.as_str().is_some_and(app_ref) { return Err("Invalid default Flatpak ref".into()); }
}
call("/usr/bin/flatpak", &["remote-add", "--system", "--if-not-exists", remote, remote_file])?;
for (key, expected) in [("url", url), ("gpg-verify", "true")] {
if output("/usr/bin/ostree", &["--repo=/var/lib/flatpak/repo", "config", "get", &format!("remote \"{remote}\".{key}")])?.trim() != expected {
return Err("Existing Flatpak remote differs from the configured policy; reconcile explicitly".into());
}
}
for app in apps {
let reference = app.as_str().unwrap();
let id = reference.split('/').nth(1).unwrap();
let record = state.join("completed").join(id);
if record.is_file() { continue; } // Includes apps subsequently removed by the user.
// Adopt an existing user/admin choice without upgrading it as a side effect.
if output("/usr/bin/flatpak", &["info", "--system", "--show-ref", reference]).is_err() {
call("/usr/bin/flatpak", &["install", "--system", "--noninteractive", "--assumeyes", remote, reference])?;
}
let commit = output("/usr/bin/flatpak", &["info", "--system", "--show-commit", reference])?;
atomic(&record, format!("{reference}\n{}\n", commit.trim()).as_bytes())?;
}
atomic(&state.join("done"), b"Initial application seeding complete; subsequent lifecycle belongs to Flatpak.\n")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn busctl_properties_use_typed_scalar_data() {
assert_eq!(property_value(r#"{"type":"t","data":1000}"#).unwrap(), 1000);
assert_eq!(property_value(r#"{"type":"b","data":false}"#).unwrap(), false);
assert_eq!(property_value(r#"{"type":"i","data":1}"#).unwrap(), 1);
assert_eq!(property_value(r#"{"type":"s","data":"coretest"}"#).unwrap(), "coretest");
for text in [r#"{"type":"t","data":[1000]}"#, r#"{"type":"b","data":0}"#,
r#"{"type":"t","data":-1}"#, r#"{"data":false}"#] {
assert!(property_value(text).is_err());
}
}
#[test]
fn workload_refs_cannot_change_scope_or_origin() {
assert!(app_ref("app/org.gnome.clocks/x86_64/stable"));
for value in ["--user", "app/org.gnome.TextEditor/x86_64/nightly", "app/../x86_64/stable",
"runtime/org.gnome.Platform/x86_64/stable", "app/org.gnome.Foo/../../etc/passwd"] {
assert!(!app_ref(value));
}
}
}

205
src/extensions.rs Normal file
View file

@ -0,0 +1,205 @@
//! Experimental requested-set lifecycle. pacman and OSTree remain the engines.
use serde_json::{Value, json};
use std::{collections::BTreeSet, fs::{self, File}, os::unix::fs::DirBuilderExt,
path::Path, process::Command, time::{SystemTime, UNIX_EPOCH}};
const REPO: &str = "--repo=/sysroot/ostree/repo";
const STATE: &str = "/var/lib/archipelago/host-extensions/generations";
const METADATA: &str = "/usr/lib/archipelago/extensions.json";
fn output(program: &str, args: &[&str]) -> Result<String, String> {
let out = Command::new(program).args(args).output().map_err(|e| e.to_string())?;
if !out.status.success() {
return Err(format!("{program}: {}", String::from_utf8_lossy(&out.stderr)));
}
String::from_utf8(out.stdout).map_err(|e| e.to_string())
}
fn run(program: &str, args: &[&str]) -> Result<(), String> {
let status = Command::new(program).args(args).status().map_err(|e| e.to_string())?;
if status.success() { Ok(()) } else { Err(format!("{program}: {status}")) }
}
fn checksum(value: &str) -> Result<String, String> {
if value.len() == 64 && value.bytes().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()) {
Ok(value.to_string())
} else { Err("invalid OSTree checksum".into()) }
}
fn names(values: &[String]) -> Result<BTreeSet<String>, String> {
if values.is_empty() { return Err("provide at least one package name".into()); }
values.iter().map(|name| {
if name.is_empty() || name.starts_with(['-', '.']) || !name.bytes().all(|c|
c.is_ascii_alphanumeric() || b"@._+-".contains(&c)) {
Err(format!("expected a package name, not an option, group or path: {name}"))
} else { Ok(name.clone()) }
}).collect()
}
pub(crate) fn status() -> Result<Value, String> {
serde_json::from_str(&output("ostree", &["admin", "status", "--json"])?).map_err(|e| e.to_string())
}
fn select(status: &Value) -> Result<(String, bool), String> {
let entries = status["deployments"].as_array().ok_or("missing deployments")?;
let own: Vec<_> = entries.iter().filter(|d| d["stateroot"] == "archipelago").collect();
if let Some(pending) = own.iter().find(|d| d["pending"] == true || d["staged"] == true) {
if pending["staged"] != true {
return Err("activate the non-staged pending deployment before modifying extensions".into());
}
return Ok((checksum(pending["checksum"].as_str().ok_or("missing pending checksum")?)?, true));
}
let booted = own.iter().find(|d| d["booted"] == true).ok_or("no booted Archipelago deployment")?;
Ok((checksum(booted["checksum"].as_str().ok_or("missing booted checksum")?)?, false))
}
fn cat(commit: &str, path: &str) -> Result<String, String> {
output("ostree", &[REPO, "cat", commit, path])
}
pub(crate) fn intent(commit: &str) -> Result<(String, BTreeSet<String>), String> {
// Listing first distinguishes an absent metadata file from malformed metadata.
let listing = output("ostree", &[REPO, "ls", commit, "/usr/lib/archipelago"])?;
if listing.lines().any(|line| line.ends_with("/extensions.json")) {
let data: Value = serde_json::from_str(&cat(commit, METADATA)?).map_err(|e| e.to_string())?;
if data["version"] != 1 { return Err("unsupported extension metadata version".into()); }
let requested = data["requested"].as_array().ok_or("missing requested set")?.iter()
.map(|v| v.as_str().map(str::to_string).ok_or("invalid request".to_string()))
.collect::<Result<Vec<_>, _>>()?;
return Ok((checksum(data["base"].as_str().ok_or("missing extension base")?)?, names(&requested)?));
}
if listing.lines().any(|line| line.ends_with("/host-extensions")) {
// Migrate the single-generation nano fixture used by Core ISO 01–10.
let requested: Vec<_> = cat(commit, "/usr/lib/archipelago/host-extensions")?.lines().map(str::to_string).collect();
let base = output("ostree", &[REPO, "show", "--print-metadata-key=archipelago.base", commit])?;
return Ok((checksum(base.trim().trim_matches('\''))?, names(&requested)?));
}
Ok((commit.to_string(), BTreeSet::new()))
}
pub fn describe() -> Result<(), String> {
let state = status()?;
for deployment in state["deployments"].as_array().ok_or("missing deployments")? {
if deployment["stateroot"] != "archipelago" ||
!(deployment["booted"] == true || deployment["pending"] == true || deployment["staged"] == true) { continue; }
let commit = checksum(deployment["checksum"].as_str().ok_or("missing checksum")?)?;
let (base, requested) = intent(&commit)?;
let role = if deployment["booted"] == true { "Booted" } else { "Pending" };
println!("{role} base: {base}\n{role} requested extensions: {}", requested.into_iter().collect::<Vec<_>>().join(" "));
}
Ok(())
}
fn write(path: impl AsRef<Path>, data: impl AsRef<[u8]>) -> Result<(), String> {
fs::write(path, data).map_err(|e| e.to_string())
}
pub fn add(packages: &[String]) -> Result<(), String> {
let additions = names(packages)?;
if output("id", &["-u"])?.trim() != "0" { return Err("Run as root".into()); }
if !Path::new("/run/ostree-booted").exists() || !Path::new("/etc/archipelago/provisioned").exists() {
return Err("complete firstboot in an installed OSTree deployment first".into());
}
let lock = File::options().create(true).truncate(false).write(true)
.open("/run/archipelago-compose.lock").map_err(|e| e.to_string())?;
lock.try_lock().map_err(|e| format!("another composition is running: {e}"))?;
let initial = status()?;
let (source, pending) = select(&initial)?;
let (base, mut requested) = intent(&source)?;
let previous = requested.clone();
requested.extend(additions);
if requested == previous {
println!("Already requested in {} deployment; no changes.", if pending { "pending" } else { "booted" });
return Ok(());
}
let id = format!("{}-{}", SystemTime::now().duration_since(UNIX_EPOCH).map_err(|e| e.to_string())?.as_nanos(), std::process::id());
let generation = Path::new(STATE).join(&id);
fs::DirBuilder::new().recursive(true).mode(0o700).create(&generation).map_err(|e| e.to_string())?;
let snapshot = cat(&base, "/usr/lib/archipelago/snapshot")?;
write(generation.join("base"), format!("{base}\n"))?;
write(generation.join("source"), format!("{source}\n"))?;
write(generation.join("snapshot"), &snapshot)?;
write(generation.join("requested"), requested.iter().map(|n| format!("{n}\n")).collect::<String>())?;
let result = compose(&generation, &id, &base, &snapshot, &requested, &initial);
if let Err(error) = &result {
let _ = write(generation.join("failure"), error);
eprintln!("Extension composition failed; diagnostics and inputs: {}", generation.display());
}
result
}
pub(crate) fn reapply(base: &str, requested: &BTreeSet<String>, initial: &Value) -> Result<(), String> {
// Caller holds the same host mutation lock as extension add.
let id = format!("update-{}-{}", SystemTime::now().duration_since(UNIX_EPOCH)
.map_err(|e| e.to_string())?.as_nanos(), std::process::id());
let generation = Path::new(STATE).join(&id);
fs::DirBuilder::new().recursive(true).mode(0o700).create(&generation).map_err(|e| e.to_string())?;
let snapshot = cat(base, "/usr/lib/archipelago/snapshot")?;
write(generation.join("base"), format!("{base}\n"))?;
write(generation.join("snapshot"), &snapshot)?;
write(generation.join("requested"), requested.iter().map(|n| format!("{n}\n")).collect::<String>())?;
let result = compose(&generation, &id, base, &snapshot, requested, initial);
if let Err(error) = &result { let _ = write(generation.join("failure"), error); }
result
}
fn compose(generation: &Path, id: &str, base: &str, snapshot: &str,
requested: &BTreeSet<String>, initial: &Value) -> Result<(), String> {
let root = generation.join("root");
let rootstr = root.to_str().ok_or("invalid workspace path")?;
run("ostree", &[REPO, "refs", &format!("--create=extensions/bases/{id}"), base])?;
run("ostree", &[REPO, "checkout", "--force-copy", base, rootstr])?;
write(generation.join("dkms-policy.tsv"), include_str!("../adapters/dkms-policy.tsv"))?;
write(generation.join("dkms-finalize.sh"), include_str!("../adapters/dkms-finalize.sh"))?;
let transaction = Command::new("/bin/bash").args(["-euo", "pipefail", "-c",
include_str!("../adapters/extensions.sh"), "archipelago-extension"])
.arg(generation).status().map_err(|e| e.to_string())?;
if !transaction.success() { return Err(format!("package transaction/finalization failed: {transaction}")); }
write(root.join("usr/lib/archipelago/extensions.json"), serde_json::to_vec_pretty(&json!({
"version": 1, "base": base, "snapshot": snapshot.trim(), "generation": id,
"requested": requested,
})).map_err(|e| e.to_string())?)?;
write(root.join("usr/lib/archipelago/host-extensions"), requested.iter().map(|n| format!("{n}\n")).collect::<String>())?;
let commit = checksum(output("ostree", &[REPO, "commit", "-b", &format!("extensions/results/{id}"),
&format!("--tree=dir={rootstr}"), &format!("--add-metadata-string=archipelago.base={base}"),
&format!("--add-metadata-string=archipelago.snapshot={}", snapshot.trim())])?.trim())?;
write(generation.join("result"), format!("{commit}\n"))?;
// Native OSTree clients do not take our lock. Refuse a stale selection before
// asking OSTree to atomically replace its staged deployment.
if status()? != *initial { return Err("deployment selection changed during composition; retry".into()); }
run("ostree", &["admin", "deploy", "--stage", "--retain", "--os=archipelago", &commit])?;
if let Err(error) = write(generation.join("staged"), b"success\n") {
eprintln!("Deployment staged; could not record completion: {error}");
}
// Exact archives, DB, logs and refs remain; only disposable staging is removed.
if let Err(error) = fs::remove_dir_all(&root) {
eprintln!("Deployment staged; retained disposable workspace: {error}");
}
println!("Prepared {commit}\nRequested: {}\nActivate with an explicit reboot. Current /usr unchanged.\nHistory: {}",
requested.iter().cloned().collect::<Vec<_>>().join(" "), generation.display());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_options_paths_and_dependency_expressions() {
for value in ["--overwrite", "../x", "/tmp/pkg", "repo/pkg", "a>=1", "", "a\nb"] {
assert!(names(&[value.into()]).is_err(), "{value}");
}
assert_eq!(names(&["nano".into(), "nano".into(), "lib32-glibc".into()]).unwrap().len(), 2);
}
#[test]
fn pending_intent_precedes_booted_but_finalized_pending_is_not_overwritten() {
let boot = "a".repeat(64); let next = "b".repeat(64);
let mut s = json!({"deployments": [
{"stateroot":"archipelago", "checksum":next, "pending":true,"staged":true},
{"stateroot":"archipelago", "checksum":boot, "booted":true}]});
assert_eq!(select(&s).unwrap(), (next, true));
s["deployments"][0]["staged"] = json!(false);
assert!(select(&s).is_err());
s["deployments"][0]["pending"] = json!(false);
assert_eq!(select(&s).unwrap(), (boot, false));
}
}

8
src/lib.rs Normal file
View file

@ -0,0 +1,8 @@
//! Installed-host lifecycle prototypes. No host mutations are implemented yet.
pub mod onboarding;
pub mod extensions;
pub mod desktop;
pub mod updates;
pub const HOST: &str = include_str!("../adapters/host.sh");
pub const FIRSTBOOT: &str = include_str!("../adapters/firstboot.sh");

87
src/onboarding.rs Normal file
View file

@ -0,0 +1,87 @@
//! Advisory first-run policy; adapters must supply current-deployment observations.
//! A Ready assessment is not a durable authorization token: the future executor
//! must recheck under its transaction lock before preparing another deployment.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Context {
Live,
Installed,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Frontend {
CoreCli,
GnomeInitialSetup,
PlasmaSetup,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PrimaryAccount {
Absent,
/// The same intended identity exists, but mandatory steps are unfinished.
Incomplete,
/// Identity, authentication setup, home ownership and profile requirements agree.
Consistent,
/// Unknown ownership, conflicting identity, or an observation failure.
Conflict,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Completion {
Pending,
/// Completion evidence for the effective deployment, not a shared /var flag.
Complete,
}
#[derive(Clone, Copy, Debug)]
pub struct Observation {
pub context: Context,
pub completion: Completion,
pub account: PrimaryAccount,
pub frontend: Frontend,
/// True only after the profile's adapter is available and validated.
pub frontend_available: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NextStep {
Installer,
Start(Frontend),
/// Resume the selected workflow without repeating account creation.
Resume(Frontend),
FrontendUnavailable(Frontend),
DiagnoseAccount,
Ready,
}
impl NextStep {
pub fn permits_deployment_preparation(self) -> bool {
self == Self::Ready
}
}
pub fn assess(observation: Observation) -> NextStep {
use PrimaryAccount::*;
if observation.context == Context::Live {
return NextStep::Installer;
}
if observation.account == Conflict {
return NextStep::DiagnoseAccount;
}
if observation.completion == Completion::Complete {
return if observation.account == Consistent {
NextStep::Ready
} else {
NextStep::DiagnoseAccount
};
}
if !observation.frontend_available {
return NextStep::FrontendUnavailable(observation.frontend);
}
match observation.account {
Absent => NextStep::Start(observation.frontend),
Incomplete | Consistent => NextStep::Resume(observation.frontend),
Conflict => NextStep::DiagnoseAccount,
}
}

160
src/updates.rs Normal file
View file

@ -0,0 +1,160 @@
//! Temporary hardware-test update adapter: signed OSTree, pinned plans, no reboot.
use serde_json::{json, Value};
use std::{collections::BTreeSet, fs::{self, File}, os::unix::fs::DirBuilderExt,
path::{Path, PathBuf}, process::Command, time::{SystemTime, UNIX_EPOCH}};
const STATE: &str = "/var/lib/archipelago/updates";
const REMOTE: &str = "archipelago-hardware-test";
fn output(program: &str, args: &[&str]) -> Result<String, String> {
let result = Command::new(program).args(args).env("LC_ALL", "C").output().map_err(|e| e.to_string())?;
if !result.status.success() { return Err(format!("{program}: {}", String::from_utf8_lossy(&result.stderr))); }
String::from_utf8(result.stdout).map_err(|e| e.to_string())
}
fn digest(s: &str) -> bool { s.len() == 64 && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) }
fn write(path: &Path, value: &Value) -> Result<(), String> {
fs::write(path, serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?).map_err(|e| e.to_string())
}
fn repo(args: &[&str]) -> Result<String, String> {
let r = format!("--repo={STATE}/repo");
output("ostree", &[&[r.as_str()], args].concat())
}
fn lock() -> Result<File, String> {
if output("id", &["-u"])?.trim() != "0" { return Err("Run as root".into()); }
if !Path::new("/run/ostree-booted").exists() || !Path::new("/etc/archipelago/provisioned").exists() {
return Err("complete firstboot in an installed deployment first".into());
}
let f = File::options().create(true).truncate(false).write(true).open("/run/archipelago-compose.lock").map_err(|e| e.to_string())?;
f.try_lock().map_err(|e| format!("another host operation is running: {e}"))?;
fs::DirBuilder::new().recursive(true).mode(0o700).create(STATE).map_err(|e| e.to_string())?;
Ok(f)
}
fn binding() -> Result<Value, String> {
let local = Path::new("/etc/archipelago/update.json");
let path = if local.exists() { local } else { Path::new("/usr/lib/archipelago/update.json") };
let profile: Value = serde_json::from_slice(&fs::read(path).map_err(|e| format!("update profile {}: {e}", path.display()))?).map_err(|e| e.to_string())?;
let url = profile["url"].as_str().ok_or("missing update URL")?;
let reference = profile["refs"][variant()].as_str().ok_or("missing variant ref")?;
if profile["version"] != 1 || !(url.starts_with("https://") || url.starts_with("http://") || url.starts_with("file:///")) || url.chars().any(char::is_whitespace) {
return Err("unsupported update profile URL/version".into());
}
if reference.is_empty() || reference.starts_with('/') || reference.split('/').any(|p| p.is_empty() || p == "." || p == "..") ||
!reference.bytes().all(|c| c.is_ascii_alphanumeric() || b"/_.-".contains(&c)) {
return Err("invalid update ref".into());
}
let key = profile["public_key_file"].as_str().filter(|s| s.starts_with('/')).ok_or("absolute public key path required")?;
let key_hash = output("sha256sum", &[key])?.split_whitespace().next().ok_or("missing public key checksum")?.to_string();
Ok(json!({"profile":profile,"key_sha256":key_hash,"reference":reference}))
}
fn configure(binding: &Value) -> Result<(), String> {
if !Path::new(STATE).join("repo/config").exists() { repo(&["init", "--mode=archive"])?; }
let key = format!("{STATE}/hardware-test.asc");
fs::copy(binding["profile"]["public_key_file"].as_str().ok_or("missing key")?, &key).map_err(|e| e.to_string())?;
repo(&["remote", "delete", "--if-exists", REMOTE])?;
repo(&["remote", "add", &format!("--gpg-import={key}"), "--set=gpg-verify=true",
"--set=gpg-verify-summary=true", REMOTE, binding["profile"]["url"].as_str().ok_or("missing URL")?])?;
Ok(())
}
fn booted(state: &Value) -> Result<String, String> {
let deployments = state["deployments"].as_array().ok_or("missing deployments")?;
if deployments.iter().any(|d| d["pending"] == true || d["staged"] == true) {
return Err("activate or explicitly reconcile the pending deployment first".into());
}
let d = deployments.iter().find(|d| d["booted"] == true && d["stateroot"] == "archipelago").ok_or("missing booted deployment")?;
let c = d["checksum"].as_str().ok_or("missing checksum")?;
if !digest(c) { return Err("invalid checksum".into()); }
Ok(c.into())
}
fn summary_commit(summary: &str, reference: &str) -> Result<String, String> {
let mut selected = false;
for line in summary.lines() {
if let Some(name) = line.strip_prefix("* ") { selected = name == reference; }
else if selected && digest(line.trim()) { return Ok(line.trim().into()); }
}
Err("signed summary does not contain the selected image track".into())
}
fn variant() -> &'static str {
if Path::new("/usr/lib/archipelago/gnome-firstboot").exists() { "gnome" } else { "core" }
}
fn plan_path(id: &str) -> Result<PathBuf, String> {
if !digest(id) { return Err("expected a 64-character plan digest".into()); }
Ok(Path::new(STATE).join(format!("plan-{id}.json")))
}
pub fn plan(save: bool) -> Result<(), String> {
let _lock = lock()?;
let binding = binding()?;
configure(&binding)?;
let state = crate::extensions::status()?;
let current = booted(&state)?;
let (base, requested) = crate::extensions::intent(&current)?;
let files = output("ostree", &["--repo=/sysroot/ostree/repo", "ls", &base, "/usr/lib/archipelago"])?;
if files.lines().any(|l| l.ends_with("/overlays")) {
return Err("updating custom managed overlays is not implemented; existing deployment preserved".into());
}
let reference = binding["reference"].as_str().ok_or("missing reference")?;
let target = summary_commit(&repo(&["remote", "summary", REMOTE])?, &reference)?;
let plan = json!({"version":2,"binding":binding,"variant":variant(),"reference":reference,
"target":target,"base":base,"requested":requested,"initial":state});
if !save { println!("{}", serde_json::to_string_pretty(&plan).unwrap()); return Ok(()); }
let temp = Path::new(STATE).join("plan.tmp");
write(&temp, &plan)?;
let hash = output("sha256sum", &[temp.to_str().unwrap()])?.split_whitespace().next().ok_or("missing digest")?.to_string();
fs::rename(&temp, plan_path(&hash)?).map_err(|e| e.to_string())?;
println!("Plan: {hash}\nTarget: {target}\nApply: sudo archipelago update apply --plan {hash}");
Ok(())
}
pub fn apply(id: &str) -> Result<(), String> {
let _lock = lock()?;
let path = plan_path(id)?;
if output("sha256sum", &[path.to_str().unwrap()])?.split_whitespace().next() != Some(id) {
return Err("plan integrity failure".into());
}
let plan: Value = serde_json::from_slice(&fs::read(&path).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
let operation = Path::new(STATE).join(format!("operation-{}.json", SystemTime::now().duration_since(UNIX_EPOCH).map_err(|e| e.to_string())?.as_nanos()));
write(&operation, &json!({"plan":id,"state":"executing"}))?;
let result = apply_plan(&plan);
let terminal = match &result { Ok(()) => json!({"plan":id,"state":"completed"}), Err(e) => json!({"plan":id,"state":"failed","error":e}) };
if let Err(error) = write(&operation, &terminal) {
eprintln!("Could not record terminal operation state: {error}; inspect deployment status");
}
result
}
fn apply_plan(plan: &Value) -> Result<(), String> {
let binding = binding()?;
if plan["version"] != 2 || plan["binding"] != binding || plan["variant"] != variant() { return Err("unsupported plan or infrastructure binding changed; create a new plan".into()); }
let initial = crate::extensions::status()?;
booted(&initial)?;
if initial != plan["initial"] { return Err("deployment state changed; create a new plan".into()); }
let target = plan["target"].as_str().filter(|s| digest(s)).ok_or("invalid target")?;
if plan["base"] == target { println!("Already on the selected base; no deployment created."); return Ok(()); }
configure(&binding)?;
// The signed summary selects the checksum during planning; exact-checksum pull
// verifies its commit signature without reinterpreting old build-local ref bindings.
repo(&["pull", "--depth=0", REMOTE, target])?;
let files = repo(&["ls", target, "/usr/lib/archipelago"])?;
let gnome = files.lines().any(|l| l.ends_with("/gnome-firstboot"));
if gnome != (variant() == "gnome") { return Err("candidate Purpose differs from booted Purpose".into()); }
if output("uname", &["-m"])?.trim() != "x86_64" { return Err("only x86_64 is implemented".into()); }
repo(&["cat", target, "/usr/lib/archipelago/snapshot"])?;
output("ostree", &["--repo=/sysroot/ostree/repo", "pull-local", &format!("{STATE}/repo"), target])?;
let requested: BTreeSet<String> = serde_json::from_value(plan["requested"].clone()).map_err(|e| e.to_string())?;
if crate::extensions::status()? != initial { return Err("deployment state changed during download".into()); }
if requested.is_empty() {
output("ostree", &["admin", "deploy", "--stage", "--retain", "--os=archipelago", target])?;
} else { crate::extensions::reapply(target, &requested, &initial)?; }
println!("Update prepared. Activate with an explicit reboot. Current /usr unchanged.");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn summary_track_is_exact_and_missing_track_fails() {
let a = "a".repeat(64); let b = "b".repeat(64);
let s = format!("* hardware-test/core-other\n {a}\n* hardware-test/core\n Latest Commit:\n {b}\n");
assert_eq!(summary_commit(&s, "hardware-test/core").unwrap(), b);
assert!(summary_commit(&s, "hardware-test/gnome").is_err());
assert!(plan_path("../../etc/passwd").is_err());
}
}

81
tests/onboarding.rs Normal file
View file

@ -0,0 +1,81 @@
use archipelago_system::onboarding::*;
fn pending() -> Observation {
Observation {
context: Context::Installed,
completion: Completion::Pending,
account: PrimaryAccount::Absent,
frontend: Frontend::CoreCli,
frontend_available: true,
}
}
#[test]
fn installation_first_boot_interruption_and_reboot() {
let mut state = pending();
state.context = Context::Live;
assert_eq!(assess(state), NextStep::Installer);
state.context = Context::Installed;
assert_eq!(assess(state), NextStep::Start(Frontend::CoreCli));
state.account = PrimaryAccount::Incomplete;
assert_eq!(assess(state), NextStep::Resume(Frontend::CoreCli));
state.account = PrimaryAccount::Consistent;
assert_eq!(assess(state), NextStep::Resume(Frontend::CoreCli));
state.completion = Completion::Complete;
assert_eq!(assess(state), NextStep::Ready);
assert_eq!(assess(state), NextStep::Ready);
}
#[test]
fn configured_core_can_add_desktop_without_new_account_or_wizard() {
for frontend in [Frontend::GnomeInitialSetup, Frontend::PlasmaSetup] {
let state = Observation {
completion: Completion::Complete,
account: PrimaryAccount::Consistent,
frontend,
frontend_available: false,
..pending()
};
assert_eq!(assess(state), NextStep::Ready);
}
}
#[test]
fn missing_native_adapter_does_not_silently_launch_cli() {
for frontend in [Frontend::GnomeInitialSetup, Frontend::PlasmaSetup] {
let mut state = Observation { frontend, ..pending() };
assert_eq!(assess(state), NextStep::Start(frontend));
state.frontend_available = false;
assert_eq!(assess(state), NextStep::FrontendUnavailable(frontend));
}
}
#[test]
fn stale_completion_or_conflict_requires_diagnosis() {
for account in [PrimaryAccount::Absent, PrimaryAccount::Incomplete, PrimaryAccount::Conflict] {
let state = Observation { account, completion: Completion::Complete, ..pending() };
assert_eq!(assess(state), NextStep::DiagnoseAccount);
}
let state = Observation { account: PrimaryAccount::Conflict, ..pending() };
assert_eq!(assess(state), NextStep::DiagnoseAccount);
}
#[test]
fn only_installed_complete_consistent_state_passes_deployment_gate() {
for context in [Context::Live, Context::Installed] {
for completion in [Completion::Pending, Completion::Complete] {
for account in [PrimaryAccount::Absent, PrimaryAccount::Incomplete,
PrimaryAccount::Consistent, PrimaryAccount::Conflict] {
for frontend_available in [false, true] {
let state = Observation {
context, completion, account, frontend_available, ..pending()
};
let expected = context == Context::Installed
&& completion == Completion::Complete
&& account == PrimaryAccount::Consistent;
assert_eq!(assess(state).permits_deployment_preparation(), expected);
}
}
}
}
}