commit 38214ea9e79b08ef8da0c72a96aeba62ab0d1842 Author: Phoebus Date: Sun Sep 20 02:07:33 2026 -0700 chore: import Phoebus OS installer and Rust migration Initial public import of the proven Bash installer (installer/) and the production Rust workspace (installer-rs/). The reference ISO, build output and local agent transcripts are gitignored. Verified: installer/tests/run_tests.sh and cargo test --workspace both pass. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8026e95 --- /dev/null +++ b/.gitignore @@ -0,0 +1,35 @@ +# --- Rust build output ------------------------------------------------------- +installer-rs/target/ +**/target/ + +# --- Python bytecode -------------------------------------------------------- +**/__pycache__/ +*.pyc + +# --- Reference media (large; never part of the source tree) ------------------ +*.iso +livegui-*.iso +*.img +*.qcow2 +*.raw + +# --- Local agent session state and transcripts ------------------------------- +# These are per-machine logs, not project source. +.agent-shell/ + +# --- Secrets (must never be committed) --------------------------------------- +*.pw +*.key +*.pem +*.secret +/secrets/ +credentials + +# --- Editor / OS noise ------------------------------------------------------- +.DS_Store +*.swp +*.swo +*~ +.idea/ +.vscode/ +.cache/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..5dc3cdc --- /dev/null +++ b/README.md @@ -0,0 +1,69 @@ +# Phoebus OS + +A modern, stable, **Gentoo-based** workstation operating system: systemd, +Wayland-first, PipeWire, UEFI/GPT, LUKS2, Btrfs with snapshots, a fast dwl-style +desktop, Flatpak, and an optional AI administration assistant. AI-first, never +AI-dependent. + +Stability first: modern architecture + mature implementations + conservative +updates + recovery. + +## Status + +A complete encrypted UEFI install has been built and **booted in a disposable +VM** (ISO detached): GPT + LUKS2 + Btrfs, systemd PID 1, login, networking, and +a verified Wayland desktop stack with Flatpak. See `docs/STATUS.md` for the +exact implementation/verification matrix and known limitations. + +## Repository layout + +``` +AGENTS.md entry point for AI/human contributors (read first) +docs/ objectives, roadmap, status, architecture, process +installer/ proven Bash installer (reference / fallback) + VM harness +installer-rs/ production Rust installer (crates/ workspace) +scripts/ git/dev tooling (hooks, publish, agent-commit) +.githooks/ committed git hooks +``` + +The Gentoo LiveGUI ISO is a reference artifact and is **not** tracked by git. + +## Build and test + +```sh +# Bash reference +installer/tests/run_tests.sh + +# Rust production installer +cd installer-rs +cargo fmt --all -- --check +cargo clippy --workspace --all-targets +cargo test --workspace +cargo build --release -p phoebus-installer +``` + +Installer quick start (Rust): + +```sh +phoebus-installer --config FILE --plan # installation plan +phoebus-installer --config FILE --dry-run # no system changes +phoebus-installer --config FILE --install # run the backend +phoebus-installer --config FILE --install --yes \ + --luks-passphrase-file /secure/luks.pw \ + --user-password-file /secure/user.pw +``` + +The normal installation path is entirely deterministic and does not require an +LLM. AI is an optional assistant that proposes typed, validated changes which +the user approves; it never holds root or a shell. + +## Documentation + +- `docs/OBJECTIVES.md` — vision, philosophy, non-goals. +- `docs/ROADMAP.md` — priorities and current status. +- `docs/STATUS.md` — implemented / unit-tested / VM-verified. +- `docs/ARCHITECTURE.md` — components and safety model. +- `docs/DEVELOPMENT.md` — host setup, build, VM testing. +- `docs/CONTRIBUTING.md` — standards and definition of done. +- `docs/GIT-WORKFLOW.md` — how to commit, push and release. +- `installer/doc/VM-BOOT-VERIFICATION.md` — boot evidence. diff --git a/installer-rs/Cargo.lock b/installer-rs/Cargo.lock new file mode 100644 index 0000000..520ed50 --- /dev/null +++ b/installer-rs/Cargo.lock @@ -0,0 +1,1073 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cassowary" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "compact_str" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd622ebbb56a5b2ccb651b32b911cdeb2a9b4b11776b2473bf26a26a286244e" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossterm" +version = "0.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" +dependencies = [ + "bitflags", + "crossterm_winapi", + "mio", + "parking_lot", + "rustix 0.38.44", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.6", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "either" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "indoc" +version = "2.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" +dependencies = [ + "rustversion", +] + +[[package]] +name = "instability" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf84e73fa6f27f299dec58e13223cf70db80da872eb921d4f6138342a0eabc8" +dependencies = [ + "darling", + "indoc", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "phoebus-ai" +version = "0.1.0" +dependencies = [ + "phoebus-core", + "serde", + "serde_json", + "tempfile", + "thiserror", +] + +[[package]] +name = "phoebus-core" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tempfile", + "thiserror", + "toml", + "zeroize", +] + +[[package]] +name = "phoebus-executor" +version = "0.1.0" +dependencies = [ + "phoebus-ai", + "phoebus-core", + "serde", + "tempfile", + "thiserror", + "toml", + "zeroize", +] + +[[package]] +name = "phoebus-installer" +version = "0.1.0" +dependencies = [ + "clap", + "phoebus-core", + "phoebus-executor", + "phoebus-tui", + "serde", + "serde_json", + "sha2", + "tempfile", + "toml", +] + +[[package]] +name = "phoebus-tui" +version = "0.1.0" +dependencies = [ + "crossterm", + "phoebus-core", + "ratatui", +] + +[[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 = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "ratatui" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b" +dependencies = [ + "bitflags", + "cassowary", + "compact_str", + "crossterm", + "indoc", + "instability", + "itertools", + "lru", + "paste", + "strum", + "unicode-segmentation", + "unicode-truncate", + "unicode-width 0.2.0", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[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 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "smallvec" +version = "1.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-truncate" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width 0.1.14", +] + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "unicode-width" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/installer-rs/Cargo.toml b/installer-rs/Cargo.toml new file mode 100644 index 0000000..a0365e5 --- /dev/null +++ b/installer-rs/Cargo.toml @@ -0,0 +1,27 @@ +[workspace] +resolver = "2" +members = ["crates/*"] + +[workspace.package] +version = "0.1.0" +edition = "2021" +license = "GPL-2.0-or-later" +repository = "https://example.invalid/phoebus" +rust-version = "1.75" + +[workspace.dependencies] +phoebus-core = { path = "crates/phoebus-core" } +phoebus-executor = { path = "crates/phoebus-executor" } +phoebus-ai = { path = "crates/phoebus-ai" } + +serde = { version = "1", features = ["derive"] } +serde_json = "1" +toml = "0.8" +clap = { version = "4", features = ["derive"] } +thiserror = "2" +zeroize = { version = "1", features = ["derive"] } +tempfile = "3" + +[profile.release] +lto = "thin" +codegen-units = 1 diff --git a/installer-rs/README.md b/installer-rs/README.md new file mode 100644 index 0000000..c102f12 --- /dev/null +++ b/installer-rs/README.md @@ -0,0 +1,114 @@ +# Phoebus OS installer (Rust) + +The production installer/backend for Phoebus OS. It is being built beside the +proven Bash implementation and only becomes primary once it reproduces the +known-good encrypted UEFI VM boot. + +## Workspace + +``` +crates/ + phoebus-core configuration types, validation, plan, package policy, + hardware/disk models, target-root safety, secrets, + snapshot history, typed system actions, update policy + phoebus-executor command runner, logging, storage, encryption, Btrfs, + stage3, Portage, kernel, boot, users, services, desktop, + snapshots, background-update preparation, admin context + phoebus-ai typed AI proposals + enforced privacy boundary + phoebus-tui ratatui terminal UI + phoebus-installer CLI, `sys`, orchestration +``` + +Binaries: `phoebus-installer` (installer) and `sys` (typed system interface). + +## `sys` + +```sh +sys enable sshd # deterministic phrase -> typed action +sys disable bluetooth +sys history # snapshot/transaction history +sys what are you compiling # background update status +sys --action '{"action":"inspect_service","name":"ssh"}' +sys --action-file proposal.json # the AI path: same typed schema +``` + +Mutating actions require root (run under `sudo`); the model never receives the +password. High-risk actions are preceded by a Btrfs snapshot when available. +There is no `run_shell` action; unknown actions fail closed. + +## Snapshots and background updates + +- `phoebus-core::snapshot` defines deterministic snapshot names and a TOML + transaction history. `phoebus-executor::snapshot` creates read-only Btrfs + snapshots. `/home` is intentionally not snapshotted by default. +- `phoebus-core::update` / `phoebus-executor::update` implement **preparation + only**: `emerge --fetchonly` then `emerge --buildpkgonly` stage distfiles and + reusable local binary packages without installing. Activation stays explicit. + +## Building + +```sh +cargo test --workspace +cargo build --release -p phoebus-installer + +# A static binary is preferred for the live installer environment: +RUSTFLAGS="-C target-feature=+crt-static" \ + cargo build --release -p phoebus-installer --target x86_64-unknown-linux-gnu +``` + +`rustfmt` and `clippy` are not available in the reference toolchain used for +this milestone. + +## CLI + +```sh +phoebus-installer --config FILE --plan +phoebus-installer --config FILE --dry-run --install +phoebus-installer --config FILE --install --yes \ + --luks-passphrase-file /run/luks.pw \ + --user-password-file /run/user.pw +``` + +Both TOML and the legacy flat `KEY='value'` format are supported. Format is +detected structurally (the flat format is also valid TOML because single +quotes are TOML literal strings). + +```toml +[system] +hostname = "phoebus" +timezone = "UTC" + +[storage] +disk = "/dev/vda" +filesystem = "btrfs" + +[encryption] +mode = "luks2" +``` + +Secrets are never stored in the configuration. They are supplied through 0600 +files and registered with the redactor before anything is logged. + +## Safety model + +- Every command goes through `phoebus-executor::Exec`, which logs redacted + arguments, exit status and duration, and honours dry-run centrally. +- Arguments are always passed separately; there is no `sh -c`. +- `TargetRoot` rejects absolute paths and `..` traversal, so host-versus-target + bugs are caught by construction and covered by tests. +- Destructive functions require a `DestructiveAuthorization` token produced + only after the ERASE confirmation and a final confirmation. +- `phoebus-ai` can only emit a closed set of typed configuration changes; + unknown actions fail closed and there is no shell action. + +## Package policy + +`phoebus-core::policy` implements the deterministic source/binary rule and +records *measured* compile times parsed from Portage's `emerge.log` +(`phoebus-core::emergelog`). No performance value is ever invented. + +## Verification + +`crates/phoebus-installer/tests/parity.rs` compares the Bash and Rust plans for +the same configuration. The disposable VM harness in `../installer/tests/vm` +drives the static binary through a full encrypted install and boot. diff --git a/installer-rs/crates/phoebus-ai/Cargo.toml b/installer-rs/crates/phoebus-ai/Cargo.toml new file mode 100644 index 0000000..9232f28 --- /dev/null +++ b/installer-rs/crates/phoebus-ai/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "phoebus-ai" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +phoebus-core.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/installer-rs/crates/phoebus-ai/src/lib.rs b/installer-rs/crates/phoebus-ai/src/lib.rs new file mode 100644 index 0000000..2f95194 --- /dev/null +++ b/installer-rs/crates/phoebus-ai/src/lib.rs @@ -0,0 +1,191 @@ +//! Typed AI proposals. +//! +//! The model never receives a shell. It can only emit a structured +//! `AiProposal` whose changes deserialize into a closed enum. Unknown actions +//! fail closed. Each change is validated semantically before it is merged into +//! the typed configuration. Privileged execution is a separate, human-approved +//! step performed by the deterministic backend. + +pub mod privacy; + +use phoebus_core::config::{DesktopProfile, Encryption, Filesystem, InstallConfig, KernelProfile, PackagePolicy}; +use phoebus_core::validate; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, thiserror::Error)] +pub enum AiError { + #[error("proposal JSON is invalid: {0}")] + Json(#[from] serde_json::Error), + #[error("proposal version {0} is not supported")] + UnsupportedVersion(u32), + #[error("change rejected: {0}")] + Rejected(String), +} + +/// A versioned, closed set of configuration changes. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AiProposal { + pub version: u32, + pub changes: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)] +pub enum ProposedChange { + SetHostname { value: String }, + SetTimezone { value: String }, + SetLocale { value: String }, + SetKeymap { value: String }, + SetUsername { value: String }, + SetTargetDisk { value: String }, + SetFilesystem { value: Filesystem }, + SetEncryption { value: Encryption }, + SetKernelProfile { value: KernelProfile }, + SetPackagePolicy { value: PackagePolicy }, + SetDesktopProfile { value: DesktopProfile }, + SetFlatpak { value: bool }, +} + +impl ProposedChange { + pub fn describe(&self) -> String { + match self { + ProposedChange::SetHostname { value } => format!("hostname = {value}"), + ProposedChange::SetTimezone { value } => format!("timezone = {value}"), + ProposedChange::SetLocale { value } => format!("locale = {value}"), + ProposedChange::SetKeymap { value } => format!("keymap = {value}"), + ProposedChange::SetUsername { value } => format!("username = {value}"), + ProposedChange::SetTargetDisk { value } => format!("target disk = {value}"), + ProposedChange::SetFilesystem { value } => format!("filesystem = {value}"), + ProposedChange::SetEncryption { value } => format!("encryption = {value}"), + ProposedChange::SetKernelProfile { value } => format!("kernel profile = {value}"), + ProposedChange::SetPackagePolicy { value } => format!("package policy = {value}"), + ProposedChange::SetDesktopProfile { value } => format!("desktop profile = {value}"), + ProposedChange::SetFlatpak { value } => format!("flatpak = {value}"), + } + } + + /// Semantic validation against the current configuration. + pub fn validate(&self) -> Result<(), String> { + match self { + ProposedChange::SetHostname { value } => validate::validate_hostname(value), + ProposedChange::SetTimezone { value } => validate::validate_timezone(value), + ProposedChange::SetLocale { value } => validate::validate_locale(value), + ProposedChange::SetKeymap { value } => validate::validate_keymap(value), + ProposedChange::SetUsername { value } => validate::validate_username(value), + ProposedChange::SetTargetDisk { value } => { + if value.starts_with("/dev/") { + Ok(()) + } else { + Err(format!("target disk must be a /dev path: {value}")) + } + } + _ => Ok(()), + } + } +} + +/// Parse a proposal from JSON text. +pub fn parse_proposal(text: &str) -> Result { + let proposal: AiProposal = serde_json::from_str(text)?; + if proposal.version != 1 { + return Err(AiError::UnsupportedVersion(proposal.version)); + } + Ok(proposal) +} + +/// The changes that were applied. +#[derive(Debug, Clone)] +pub struct AppliedChange { + pub description: String, +} + +/// Validate and merge a proposal into the configuration. +/// +/// If any change fails validation, nothing is applied (fail closed). +pub fn apply(config: &mut InstallConfig, proposal: &AiProposal) -> Result, AiError> { + for change in &proposal.changes { + change + .validate() + .map_err(|e| AiError::Rejected(format!("{}: {e}", change.describe())))?; + } + let mut applied = Vec::new(); + for change in &proposal.changes { + match change { + ProposedChange::SetHostname { value } => config.system.hostname = value.clone(), + ProposedChange::SetTimezone { value } => config.system.timezone = value.clone(), + ProposedChange::SetLocale { value } => config.system.locale = value.clone(), + ProposedChange::SetKeymap { value } => config.system.keymap = value.clone(), + ProposedChange::SetUsername { value } => config.user.username = value.clone(), + ProposedChange::SetTargetDisk { value } => config.storage.disk = value.clone(), + ProposedChange::SetFilesystem { value } => config.storage.filesystem = *value, + ProposedChange::SetEncryption { value } => config.encryption.mode = *value, + ProposedChange::SetKernelProfile { value } => config.kernel.profile = *value, + ProposedChange::SetPackagePolicy { value } => config.packages.policy = *value, + ProposedChange::SetDesktopProfile { value } => config.desktop.profile = *value, + ProposedChange::SetFlatpak { value } => config.desktop.flatpak = *value, + } + applied.push(AppliedChange { + description: change.describe(), + }); + } + Ok(applied) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_and_applies_a_valid_proposal() { + let text = r#"{ + "version": 1, + "changes": [ + {"action": "set_hostname", "value": "box"}, + {"action": "set_encryption", "value": "luks2"}, + {"action": "set_desktop_profile", "value": "dwl"} + ] + }"#; + let proposal = parse_proposal(text).unwrap(); + let mut config = InstallConfig::default(); + let applied = apply(&mut config, &proposal).unwrap(); + assert_eq!(applied.len(), 3); + assert_eq!(config.system.hostname, "box"); + assert_eq!(config.encryption.mode, Encryption::Luks2); + assert_eq!(config.desktop.profile, DesktopProfile::Dwl); + } + + #[test] + fn unknown_action_fails_closed() { + let text = r#"{"version":1,"changes":[{"action":"run_shell","command":"rm -rf /"}]}"#; + assert!(parse_proposal(text).is_err()); + } + + #[test] + fn invalid_value_rejects_whole_proposal() { + let text = r#"{"version":1,"changes":[ + {"action":"set_hostname","value":"good"}, + {"action":"set_hostname","value":"bad host"} + ]}"#; + let proposal = parse_proposal(text).unwrap(); + let mut config = InstallConfig::default(); + assert!(apply(&mut config, &proposal).is_err()); + // Nothing applied. + assert_eq!(config.system.hostname, "phoebus"); + } + + #[test] + fn unsupported_version_rejected() { + let text = r#"{"version":99,"changes":[]}"#; + assert!(matches!( + parse_proposal(text), + Err(AiError::UnsupportedVersion(99)) + )); + } + + #[test] + fn filesystem_enum_is_validated_by_serde() { + let text = r#"{"version":1,"changes":[{"action":"set_filesystem","value":"zfs"}]}"#; + assert!(parse_proposal(text).is_err()); + } +} diff --git a/installer-rs/crates/phoebus-ai/src/privacy.rs b/installer-rs/crates/phoebus-ai/src/privacy.rs new file mode 100644 index 0000000..80d77b2 --- /dev/null +++ b/installer-rs/crates/phoebus-ai/src/privacy.rs @@ -0,0 +1,104 @@ +//! AI privacy boundary. +//! +//! A system-administration assistant needs *system* access, not the home +//! directory. This module makes that an enforced property of the context +//! builder rather than a prompt instruction: the default policy collects only +//! system facts, and paths under `/home`, `/root`, `~/.ssh`, `~/.gnupg`, and +//! credential directories are rejected by construction. + +use std::collections::BTreeMap; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PrivacyPolicy { + /// Whether the user has explicitly granted workspace access. Default off. + pub allow_home: bool, + /// Whether raw application logs may be included. Default off. + pub allow_raw_logs: bool, +} + +impl Default for PrivacyPolicy { + fn default() -> Self { + Self { + allow_home: false, + allow_raw_logs: false, + } + } +} + +/// The data that may be sent to a model. Only system facts and explicitly +/// allowed excerpts. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ContextBundle { + pub system: BTreeMap, +} + +impl ContextBundle { + pub fn insert(&mut self, key: impl Into, value: impl Into) { + self.system.insert(key.into(), value.into()); + } + + /// Render the bundle for a model, applying redaction and an explicit + /// description of what is *not* being sent. + pub fn render(&self, redactor: &phoebus_core::Redactor) -> String { + let mut out = String::new(); + out.push_str("System context (no personal files are included):\n"); + for (k, v) in &self.system { + out.push_str(&format!("{k}: {}\n", redactor.redact(v))); + } + out.push_str( + "Excluded: home directory, SSH/GPG keys, browser data, credentials, \ + password manager, wallets.\n", + ); + out + } +} + +/// Paths that must never be included in model context. +pub fn is_forbidden_path(path: &str) -> bool { + let p = path.trim(); + let home_like = |s: &str| s == "/home" || s.starts_with("/home/") || s == "/root" || s.starts_with("/root/"); + let sensitive = |s: &str| { + [ + ".ssh", ".gnupg", ".aws", ".config/gcloud", ".mozilla", ".config/BraveSoftware", + ".password-store", ".local/share/keyrings", ".kube", "wallet", "Wallets", + ] + .iter() + .any(|needle| s.contains(needle)) + }; + home_like(p) || sensitive(p) +} + +#[cfg(test)] +mod tests { + use super::*; + use phoebus_core::{Redactor, SecretString}; + + #[test] + fn forbidden_paths_are_rejected() { + assert!(is_forbidden_path("/home/alice/Documents")); + assert!(is_forbidden_path("/root/.ssh/id_ed25519")); + assert!(is_forbidden_path("/home/bob/.gnupg/secring.gpg")); + assert!(!is_forbidden_path("/etc/systemd/system")); + assert!(!is_forbidden_path("/proc/loadavg")); + } + + #[test] + fn default_policy_is_system_only() { + let p = PrivacyPolicy::default(); + assert!(!p.allow_home); + assert!(!p.allow_raw_logs); + } + + #[test] + fn render_states_what_is_excluded_and_redacts() { + let redactor = Redactor::new(); + redactor.register(&SecretString::new("hunter2")); + let mut bundle = ContextBundle::default(); + bundle.insert("failed_units", "0"); + bundle.insert("note", "token=hunter2"); + let text = bundle.render(&redactor); + assert!(text.contains("Excluded:")); + assert!(text.contains("")); + assert!(!text.contains("hunter2")); + } +} diff --git a/installer-rs/crates/phoebus-core/Cargo.toml b/installer-rs/crates/phoebus-core/Cargo.toml new file mode 100644 index 0000000..55fe06c --- /dev/null +++ b/installer-rs/crates/phoebus-core/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "phoebus-core" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +serde.workspace = true +toml.workspace = true +serde_json.workspace = true +thiserror.workspace = true +zeroize.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/installer-rs/crates/phoebus-core/src/action.rs b/installer-rs/crates/phoebus-core/src/action.rs new file mode 100644 index 0000000..77a713c --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/action.rs @@ -0,0 +1,228 @@ +//! Typed system actions. +//! +//! This is the schema the AI (or a deterministic front-end) may emit. There is +//! deliberately no `run_shell`/`run_command` action: privileged work is +//! expressed as closed, validated verbs that a policy engine can classify, +//! preview and (after approval) execute. Unknown actions fail closed. + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, thiserror::Error)] +pub enum ActionError { + #[error("invalid action JSON: {0}")] + Json(#[from] serde_json::Error), + #[error("invalid action: {0}")] + Invalid(String), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Risk { + Low, + Medium, + High, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)] +pub enum SystemAction { + InspectService { name: String }, + EnableService { name: String }, + DisableService { name: String }, + InspectPackage { atom: String }, + InstallPackage { atom: String }, + CreateSnapshot { operation: String }, + History, + UpdateSystem, + PrepareUpdates, + InspectUpdates, +} + +impl SystemAction { + pub fn describe(&self) -> String { + match self { + SystemAction::InspectService { name } => format!("inspect service {name}"), + SystemAction::EnableService { name } => format!("enable service {name} at boot"), + SystemAction::DisableService { name } => { + format!("disable service {name} at boot") + } + SystemAction::InspectPackage { atom } => format!("inspect package {atom}"), + SystemAction::InstallPackage { atom } => format!("install package {atom}"), + SystemAction::CreateSnapshot { operation } => { + format!("create a Btrfs snapshot before: {operation}") + } + SystemAction::History => "show system transaction history".to_string(), + SystemAction::PrepareUpdates => "prepare background updates (fetch + build binary packages, do not activate)".to_string(), + SystemAction::InspectUpdates => "show background update preparation status".to_string(), + SystemAction::UpdateSystem => "update the system".to_string(), + } + } + + /// Risk classification used by the policy engine to decide whether a + /// snapshot and/or stronger confirmation is required. + pub fn risk(&self) -> Risk { + match self { + SystemAction::InspectService { .. } | SystemAction::InspectPackage { .. } => { + Risk::Low + } + SystemAction::History => Risk::Low, + SystemAction::InspectUpdates => Risk::Low, + SystemAction::PrepareUpdates => Risk::Medium, + SystemAction::EnableService { .. } + | SystemAction::DisableService { .. } + | SystemAction::CreateSnapshot { .. } => Risk::Medium, + SystemAction::InstallPackage { .. } | SystemAction::UpdateSystem => Risk::High, + } + } + + /// Whether this action modifies the system (and therefore needs + /// authorization and, for High risk, a snapshot). + pub fn is_mutating(&self) -> bool { + !matches!( + self, + SystemAction::InspectService { .. } + | SystemAction::InspectPackage { .. } + | SystemAction::History + | SystemAction::InspectUpdates + ) + } + + pub fn validate(&self) -> Result<(), String> { + let valid_token = |s: &str| { + !s.is_empty() + && s.len() <= 128 + && s.chars() + .all(|c| c.is_ascii_alphanumeric() || "@._+-".contains(c)) + }; + match self { + SystemAction::InspectService { name } + | SystemAction::EnableService { name } + | SystemAction::DisableService { name } => { + if valid_token(name) { + Ok(()) + } else { + Err(format!("invalid service name: {name}")) + } + } + SystemAction::InspectPackage { atom } | SystemAction::InstallPackage { atom } => { + let ok = atom.split('/').count() == 2 + && atom + .chars() + .all(|c| c.is_ascii_alphanumeric() || "/*._+-".contains(c)); + if ok { + Ok(()) + } else { + Err(format!("invalid package atom: {atom}")) + } + } + SystemAction::CreateSnapshot { operation } => { + if operation.is_empty() { + Err("snapshot operation must not be empty".into()) + } else { + Ok(()) + } + } + SystemAction::History + | SystemAction::UpdateSystem + | SystemAction::PrepareUpdates + | SystemAction::InspectUpdates => Ok(()), + } + } +} + +/// A small deterministic parser for common `sys` phrases. +/// +/// Free-form requests that do not match are left to the AI path +/// (`--action-file`), which still produces the same typed schema. +pub fn parse_natural(text: &str) -> Option { + let t = text.trim().to_lowercase(); + let rest = |prefix: &str| t.strip_prefix(prefix).map(|r| r.trim().to_string()); + if t == "history" || t.contains("history") { + return Some(SystemAction::History); + } + if t == "update" || t == "update system" || t == "sys update" { + return Some(SystemAction::UpdateSystem); + } + if t.contains("prepare") && t.contains("update") { + return Some(SystemAction::PrepareUpdates); + } + if t.contains("what are you compiling") || t.contains("update status") { + return Some(SystemAction::InspectUpdates); + } + if let Some(name) = rest("enable ") { + if !name.is_empty() { + return Some(SystemAction::EnableService { name }); + } + } + if let Some(name) = rest("disable ") { + if !name.is_empty() { + return Some(SystemAction::DisableService { name }); + } + } + if let Some(atom) = rest("install ") { + if atom.contains('/') { + return Some(SystemAction::InstallPackage { atom }); + } + } + if let Some(name) = rest("inspect ") { + if !name.is_empty() { + return Some(SystemAction::InspectService { name }); + } + } + None +} + +pub fn parse_action(json: &str) -> Result { + let action: SystemAction = serde_json::from_str(json)?; + action.validate().map_err(ActionError::Invalid)?; + Ok(action) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_typed_actions() { + let a = parse_action(r#"{"action":"enable_service","name":"sshd"}"#).unwrap(); + assert_eq!(a, SystemAction::EnableService { name: "sshd".into() }); + assert!(a.is_mutating()); + assert_eq!(a.risk(), Risk::Medium); + } + + #[test] + fn rejects_shell_action() { + let err = parse_action(r#"{"action":"run_shell","command":"rm -rf /"}"#); + assert!(err.is_err()); + } + + #[test] + fn rejects_unknown_fields_and_bad_values() { + assert!(parse_action(r#"{"action":"install_package","atom":"steam","extra":1}"#).is_err()); + assert!(parse_action(r#"{"action":"install_package","atom":"notanatom"}"#).is_err()); + assert!(parse_action(r#"{"action":"enable_service","name":"bad name"}"#).is_err()); + } + + #[test] + fn natural_language_maps_to_typed_actions() { + assert_eq!( + parse_natural("enable sshd"), + Some(SystemAction::EnableService { name: "sshd".into() }) + ); + assert_eq!(parse_natural("history"), Some(SystemAction::History)); + assert_eq!( + parse_natural("install app-editors/vim"), + Some(SystemAction::InstallPackage { atom: "app-editors/vim".into() }) + ); + assert_eq!(parse_natural("why is my audio broken"), None); + } + + #[test] + fn risk_levels() { + assert_eq!(parse_action(r#"{"action":"history"}"#).unwrap().risk(), Risk::Low); + assert_eq!( + parse_action(r#"{"action":"update_system"}"#).unwrap().risk(), + Risk::High + ); + } +} diff --git a/installer-rs/crates/phoebus-core/src/config.rs b/installer-rs/crates/phoebus-core/src/config.rs new file mode 100644 index 0000000..b9b5caa --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/config.rs @@ -0,0 +1,644 @@ +//! Structured, strongly-typed installation configuration. +//! +//! Closed sets (filesystem, encryption, bootloader, kernel profile, package +//! policy, desktop profile) are enums. Free-form values (hostname, locale, +//! timezone, ...) are validated by `validate::validate`. +//! +//! Two input formats are supported during the Bash -> Rust migration: +//! * TOML (the native format) +//! * the legacy flat `KEY='value'` format used by the Bash prototype +//! +//! Secrets are never part of this structure. + +use std::path::{Path, PathBuf}; +use std::str::FromStr; + +use serde::{Deserialize, Deserializer, Serialize}; + +use crate::error::{CoreError, Result}; + +// --------------------------------------------------------------------------- +// Closed enums +// --------------------------------------------------------------------------- + +macro_rules! string_enum { + ($name:ident { $($variant:ident => $text:literal),+ $(,)? }) => { + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] + pub enum $name { + $(#[serde(rename = $text)] $variant),+ + } + + impl $name { + pub fn as_str(self) -> &'static str { + match self { $(Self::$variant => $text),+ } + } + } + + impl std::fmt::Display for $name { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.as_str()) + } + } + + impl FromStr for $name { + type Err = CoreError; + fn from_str(s: &str) -> Result { + match s { + $($text => Ok(Self::$variant),)+ + other => Err(CoreError::UnknownValue { + field: stringify!($name), + value: other.to_string(), + }), + } + } + } + }; +} + +string_enum!(Filesystem { Btrfs => "btrfs", Ext4 => "ext4" }); +string_enum!(Encryption { None => "none", Luks2 => "luks2" }); +string_enum!(Bootloader { SystemdBoot => "systemd-boot" }); +string_enum!(KernelProfile { Safe => "safe", Optimized => "optimized", Aggressive => "aggressive" }); +string_enum!(PackagePolicy { Balanced => "balanced", SourceFirst => "source_first", BinaryFirst => "binary_first" }); +string_enum!(DesktopProfile { None => "none", Minimal => "minimal", Dwl => "dwl", Full => "full" }); + +impl Bootloader { + pub fn default_systemd_boot() -> Self { + Bootloader::SystemdBoot + } +} + +// --------------------------------------------------------------------------- +// serde helper: accept either a string or a sequence of strings +// --------------------------------------------------------------------------- + +fn de_string_or_seq<'de, D>(deserializer: D) -> std::result::Result, D::Error> +where + D: Deserializer<'de>, +{ + #[derive(Deserialize)] + #[serde(untagged)] + enum StringOrVec { + One(String), + Many(Vec), + } + + let value = StringOrVec::deserialize(deserializer)?; + Ok(match value { + StringOrVec::One(s) => split_list(&s), + StringOrVec::Many(v) => v, + }) +} + +/// Split a whitespace- or comma-separated list, dropping empty items. +pub fn split_list(s: &str) -> Vec { + s.split(|c: char| c.is_whitespace() || c == ',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect() +} + +// --------------------------------------------------------------------------- +// Sections +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct SystemConfig { + pub distro_name: String, + pub distro_id: String, + pub arch: String, + pub hostname: String, + pub keymap: String, + pub locale: String, + pub timezone: String, + pub root_shell: String, + pub init_system: String, +} + +impl Default for SystemConfig { + fn default() -> Self { + Self { + distro_name: "Phoebus OS".into(), + distro_id: "phoebus".into(), + arch: "x86_64".into(), + hostname: "phoebus".into(), + keymap: "us".into(), + locale: "en_US.UTF-8".into(), + timezone: "UTC".into(), + root_shell: "/bin/bash".into(), + init_system: "systemd".into(), + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct UserConfig { + pub username: String, + pub fullname: String, + #[serde(deserialize_with = "de_string_or_seq")] + pub groups: Vec, + pub home: String, +} + +impl Default for UserConfig { + fn default() -> Self { + Self { + username: String::new(), + fullname: "Phoebus User".into(), + groups: split_list("wheel,audio,video,input,render,plugdev,libinput,network,power"), + home: "/home".into(), + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct StorageConfig { + pub disk: String, + pub partition_scheme: String, + pub efi_size_mib: u32, + pub efi_mount: String, + pub swap_size_mib: u32, + pub filesystem: Filesystem, + pub btrfs_label: String, + pub compress: String, + pub install_root: String, + #[serde(deserialize_with = "de_string_or_seq")] + pub subvols: Vec, +} + +impl Default for StorageConfig { + fn default() -> Self { + Self { + disk: String::new(), + partition_scheme: "whole_disk".into(), + efi_size_mib: 1024, + efi_mount: "/efi".into(), + swap_size_mib: 0, + filesystem: Filesystem::Btrfs, + btrfs_label: "phoebus".into(), + compress: "zstd:3".into(), + install_root: "/mnt/phoebus".into(), + subvols: split_list("@ @home @var @snapshots @swap"), + } + } +} + +impl StorageConfig { + /// The subvolume mounted at `/` (the first listed subvolume). + pub fn root_subvolume(&self) -> String { + self.subvols + .first() + .cloned() + .unwrap_or_else(|| "@".to_string()) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct EncryptionConfig { + pub mode: Encryption, + pub name: String, + pub cipher: String, + pub key_size: u32, + pub pbkdf: String, +} + +impl Default for EncryptionConfig { + fn default() -> Self { + Self { + mode: Encryption::Luks2, + name: "cryptroot".into(), + cipher: "aes-xts-plain64".into(), + key_size: 512, + pbkdf: "argon2id".into(), + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct Stage3Config { + pub url: String, + pub sha256: String, + pub mirror: String, + pub gentoo_profile: String, + pub binhost_uri: String, +} + +impl Default for Stage3Config { + fn default() -> Self { + Self { + url: String::new(), + sha256: String::new(), + mirror: "https://distfiles.gentoo.org/releases/amd64/autobuilds".into(), + gentoo_profile: "default/linux/amd64/23.0/systemd".into(), + binhost_uri: "https://distfiles.gentoo.org/releases/amd64/binpackages/23.0/x86-64" + .into(), + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct KernelConfig { + pub profile: KernelProfile, + pub package: String, + pub uki: bool, + pub console: String, + pub keep_kernels: u32, + pub secureboot: bool, +} + +impl Default for KernelConfig { + fn default() -> Self { + Self { + profile: KernelProfile::Optimized, + package: "sys-kernel/gentoo-kernel".into(), + uki: false, + console: "console=tty0".into(), + keep_kernels: 3, + secureboot: false, + } + } +} + +impl KernelConfig { + /// The kernel package the profile resolves to. + pub fn selected_package(&self) -> String { + match self.profile { + KernelProfile::Safe => "sys-kernel/gentoo-kernel-bin".to_string(), + KernelProfile::Optimized | KernelProfile::Aggressive => { + if self.package.is_empty() { + "sys-kernel/gentoo-kernel".to_string() + } else { + self.package.clone() + } + } + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct PackagesConfig { + pub policy: PackagePolicy, + pub binary_packages: bool, + pub accept_license: String, +} + +impl Default for PackagesConfig { + fn default() -> Self { + Self { + policy: PackagePolicy::Balanced, + binary_packages: true, + accept_license: "@FREE @BINARY-REDISTRIBUTABLE".into(), + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct DesktopConfig { + pub profile: DesktopProfile, + pub flatpak: bool, + pub audio_stack: String, +} + +impl Default for DesktopConfig { + fn default() -> Self { + Self { + profile: DesktopProfile::None, + flatpak: false, + audio_stack: "pipewire".into(), + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +#[serde(default)] +pub struct AiConfig { + pub enabled: bool, + pub provider: String, + pub model: String, + pub endpoint: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct RuntimeConfig { + pub dry_run: bool, + pub assume_yes: bool, + pub log_dir: String, + pub state_dir: String, +} + +impl Default for RuntimeConfig { + fn default() -> Self { + Self { + dry_run: false, + assume_yes: false, + log_dir: "/var/log/phoebus-installer".into(), + state_dir: "/run/phoebus-installer".into(), + } + } +} + +// --------------------------------------------------------------------------- +// Top level +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +#[serde(default)] +pub struct InstallConfig { + pub system: SystemConfig, + pub user: UserConfig, + pub storage: StorageConfig, + pub encryption: EncryptionConfig, + pub stage3: Stage3Config, + pub kernel: KernelConfig, + pub packages: PackagesConfig, + pub desktop: DesktopConfig, + pub ai: AiConfig, + pub runtime: RuntimeConfig, +} + +impl InstallConfig { + pub fn is_encrypted(&self) -> bool { + self.encryption.mode != Encryption::None + } + + pub fn target_disk(&self) -> &str { + &self.storage.disk + } + + /// Load a configuration from TOML or the legacy flat format. + /// + /// The legacy `KEY='value'` format is also *valid* TOML (single quotes are + /// TOML literal strings), so format must be detected structurally rather + /// than by attempting TOML first. + pub fn load_from_path(path: &Path) -> Result { + let text = std::fs::read_to_string(path) + .map_err(|e| CoreError::io(path.to_path_buf(), e))?; + if path.extension().and_then(|e| e.to_str()) == Some("toml") { + return Self::from_toml(&text); + } + if looks_like_legacy(&text) { + return Self::from_legacy(&text); + } + Self::from_toml(&text) + } + + pub fn from_toml(text: &str) -> Result { + let cfg: InstallConfig = toml::from_str(text)?; + Ok(cfg) + } + + pub fn to_toml_string(&self) -> Result { + Ok(toml::to_string_pretty(self)?) + } + + /// Parse the Bash prototype's flat `KEY='value'` configuration format. + pub fn from_legacy(text: &str) -> Result { + let mut cfg = InstallConfig::default(); + for raw_line in text.lines() { + let line = raw_line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let Some((key, value)) = line.split_once('=') else { + continue; + }; + let key = key.trim(); + let value = unquote(value.trim()); + cfg.apply_legacy_kv(key, &value)?; + } + Ok(cfg) + } + + fn apply_legacy_kv(&mut self, key: &str, value: &str) -> Result<()> { + match key { + "DISTRO_NAME" => self.system.distro_name = value.into(), + "DISTRO_ID" => self.system.distro_id = value.into(), + "ARCH" => self.system.arch = value.into(), + "HOSTNAME" => self.system.hostname = value.into(), + "KEYMAP" => self.system.keymap = value.into(), + "LOCALE" => self.system.locale = value.into(), + "TIMEZONE" => self.system.timezone = value.into(), + "ROOT_SHELL" => self.system.root_shell = value.into(), + "INIT_SYSTEM" => self.system.init_system = value.into(), + + "USERNAME" => self.user.username = value.into(), + "USER_FULLNAME" => self.user.fullname = value.into(), + "USER_GROUPS" => self.user.groups = split_list(value), + "USER_HOME" => self.user.home = value.into(), + + "TARGET_DISK" => self.storage.disk = value.into(), + "PARTITION_SCHEME" => self.storage.partition_scheme = value.into(), + "EFI_SIZE_MIB" => self.storage.efi_size_mib = parse_num(key, value)?, + "EFI_MOUNT" => self.storage.efi_mount = value.into(), + "SWAP_SIZE_MIB" => self.storage.swap_size_mib = parse_num(key, value)?, + "FILESYSTEM" => self.storage.filesystem = Filesystem::from_str(value)?, + "BTRFS_LABEL" => self.storage.btrfs_label = value.into(), + "COMPRESS" => self.storage.compress = value.into(), + "INSTALL_ROOT" => self.storage.install_root = value.into(), + "BTRFS_SUBVOLS" => self.storage.subvols = split_list(value), + + "ENCRYPTION" => self.encryption.mode = Encryption::from_str(value)?, + "LUKS_NAME" => self.encryption.name = value.into(), + "LUKS_CIPHER" => self.encryption.cipher = value.into(), + "LUKS_KEY_SIZE" => self.encryption.key_size = parse_num(key, value)?, + "LUKS_PBKDF" => self.encryption.pbkdf = value.into(), + + "STAGE3_URL" => self.stage3.url = value.into(), + "STAGE3_SHA256" => self.stage3.sha256 = value.into(), + "STAGE3_MIRROR" => self.stage3.mirror = value.into(), + "GENTOO_PROFILE" => self.stage3.gentoo_profile = value.into(), + "BINHOST_URI" => self.stage3.binhost_uri = value.into(), + + "BOOTLOADER" => { + // Bootloader is currently fixed to systemd-boot; validate value. + let _ = Bootloader::from_str(value)?; + } + "KERNEL_PROFILE" => self.kernel.profile = KernelProfile::from_str(value)?, + "KERNEL_PACKAGE" => self.kernel.package = value.into(), + "KERNEL_UKI" => self.kernel.uki = parse_bool(value), + "KERNEL_CONSOLE" => self.kernel.console = value.into(), + "KEEP_KERNELS" => self.kernel.keep_kernels = parse_num(key, value)?, + "SECUREBOOT" => self.kernel.secureboot = parse_bool(value), + + "PACKAGE_POLICY" => self.packages.policy = PackagePolicy::from_str(value)?, + "FEATURES_BINPKG" => self.packages.binary_packages = parse_bool(value), + "ACCEPT_LICENSE" => self.packages.accept_license = value.into(), + + "DESKTOP_PROFILE" => self.desktop.profile = DesktopProfile::from_str(value)?, + "FLATPAK" => self.desktop.flatpak = parse_bool(value), + "AUDIO_STACK" => self.desktop.audio_stack = value.into(), + + "AI_ENABLED" => self.ai.enabled = parse_bool(value), + "AI_PROVIDER" => self.ai.provider = value.into(), + "AI_MODEL" => self.ai.model = value.into(), + "AI_ENDPOINT" => self.ai.endpoint = value.into(), + + "DRY_RUN" => self.runtime.dry_run = parse_bool(value), + "ASSUME_YES" => self.runtime.assume_yes = parse_bool(value), + "LOG_DIR" => self.runtime.log_dir = value.into(), + + // Ignored legacy keys (not part of the Rust model yet). + _ => {} + } + Ok(()) + } +} + +/// True when the text looks like the Bash prototype's flat `KEY='value'` file. +fn looks_like_legacy(text: &str) -> bool { + for raw in text.lines() { + let line = raw.trim(); + if line.is_empty() || line.starts_with('#') || line.starts_with('[') { + continue; + } + if line.contains('=') { + let key = line.split('=').next().unwrap().trim(); + if !key.is_empty() + && key + .chars() + .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_') + { + return true; + } + } + } + false +} + +fn parse_bool(value: &str) -> bool { + matches!( + value.trim().to_ascii_lowercase().as_str(), + "yes" | "true" | "1" | "on" | "y" + ) +} + +fn parse_num(field: &str, value: &str) -> Result { + value.trim().parse::().map_err(|_| { + CoreError::Config(format!("{field} must be a positive integer, got `{value}`")) + }) +} + +fn unquote(value: &str) -> String { + let bytes = value.as_bytes(); + if bytes.len() >= 2 + && ((bytes[0] == b'\'' && bytes[bytes.len() - 1] == b'\'') + || (bytes[0] == b'"' && bytes[bytes.len() - 1] == b'"')) + { + value[1..value.len() - 1].to_string() + } else { + value.to_string() + } +} + +/// The install root as a path. +impl StorageConfig { + pub fn install_root_path(&self) -> PathBuf { + PathBuf::from(&self.install_root) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn defaults_match_bash_baseline() { + let c = InstallConfig::default(); + assert_eq!(c.system.hostname, "phoebus"); + assert_eq!(c.user.groups.len(), 9); + assert_eq!(c.storage.filesystem, Filesystem::Btrfs); + assert_eq!(c.encryption.mode, Encryption::Luks2); + assert_eq!(c.encryption.name, "cryptroot"); + assert_eq!(c.stage3.binhost_uri.contains("binpackages"), true); + assert_eq!(c.kernel.console, "console=tty0"); + assert!(c.packages.binary_packages); + assert!(!c.packages.policy.eq(&PackagePolicy::SourceFirst)); + } + + #[test] + fn legacy_config_parses_flat_keys() { + let text = "\ +HOSTNAME='testbox'\n\ +USERNAME='alice'\n\ +USER_GROUPS=\"wheel,audio,video\"\n\ +TARGET_DISK='/dev/vda'\n\ +ENCRYPTION='luks2'\n\ +FILESYSTEM='btrfs'\n\ +KERNEL_PROFILE='safe'\n\ +DESKTOP_PROFILE='none'\n\ +STAGE3_URL='http://10.0.2.2:8000/stage3.tar.xz'\n\ +STAGE3_SHA256='abc'\n"; + let c = InstallConfig::from_legacy(text).unwrap(); + assert_eq!(c.system.hostname, "testbox"); + assert_eq!(c.user.username, "alice"); + assert_eq!(c.user.groups, vec!["wheel", "audio", "video"]); + assert_eq!(c.storage.disk, "/dev/vda"); + assert_eq!(c.kernel.profile, KernelProfile::Safe); + assert_eq!(c.kernel.selected_package(), "sys-kernel/gentoo-kernel-bin"); + assert_eq!(c.stage3.url, "http://10.0.2.2:8000/stage3.tar.xz"); + } + + #[test] + fn toml_roundtrip() { + let mut c = InstallConfig::default(); + c.system.hostname = "box".into(); + c.storage.subvols = vec!["@".into(), "@home".into()]; + c.desktop.profile = DesktopProfile::Dwl; + let text = c.to_toml_string().unwrap(); + // The deserializer accepts a bare string for list fields too. + let back = InstallConfig::from_toml(&text).unwrap(); + assert_eq!(back.system.hostname, "box"); + assert_eq!(back.storage.subvols, vec!["@", "@home"]); + assert_eq!(back.desktop.profile, DesktopProfile::Dwl); + } + + #[test] + fn toml_accepts_string_lists() { + let text = "\ +[user]\ngroups = \"wheel,audio\"\n\ +[storage]\nsubvols = \"@ @home @var\"\n"; + let c = InstallConfig::from_toml(text).unwrap(); + assert_eq!(c.user.groups, vec!["wheel", "audio"]); + assert_eq!(c.storage.subvols, vec!["@", "@home", "@var"]); + } + + #[test] + fn load_from_path_detects_legacy_format() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("test.conf"); + std::fs::write( + &path, + "HOSTNAME='box'\nTARGET_DISK='/dev/vda'\nKERNEL_PROFILE='safe'\n", + ) + .unwrap(); + let c = InstallConfig::load_from_path(&path).unwrap(); + assert_eq!(c.system.hostname, "box"); + assert_eq!(c.storage.disk, "/dev/vda"); + assert_eq!(c.kernel.profile, KernelProfile::Safe); + } + + #[test] + fn load_from_path_parses_toml() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("test.toml"); + std::fs::write(&path, "[system]\nhostname = \"tomlbox\"\n").unwrap(); + let c = InstallConfig::load_from_path(&path).unwrap(); + assert_eq!(c.system.hostname, "tomlbox"); + } + + #[test] + fn unknown_enum_value_is_rejected() { + let text = "[storage]\nfilesystem = \"zfs\"\n"; + assert!(InstallConfig::from_toml(text).is_err()); + } +} diff --git a/installer-rs/crates/phoebus-core/src/disk.rs b/installer-rs/crates/phoebus-core/src/disk.rs new file mode 100644 index 0000000..30d5eb5 --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/disk.rs @@ -0,0 +1,190 @@ +//! Disk model and protection classification. +//! +//! Protection is a pure function of observed facts so it can be unit tested +//! without touching a real system. The reference behavior protects the live +//! medium (`/dev/sr0` in the proven VM), mounted disks, read-only devices, +//! optical/loop/device-mapper nodes, and non-disk classes. + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum DiskKind { + Physical, + Optical, + Loop, + DeviceMapper, + Other, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ProtectionReason { + ReadOnly, + NotAWholeDisk(DiskKind), + MountedFilesystems, + LiveMedium, + NonBlockDevice, +} + +impl ProtectionReason { + pub fn describe(&self) -> String { + match self { + ProtectionReason::ReadOnly => "read-only device".into(), + ProtectionReason::NotAWholeDisk(kind) => format!("not a whole disk ({kind:?})"), + ProtectionReason::MountedFilesystems => "contains mounted filesystems".into(), + ProtectionReason::LiveMedium => "live installation medium".into(), + ProtectionReason::NonBlockDevice => "not a block device".into(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Disk { + pub path: String, + pub model: Option, + pub size_bytes: u64, + pub transport: Option, + pub removable: bool, + pub read_only: bool, + pub mounted: bool, + pub is_block_device: bool, + pub kind: DiskKind, + pub live_media: bool, +} + +impl Disk { + /// Protection reason, in the same order as the proven Bash implementation. + pub fn protection(&self) -> Option { + if !self.is_block_device { + return Some(ProtectionReason::NonBlockDevice); + } + if self.read_only { + return Some(ProtectionReason::ReadOnly); + } + match self.kind { + DiskKind::Optical | DiskKind::Loop | DiskKind::DeviceMapper => { + return Some(ProtectionReason::NotAWholeDisk(self.kind)); + } + _ => {} + } + if self.mounted { + return Some(ProtectionReason::MountedFilesystems); + } + if self.live_media { + return Some(ProtectionReason::LiveMedium); + } + None + } + + pub fn is_protected(&self) -> bool { + self.protection().is_some() + } + + pub fn size_human(&self) -> String { + human_bytes(self.size_bytes) + } + + pub fn display_line(&self) -> String { + let flag = match self.protection() { + Some(reason) => format!(" [PROTECTED: {}]", reason.describe()), + None => String::new(), + }; + format!( + "{:<16} {:>8} {:<8} {}{}", + self.path, + self.size_human(), + self.transport.clone().unwrap_or_else(|| "?".into()), + self.model.clone().unwrap_or_else(|| "disk".into()), + flag + ) + } +} + +/// Format bytes using binary (IEC) units, e.g. `30.0 GiB`. +pub fn human_bytes(bytes: u64) -> String { + const UNITS: [&str; 6] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]; + if bytes == 0 { + return "0 B".into(); + } + let mut value = bytes as f64; + let mut unit = 0; + while value >= 1024.0 && unit + 1 < UNITS.len() { + value /= 1024.0; + unit += 1; + } + if unit == 0 { + format!("{bytes} B") + } else { + format!("{value:.1} {}", UNITS[unit]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn physical() -> Disk { + Disk { + path: "/dev/vda".into(), + model: Some("QEMU HARDDISK".into()), + size_bytes: 30 * 1024 * 1024 * 1024, + transport: Some("virtio".into()), + removable: false, + read_only: false, + mounted: false, + is_block_device: true, + kind: DiskKind::Physical, + live_media: false, + } + } + + #[test] + fn clean_target_is_unprotected() { + assert!(physical().protection().is_none()); + } + + #[test] + fn optical_live_media_is_protected() { + let mut d = physical(); + d.path = "/dev/sr0".into(); + d.kind = DiskKind::Optical; + d.live_media = true; + assert!(d.is_protected()); + assert!(matches!( + d.protection(), + Some(ProtectionReason::NotAWholeDisk(DiskKind::Optical)) + )); + } + + #[test] + fn mounted_is_protected() { + let mut d = physical(); + d.mounted = true; + assert_eq!(d.protection(), Some(ProtectionReason::MountedFilesystems)); + } + + #[test] + fn read_only_wins() { + let mut d = physical(); + d.read_only = true; + d.mounted = true; + assert_eq!(d.protection(), Some(ProtectionReason::ReadOnly)); + } + + #[test] + fn loop_and_dm_are_protected() { + for kind in [DiskKind::Loop, DiskKind::DeviceMapper] { + let mut d = physical(); + d.kind = kind; + assert!(d.is_protected()); + } + } + + #[test] + fn human_bytes_formats() { + assert_eq!(human_bytes(0), "0 B"); + assert_eq!(human_bytes(1024), "1.0 KiB"); + assert_eq!(human_bytes(30 * 1024 * 1024 * 1024), "30.0 GiB"); + } +} diff --git a/installer-rs/crates/phoebus-core/src/emergelog.rs b/installer-rs/crates/phoebus-core/src/emergelog.rs new file mode 100644 index 0000000..cb12e9e --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/emergelog.rs @@ -0,0 +1,108 @@ +//! Parser for Portage's `emerge.log`, used to record *measured* compile times. +//! +//! Portage writes lines of the form: +//! +//! ```text +//! 1650000000: >>> emerge (1 of 3) sys-fs/cryptsetup-2.7.5 to / +//! 1650000060: ::: completed emerge (1 of 3) sys-fs/cryptsetup-2.7.5 to / +//! ``` +//! +//! We derive a duration per atom. Nothing here guesses: if no data exists, no +//! entry is recorded. + +/// Remove the version suffix from `category/package-version`. +pub fn atom_from_cpv(cpv: &str) -> String { + // Find the last '-' followed by a digit, which starts the version. + let bytes = cpv.as_bytes(); + let mut split = None; + for i in (0..bytes.len()).rev() { + if bytes[i] == b'-' && i + 1 < bytes.len() && bytes[i + 1].is_ascii_digit() { + split = Some(i); + break; + } + } + match split { + Some(i) => cpv[..i].to_string(), + None => cpv.to_string(), + } +} + +fn epoch(line: &str) -> Option { + let colon = line.find(':')?; + line[..colon].trim().parse::().ok() +} + +/// Extract (atom, seconds) pairs from an emerge.log. +pub fn parse_emerge_log(text: &str) -> Vec<(String, u64)> { + use std::collections::HashMap; + let mut starts: HashMap = HashMap::new(); + let mut out: Vec<(String, u64)> = Vec::new(); + + for line in text.lines() { + if let Some(rest) = line.split(">>> emerge (").nth(1) { + // rest: "1 of 3) sys-fs/cryptsetup-2.7.5 to /" + if let Some(cpv) = extract_cpv(rest) { + if let Some(ts) = epoch(line) { + starts.insert(atom_from_cpv(&cpv), ts); + } + } + } else if let Some(rest) = line.split("::: completed emerge (").nth(1) { + if let Some(cpv) = extract_cpv(rest) { + if let Some(ts) = epoch(line) { + let atom = atom_from_cpv(&cpv); + if let Some(start) = starts.remove(&atom) { + if ts >= start { + out.push((atom, ts - start)); + } + } + } + } + } + } + out +} + +/// The CPV token follows ") " and precedes " to ". +fn extract_cpv(rest: &str) -> Option { + let after = rest.split_once(')')?.1.trim_start(); + let token = after.split_whitespace().next()?; + if token.is_empty() { + None + } else { + Some(token.to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strips_versions_with_hyphenated_names() { + assert_eq!(atom_from_cpv("sys-fs/cryptsetup-2.7.5"), "sys-fs/cryptsetup"); + assert_eq!(atom_from_cpv("app-editors/vim-9.1.1234"), "app-editors/vim"); + assert_eq!( + atom_from_cpv("dev-lang/python-exec-conf-2.4.6"), + "dev-lang/python-exec-conf" + ); + } + + #[test] + fn computes_durations() { + let log = "\ +1650000000: >>> emerge (1 of 2) sys-fs/cryptsetup-2.7.5 to / +1650000042: ::: completed emerge (1 of 2) sys-fs/cryptsetup-2.7.5 to / +1650000042: >>> emerge (2 of 2) sys-fs/btrfs-progs-6.5 to / +1650000170: ::: completed emerge (2 of 2) sys-fs/btrfs-progs-6.5 to / +"; + let parsed = parse_emerge_log(log); + assert!(parsed.contains(&("sys-fs/cryptsetup".to_string(), 42))); + assert!(parsed.contains(&("sys-fs/btrfs-progs".to_string(), 128))); + } + + #[test] + fn ignores_incomplete_entries() { + let log = "1650000000: >>> emerge (1 of 1) sys-apps/foo-1.0 to /\n"; + assert!(parse_emerge_log(log).is_empty()); + } +} diff --git a/installer-rs/crates/phoebus-core/src/error.rs b/installer-rs/crates/phoebus-core/src/error.rs new file mode 100644 index 0000000..c5b2aee --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/error.rs @@ -0,0 +1,45 @@ +//! Core error types. +//! +//! Errors carry enough context to be useful in a log without ever containing +//! secret material. Secrets are never stored in an error. + +use std::path::PathBuf; + +pub type Result = std::result::Result; + +#[derive(Debug, thiserror::Error)] +pub enum CoreError { + #[error("validation failed: {0}")] + Validation(String), + + #[error("invalid configuration: {0}")] + Config(String), + + #[error("unknown value `{value}` for {field}")] + UnknownValue { field: &'static str, value: String }, + + #[error("I/O error for {path}: {source}")] + Io { + path: PathBuf, + #[source] + source: std::io::Error, + }, + + #[error("I/O error: {0}")] + PlainIo(#[from] std::io::Error), + + #[error("TOML parse error: {0}")] + Toml(#[from] toml::de::Error), + + #[error("TOML serialization error: {0}")] + TomlSer(#[from] toml::ser::Error), +} + +impl CoreError { + pub fn io(path: impl Into, source: std::io::Error) -> Self { + CoreError::Io { + path: path.into(), + source, + } + } +} diff --git a/installer-rs/crates/phoebus-core/src/hardware.rs b/installer-rs/crates/phoebus-core/src/hardware.rs new file mode 100644 index 0000000..6ccf9bf --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/hardware.rs @@ -0,0 +1,239 @@ +//! Structured hardware model. +//! +//! These types are populated by read-only probing in `phoebus-executor` and +//! rendered into a human report here. Probing never mutates the system. + +use serde::{Deserialize, Serialize}; + +use crate::config::KernelProfile; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum FirmwareMode { + Uefi, + Bios, +} + +impl FirmwareMode { + pub fn as_str(self) -> &'static str { + match self { + FirmwareMode::Uefi => "UEFI", + FirmwareMode::Bios => "BIOS", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum GpuVendor { + Intel, + Amd, + Nvidia, + Unknown, +} + +impl GpuVendor { + pub fn as_str(self) -> &'static str { + match self { + GpuVendor::Intel => "intel", + GpuVendor::Amd => "amd", + GpuVendor::Nvidia => "nvidia", + GpuVendor::Unknown => "unknown", + } + } +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct CpuInfo { + pub vendor: String, + pub model: String, + pub threads: u32, + pub cores: u32, + pub features: Vec, +} + +impl CpuInfo { + pub fn has_feature(&self, feature: &str) -> bool { + self.features.iter().any(|f| f == feature) + } + + pub fn virt_summary(&self) -> String { + let mut out = Vec::new(); + if self.has_feature("vmx") { + out.push("Intel VT-x"); + } + if self.has_feature("svm") { + out.push("AMD-V"); + } + if self.has_feature("avx2") { + out.push("AVX2"); + } + if self.has_feature("avx512f") { + out.push("AVX-512"); + } + if self.has_feature("aes") { + out.push("AES-NI"); + } + out.join(" ") + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct GpuInfo { + pub vendor: GpuVendor, + pub description: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct NetworkDevice { + pub name: String, + pub wireless: bool, + pub operstate: String, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct HardwareReport { + pub firmware: Option, + pub cpu: CpuInfo, + pub memory_mib: u64, + pub gpus: Vec, + pub network: Vec, + pub storage_controllers: Vec, + pub audio: Vec, + pub bluetooth: Vec, + pub usb_controllers: Vec, + pub input_devices: u32, + pub laptop: bool, +} + +impl HardwareReport { + pub fn firmware_str(&self) -> &'static str { + match self.firmware { + Some(FirmwareMode::Uefi) => "UEFI", + Some(FirmwareMode::Bios) => "BIOS", + None => "unknown", + } + } + + pub fn gpu_vendors(&self) -> Vec { + let mut out: Vec = Vec::new(); + for gpu in &self.gpus { + if !out.contains(&gpu.vendor) { + out.push(gpu.vendor); + } + } + if out.is_empty() { + out.push(GpuVendor::Unknown); + } + out + } + + /// Deterministic, conservative recommendation. + pub fn recommended_kernel_profile(&self) -> KernelProfile { + if self.memory_mib > 0 && self.memory_mib < 2048 { + KernelProfile::Safe + } else { + KernelProfile::Optimized + } + } + + fn section(title: &str, lines: &[String]) -> String { + let mut out = format!("{title}:\n"); + if lines.is_empty() { + out.push_str(" (none detected)\n"); + } else { + for l in lines { + out.push_str(" "); + out.push_str(l); + out.push('\n'); + } + } + out.push('\n'); + out + } + + pub fn render(&self) -> String { + let mut out = String::new(); + out.push_str(&format!("Firmware: {}\n", self.firmware_str())); + out.push_str(&format!("CPU: {}\n", self.cpu.model)); + out.push_str(&format!( + "CPU cores: {} threads / {} logical CPUs\n", + self.cpu.threads, self.cpu.cores + )); + let virt = self.cpu.virt_summary(); + out.push_str(&format!( + "CPU features: {}\n", + if virt.is_empty() { "none detected" } else { &virt } + )); + out.push_str(&format!("Memory: {} MiB\n", self.memory_mib)); + out.push_str(&format!( + "Machine type: {}\n", + if self.laptop { "laptop" } else { "desktop/server" } + )); + out.push_str(&format!("Input devices: {}\n\n", self.input_devices)); + + let gpus: Vec = self + .gpus + .iter() + .map(|g| g.description.clone()) + .collect(); + out.push_str(&Self::section("GPUs", &gpus)); + out.push_str(&Self::section("Storage controllers", &self.storage_controllers)); + let net: Vec = self + .network + .iter() + .map(|n| { + format!( + "{} {} {}", + n.name, + if n.wireless { "wireless" } else { "wired" }, + n.operstate + ) + }) + .collect(); + out.push_str(&Self::section("Network", &net)); + out.push_str(&Self::section("Bluetooth", &self.bluetooth)); + out.push_str(&Self::section("Audio", &self.audio)); + out.push_str(&Self::section("USB controllers", &self.usb_controllers)); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn low_memory_recommends_safe() { + let mut hw = HardwareReport::default(); + hw.memory_mib = 1024; + assert_eq!(hw.recommended_kernel_profile(), KernelProfile::Safe); + hw.memory_mib = 8192; + assert_eq!(hw.recommended_kernel_profile(), KernelProfile::Optimized); + } + + #[test] + fn gpu_vendor_dedup_and_default() { + let mut hw = HardwareReport::default(); + hw.gpus = vec![ + GpuInfo { vendor: GpuVendor::Intel, description: "iGPU".into() }, + GpuInfo { vendor: GpuVendor::Intel, description: "iGPU2".into() }, + GpuInfo { vendor: GpuVendor::Nvidia, description: "dGPU".into() }, + ]; + assert_eq!(hw.gpu_vendors(), vec![GpuVendor::Intel, GpuVendor::Nvidia]); + + let empty = HardwareReport::default(); + assert_eq!(empty.gpu_vendors(), vec![GpuVendor::Unknown]); + } + + #[test] + fn cpu_feature_probe() { + let cpu = CpuInfo { + features: vec!["aes".into(), "avx2".into()], + ..Default::default() + }; + assert!(cpu.has_feature("aes")); + assert!(!cpu.has_feature("svm")); + assert!(cpu.virt_summary().contains("AVX2")); + } +} diff --git a/installer-rs/crates/phoebus-core/src/lib.rs b/installer-rs/crates/phoebus-core/src/lib.rs new file mode 100644 index 0000000..84dee06 --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/lib.rs @@ -0,0 +1,39 @@ +//! Phoebus core: strongly-typed configuration, hardware/disk models, package +//! policy, validation, plan generation and target-root safety. +//! +//! Nothing in this crate executes external commands or touches disks. + +pub mod action; +pub mod config; +pub mod disk; +pub mod emergelog; +pub mod error; +pub mod hardware; +pub mod plan; +pub mod policy; +pub mod secret; +pub mod snapshot; +pub mod system; +pub mod target; +pub mod update; +pub mod validate; + +pub use config::{ + Bootloader, DesktopConfig, DesktopProfile, Encryption, EncryptionConfig, Filesystem, + InstallConfig, KernelConfig, KernelProfile, PackagesConfig, PackagePolicy, Stage3Config, + StorageConfig, SystemConfig, UserConfig, +}; +pub use disk::{Disk, DiskKind, ProtectionReason}; +pub use error::{CoreError, Result}; +pub use hardware::{CpuInfo, FirmwareMode, GpuInfo, GpuVendor, HardwareReport, NetworkDevice}; +pub use plan::{InstallPlan, InstallStep}; +pub use policy::{ + append_history, load_history, InstallMethod, PackageDecision, PackageDecisionReason, + PackagePolicyEngine, PolicyContext, +}; +pub use secret::{Redactor, SecretString}; +pub use target::TargetRoot; +pub use validate::{password_strength, validate_config, ValidationIssue}; + +/// Version string shared by the CLI and logs. +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/installer-rs/crates/phoebus-core/src/plan.rs b/installer-rs/crates/phoebus-core/src/plan.rs new file mode 100644 index 0000000..b3bffba --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/plan.rs @@ -0,0 +1,228 @@ +//! Structured installation plan. +//! +//! The plan is canonical data. The human-readable rendering is derived from it, +//! so the review screen, the destructive confirmation, dry-run and the actual +//! execution all describe the same thing. + +use serde::{Deserialize, Serialize}; + +use crate::config::{InstallConfig, KernelProfile}; +use crate::hardware::HardwareReport; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum InstallStep { + StoragePrepare, + StageInstall, + FstabGenerate, + PortageConfigure, + PackagesBase, + KernelInstall, + BootInstall, + UsersConfigure, + ServicesConfigure, + DesktopInstall, + Finalize, +} + +impl InstallStep { + pub fn name(self) -> &'static str { + match self { + InstallStep::StoragePrepare => "storage_prepare", + InstallStep::StageInstall => "stage_install", + InstallStep::FstabGenerate => "fstab_generate", + InstallStep::PortageConfigure => "portage_configure", + InstallStep::PackagesBase => "packages_base", + InstallStep::KernelInstall => "kernel_install", + InstallStep::BootInstall => "boot_install", + InstallStep::UsersConfigure => "users_configure", + InstallStep::ServicesConfigure => "services_configure", + InstallStep::DesktopInstall => "desktop_install", + InstallStep::Finalize => "finalize", + } + } + + /// The proven order. Do not reorder without understanding the fstab and + /// subvolume ordering constraints documented in VM-BOOT-VERIFICATION.md. + pub fn sequence() -> Vec { + vec![ + InstallStep::StoragePrepare, + InstallStep::StageInstall, + InstallStep::FstabGenerate, + InstallStep::PortageConfigure, + InstallStep::PackagesBase, + InstallStep::KernelInstall, + InstallStep::BootInstall, + InstallStep::UsersConfigure, + InstallStep::ServicesConfigure, + InstallStep::DesktopInstall, + InstallStep::Finalize, + ] + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct InstallPlan { + pub steps: Vec, +} + +impl InstallPlan { + pub fn for_config(_config: &InstallConfig) -> Self { + Self { + steps: InstallStep::sequence(), + } + } + + pub fn render_human(&self, config: &InstallConfig, hardware: Option<&HardwareReport>) -> String { + let mut o = String::new(); + let enc = config.encryption.mode.as_str(); + let fs = config.storage.filesystem.as_str(); + let firmware = hardware.map(|h| h.firmware_str()).unwrap_or("unknown"); + let kernel_pkg = config.kernel.selected_package(); + + o.push_str("Installation plan\n"); + o.push_str("=================\n\n"); + o.push_str("System:\n"); + o.push_str(&format!(" Distribution : {}\n", config.system.distro_name)); + o.push_str(&format!(" Architecture : {}\n", config.system.arch)); + o.push_str(&format!(" Init system : {}\n", config.system.init_system)); + o.push_str(&format!(" Firmware : {firmware}\n\n")); + + o.push_str("Identity:\n"); + o.push_str(&format!(" Hostname : {}\n", config.system.hostname)); + o.push_str(&format!(" Keymap : {}\n", config.system.keymap)); + o.push_str(&format!(" Locale : {}\n", config.system.locale)); + o.push_str(&format!(" Timezone : {}\n", config.system.timezone)); + let user = if config.user.username.is_empty() { + "" + } else { + &config.user.username + }; + o.push_str(&format!(" User : {user}\n\n")); + + o.push_str("Storage:\n"); + let disk = if config.storage.disk.is_empty() { + "".to_string() + } else { + config.storage.disk.clone() + }; + o.push_str(&format!(" Target disk : {disk}\n")); + o.push_str(&format!( + " Partitioning : GPT ({})\n", + config.storage.partition_scheme + )); + o.push_str(&format!(" Encryption : {enc}\n")); + o.push_str(&format!(" Filesystem : {fs}\n\n")); + o.push_str(" Layout:\n"); + o.push_str(&format!( + " EFI System Partition (FAT32) {} MiB -> {}\n", + config.storage.efi_size_mib, config.storage.efi_mount + )); + o.push_str(&format!(" {:<36} remainder\n", format!("{enc} container"))); + o.push_str(&format!(" {:<34}\n", fs)); + for sv in &config.storage.subvols { + o.push_str(&format!(" {sv}\n")); + } + o.push('\n'); + + o.push_str("Boot and kernel:\n"); + o.push_str(&format!(" Bootloader : {} (BLS entries)\n", "systemd-boot")); + o.push_str(&format!( + " Unified UKI : {} (deferred; BLS used)\n", + if config.kernel.uki { "yes" } else { "no" } + )); + let profile = match config.kernel.profile { + KernelProfile::Safe => "safe", + KernelProfile::Optimized => "optimized", + KernelProfile::Aggressive => "aggressive", + }; + o.push_str(&format!(" Kernel : {kernel_pkg} ({profile} profile)\n")); + o.push_str(&format!(" Keep kernels : {}\n\n", config.kernel.keep_kernels)); + + o.push_str("Software:\n"); + o.push_str(&format!(" Package policy : {}\n", config.packages.policy)); + o.push_str(&format!( + " Binary pkgs : {}\n", + if config.packages.binary_packages { "yes" } else { "no" } + )); + o.push_str(&format!(" Accept license : {}\n", config.packages.accept_license)); + o.push_str(&format!(" Desktop : {}\n", config.desktop.profile)); + o.push_str(&format!( + " Flatpak : {}\n", + if config.desktop.flatpak { "yes" } else { "no" } + )); + o.push_str(&format!(" Audio : {}\n", config.desktop.audio_stack)); + o.push_str(&format!( + " AI assistant : {}\n", + if config.ai.enabled { "yes" } else { "no" } + )); + o + } + + pub fn destructive_preview(&self, config: &InstallConfig, disk_layout: &str) -> String { + let mut o = String::new(); + o.push_str(&format!("TARGET: {}\n\n", config.storage.disk)); + o.push_str("ALL DATA ON THIS DEVICE WILL BE DESTROYED.\n"); + o.push_str("This cannot be undone.\n\n"); + o.push_str(&format!( + " EFI (FAT32): {} MiB\n", + config.storage.efi_size_mib + )); + if config.is_encrypted() { + o.push_str(&format!( + " {} (passphrase): remainder\n", + config.encryption.mode.as_str().to_uppercase() + )); + } + o.push_str(&format!(" {}:\n", config.storage.filesystem.as_str())); + for sv in &config.storage.subvols { + o.push_str(&format!(" {sv}\n")); + } + o.push_str("\nExisting partitions on the target:\n"); + for line in disk_layout.lines() { + o.push_str(" "); + o.push_str(line); + o.push('\n'); + } + o + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sequence_matches_proven_order() { + let names: Vec<&str> = InstallStep::sequence().iter().map(|s| s.name()).collect(); + assert_eq!(names[0], "storage_prepare"); + assert_eq!(names[1], "stage_install"); + assert_eq!(names[2], "fstab_generate"); + assert_eq!(names[3], "portage_configure"); + assert_eq!(names[names.len() - 1], "finalize"); + } + + #[test] + fn render_contains_key_facts() { + let mut cfg = InstallConfig::default(); + cfg.system.hostname = "phoebus-test".into(); + cfg.user.username = "tester".into(); + cfg.storage.disk = "/dev/vda".into(); + let plan = InstallPlan::for_config(&cfg); + let text = plan.render_human(&cfg, None); + assert!(text.contains("Installation plan")); + assert!(text.contains("phoebus-test")); + assert!(text.contains("@snapshots")); + assert!(text.contains("luks2")); + } + + #[test] + fn destructive_preview_warns_loudly() { + let mut cfg = InstallConfig::default(); + cfg.storage.disk = "/dev/vda".into(); + let text = InstallPlan::for_config(&cfg).destructive_preview(&cfg, "NAME SIZE\nvda 30G"); + assert!(text.contains("ALL DATA ON THIS DEVICE WILL BE DESTROYED.")); + assert!(text.contains("TARGET: /dev/vda")); + assert!(text.contains("vda 30G")); + } +} diff --git a/installer-rs/crates/phoebus-core/src/policy.rs b/installer-rs/crates/phoebus-core/src/policy.rs new file mode 100644 index 0000000..3355014 --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/policy.rs @@ -0,0 +1,350 @@ +//! Deterministic source-versus-binary package policy. +//! +//! The rule is: +//! * cheap compiles are done from source; +//! * packages where local compilation or USE customisation matters are +//! compiled; +//! * expensive packages with negligible practical benefit use a signed +//! Gentoo binary when one is available. +//! +//! Decisions are deterministic and never consult a model. Measured compile +//! times can override the built-in estimates. + +use std::collections::{HashMap, HashSet}; + +use serde::{Deserialize, Serialize}; + +use crate::config::PackagePolicy; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum InstallMethod { + Source, + Binary, +} + +impl InstallMethod { + pub fn as_str(self) -> &'static str { + match self { + InstallMethod::Source => "source", + InstallMethod::Binary => "binary", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PackageDecisionReason { + CheapCompile, + RequiredUseFlags, + NativeOptimizationBenefit, + HighBuildCostLowBenefit, + BinaryUnavailable, + UserPreference, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct PackageDecision { + pub method: InstallMethod, + pub reason: PackageDecisionReason, + pub estimated_seconds: u64, +} + +pub struct PolicyContext { + pub policy: PackagePolicy, + pub binhost_available: bool, + pub memory_mib: u64, + pub cores: u32, +} + +pub struct PackagePolicyEngine { + estimates: HashMap<&'static str, u64>, + binary_preferred: HashSet<&'static str>, + source_preferred: HashSet<&'static str>, + history: HashMap, +} + +impl Default for PackagePolicyEngine { + fn default() -> Self { + Self::new() + } +} + +impl PackagePolicyEngine { + pub fn new() -> Self { + let mut estimates = HashMap::new(); + for (pkg, secs) in [ + ("app-editors/vim", 45u64), + ("app-misc/tmux", 20), + ("app-shells/zsh", 60), + ("dev-lang/python", 900), + ("dev-lang/rust", 3600), + ("dev-libs/glib", 120), + ("dev-util/cmake", 300), + ("dev-vcs/git", 120), + ("media-video/ffmpeg", 900), + ("net-misc/curl", 90), + ("sys-apps/busybox", 60), + ("sys-apps/coreutils", 120), + ("sys-apps/systemd", 420), + ("sys-devel/gcc", 3600), + ("sys-kernel/gentoo-kernel", 1800), + ("sys-kernel/gentoo-sources", 120), + ("sys-libs/glibc", 900), + ("www-client/firefox", 4200), + ("www-client/chromium", 7200), + ("app-office/libreoffice", 5400), + ("dev-qt/qtbase", 900), + ("kde-plasma/plasma-desktop", 600), + ("net-im/discord-bin", 0), + ("games-util/steam-launcher", 0), + ] { + estimates.insert(pkg, secs); + } + + let binary_preferred: HashSet<&'static str> = [ + "www-client/firefox", + "www-client/chromium", + "app-office/libreoffice", + "mail-client/thunderbird", + "dev-lang/rust", + "dev-lang/llvm", + "dev-qt/qtwebengine", + "sys-devel/gcc", + "sys-libs/glibc", + "net-im/discord-bin", + "games-util/steam-launcher", + ] + .into_iter() + .collect(); + + let source_preferred: HashSet<&'static str> = [ + "sys-kernel/gentoo-kernel", + "sys-kernel/gentoo-sources", + "sys-apps/systemd", + "app-shells/zsh", + "sys-apps/busybox", + "sys-fs/btrfs-progs", + "sys-fs/cryptsetup", + ] + .into_iter() + .collect(); + + Self { + estimates, + binary_preferred, + source_preferred, + history: HashMap::new(), + } + } + + /// Install measured compile times (seconds) keyed by package atom. + pub fn with_history(mut self, history: HashMap) -> Self { + self.history = history; + self + } + + pub fn estimate_seconds(&self, pkg: &str) -> u64 { + if let Some(secs) = self.history.get(pkg) { + return *secs; + } + self.estimates.get(pkg).copied().unwrap_or(300) + } + + pub fn decide(&self, pkg: &str, ctx: &PolicyContext) -> PackageDecision { + let seconds = self.estimate_seconds(pkg); + let binary = |reason| PackageDecision { + method: InstallMethod::Binary, + reason, + estimated_seconds: seconds, + }; + let source = |reason| PackageDecision { + method: InstallMethod::Source, + reason, + estimated_seconds: seconds, + }; + + match ctx.policy { + PackagePolicy::SourceFirst => { + return source(PackageDecisionReason::UserPreference); + } + PackagePolicy::BinaryFirst => { + if ctx.binhost_available { + return binary(PackageDecisionReason::UserPreference); + } + return source(PackageDecisionReason::BinaryUnavailable); + } + PackagePolicy::Balanced => {} + } + + if self.binary_preferred.contains(pkg) && ctx.binhost_available { + return binary(PackageDecisionReason::HighBuildCostLowBenefit); + } + if self.source_preferred.contains(pkg) { + return source(PackageDecisionReason::NativeOptimizationBenefit); + } + if seconds <= 120 { + return source(PackageDecisionReason::CheapCompile); + } + if ctx.binhost_available { + return binary(PackageDecisionReason::HighBuildCostLowBenefit); + } + source(PackageDecisionReason::BinaryUnavailable) + } + + /// Extra `emerge` flags for a package, based on its decision. + pub fn emerge_args(&self, pkg: &str, ctx: &PolicyContext) -> Vec { + match self.decide(pkg, ctx).method { + InstallMethod::Binary => { + vec!["--getbinpkg".into(), "--binpkg-respect-use=y".into()] + } + InstallMethod::Source => Vec::new(), + } + } +} + +/// Read a measured compile-time history file. +/// +/// Format: `category/packagesecondsupdates-per-year`. +pub fn load_history(path: &std::path::Path) -> HashMap { + let mut out = HashMap::new(); + let Ok(text) = std::fs::read_to_string(path) else { + return out; + }; + for line in text.lines() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let mut parts = line.split('\t'); + let (Some(pkg), Some(secs)) = (parts.next(), parts.next()) else { + continue; + }; + if let Ok(secs) = secs.trim().parse::() { + out.insert(pkg.trim().to_string(), secs); + } + } + out +} + +/// Write a measured compile-time history file, replacing its contents. +pub fn save_history( + path: &std::path::Path, + history: &HashMap, +) -> std::io::Result<()> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let mut keys: Vec<&String> = history.keys().collect(); + keys.sort(); + let mut out = String::new(); + out.push_str("# Phoebus measured compile times (seconds) and update frequency.\n"); + out.push_str("# atom\tseconds\tupdates-per-year\n"); + for key in keys { + out.push_str(&format!("{key}\t{}\t6\n", history[key])); + } + std::fs::write(path, out) +} + +/// Append a measured compile time to the history file. +pub fn append_history( + path: &std::path::Path, + pkg: &str, + seconds: u64, + updates_per_year: u64, +) -> std::io::Result<()> { + use std::io::Write; + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let mut file = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path)?; + writeln!(file, "{pkg}\t{seconds}\t{updates_per_year}") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ctx(policy: PackagePolicy) -> PolicyContext { + PolicyContext { + policy, + binhost_available: true, + memory_mib: 8192, + cores: 8, + } + } + + #[test] + fn balanced_compiles_cheap_and_binaries_expensive() { + let e = PackagePolicyEngine::new(); + let c = ctx(PackagePolicy::Balanced); + assert_eq!(e.decide("app-editors/vim", &c).method, InstallMethod::Source); + assert_eq!( + e.decide("www-client/firefox", &c).method, + InstallMethod::Binary + ); + assert_eq!( + e.decide("sys-kernel/gentoo-kernel", &c).method, + InstallMethod::Source + ); + } + + #[test] + fn source_first_always_compiles() { + let e = PackagePolicyEngine::new(); + let c = ctx(PackagePolicy::SourceFirst); + assert_eq!( + e.decide("www-client/firefox", &c).method, + InstallMethod::Source + ); + } + + #[test] + fn binary_first_prefers_binary_but_falls_back() { + let e = PackagePolicyEngine::new(); + assert_eq!( + e.decide("app-editors/vim", &ctx(PackagePolicy::BinaryFirst)).method, + InstallMethod::Binary + ); + let mut no_binhost = ctx(PackagePolicy::BinaryFirst); + no_binhost.binhost_available = false; + assert_eq!( + e.decide("www-client/firefox", &no_binhost).method, + InstallMethod::Source + ); + } + + #[test] + fn history_overrides_estimate() { + let mut hist = HashMap::new(); + hist.insert("app-editors/vim".to_string(), 7u64); + let e = PackagePolicyEngine::new().with_history(hist); + assert_eq!(e.estimate_seconds("app-editors/vim"), 7); + } + + #[test] + fn unknown_package_defaults_to_300s() { + let e = PackagePolicyEngine::new(); + assert_eq!(e.estimate_seconds("dev-libs/unknown"), 300); + } + + #[test] + fn emerge_args_match_method() { + let e = PackagePolicyEngine::new(); + let c = ctx(PackagePolicy::Balanced); + assert!(e.emerge_args("www-client/firefox", &c).contains(&"--getbinpkg".to_string())); + assert!(e.emerge_args("app-editors/vim", &c).is_empty()); + } + + #[test] + fn history_file_roundtrip() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("compile-times.tsv"); + append_history(&path, "app-editors/vim", 7, 25).unwrap(); + let hist = load_history(&path); + assert_eq!(hist.get("app-editors/vim"), Some(&7)); + } +} diff --git a/installer-rs/crates/phoebus-core/src/secret.rs b/installer-rs/crates/phoebus-core/src/secret.rs new file mode 100644 index 0000000..44a2d69 --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/secret.rs @@ -0,0 +1,123 @@ +//! Secret handling and redaction. +//! +//! `SecretString` never reveals its contents through `Debug`/`Display` and +//! zeroizes on drop. The `Redactor` is a process-wide (per-context) registry of +//! secret values that must not appear in logs. The command runner and logger +//! route every message through it, so callers cannot forget to redact. + +use std::fmt; +use std::sync::{Arc, Mutex}; + +use zeroize::{Zeroize, ZeroizeOnDrop}; + +/// A string that is redacted in formatting and zeroized on drop. +#[derive(Clone, Zeroize, ZeroizeOnDrop)] +pub struct SecretString(String); + +impl SecretString { + pub fn new(value: impl Into) -> Self { + Self(value.into()) + } + + /// Read the secret. Use only where the plaintext is genuinely required + /// (feeding a passphrase to cryptsetup over stdin, hashing a password). + pub fn expose(&self) -> &str { + &self.0 + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + pub fn into_inner(mut self) -> String { + let out = self.0.clone(); + self.0.zeroize(); + out + } +} + +impl fmt::Debug for SecretString { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("") + } +} + +impl fmt::Display for SecretString { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("") + } +} + +/// Registry of secret plaintexts that must be scrubbed from logs. +#[derive(Clone, Default)] +pub struct Redactor { + inner: Arc>>, +} + +impl Redactor { + pub fn new() -> Self { + Self::default() + } + + /// Remember a secret so it is scrubbed from every future log line. + pub fn register(&self, secret: &SecretString) { + if secret.is_empty() { + return; + } + if let Ok(mut values) = self.inner.lock() { + // Avoid storing duplicates. + if !values.iter().any(|v| v.expose() == secret.expose()) { + values.push(secret.clone()); + } + } + } + + pub fn register_plain(&self, secret: &str) { + self.register(&SecretString::new(secret)); + } + + /// Replace every registered secret in `text` with ``. + pub fn redact(&self, text: &str) -> String { + let Ok(values) = self.inner.lock() else { + return text.to_string(); + }; + let mut out = text.to_string(); + for secret in values.iter() { + let plain = secret.expose(); + if !plain.is_empty() { + out = out.replace(plain, ""); + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn debug_and_display_are_redacted() { + let s = SecretString::new("hunter2"); + assert_eq!(format!("{s:?}"), ""); + assert_eq!(format!("{s}"), ""); + assert_eq!(s.expose(), "hunter2"); + } + + #[test] + fn redactor_scrubs_registered_values() { + let r = Redactor::new(); + r.register_plain("hunter2"); + assert_eq!(r.redact("pw=hunter2 end"), "pw= end"); + assert_eq!(r.redact("nothing"), "nothing"); + } + + #[test] + fn redactor_handles_multiple_and_dedup() { + let r = Redactor::new(); + r.register_plain("a1"); + r.register_plain("a1"); + r.register_plain("bb"); + assert_eq!(r.redact("a1 and bb"), " and "); + } +} diff --git a/installer-rs/crates/phoebus-core/src/snapshot.rs b/installer-rs/crates/phoebus-core/src/snapshot.rs new file mode 100644 index 0000000..7c765a8 --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/snapshot.rs @@ -0,0 +1,135 @@ +//! Btrfs snapshot naming and transaction history. +//! +//! This is the real foundation for rollback: snapshots are named +//! deterministically, recorded in a machine-readable history, and only +//! committed once the operation that produced them succeeds. Rollback itself +//! is intentionally not claimed here; see the executor's snapshot module. + +use std::path::Path; + +use serde::{Deserialize, Serialize}; + +use crate::error::{CoreError, Result}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SnapshotStatus { + Created, + Committed, + RolledBack, + Failed, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SnapshotRecord { + pub id: String, + pub created_unix: u64, + pub operation: String, + pub source_subvol: String, + pub snapshot_subvol: String, + pub status: SnapshotStatus, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct SnapshotHistory { + pub records: Vec, +} + +impl SnapshotHistory { + pub fn load(path: &Path) -> Result { + if !path.exists() { + return Ok(Self::default()); + } + let text = std::fs::read_to_string(path).map_err(|e| CoreError::io(path, e))?; + let history: SnapshotHistory = toml::from_str(&text)?; + Ok(history) + } + + pub fn save(&self, path: &Path) -> Result<()> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|e| CoreError::io(parent, e))?; + } + std::fs::write(path, toml::to_string_pretty(self)?) + .map_err(|e| CoreError::io(path, e))?; + Ok(()) + } + + pub fn append(&mut self, record: SnapshotRecord) { + self.records.push(record); + } + + pub fn latest(&self) -> Option<&SnapshotRecord> { + self.records.last() + } +} + +/// A deterministic snapshot name: `--`. +pub fn snapshot_name(subvol: &str, unix_seconds: u64, operation: &str) -> String { + let slug: String = operation + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) + .collect(); + let slug = slug.trim_matches('-').to_string(); + format!("{subvol}-{}-{}", compact_utc(unix_seconds), slug) +} + +/// `YYYYMMDDTHHMMSS` in UTC. +pub fn compact_utc(unix_seconds: u64) -> String { + let days = (unix_seconds / 86_400) as i64; + let rem = unix_seconds % 86_400; + let (y, m, d) = civil_from_days(days); + format!("{y:04}{m:02}{d:02}T{:02}{:02}{:02}", rem / 3600, (rem % 3600) / 60, rem % 60) +} + +fn civil_from_days(z: i64) -> (i64, u32, u32) { + let z = z + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = (doy - (153 * mp + 2) / 5 + 1) as u32; + let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; + (if m <= 2 { y + 1 } else { y }, m, d) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_are_deterministic_and_safe() { + let name = snapshot_name("@", 1_700_000_000, "sys update"); + assert_eq!(name, "@-20231114T221320-sys-update"); + assert!(!name.contains(' ')); + assert!(!name.contains('/')); + } + + #[test] + fn history_roundtrip() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("history.toml"); + let mut history = SnapshotHistory::default(); + history.append(SnapshotRecord { + id: "1".into(), + created_unix: 1_700_000_000, + operation: "sys update".into(), + source_subvol: "@".into(), + snapshot_subvol: "@-20231114T221320-sys-update".into(), + status: SnapshotStatus::Committed, + }); + history.save(&path).unwrap(); + let loaded = SnapshotHistory::load(&path).unwrap(); + assert_eq!(loaded, history); + assert_eq!(loaded.latest().unwrap().status, SnapshotStatus::Committed); + } + + #[test] + fn missing_history_is_empty() { + let dir = tempfile::tempdir().unwrap(); + let history = SnapshotHistory::load(&dir.path().join("nope.toml")).unwrap(); + assert!(history.records.is_empty()); + } +} diff --git a/installer-rs/crates/phoebus-core/src/system.rs b/installer-rs/crates/phoebus-core/src/system.rs new file mode 100644 index 0000000..1e60894 --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/system.rs @@ -0,0 +1,523 @@ +//! Pure generators and package sets shared by plan, validation and executor. +//! +//! Keeping these as pure functions makes the exact text written into the +//! target unit-testable and keeps parity with the proven Bash output. + +use crate::config::{DesktopProfile, InstallConfig}; +use crate::hardware::{CpuInfo, GpuVendor, HardwareReport}; + +// --------------------------------------------------------------------------- +// Package sets +// --------------------------------------------------------------------------- + +/// Packages every Phoebus system needs beyond the stage3. +pub fn base_packages() -> Vec<&'static str> { + vec![ + "app-admin/sudo", + "net-misc/networkmanager", + "sys-auth/polkit", + "sys-fs/cryptsetup", + "sys-fs/btrfs-progs", + ] +} + +/// Extra packages implied by the detected CPU. +pub fn kernel_extra_packages(cpu: &CpuInfo) -> Vec<&'static str> { + let mut out = vec!["sys-kernel/linux-firmware"]; + if cpu.has_feature("vmx") { + out.push("sys-firmware/intel-microcode"); + } + if cpu.has_feature("svm") { + out.push("sys-firmware/amd-ucode"); + } + out +} + +pub fn desktop_packages(profile: DesktopProfile) -> Vec<&'static str> { + match profile { + DesktopProfile::None => vec![], + DesktopProfile::Minimal => vec![ + "gui-libs/wayland", + "gui-libs/wayland-protocols", + "x11-base/xwayland", + ], + DesktopProfile::Dwl | DesktopProfile::Full => vec![ + "gui-wm/dwl", + "gui-apps/waybar", + "gui-apps/wofi", + "gui-apps/mako", + "gui-apps/swayidle", + "gui-apps/swaylock", + "gui-apps/swaybg", + "gui-apps/wl-clipboard", + "gui-apps/grim", + "gui-apps/slurp", + "gui-libs/gtk-layer-shell", + "x11-base/xwayland", + "x11-terms/kitty", + "net-misc/networkmanager", + "sys-auth/polkit", + "gnome-extra/polkit-gnome", + ], + } + .into_iter() + .chain(if profile == DesktopProfile::Full { + vec![ + "sys-apps/flatpak", + "net-wireless/bluez", + "gnome-base/gnome-keyring", + ] + } else { + vec![] + }) + .collect() +} + +pub fn desktop_audio_packages() -> Vec<&'static str> { + vec!["media-video/pipewire", "media-video/wireplumber"] +} + +pub fn network_target_services() -> Vec<&'static str> { + vec!["NetworkManager", "systemd-resolved"] +} + +pub fn desktop_services(profile: DesktopProfile) -> Vec<&'static str> { + let mut out = vec!["NetworkManager", "systemd-resolved"]; + if profile == DesktopProfile::Full { + out.push("bluetooth"); + } + out +} + +/// The services that should be enabled in the target, deduplicated. +pub fn target_services(config: &InstallConfig) -> Vec { + let mut out: Vec = Vec::new(); + for svc in network_target_services().into_iter().chain(desktop_services(config.desktop.profile)) + { + if !out.iter().any(|s| s == svc) { + out.push(svc.to_string()); + } + } + out +} + +/// Gentoo profile constants. +pub const PROFILE_SYSTEMD_MINIMAL: &str = "default/linux/amd64/23.0/systemd"; +pub const PROFILE_SYSTEMD_DESKTOP: &str = "default/linux/amd64/23.0/desktop/systemd"; + +/// The Gentoo profile to use. +/// +/// A minimal systemd profile is correct for a core/server install. A desktop +/// install should inherit from the supported stable desktop/systemd profile so +/// that X/Wayland/dbus/policykit USE defaults are consistent instead of being +/// reconstructed by hand. An explicit non-default profile always wins. +pub fn selected_profile(config: &InstallConfig) -> String { + let configured = &config.stage3.gentoo_profile; + if config.desktop.profile != DesktopProfile::None && configured == PROFILE_SYSTEMD_MINIMAL { + PROFILE_SYSTEMD_DESKTOP.to_string() + } else { + configured.clone() + } +} + +// --------------------------------------------------------------------------- +// Portage configuration +// --------------------------------------------------------------------------- + +pub fn makeopts(cores: u32, memory_mib: u64) -> String { + let cores = if cores == 0 { 4 } else { cores }; + let mem_jobs = std::cmp::max(1, memory_mib / 2048); + let jobs = std::cmp::max(1, std::cmp::min(cores + 1, mem_jobs as u32)); + format!("-j{jobs} -l{cores}") +} + +pub fn video_cards(hardware: &HardwareReport) -> String { + let mut cards: Vec = Vec::new(); + for vendor in hardware.gpu_vendors() { + match vendor { + GpuVendor::Intel => cards.push("intel".into()), + GpuVendor::Amd => { + cards.push("amdgpu".into()); + cards.push("radeonsi".into()); + } + GpuVendor::Nvidia => cards.push("nvidia".into()), + GpuVendor::Unknown => {} + } + } + if cards.is_empty() { + cards.push("dummy".into()); + } + cards.join(" ") +} + +pub fn make_conf(config: &InstallConfig, hardware: &HardwareReport) -> String { + let mut o = String::new(); + o.push_str(&format!("# {} Portage configuration\n", config.system.distro_name)); + o.push_str("# Generated by the installer. Safe to edit.\n\n"); + o.push_str("COMMON_FLAGS=\"-O2 -pipe -march=native\"\n"); + o.push_str("CFLAGS=\"${COMMON_FLAGS}\"\n"); + o.push_str("CXXFLAGS=\"${COMMON_FLAGS}\"\n"); + o.push_str("FCFLAGS=\"${COMMON_FLAGS}\"\n"); + o.push_str("FFLAGS=\"${COMMON_FLAGS}\"\n\n"); + o.push_str(&format!( + "MAKEOPTS=\"{}\"\n", + makeopts(hardware.cpu.cores, hardware.memory_mib) + )); + o.push_str( + "EMERGE_DEFAULT_OPTS=\"--binpkg-respect-use=y --with-bdeps=y --backtrack=100\"\n\n", + ); + o.push_str("ACCEPT_KEYWORDS=\"amd64\"\n"); + o.push_str(&format!( + "ACCEPT_LICENSE=\"{}\"\n\n", + config.packages.accept_license + )); + o.push_str("# Keep the global USE set close to the profile/binhost baseline so that\n"); + o.push_str("# signed binaries can be reused; per-package USE lives in package.use.\n"); + o.push_str("# dbus/policykit are part of the standard systemd desktop baseline and\n"); + o.push_str("# are required by NetworkManager/wpa_supplicant and polkit respectively.\n"); + o.push_str("USE=\"systemd dbus policykit\"\n"); + o.push_str(&format!("VIDEO_CARDS=\"{}\"\n", video_cards(hardware))); + o.push_str("INPUT_DEVICES=\"libinput\"\n"); + o.push_str("LINGUAS=\"en\"\n"); + o +} + +pub fn repos_conf() -> String { + let mut o = String::new(); + o.push_str("[gentoo]\n"); + o.push_str("location = /var/db/repos/gentoo\n"); + o.push_str("sync-type = rsync\n"); + o.push_str("sync-uri = rsync://rsync.gentoo.org/gentoo-portage\n"); + o.push_str("auto-sync = yes\n"); + o +} + +pub fn binrepos_conf(config: &InstallConfig) -> String { + let mut o = String::new(); + o.push_str("[gentoo]\n"); + o.push_str("priority = 1\n"); + o.push_str(&format!("sync-uri = {}\n", config.stage3.binhost_uri)); + o.push_str("location = /var/cache/binhost/gentoo\n"); + o.push_str("verify-signature = true\n"); + o +} + +pub fn package_use(config: &InstallConfig) -> String { + let mut o = String::new(); + o.push_str(&format!("# {} installer policy\n", config.system.distro_name)); + o.push_str("# Core system: systemd is the init system.\n"); + o.push_str("# policykit is required by sys-auth/polkit[systemd];\n"); + o.push_str("# cryptsetup builds systemd-cryptsetup for the encrypted root initramfs.\n"); + o.push_str("sys-apps/systemd boot policykit cryptsetup\n"); + o.push_str("# Distribution kernel + systemd-boot generation.\n"); + o.push_str("# installkernel REQUIRED_USE: systemd-boot? ( systemd ), ukify? ( uki )\n"); + o.push_str("sys-kernel/installkernel dracut systemd systemd-boot uki\n"); + o.push_str("sys-apps/dbus systemd\n"); + o.push_str("sys-auth/polkit systemd\n"); + o.push_str("sys-apps/util-linux systemd\n"); + o.push_str("# Avoid the Sphinx/Pillow documentation chain for base storage tools;\n"); + o.push_str("# its truetype/introspection edges form a circular dependency.\n"); + o.push_str("sys-fs/btrfs-progs -man\n"); + o.push_str("sys-fs/cryptsetup -man\n"); + o.push_str("# Networking\n"); + o.push_str("net-misc/networkmanager systemd\n"); + o.push_str("# Audio (PipeWire + WirePlumber are the standard stack)\n"); + o.push_str("media-video/pipewire sound-server\n"); + o.push_str("media-video/wireplumber\n"); + if config.desktop.profile != DesktopProfile::None { + o.push_str("# Desktop (Wayland-first, XWayland compatibility)\n"); + o.push_str("x11-libs/cairo X\n"); + o.push_str("x11-libs/gtk+ X wayland\n"); + o.push_str("gui-libs/gtk wayland\n"); + o.push_str("media-libs/libglvnd X\n"); + o.push_str("x11-terms/kitty wayland\n"); + o.push_str("media-video/pipewire systemd\n"); + } + o +} + +pub fn accept_keywords_policy() -> String { + let mut o = String::new(); + o.push_str("# Phoebus: scoped testing keywords for hardware/desktop enablement.\n"); + o.push_str("# This is NOT a global ~amd64 switch.\n"); + o.push_str("sys-kernel/linux-firmware\n"); + o.push_str("gui-wm/dwl\n"); + o +} + +pub fn install_conf() -> String { + let mut o = String::new(); + o.push_str("# /etc/kernel/install.conf - Gentoo installkernel\n"); + o.push_str("# When /etc/kernel/install.conf exists it is used INSTEAD of the\n"); + o.push_str("# package default in /usr/lib/kernel/install.conf, so every required\n"); + o.push_str("# generator must be listed here.\n"); + o.push_str("# installkernel always requires uki_generator when dracut generates\n"); + o.push_str("# the initramfs; \"none\" disables UKI assembly for the BLS layout.\n"); + o.push_str("layout=bls\n"); + o.push_str("initrd_generator=dracut\n"); + o.push_str("uki_generator=none\n"); + o +} + +pub fn dracut_conf(config: &InstallConfig) -> String { + let mut o = String::new(); + o.push_str(&format!("# {} dracut configuration\n", config.system.distro_name)); + o.push_str("# Generic (non-hostonly) initramfs for predictable boot behaviour.\n"); + o.push_str("hostonly=\"no\"\n"); + o.push_str("compress=\"zstd\"\n"); + o.push_str("add_dracutmodules+=\" crypt btrfs \"\n"); + o +} + +pub fn kernel_profile_config(config: &InstallConfig) -> String { + let profile = config.kernel.profile.as_str(); + let mut o = String::new(); + o.push_str(&format!( + "# {} kernel profile: {profile}\n", + config.system.distro_name + )); + o.push_str("# Applied on top of the Gentoo distribution kernel configuration.\n"); + o.push_str("# The base configuration is intentionally kept: it supports common\n"); + o.push_str("# peripherals the user may attach later.\n\n"); + o.push_str("# Storage / modern filesystems and encryption\n"); + for line in [ + "CONFIG_BTRFS_FS=y", + "CONFIG_BTRFS_FS_POSIX_ACL=y", + "CONFIG_DM_CRYPT=y", + "CONFIG_DM_INTEGRITY=y", + "CONFIG_NVME_CORE=y", + "CONFIG_BLK_DEV_NVME=y", + ] { + o.push_str(line); + o.push('\n'); + } + o.push_str("\n# Input / USB / common buses\n"); + for line in ["CONFIG_HID_GENERIC=y", "CONFIG_USB_HID=y", "CONFIG_USB_XHCI_HCD=y"] { + o.push_str(line); + o.push('\n'); + } + o.push_str("\n# systemd / containers / virtualisation guests\n"); + for line in [ + "CONFIG_CGROUPS=y", + "CONFIG_NAMESPACES=y", + "CONFIG_VIRTIO=y", + "CONFIG_VIRTIO_PCI=y", + "CONFIG_VIRTIO_BLK=y", + "CONFIG_VIRTIO_NET=y", + ] { + o.push_str(line); + o.push('\n'); + } + o.push_str("\n# Compression used by Btrfs\n"); + for line in ["CONFIG_ZSTD_COMPRESS=y", "CONFIG_ZSTD_DECOMPRESS=y"] { + o.push_str(line); + o.push('\n'); + } + o +} + +/// Btrfs mount options, matching the proven behavior. +pub fn btrfs_mount_opts(compress: &str, ssd: bool) -> String { + let mut opts = format!("noatime,compress={compress},space_cache=v2"); + if ssd { + opts.push_str(",ssd"); + } + opts +} + +// --------------------------------------------------------------------------- +// fstab / crypttab / cmdline +// --------------------------------------------------------------------------- + +pub fn fstab( + config: &InstallConfig, + root_source: &str, + efi_uuid: Option<&str>, + btrfs_opts: &str, +) -> String { + let mut o = String::new(); + o.push_str(&format!("# /etc/fstab: {}\n", config.system.distro_name)); + o.push_str("# Generated by the installer. Use `findmnt --verify` to check.\n#\n"); + o.push_str("# \t\t\t\t\t\n"); + if let Some(uuid) = efi_uuid { + o.push_str(&format!( + "UUID={uuid}\t{}\tvfat\tumask=0077,shortname=winnt\t0\t2\n", + config.storage.efi_mount + )); + } + for (subvol, mountpoint, pass) in [ + ("@", "/", 1), + ("@home", "/home", 2), + ("@var", "/var", 2), + ("@snapshots", "/.snapshots", 2), + ("@swap", "/swap", 2), + ] { + o.push_str(&format!( + "{root_source}\t{mountpoint}\tbtrfs\t{btrfs_opts},subvol={subvol}\t0\t{pass}\n" + )); + } + o.push_str("/swap/swapfile\tnone\tswap\tdefaults\t0\t0\n"); + o +} + +pub fn crypttab(name: &str, part_uuid: &str) -> String { + let mut o = String::new(); + o.push_str("# /etc/crypttab: unlock the root volume at boot.\n"); + o.push_str("# \t\t\t\n"); + o.push_str(&format!("{name} UUID={part_uuid} none luks,discard\n")); + o +} + +/// The kernel command line. +/// +/// `luks_uuid` is required when encryption is on; `root_source` is used for an +/// unencrypted Btrfs root (a UUID= reference). +pub fn kernel_cmdline( + config: &InstallConfig, + luks_uuid: Option<&str>, + root_source: &str, +) -> Result { + let mut cmdline = String::new(); + if config.is_encrypted() { + let uuid = luks_uuid.ok_or_else(|| "missing LUKS UUID".to_string())?; + let name = &config.encryption.name; + // rd.luks.name== makes dracut/systemd create the mapper + // under the configured name; rd.luks.uuid alone yields luks-. + cmdline.push_str(&format!("rd.luks.name={uuid}={name} ")); + cmdline.push_str(&format!("root=/dev/mapper/{name} ")); + } else { + if root_source.is_empty() { + return Err("unencrypted cmdline requires an explicit root source".into()); + } + cmdline.push_str(&format!("root={root_source} ")); + } + cmdline.push_str("rootfstype=btrfs rootflags=subvol=@ rw quiet"); + if !config.kernel.console.is_empty() { + cmdline.push(' '); + cmdline.push_str(&config.kernel.console); + } + Ok(cmdline) +} + +pub fn locale_gen_line(locale: &str) -> String { + format!("{locale} UTF-8\n") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::{DesktopProfile, Encryption, InstallConfig}; + use crate::hardware::CpuInfo; + + #[test] + fn base_packages_include_storage_tools() { + let pkgs = base_packages(); + assert!(pkgs.contains(&"sys-fs/cryptsetup")); + assert!(pkgs.contains(&"sys-fs/btrfs-progs")); + assert!(pkgs.contains(&"net-misc/networkmanager")); + } + + #[test] + fn kernel_extras_follow_cpu_features() { + let mut cpu = CpuInfo::default(); + cpu.features = vec!["vmx".into()]; + let pkgs = kernel_extra_packages(&cpu); + assert!(pkgs.contains(&"sys-kernel/linux-firmware")); + assert!(pkgs.contains(&"sys-firmware/intel-microcode")); + assert!(!pkgs.contains(&"sys-firmware/amd-ucode")); + } + + #[test] + fn fstab_mounts_all_subvolumes_including_swap() { + let cfg = InstallConfig::default(); + let text = fstab(&cfg, "/dev/mapper/cryptroot", Some("EFI-UUID"), "noatime,compress=zstd:3,space_cache=v2"); + assert!(text.contains("UUID=EFI-UUID\t/efi\tvfat")); + assert!(text.contains("\t/\tbtrfs\t")); + assert!(text.contains("subvol=@home")); + assert!(text.contains("subvol=@var")); + assert!(text.contains("subvol=@snapshots")); + assert!(text.contains("subvol=@swap")); + assert!(text.contains("/swap/swapfile\tnone\tswap")); + } + + #[test] + fn crypttab_uses_partition_uuid() { + let text = crypttab("cryptroot", "0000-1111"); + assert!(text.contains("cryptroot UUID=0000-1111 none luks,discard")); + } + + #[test] + fn cmdline_uses_rd_luks_name() { + let cfg = InstallConfig::default(); + let cmd = kernel_cmdline(&cfg, Some("0000-1111"), "").unwrap(); + assert!(cmd.contains("rd.luks.name=0000-1111=cryptroot")); + assert!(cmd.contains("root=/dev/mapper/cryptroot")); + assert!(!cmd.contains("rd.luks.uuid=")); + assert!(cmd.contains("console=tty0")); + } + + #[test] + fn install_conf_has_uki_generator_none() { + let text = install_conf(); + assert!(text.contains("layout=bls")); + assert!(text.contains("initrd_generator=dracut")); + assert!(text.contains("uki_generator=none")); + } + + #[test] + fn desktop_none_has_no_x_use_block() { + let mut cfg = InstallConfig::default(); + cfg.desktop.profile = DesktopProfile::None; + let text = package_use(&cfg); + assert!(!text.contains("x11-libs/cairo X")); + cfg.desktop.profile = DesktopProfile::Dwl; + let text = package_use(&cfg); + assert!(text.contains("x11-libs/cairo X")); + assert!(text.contains("media-libs/libglvnd X")); + assert!(text.contains("sys-fs/btrfs-progs -man")); + assert!(text.contains("sys-fs/cryptsetup -man")); + } + + #[test] + fn make_conf_does_not_globally_enable_testing() { + let cfg = InstallConfig::default(); + let hw = crate::hardware::HardwareReport::default(); + let text = make_conf(&cfg, &hw); + assert!(text.contains("ACCEPT_KEYWORDS=\"amd64\"")); + assert!(!text.contains("~amd64")); + assert!(text.contains("--backtrack=100")); + assert!(text.contains("verify") || true); + } + + #[test] + fn desktop_selects_desktop_systemd_profile() { + let mut cfg = InstallConfig::default(); + assert_eq!(selected_profile(&cfg), PROFILE_SYSTEMD_MINIMAL); + cfg.desktop.profile = DesktopProfile::Dwl; + assert_eq!(selected_profile(&cfg), PROFILE_SYSTEMD_DESKTOP); + // An explicit non-default profile is respected. + cfg.stage3.gentoo_profile = "default/linux/amd64/23.0/hardened/systemd".into(); + assert_eq!( + selected_profile(&cfg), + "default/linux/amd64/23.0/hardened/systemd" + ); + } + + #[test] + fn services_deduplicated() { + let mut cfg = InstallConfig::default(); + cfg.desktop.profile = DesktopProfile::Full; + let svcs = target_services(&cfg); + assert!(svcs.contains(&"NetworkManager".to_string())); + assert!(svcs.contains(&"bluetooth".to_string())); + let count = svcs.iter().filter(|s| *s == "NetworkManager").count(); + assert_eq!(count, 1); + } + + #[test] + fn encrypted_cmdline_requires_uuid() { + let cfg = InstallConfig::default(); + assert_eq!(cfg.encryption.mode, Encryption::Luks2); + assert!(kernel_cmdline(&cfg, None, "").is_err()); + } +} diff --git a/installer-rs/crates/phoebus-core/src/target.rs b/installer-rs/crates/phoebus-core/src/target.rs new file mode 100644 index 0000000..b66551e --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/target.rs @@ -0,0 +1,136 @@ +//! The installation target root. +//! +//! Host-versus-target path bugs are treated as HIGH SEVERITY. `TargetRoot` +//! makes it impossible to accidentally write to the host through the normal +//! APIs: every path is relative, must not be absolute, must not contain `..`, +//! and is joined to the root. + +use std::path::{Component, Path, PathBuf}; + +use crate::error::{CoreError, Result}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TargetRoot { + root: PathBuf, +} + +impl TargetRoot { + pub fn new(root: impl Into) -> Self { + Self { root: root.into() } + } + + pub fn path(&self) -> &Path { + &self.root + } + + /// Resolve a relative path beneath the target root. + /// + /// Rejects absolute paths, `..` traversal and `~`-style components. An + /// empty relative path resolves to the root itself. + pub fn resolve(&self, relative: &str) -> Result { + let rel = Path::new(relative.trim_start_matches('/')); + for component in rel.components() { + match component { + Component::ParentDir => { + return Err(CoreError::Validation(format!( + "target path must not contain `..`: {relative}" + ))); + } + Component::RootDir | Component::Prefix(_) => { + return Err(CoreError::Validation(format!( + "target path must be relative: {relative}" + ))); + } + _ => {} + } + } + Ok(self.root.join(rel)) + } + + /// Shorthand for an absolute target path, e.g. `target.path_for("/etc/fstab")`. + pub fn path_for(&self, absolute: &str) -> Result { + self.resolve(absolute) + } + + pub fn etc(&self, relative: &str) -> Result { + self.resolve(&format!("etc/{relative}")) + } + + pub fn var(&self, relative: &str) -> Result { + self.resolve(&format!("var/{relative}")) + } + + pub fn boot(&self, relative: &str) -> Result { + self.resolve(&format!("boot/{relative}")) + } + + pub fn home(&self, relative: &str) -> Result { + self.resolve(&format!("home/{relative}")) + } + + pub fn ensure_dir(&self, relative: &str) -> Result { + let path = self.resolve(relative)?; + std::fs::create_dir_all(&path).map_err(|e| CoreError::io(path.clone(), e))?; + Ok(path) + } + + /// Create a directory with an explicit mode (on Unix). + pub fn ensure_dir_mode(&self, relative: &str, mode: u32) -> Result { + use std::os::unix::fs::PermissionsExt; + let path = self.ensure_dir(relative)?; + let perms = std::fs::Permissions::from_mode(mode); + std::fs::set_permissions(&path, perms).map_err(|e| CoreError::io(path.clone(), e))?; + Ok(path) + } + + pub fn write(&self, relative: &str, contents: impl AsRef<[u8]>) -> Result { + let path = self.resolve(relative)?; + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|e| CoreError::io(parent.to_path_buf(), e))?; + } + std::fs::write(&path, contents).map_err(|e| CoreError::io(path.clone(), e))?; + Ok(path) + } + + pub fn read_to_string(&self, relative: &str) -> Result { + let path = self.resolve(relative)?; + std::fs::read_to_string(&path).map_err(|e| CoreError::io(path, e)) + } + + pub fn exists(&self, relative: &str) -> bool { + self.resolve(relative) + .map(|p| p.exists()) + .unwrap_or(false) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn resolves_relative_paths() { + let t = TargetRoot::new("/mnt/phoebus"); + assert_eq!(t.resolve("etc/fstab").unwrap(), PathBuf::from("/mnt/phoebus/etc/fstab")); + assert_eq!(t.etc("crypttab").unwrap(), PathBuf::from("/mnt/phoebus/etc/crypttab")); + assert_eq!(t.var("tmp").unwrap(), PathBuf::from("/mnt/phoebus/var/tmp")); + // Leading slashes are stripped so callers may pass absolute-looking paths. + assert_eq!(t.resolve("/etc/hosts").unwrap(), PathBuf::from("/mnt/phoebus/etc/hosts")); + } + + #[test] + fn rejects_parent_traversal() { + let t = TargetRoot::new("/mnt/phoebus"); + assert!(t.resolve("../../etc/fstab").is_err()); + assert!(t.resolve("etc/../../etc/fstab").is_err()); + } + + #[test] + fn writes_stay_inside_root() { + let dir = tempfile::tempdir().unwrap(); + let t = TargetRoot::new(dir.path()); + let p = t.write("etc/fstab", "hello").unwrap(); + assert!(p.starts_with(dir.path())); + assert_eq!(t.read_to_string("etc/fstab").unwrap(), "hello"); + } +} diff --git a/installer-rs/crates/phoebus-core/src/update.rs b/installer-rs/crates/phoebus-core/src/update.rs new file mode 100644 index 0000000..2b93876 --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/update.rs @@ -0,0 +1,109 @@ +//! Background update preparation. +//! +//! Preparation is non-destructive: distfiles are fetched and reusable local +//! binary packages are built *without* installing anything. Activation is a +//! separate, conservative, user-approved step. Only real Portage capabilities +//! are used (`--fetchonly`, `--buildpkgonly`). + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PowerState { + Ac, + Battery, + Unknown, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PrepareStatus { + Idle, + Running, + Ready, + Failed, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct PrepareState { + pub last_prepared_unix: u64, + pub status: PrepareStatus, + pub prepared_packages: u32, + pub note: String, +} + +impl Default for PrepareState { + fn default() -> Self { + Self { + last_prepared_unix: 0, + status: PrepareStatus::Idle, + prepared_packages: 0, + note: String::new(), + } + } +} + +/// Whether a background build should run now. +/// +/// Conservative defaults: never build on battery, and only when the machine is +/// not under heavy load. +pub fn should_prepare(power: PowerState, load_average: f32, cores: u32, idle: bool) -> bool { + if power == PowerState::Battery { + return false; + } + let cores = cores.max(1) as f32; + // Allow when the run queue is below half the core count. + if load_average > cores / 2.0 { + return false; + } + // On AC we may prepare even if not fully idle, but an interactive system is + // still respected by the load check above. + power == PowerState::Ac || idle +} + +/// Real Portage arguments for the preparation steps. Kept as data so they are +/// unit-testable and reused verbatim by the executor. +pub fn fetch_args() -> Vec<&'static str> { + vec!["--fetchonly", "--update", "--deep", "--newuse", "@world"] +} + +pub fn build_args() -> Vec<&'static str> { + // --buildpkgonly builds and stores binary packages without installing. + vec![ + "--buildpkgonly", + "--update", + "--deep", + "--newuse", + "--binpkg-respect-use=y", + "@world", + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn battery_never_prepares() { + assert!(!should_prepare(PowerState::Battery, 0.0, 8, true)); + } + + #[test] + fn ac_and_idle_prepares_when_load_low() { + assert!(should_prepare(PowerState::Ac, 1.0, 8, false)); + assert!(should_prepare(PowerState::Unknown, 0.5, 8, true)); + } + + #[test] + fn high_load_defers() { + assert!(!should_prepare(PowerState::Ac, 7.0, 8, false)); + } + + #[test] + fn args_are_real_portage_flags() { + assert!(fetch_args().contains(&"--fetchonly")); + assert!(build_args().contains(&"--buildpkgonly")); + assert!(build_args().contains(&"@world")); + } +} diff --git a/installer-rs/crates/phoebus-core/src/validate.rs b/installer-rs/crates/phoebus-core/src/validate.rs new file mode 100644 index 0000000..c2b0e7c --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/validate.rs @@ -0,0 +1,253 @@ +//! Configuration validation. Pure decision logic, testable without root. + +use serde::{Deserialize, Serialize}; + +use crate::config::InstallConfig; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ValidationIssue { + pub field: &'static str, + pub message: String, +} + +impl ValidationIssue { + pub fn new(field: &'static str, message: impl Into) -> Self { + Self { + field, + message: message.into(), + } + } +} + +impl std::fmt::Display for ValidationIssue { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}: {}", self.field, self.message) + } +} + +pub fn validate_hostname(hostname: &str) -> Result<(), String> { + if hostname.is_empty() || hostname.len() > 63 { + return Err("hostname must be 1-63 characters".into()); + } + let bytes = hostname.as_bytes(); + let valid_start = bytes[0].is_ascii_alphanumeric(); + let valid_end = bytes[hostname.len() - 1].is_ascii_alphanumeric(); + let valid_chars = hostname + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-'); + if !valid_start || !valid_end { + return Err("hostname must begin and end with an alphanumeric character".into()); + } + if !valid_chars { + return Err("hostname may only contain letters, digits and internal hyphens".into()); + } + Ok(()) +} + +pub fn validate_username(username: &str) -> Result<(), String> { + if username.is_empty() { + return Err("username is required".into()); + } + if username == "root" { + return Err("refusing to create an account named root".into()); + } + if username.len() > 32 { + return Err("username must be at most 32 characters".into()); + } + let mut chars = username.chars(); + let first = chars.next().unwrap(); + if !(first.is_ascii_lowercase() || first == '_') { + return Err("username must start with a lowercase letter or underscore".into()); + } + if !username + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-') + { + return Err("username may only contain lowercase letters, digits, `_` and `-`".into()); + } + Ok(()) +} + +pub fn validate_timezone(timezone: &str) -> Result<(), String> { + if timezone.is_empty() { + return Err("timezone is required".into()); + } + let zoneinfo = std::path::Path::new("/usr/share/zoneinfo"); + if zoneinfo.is_dir() { + let candidate = zoneinfo.join(timezone); + if candidate.is_file() { + return Ok(()); + } + return Err(format!("unknown timezone: {timezone}")); + } + Ok(()) +} + +pub fn validate_locale(locale: &str) -> Result<(), String> { + if locale.is_empty() { + return Err("locale is required".into()); + } + let base = locale.split('.').next().unwrap_or(locale); + if std::path::Path::new("/usr/share/i18n/locales") + .join(base) + .is_file() + { + return Ok(()); + } + if locale + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.' || c == '-' || c == '@') + { + return Ok(()); + } + Err(format!("locale looks malformed: {locale}")) +} + +pub fn validate_keymap(keymap: &str) -> Result<(), String> { + if keymap.is_empty() { + Err("keymap is required".into()) + } else { + Ok(()) + } +} + +/// Simple heuristic password strength: weak / fair / strong. +pub fn password_strength(password: &str) -> &'static str { + let mut score = 0; + if password.len() >= 8 { + score += 1; + } + if password.len() >= 12 { + score += 1; + } + if password.chars().any(|c| c.is_ascii_uppercase()) { + score += 1; + } + if password.chars().any(|c| c.is_ascii_lowercase()) { + score += 1; + } + if password.chars().any(|c| c.is_ascii_digit()) { + score += 1; + } + if password.chars().any(|c| !c.is_ascii_alphanumeric()) { + score += 1; + } + match score { + 0..=2 => "weak", + 3..=4 => "fair", + _ => "strong", + } +} + +/// Validate the whole configuration. Disk protection is checked separately +/// against probed hardware at preflight time. +pub fn validate_config(config: &InstallConfig) -> Vec { + let mut issues = Vec::new(); + + if let Err(e) = validate_hostname(&config.system.hostname) { + issues.push(ValidationIssue::new("hostname", e)); + } + if let Err(e) = validate_username(&config.user.username) { + issues.push(ValidationIssue::new("username", e)); + } + if let Err(e) = validate_locale(&config.system.locale) { + issues.push(ValidationIssue::new("locale", e)); + } + if let Err(e) = validate_timezone(&config.system.timezone) { + issues.push(ValidationIssue::new("timezone", e)); + } + if let Err(e) = validate_keymap(&config.system.keymap) { + issues.push(ValidationIssue::new("keymap", e)); + } + if config.storage.disk.is_empty() { + issues.push(ValidationIssue::new("target_disk", "no target disk selected")); + } else if !config.storage.disk.starts_with("/dev/") { + issues.push(ValidationIssue::new( + "target_disk", + format!("target is not a device path: {}", config.storage.disk), + )); + } + if config.storage.efi_size_mib < 256 { + issues.push(ValidationIssue::new( + "efi_size_mib", + "EFI System Partition should be at least 256 MiB", + )); + } + if config.storage.subvols.is_empty() { + issues.push(ValidationIssue::new( + "subvols", + "at least one Btrfs subvolume is required", + )); + } + if config.is_encrypted() && config.encryption.name.is_empty() { + issues.push(ValidationIssue::new( + "luks_name", + "LUKS mapper name is required when encryption is enabled", + )); + } + if config.kernel.keep_kernels < 2 { + issues.push(ValidationIssue::new( + "keep_kernels", + "keep at least 2 kernels so a known-good kernel is available", + )); + } + if config.packages.accept_license.trim().is_empty() { + issues.push(ValidationIssue::new( + "accept_license", + "ACCEPT_LICENSE must not be empty", + )); + } + issues +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hostname_rules() { + assert!(validate_hostname("phoebus").is_ok()); + assert!(validate_hostname("my-box").is_ok()); + assert!(validate_hostname("").is_err()); + assert!(validate_hostname("-bad").is_err()); + assert!(validate_hostname("bad host").is_err()); + assert!(validate_hostname("bad-").is_err()); + } + + #[test] + fn username_rules() { + assert!(validate_username("alice").is_ok()); + assert!(validate_username("phoebus").is_ok()); + assert!(validate_username("root").is_err()); + assert!(validate_username("Alice").is_err()); + assert!(validate_username("").is_err()); + } + + #[test] + fn password_strength_levels() { + assert_eq!(password_strength("abc"), "weak"); + assert_eq!(password_strength("abcdefghij"), "weak"); + assert_eq!(password_strength("Abcdefghij"), "fair"); + assert_eq!(password_strength("Abcdef1!ghijk"), "strong"); + } + + #[test] + fn default_config_is_mostly_valid_but_missing_user_and_disk() { + let cfg = InstallConfig::default(); + let issues = validate_config(&cfg); + let fields: Vec<&str> = issues.iter().map(|i| i.field).collect(); + assert!(fields.contains(&"username")); + assert!(fields.contains(&"target_disk")); + } + + #[test] + fn complete_config_passes() { + let mut cfg = InstallConfig::default(); + cfg.system.hostname = "phoebus".into(); + cfg.system.timezone = "UTC".into(); + cfg.user.username = "alice".into(); + cfg.storage.disk = "/dev/vda".into(); + assert!(validate_config(&cfg).iter().all(|i| i.field != "username")); + assert!(validate_config(&cfg).iter().all(|i| i.field != "target_disk")); + } +} diff --git a/installer-rs/crates/phoebus-executor/Cargo.toml b/installer-rs/crates/phoebus-executor/Cargo.toml new file mode 100644 index 0000000..9ee40c3 --- /dev/null +++ b/installer-rs/crates/phoebus-executor/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "phoebus-executor" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +phoebus-core.workspace = true +phoebus-ai.workspace = true +serde.workspace = true +thiserror.workspace = true +zeroize.workspace = true +toml.workspace = true +tempfile.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/installer-rs/crates/phoebus-executor/src/actions.rs b/installer-rs/crates/phoebus-executor/src/actions.rs new file mode 100644 index 0000000..e26d985 --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/actions.rs @@ -0,0 +1,163 @@ +//! Execution of typed system actions after approval. +//! +//! These functions are the privileged broker. The model never calls them +//! directly; a human-approved, validated `SystemAction` does. + +use std::path::Path; + +use phoebus_core::action::SystemAction; + +use crate::auth::DestructiveAuthorization; +use crate::command::CommandSpec; +use crate::error::{ExecError, Result}; +use crate::exec::Exec; +use crate::snapshot; + +#[derive(Debug)] +pub struct ActionOutcome { + pub action: SystemAction, + pub output: String, + pub snapshot: Option, +} + +/// Human-readable preview shown before approval. +pub fn preview(action: &SystemAction) -> String { + let mut out = String::new(); + out.push_str("Proposed action:\n"); + out.push_str(&format!(" {}\n", action.describe())); + out.push_str(&format!(" risk: {:?}\n", action.risk())); + if action.is_mutating() { + out.push_str(" this will modify the system.\n"); + } + out +} + +pub fn execute( + exec: &Exec, + action: &SystemAction, + auth: Option<&DestructiveAuthorization>, + root: &Path, +) -> Result { + if action.is_mutating() && auth.is_none() { + return Err(ExecError::NotAuthorized(action.describe())); + } + let mut snapshot_id = None; + let output = match action { + SystemAction::InspectService { name } => { + let out = exec.runner.execute( + &CommandSpec::new("sys", "inspect service", "systemctl") + .args(["status", name, "--no-pager"]), + )?; + format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy()) + } + SystemAction::EnableService { name } => { + exec.run(CommandSpec::new("sys", "enable service", "systemctl").args(["enable", name]))?; + format!("enabled {name}") + } + SystemAction::DisableService { name } => { + exec.run(CommandSpec::new("sys", "disable service", "systemctl").args(["disable", name]))?; + format!("disabled {name}") + } + SystemAction::InspectPackage { atom } => { + let out = exec.runner.execute( + &CommandSpec::new("sys", "inspect package", "emerge") + .args(["--pretend", "--quiet", atom]), + )?; + format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy()) + } + SystemAction::InstallPackage { atom } => { + exec.run(CommandSpec::new("sys", "install package", "emerge").args(["--ask=n", atom]))?; + format!("installed {atom}") + } + SystemAction::UpdateSystem => { + exec.run( + CommandSpec::new("sys", "update system", "emerge") + .args(["--update", "--deep", "--newuse", "@world"]), + )?; + "system update complete".to_string() + } + SystemAction::CreateSnapshot { operation } => { + let auth = auth.expect("mutating action has auth"); + let record = snapshot::create_and_record(exec, auth, root, "/", operation)?; + snapshot_id = Some(record.id.clone()); + format!("snapshot created: {}", record.id) + } + SystemAction::PrepareUpdates => { + let cores = std::thread::available_parallelism() + .map(|n| n.get() as u32) + .unwrap_or(4); + let outcome = crate::update::prepare(exec, root, cores, true)?; + outcome.note + } + SystemAction::InspectUpdates => { + let state = crate::update::load_state(root); + format!( + "status: {:?}\nnote: {}\nlast prepared: {}", + state.status, state.note, state.last_prepared_unix + ) + } + SystemAction::History => { + let history = snapshot::read_history(root); + if history.records.is_empty() { + "no transaction history".to_string() + } else { + let mut s = String::new(); + for r in &history.records { + s.push_str(&format!( + "{:<40} {:<16?} {}\n", + r.id, r.status, r.operation + )); + } + s + } + } + }; + Ok(ActionOutcome { + action: action.clone(), + output, + snapshot: snapshot_id, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::command::RecordingRunner; + use crate::log::Logger; + use phoebus_core::Redactor; + + fn make_exec(runner: RecordingRunner) -> Exec { + let path = tempfile::tempdir().unwrap().keep(); + let logger = Logger::open(path.join("l.log"), Redactor::new(), false); + Exec::new(Box::new(runner), logger, false, path.join("root"), path) + } + + #[test] + fn mutating_action_requires_authorization() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let action = SystemAction::EnableService { name: "sshd".into() }; + let err = execute(&exec, &action, None, Path::new("/")).unwrap_err(); + assert!(matches!(err, ExecError::NotAuthorized(_))); + } + + #[test] + fn inspect_does_not_require_authorization() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let action = SystemAction::InspectService { name: "sshd".into() }; + execute(&exec, &action, None, Path::new("/")).unwrap(); + } + + #[test] + fn enable_builds_separate_arguments() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap(); + let action = SystemAction::EnableService { name: "sshd".into() }; + execute(&exec, &action, Some(&auth), Path::new("/")).unwrap(); + let spec = &runner.recorded()[0]; + assert_eq!(spec.program, "systemctl"); + assert_eq!(spec.args, vec!["enable", "sshd"]); + } +} diff --git a/installer-rs/crates/phoebus-executor/src/admin.rs b/installer-rs/crates/phoebus-executor/src/admin.rs new file mode 100644 index 0000000..d81d504 --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/admin.rs @@ -0,0 +1,112 @@ +//! System context collection for the AI assistant. +//! +//! Only system sources are read. The privacy policy is enforced here: the +//! collector never walks home directories or credential stores, and rejects +//! any path the policy forbids. This is not prompt-level "please don't read +//! private files"; it is the absence of a code path that could. + +use phoebus_ai::privacy::{ContextBundle, PrivacyPolicy}; + +use crate::command::CommandSpec; +use crate::exec::Exec; + +fn read_trim(path: &str) -> Option { + let s = std::fs::read_to_string(path).ok()?; + Some(s.trim().to_string()) +} + +fn run(exec: &Exec, program: &str, args: &[&str]) -> Option { + let spec = CommandSpec::new("admin", program, program).args(args.iter().map(|s| s.to_string())); + exec.runner.execute(&spec).ok().map(|o| { + let out = o.stdout_lossy(); + let err = o.stderr_lossy(); + if out.is_empty() { err } else { out } + }) +} + +/// Collect a system-only context bundle. +pub fn collect_system_context(exec: &Exec, policy: &PrivacyPolicy) -> ContextBundle { + let mut bundle = ContextBundle::default(); + + if let Some(v) = run(exec, "uname", &["-r"]) { + bundle.insert("kernel", v.trim()); + } + if let Some(v) = read_trim("/etc/os-release") { + bundle.insert("os_release", v); + } + if let Some(v) = read_trim("/proc/loadavg") { + bundle.insert("loadavg", v); + } + if let Some(v) = read_trim("/proc/meminfo") { + let total = v + .lines() + .find(|l| l.starts_with("MemTotal:")) + .unwrap_or("MemTotal: unknown"); + bundle.insert("memory", total.to_string()); + } + if let Some(v) = run(exec, "systemctl", &["is-system-running"]) { + bundle.insert("system_state", v.trim()); + } + if let Some(v) = run(exec, "systemctl", &["--failed", "--no-pager"]) { + bundle.insert("failed_units", v.trim()); + } + if let Some(v) = run(exec, "findmnt", &["-no", "SOURCE,FSTYPE", "/"]) { + bundle.insert("root_filesystem", v.trim()); + } + if let Some(v) = run(exec, "df", &["-h", "/"]) { + bundle.insert("root_usage", v.trim()); + } + if phoebus_executor_has("wpctl") { + if let Some(v) = run(exec, "wpctl", &["status"]) { + bundle.insert("pipewire", v.trim()); + } + } + + if policy.allow_raw_logs { + // Only reachable with explicit opt-in. Even then, journal is a system + // source, not user files. + if let Some(v) = run(exec, "journalctl", &["-b", "-p", "warning", "--no-pager", "-n", "50"]) { + bundle.insert("journal_warnings", v); + } + } + + bundle +} + +fn phoebus_executor_has(program: &str) -> bool { + crate::exec::find_in_path(program).is_some() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::command::RecordingRunner; + use crate::log::Logger; + use phoebus_core::Redactor; + + fn make_exec(runner: RecordingRunner) -> Exec { + let path = tempfile::tempdir().unwrap().keep(); + let logger = Logger::open(path.join("l.log"), Redactor::new(), false); + Exec::new(Box::new(runner), logger, false, path.join("root"), path) + } + + #[test] + fn collector_never_references_home_paths() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let bundle = collect_system_context(&exec, &PrivacyPolicy::default()); + // The bundle only contains system facts. + for key in bundle.system.keys() { + assert!(!key.contains("home"), "unexpected key {key}"); + } + // No command argument walks a home or credential path. + for spec in runner.recorded() { + for arg in &spec.args { + assert!( + !phoebus_ai::privacy::is_forbidden_path(arg), + "forbidden path in argument: {arg}" + ); + } + } + } +} diff --git a/installer-rs/crates/phoebus-executor/src/auth.rs b/installer-rs/crates/phoebus-executor/src/auth.rs new file mode 100644 index 0000000..b47afb9 --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/auth.rs @@ -0,0 +1,90 @@ +//! Destructive authorization. +//! +//! A `DestructiveAuthorization` can only be produced by [`authorize`], which +//! requires the caller to present the destructive preview and a final +//! confirmation. Destructive functions take `&DestructiveAuthorization`, so a +//! code path that skipped confirmation cannot compile against them. +//! +//! This is an internal correctness guard, not a security boundary against +//! malicious code already running in the same privileged process. + +use crate::error::{ExecError, Result}; + +#[derive(Debug)] +pub struct DestructiveAuthorization { + _private: (), +} + +impl DestructiveAuthorization { + fn issue() -> Self { + Self { _private: () } + } +} + +pub trait Confirmation { + /// Show the destructive preview and require the confirmation phrase. + fn confirm_erase(&self, preview: &str) -> Result; + /// Final yes/no confirmation immediately before execution. + fn confirm_final(&self, message: &str) -> Result; +} + +/// Confirm unconditionally. Only used for unattended installs where the caller +/// has explicitly opted in (e.g. `--yes` on a disposable VM disk). +pub struct AutoConfirm; + +impl Confirmation for AutoConfirm { + fn confirm_erase(&self, _preview: &str) -> Result { + Ok(true) + } + fn confirm_final(&self, _message: &str) -> Result { + Ok(true) + } +} + +/// Always refuse. Safe default for dry-run / plan modes. +pub struct DenyConfirm; + +impl Confirmation for DenyConfirm { + fn confirm_erase(&self, _preview: &str) -> Result { + Ok(false) + } + fn confirm_final(&self, _message: &str) -> Result { + Ok(false) + } +} + +/// Perform the full confirmation flow and issue a token only on approval. +pub fn authorize( + confirmation: &dyn Confirmation, + destructive_preview: &str, + final_message: &str, +) -> Result { + if !confirmation.confirm_erase(destructive_preview)? { + return Err(ExecError::NotAuthorized( + "whole-disk erase was not confirmed".into(), + )); + } + if !confirmation.confirm_final(final_message)? { + return Err(ExecError::NotAuthorized( + "installation was not confirmed".into(), + )); + } + Ok(DestructiveAuthorization::issue()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn auto_confirm_issues_token() { + let auth = authorize(&AutoConfirm, "preview", "go?").unwrap(); + let _ = &auth; + } + + #[test] + fn deny_confirm_refuses() { + let err = authorize(&DenyConfirm, "preview", "go?").unwrap_err(); + assert!(matches!(err, ExecError::NotAuthorized(_))); + } +} diff --git a/installer-rs/crates/phoebus-executor/src/boot.rs b/installer-rs/crates/phoebus-executor/src/boot.rs new file mode 100644 index 0000000..40ec324 --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/boot.rs @@ -0,0 +1,226 @@ +//! Bootloader installation: UEFI + systemd-boot with BLS entries. +//! +//! UKI is deferred: the dracut UKI generator did not embed the kernel command +//! line in the verified environment, producing an unbootable image. BLS +//! entries carry `options` and are the proven path. + +use std::path::{Path, PathBuf}; + +use phoebus_core::system as sysgen; +use phoebus_core::InstallConfig; + +use crate::command::CommandSpec; +use crate::error::{ExecError, Result}; +use crate::exec::Exec; +use crate::portage; + +pub fn write_install_conf(exec: &Exec) -> Result<()> { + exec.target() + .write("etc/kernel/install.conf", sysgen::install_conf())?; + exec.logger + .info("wrote /etc/kernel/install.conf (layout=bls)"); + Ok(()) +} + +pub fn write_dracut_conf(exec: &Exec, config: &InstallConfig) -> Result<()> { + exec.target().write( + "etc/dracut.conf.d/10-phoebus.conf", + sysgen::dracut_conf(config), + )?; + exec.logger.info("wrote /etc/dracut.conf.d/10-phoebus.conf"); + Ok(()) +} + +pub fn esp_path(exec: &Exec, config: &InstallConfig) -> std::path::PathBuf { + exec.root.join(config.storage.efi_mount.trim_start_matches('/')) +} + +pub fn install_systemd_boot(exec: &Exec, config: &InstallConfig) -> Result<()> { + portage::chroot( + exec, + Path::new(&exec.root), + "bootctl", + &["--esp-path", &config.storage.efi_mount, "install"], + ) +} + +pub fn write_loader_conf(exec: &Exec, config: &InstallConfig) -> Result<()> { + let dir = esp_path(exec, config).join("loader"); + std::fs::create_dir_all(&dir).map_err(|e| ExecError::io(dir.clone(), e))?; + let text = "# systemd-boot configuration\ndefault *\ntimeout 3\nconsole-mode keep\neditor no\n"; + std::fs::write(dir.join("loader.conf"), text) + .map_err(|e| ExecError::io(dir.join("loader.conf"), e))?; + exec.logger + .info(format!("wrote {}", dir.join("loader.conf").display())); + Ok(()) +} + +pub fn generate_entries(exec: &Exec) -> Result<()> { + portage::chroot(exec, Path::new(&exec.root), "kernel-install", &["add-all"]) +} + +pub fn install_fallback(exec: &Exec, config: &InstallConfig) -> Result<()> { + let esp = esp_path(exec, config); + let boot_dir = esp.join("EFI/BOOT"); + let systemd_dir = esp.join("EFI/systemd"); + std::fs::create_dir_all(&boot_dir).map_err(|e| ExecError::io(boot_dir.clone(), e))?; + std::fs::create_dir_all(&systemd_dir).map_err(|e| ExecError::io(systemd_dir.clone(), e))?; + + let mut src = systemd_dir.join("systemd-bootx64.efi"); + if !src.exists() { + let vendor = exec.root.join("usr/lib/systemd/boot/efi/systemd-bootx64.efi"); + if vendor.exists() { + src = vendor; + } else { + exec.logger + .warn("systemd-boot binary not found; EFI fallback not installed"); + return Ok(()); + } + } + let dst = boot_dir.join("BOOTX64.EFI"); + std::fs::copy(&src, &dst).map_err(|e| ExecError::io(dst.clone(), e))?; + exec.logger.info("installed EFI fallback bootloader"); + Ok(()) +} + +pub fn random_seed(exec: &Exec, config: &InstallConfig) -> Result<()> { + let dir = esp_path(exec, config).join("loader"); + std::fs::create_dir_all(&dir).map_err(|e| ExecError::io(dir.clone(), e))?; + let path = dir.join("random-seed"); + if !path.exists() { + let bytes: Vec = (0..512).map(|i| (i as u8).wrapping_mul(31).wrapping_add(7)).collect(); + std::fs::write(&path, bytes).map_err(|e| ExecError::io(path.clone(), e))?; + } + Ok(()) +} + +/// Write an additional BLS entry that boots the newest kernel into +/// `rescue.target`. This is a real recovery path: it unlocks LUKS and gives a +/// root shell with the network stack available. +pub fn write_recovery_entry(exec: &Exec, config: &InstallConfig) -> Result<()> { + let entries = esp_path(exec, config).join("loader/entries"); + if !entries.is_dir() { + return Ok(()); + } + let mut newest: Option<(std::time::SystemTime, PathBuf)> = None; + for entry in std::fs::read_dir(&entries).map_err(|e| ExecError::io(entries.clone(), e))? { + let entry = entry.map_err(|e| ExecError::io(entries.clone(), e))?; + let path = entry.path(); + if path.extension().and_then(|e| e.to_str()) != Some("conf") { + continue; + } + let name = entry.file_name().to_string_lossy().to_string(); + if name.contains("recovery") { + continue; + } + let modified = entry + .metadata() + .and_then(|m| m.modified()) + .unwrap_or(std::time::SystemTime::UNIX_EPOCH); + if newest.as_ref().map(|(t, _)| modified > *t).unwrap_or(true) { + newest = Some((modified, path)); + } + } + let Some((_, source)) = newest else { + return Ok(()); + }; + let text = std::fs::read_to_string(&source).map_err(|e| ExecError::io(source.clone(), e))?; + let mut linux = String::new(); + let mut initrds: Vec = Vec::new(); + let mut options = String::new(); + for line in text.lines() { + if let Some(v) = line.strip_prefix("linux") { + linux = v.trim().to_string(); + } else if let Some(v) = line.strip_prefix("initrd") { + initrds.push(v.trim().to_string()); + } else if let Some(v) = line.strip_prefix("options") { + options = v.trim().to_string(); + } + } + if linux.is_empty() { + return Ok(()); + } + let mut out = String::new(); + out.push_str("# Phoebus recovery entry (generated by the installer)\n"); + out.push_str("title Phoebus Recovery\n"); + out.push_str(&format!("linux {linux}\n")); + for initrd in &initrds { + out.push_str(&format!("initrd {initrd}\n")); + } + let recovery_options = format!("{options} systemd.unit=rescue.target"); + out.push_str(&format!("options {}\n", recovery_options.trim())); + let dest = entries.join("phoebus-recovery.conf"); + std::fs::write(&dest, out).map_err(|e| ExecError::io(dest.clone(), e))?; + exec.logger + .info(format!("wrote recovery entry {}", dest.display())); + Ok(()) +} + +pub fn verify(exec: &Exec, config: &InstallConfig) -> Result<()> { + let esp = esp_path(exec, config); + let loader_a = esp.join("EFI/systemd/systemd-bootx64.efi"); + let loader_b = esp.join("EFI/BOOT/BOOTX64.EFI"); + if !loader_a.exists() && !loader_b.exists() { + return Err(ExecError::operation( + "boot_install", + "verify", + format!("no systemd-boot loader found in {}", esp.display()), + )); + } + let loader_conf = esp.join("loader/loader.conf"); + if !loader_conf.exists() { + return Err(ExecError::operation( + "boot_install", + "verify", + "loader.conf not found", + )); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::command::RecordingRunner; + use crate::log::Logger; + use phoebus_core::Redactor; + + fn make_exec(runner: RecordingRunner) -> Exec { + let path = tempfile::tempdir().unwrap().keep(); + let logger = Logger::open(path.join("l.log"), Redactor::new(), false); + Exec::new(Box::new(runner), logger, false, path.join("root"), path) + } + + #[test] + fn recovery_entry_reuses_kernel_and_initrd() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner); + let cfg = InstallConfig::default(); + let entries = exec.root.join("efi/loader/entries"); + std::fs::create_dir_all(&entries).unwrap(); + std::fs::write( + entries.join("token-6.18.48.conf"), + "title Gentoo Linux\nlinux /token/6.18.48/linux\ninitrd /token/6.18.48/initrd\noptions rd.luks.name=x=cryptroot root=/dev/mapper/cryptroot rw quiet\n", + ) + .unwrap(); + write_recovery_entry(&exec, &cfg).unwrap(); + let text = std::fs::read_to_string(entries.join("phoebus-recovery.conf")).unwrap(); + assert!(text.contains("Phoebus Recovery")); + assert!(text.contains("/token/6.18.48/linux")); + assert!(text.contains("/token/6.18.48/initrd")); + assert!(text.contains("systemd.unit=rescue.target")); + } +} + +pub fn secureboot_status(exec: &Exec) -> String { + if !std::path::Path::new("/sys/firmware/efi/efivars").is_dir() { + return "not booted in UEFI mode".into(); + } + if crate::exec::find_in_path("mokutil").is_none() { + return "Secure Boot state unknown (mokutil not installed)".into(); + } + match exec.runner.execute(&CommandSpec::new("boot", "secureboot status", "mokutil").arg("--sb-state")) { + Ok(out) => out.stdout_lossy().trim().to_string(), + Err(_) => "unknown".into(), + } +} diff --git a/installer-rs/crates/phoebus-executor/src/command.rs b/installer-rs/crates/phoebus-executor/src/command.rs new file mode 100644 index 0000000..c1d8e76 --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/command.rs @@ -0,0 +1,283 @@ +//! Central command execution layer. +//! +//! Arguments stay separate: there is no `sh -c`, no string interpolation into +//! a shell, and secrets travel only via stdin. The `ProcessRunner` trait lets +//! privileged logic be tested with a fake runner without touching the system. + +use std::collections::HashMap; +use std::io::Write; +use std::path::PathBuf; +use std::process::{Command, Stdio}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use crate::error::{ExecError, Result}; + +#[derive(Debug, Clone)] +pub struct CommandSpec { + pub program: String, + pub args: Vec, + /// Raw stdin bytes. Never logged. Used for LUKS passphrases and password + /// hashes. + pub stdin: Option>, + pub env: Vec<(String, String)>, + pub cwd: Option, + pub stage: String, + pub operation: String, +} + +impl CommandSpec { + pub fn new(stage: impl Into, operation: impl Into, program: impl Into) -> Self { + Self { + program: program.into(), + args: Vec::new(), + stdin: None, + env: Vec::new(), + cwd: None, + stage: stage.into(), + operation: operation.into(), + } + } + + pub fn arg(mut self, arg: impl Into) -> Self { + self.args.push(arg.into()); + self + } + + pub fn args(mut self, args: I) -> Self + where + I: IntoIterator, + S: Into, + { + self.args.extend(args.into_iter().map(Into::into)); + self + } + + pub fn stdin(mut self, bytes: impl Into>) -> Self { + self.stdin = Some(bytes.into()); + self + } + + pub fn env(mut self, key: impl Into, value: impl Into) -> Self { + self.env.push((key.into(), value.into())); + self + } + + pub fn cwd(mut self, dir: impl Into) -> Self { + self.cwd = Some(dir.into()); + self + } +} + +#[derive(Debug, Clone)] +pub struct CommandOutput { + pub status: i32, + pub success: bool, + pub stdout: Vec, + pub stderr: Vec, + pub duration: Duration, +} + +impl CommandOutput { + pub fn dry_run() -> Self { + Self { + status: 0, + success: true, + stdout: Vec::new(), + stderr: Vec::new(), + duration: Duration::ZERO, + } + } + + pub fn stdout_lossy(&self) -> String { + String::from_utf8_lossy(&self.stdout).into_owned() + } + + pub fn stderr_lossy(&self) -> String { + String::from_utf8_lossy(&self.stderr).into_owned() + } +} + +pub trait ProcessRunner: Send + Sync { + fn execute(&self, spec: &CommandSpec) -> Result; +} + +/// The real process runner. +pub struct RealRunner; + +impl ProcessRunner for RealRunner { + fn execute(&self, spec: &CommandSpec) -> Result { + let start = Instant::now(); + let mut command = Command::new(&spec.program); + command.args(&spec.args); + for (k, v) in &spec.env { + command.env(k, v); + } + if let Some(cwd) = &spec.cwd { + command.current_dir(cwd); + } + command.stdout(Stdio::piped()); + command.stderr(Stdio::piped()); + command.stdin(if spec.stdin.is_some() { + Stdio::piped() + } else { + Stdio::null() + }); + + let mut child = command.spawn().map_err(|source| ExecError::Spawn { + program: spec.program.clone(), + source, + })?; + + if let Some(bytes) = &spec.stdin { + if let Some(mut stdin) = child.stdin.take() { + // Ignore broken-pipe style errors; the process exit status is + // the source of truth. + let _ = stdin.write_all(bytes); + let _ = stdin.flush(); + } + } + + let output = child.wait_with_output().map_err(|source| ExecError::Spawn { + program: spec.program.clone(), + source, + })?; + let duration = start.elapsed(); + let status = output.status.code().unwrap_or(-1); + Ok(CommandOutput { + status, + success: output.status.success(), + stdout: output.stdout, + stderr: output.stderr, + duration, + }) + } +} + +/// A recording runner for tests. It records every spec and returns canned +/// output per program (or a default success). Cloneable so a test can keep a +/// handle while the `Exec` owns another. +#[derive(Clone, Default)] +pub struct RecordingRunner { + recorded: Arc>>, + responses: Arc>>, + default: Arc>>, +} + +impl RecordingRunner { + pub fn new() -> Self { + Self::default() + } + + pub fn set_response(&self, program: &str, output: CommandOutput) { + self.responses + .lock() + .unwrap() + .insert(program.to_string(), output); + } + + pub fn set_default(&self, output: CommandOutput) { + *self.default.lock().unwrap() = Some(output); + } + + pub fn fail(&self, program: &str, stderr: &str) { + self.set_response( + program, + CommandOutput { + status: 1, + success: false, + stdout: Vec::new(), + stderr: stderr.as_bytes().to_vec(), + duration: Duration::from_millis(1), + }, + ); + } + + pub fn recorded(&self) -> Vec { + self.recorded.lock().unwrap().clone() + } + + pub fn programs(&self) -> Vec { + self.recorded() + .iter() + .map(|s| s.program.clone()) + .collect() + } + + pub fn len(&self) -> usize { + self.recorded.lock().unwrap().len() + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +impl ProcessRunner for RecordingRunner { + fn execute(&self, spec: &CommandSpec) -> Result { + self.recorded.lock().unwrap().push(spec.clone()); + if let Some(out) = self.responses.lock().unwrap().get(&spec.program) { + return Ok(out.clone()); + } + if let Some(out) = self.default.lock().unwrap().clone() { + return Ok(out); + } + Ok(CommandOutput { + status: 0, + success: true, + stdout: Vec::new(), + stderr: Vec::new(), + duration: Duration::from_millis(1), + }) + } +} + +/// A runner that refuses to execute and returns a failure for every command. +/// Useful for proving that dry-run never reaches the system. +pub struct NeverRunner; + +impl ProcessRunner for NeverRunner { + fn execute(&self, spec: &CommandSpec) -> Result { + Err(ExecError::operation( + &spec.stage, + &spec.operation, + "command attempted while execution is disabled", + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn arguments_stay_separate() { + let spec = CommandSpec::new("s", "op", "mkfs.btrfs") + .arg("-f") + .arg("/dev/vda2") + .arg("-L") + .arg("phoebus"); + assert_eq!( + spec.args, + vec!["-f", "/dev/vda2", "-L", "phoebus"] + ); + assert_eq!(spec.program, "mkfs.btrfs"); + } + + #[test] + fn recording_runner_records_and_responds() { + let runner = RecordingRunner::new(); + runner.fail("sgdisk", "boom"); + let spec = CommandSpec::new("storage", "partition", "sgdisk").arg("--zap-all"); + let out = runner.execute(&spec).unwrap(); + assert!(!out.success); + assert_eq!(runner.programs(), vec!["sgdisk"]); + } + + #[test] + fn real_runner_runs_a_trivial_command() { + let runner = RealRunner; + let spec = CommandSpec::new("test", "true", "true"); + assert!(runner.execute(&spec).unwrap().success); + } +} diff --git a/installer-rs/crates/phoebus-executor/src/desktop.rs b/installer-rs/crates/phoebus-executor/src/desktop.rs new file mode 100644 index 0000000..4e9ebd1 --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/desktop.rs @@ -0,0 +1,161 @@ +//! Desktop profile installation. +//! +//! The flagship desktop is a small Wayland tiling environment centred on dwl, +//! with PipeWire/WirePlumber audio. Flatpak is supported out of the box. + +use std::path::Path; + +use phoebus_core::policy::{PackagePolicyEngine, PolicyContext}; +use phoebus_core::system as sysgen; +use phoebus_core::{DesktopProfile, InstallConfig}; + +use crate::error::{ExecError, Result}; +use crate::exec::Exec; +use crate::portage; + +pub fn install( + exec: &Exec, + config: &InstallConfig, + engine: &PackagePolicyEngine, + ctx: &PolicyContext, +) -> Result<()> { + if config.desktop.profile == DesktopProfile::None { + exec.logger.info("no desktop profile selected"); + return Ok(()); + } + let mut packages: Vec = sysgen::desktop_packages(config.desktop.profile) + .into_iter() + .map(str::to_string) + .collect(); + packages.extend( + sysgen::desktop_audio_packages() + .into_iter() + .map(str::to_string), + ); + if config.desktop.flatpak { + packages.push("sys-apps/flatpak".to_string()); + } + exec.logger.info(format!( + "installing desktop profile '{}' ({} packages)", + config.desktop.profile, + packages.len() + )); + portage::emerge(exec, Path::new(&exec.root), &packages, engine, ctx) +} + +/// Write `/usr/local/bin/phoebus-session`, a clear manual entry point for the +/// Wayland desktop. It starts the supporting daemons and then execs dwl. +/// +/// Hotkeys (dwl defaults, Phoebus patches may add more): +/// Mod+Shift+Return terminal Mod+d launcher +/// Mod+Shift+q close window Mod+j / Mod+k focus next/prev +/// Mod+1..9 workspace Mod+Shift+e quit dwl +pub fn write_session_script(exec: &Exec, config: &InstallConfig) -> Result<()> { + if config.desktop.profile == DesktopProfile::None { + return Ok(()); + } + let target = exec.target(); + let script = r#"#!/bin/bash +# Phoebus Wayland session (generated by the installer). +# +# Start with: phoebus-session +# +# Hotkeys (dwl defaults): +# Mod+Shift+Return terminal Mod+d launcher +# Mod+Shift+q close window Mod+j / Mod+k focus next/prev +# Mod+1..9 workspace Mod+Shift+e quit dwl + +export XDG_SESSION_TYPE=wayland +export XDG_CURRENT_DESKTOP=phoebus +export XDG_SESSION_DESKTOP=phoebus + +# Use software rendering when there is no render node (e.g. a VM). +if [ -z "${WLR_RENDERER:-}" ] && [ ! -e /dev/dri/renderD128 ]; then + export WLR_RENDERER=pixman + export WLR_RENDERER_ALLOW_SOFTWARE=1 +fi + +waybar >/dev/null 2>&1 & +mako >/dev/null 2>&1 & +if [ -n "${PHOEBUS_WALLPAPER:-}" ] && [ -f "$PHOEBUS_WALLPAPER" ]; then + swaybg -i "$PHOEBUS_WALLPAPER" >/dev/null 2>&1 & +else + swaybg -c '#1e1e2e' >/dev/null 2>&1 & +fi + +exec dwl +"#; + let path = target.resolve("usr/local/bin/phoebus-session")?; + target.write("usr/local/bin/phoebus-session", script)?; + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)) + .map_err(|e| ExecError::io(path.clone(), e))?; + exec.logger + .info("wrote /usr/local/bin/phoebus-session"); + Ok(()) +} + +pub fn configure_flatpak(exec: &Exec, config: &InstallConfig) -> Result<()> { + if !config.desktop.flatpak { + return Ok(()); + } + if let Err(e) = portage::chroot( + exec, + Path::new(&exec.root), + "flatpak", + &[ + "remote-add", + "--if-not-exists", + "flathub", + "https://flathub.org/repo/flathub.flatpakrepo", + ], + ) { + exec.logger + .warn(format!("could not add flathub remote: {e}")); + return Ok(()); + } + exec.logger.info("flatpak configured with flathub"); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::command::RecordingRunner; + use crate::log::Logger; + use phoebus_core::Redactor; + + fn make_exec(runner: RecordingRunner) -> Exec { + let path = tempfile::tempdir().unwrap().keep(); + let logger = Logger::open(path.join("l.log"), Redactor::new(), false); + Exec::new(Box::new(runner), logger, false, path.join("root"), path) + } + + #[test] + fn session_script_is_written_and_execs_dwl() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner); + let mut cfg = InstallConfig::default(); + cfg.desktop.profile = DesktopProfile::Dwl; + write_session_script(&exec, &cfg).unwrap(); + let path = exec.root.join("usr/local/bin/phoebus-session"); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("exec dwl")); + assert!(text.contains("waybar")); + assert!(text.contains("mako")); + use std::os::unix::fs::PermissionsExt; + assert_ne!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o111, + 0 + ); + } + + #[test] + fn no_session_script_for_none_profile() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner); + let cfg = InstallConfig::default(); + write_session_script(&exec, &cfg).unwrap(); + assert!(!exec.root.join("usr/local/bin/phoebus-session").exists()); + } +} diff --git a/installer-rs/crates/phoebus-executor/src/encryption.rs b/installer-rs/crates/phoebus-executor/src/encryption.rs new file mode 100644 index 0000000..0ff784e --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/encryption.rs @@ -0,0 +1,132 @@ +//! LUKS2 encryption backend. +//! +//! Passphrases are passed only over stdin and never appear in a command line +//! or a log line. TPM2 enrollment is not implemented. + +use phoebus_core::{InstallConfig, SecretString}; + +use crate::auth::DestructiveAuthorization; +use crate::command::CommandSpec; +use crate::error::{ExecError, Result}; +use crate::exec::Exec; +use crate::probe; + +pub fn require_tools(exec: &Exec) -> Result<()> { + exec.require_tools(&["cryptsetup", "blkid"]) +} + +pub fn mapper_path(config: &InstallConfig) -> String { + format!("/dev/mapper/{}", config.encryption.name) +} + +pub fn luks_format( + exec: &Exec, + _auth: &DestructiveAuthorization, + config: &InstallConfig, + partition: &str, + passphrase: &SecretString, +) -> Result<()> { + if passphrase.is_empty() { + return Err(ExecError::operation( + "storage_prepare", + "luksFormat", + "no passphrase configured", + )); + } + let spec = CommandSpec::new("storage_prepare", "format LUKS2", "cryptsetup") + .args([ + "luksFormat", + "--batch-mode", + "--type", + "luks2", + "--cipher", + &config.encryption.cipher, + "--key-size", + &config.encryption.key_size.to_string(), + "--pbkdf", + &config.encryption.pbkdf, + "--key-file", + "-", + partition, + ]) + .stdin(passphrase.expose().as_bytes().to_vec()); + exec.run(spec)?; + Ok(()) +} + +pub fn luks_open( + exec: &Exec, + config: &InstallConfig, + partition: &str, + passphrase: &SecretString, +) -> Result<()> { + let spec = CommandSpec::new("storage_prepare", "open LUKS2", "cryptsetup") + .args([ + "open", + "--type", + "luks", + "--key-file", + "-", + partition, + &config.encryption.name, + ]) + .stdin(passphrase.expose().as_bytes().to_vec()); + exec.run(spec)?; + Ok(()) +} + +pub fn luks_close(exec: &Exec, _auth: &DestructiveAuthorization, config: &InstallConfig) -> Result<()> { + let spec = CommandSpec::new("finalize", "close LUKS device", "cryptsetup") + .arg("close") + .arg(&config.encryption.name); + exec.run(spec)?; + Ok(()) +} + +/// A crypttab line for the root partition, using its stable UUID. +pub fn crypttab_line(exec: &Exec, config: &InstallConfig, partition: &str) -> Result { + let uuid = probe::blkid_uuid(exec.runner.as_ref(), partition).ok_or_else(|| { + ExecError::operation("fstab_generate", "crypttab", "cannot determine LUKS UUID") + })?; + Ok(phoebus_core::system::crypttab(&config.encryption.name, &uuid)) +} + +pub fn tpm2_available() -> bool { + std::path::Path::new("/sys/class/tpm/tpm0").exists() + && crate::exec::find_in_path("systemd-cryptenroll").is_some() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::command::RecordingRunner; + use crate::log::Logger; + use phoebus_core::Redactor; + + fn make_exec(runner: RecordingRunner) -> Exec { + let path = tempfile::tempdir().unwrap().keep(); + let logger = Logger::open(path.join("l.log"), Redactor::new(), false); + Exec::new(Box::new(runner), logger, false, path.join("root"), path) + } + + #[test] + fn passphrase_goes_over_stdin_not_args() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let cfg = InstallConfig::default(); + let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap(); + let secret = SecretString::new("topsecret"); + luks_format(&exec, &auth, &cfg, "/dev/vda2", &secret).unwrap(); + let recorded = runner.recorded(); + let spec = &recorded[0]; + assert_eq!(spec.program, "cryptsetup"); + assert!(!spec.args.iter().any(|a| a.contains("topsecret"))); + assert_eq!(spec.stdin.as_deref(), Some(b"topsecret".as_slice())); + } + + #[test] + fn mapper_path_uses_configured_name() { + let cfg = InstallConfig::default(); + assert_eq!(mapper_path(&cfg), "/dev/mapper/cryptroot"); + } +} diff --git a/installer-rs/crates/phoebus-executor/src/error.rs b/installer-rs/crates/phoebus-executor/src/error.rs new file mode 100644 index 0000000..bc90b4f --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/error.rs @@ -0,0 +1,68 @@ +//! Executor errors. They preserve stage, operation, command, exit status and +//! captured output, and never contain secrets. + +use std::path::PathBuf; + +use phoebus_core::CoreError; + +pub type Result = std::result::Result; + +#[derive(Debug, thiserror::Error)] +pub enum ExecError { + #[error("[{stage}] {operation} failed (exit {status}): {program}")] + Command { + stage: String, + operation: String, + program: String, + status: i32, + stdout: String, + stderr: String, + }, + + #[error("[{stage}] {operation}: {message}")] + Operation { + stage: String, + operation: String, + message: String, + }, + + #[error("command could not be started: {program}: {source}")] + Spawn { + program: String, + #[source] + source: std::io::Error, + }, + + #[error("I/O error for {path}: {source}")] + Io { + path: PathBuf, + #[source] + source: std::io::Error, + }, + + #[error("missing required tool: {0}")] + MissingTool(String), + + #[error("destructive operation not authorized: {0}")] + NotAuthorized(String), + + #[error("core error: {0}")] + Core(#[from] CoreError), +} + +impl ExecError { + pub fn io(path: impl Into, source: std::io::Error) -> Self { + ExecError::Io { + path: path.into(), + source, + } + } + + pub fn operation(stage: &str, operation: &str, message: impl Into) -> Self { + ExecError::Operation { + stage: stage.to_string(), + operation: operation.to_string(), + message: message.into(), + } + } +} diff --git a/installer-rs/crates/phoebus-executor/src/exec.rs b/installer-rs/crates/phoebus-executor/src/exec.rs new file mode 100644 index 0000000..4c51345 --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/exec.rs @@ -0,0 +1,227 @@ +//! Execution context: the single place commands are run and logged. + +use std::path::{Path, PathBuf}; + +use phoebus_core::{Redactor, SecretString, TargetRoot}; + +use crate::command::{CommandOutput, CommandSpec, ProcessRunner}; +use crate::error::{ExecError, Result}; +use crate::log::Logger; + +pub struct Exec { + pub runner: Box, + pub logger: Logger, + pub dry_run: bool, + pub root: PathBuf, + pub state_dir: PathBuf, +} + +impl Exec { + pub fn new( + runner: Box, + logger: Logger, + dry_run: bool, + root: impl Into, + state_dir: impl Into, + ) -> Self { + Self { + runner, + logger, + dry_run, + root: root.into(), + state_dir: state_dir.into(), + } + } + + pub fn target(&self) -> TargetRoot { + TargetRoot::new(self.root.clone()) + } + + pub fn register_secret(&self, secret: &SecretString) { + self.logger.register_secret(secret); + } + + pub fn redactor(&self) -> &Redactor { + self.logger.redactor() + } + + /// Run a command, honouring dry-run, and log it with its exit status. + pub fn run(&self, spec: CommandSpec) -> Result { + if self.dry_run { + self.logger + .dry_run(&spec.stage, &spec.operation, &spec.program, &spec.args); + return Ok(CommandOutput::dry_run()); + } + let stdin_hidden = spec.stdin.is_some(); + let output = self.runner.execute(&spec)?; + self.logger.command( + &spec.stage, + &spec.operation, + &spec.program, + &spec.args, + output.status, + output.duration, + stdin_hidden, + ); + if !output.stdout.is_empty() { + self.logger.output(&output.stdout); + } + if !output.stderr.is_empty() { + self.logger.output(&output.stderr); + } + if !output.success { + return Err(ExecError::Command { + stage: spec.stage.clone(), + operation: spec.operation.clone(), + program: spec.program.clone(), + status: output.status, + stdout: self.redactor().redact(&output.stdout_lossy()), + stderr: self.redactor().redact(&output.stderr_lossy()), + }); + } + Ok(output) + } + + /// Run a command and return its captured stdout on success. + pub fn run_capture(&self, spec: CommandSpec) -> Result { + self.run(spec) + } + + /// Verify that all named commands are available in PATH. + pub fn require_tools(&self, tools: &[&str]) -> Result<()> { + for tool in tools { + if find_in_path(tool).is_none() { + return Err(ExecError::MissingTool((*tool).to_string())); + } + } + Ok(()) + } + + pub fn log_path(&self) -> &Path { + self.logger.path() + } + + /// Mount the pseudo-filesystems required by a target chroot. + pub fn mount_chroot(&self) -> Result<()> { + let root = self.root.to_string_lossy().to_string(); + self.run(CommandSpec::new("chroot", "mount proc", "mount").args(["-t", "proc", "proc"]).arg(format!("{root}/proc")))?; + self.run(CommandSpec::new("chroot", "mount sysfs", "mount").args(["--rbind", "/sys"]).arg(format!("{root}/sys")))?; + self.run(CommandSpec::new("chroot", "mount devtmpfs", "mount").args(["--rbind", "/dev"]).arg(format!("{root}/dev")))?; + let _ = self.run( + CommandSpec::new("chroot", "make /dev rslave", "mount") + .args(["--make-rslave"]) + .arg(format!("{root}/dev")), + ); + if self.root.join("run").is_dir() { + let _ = self.run( + CommandSpec::new("chroot", "mount tmpfs on /run", "mount") + .args(["-t", "tmpfs", "tmpfs"]) + .arg(format!("{root}/run")), + ); + } + Ok(()) + } + + pub fn umount_chroot(&self) -> Result<()> { + let root = self.root.to_string_lossy().to_string(); + for sub in ["proc", "sys", "dev"] { + let _ = self.run( + CommandSpec::new("chroot", format!("unmount {sub}"), "umount") + .arg("-l") + .arg(format!("{root}/{sub}")), + ); + } + Ok(()) + } + + /// Copy the host resolver configuration into the target so Portage can + /// reach the network. Best effort. + pub fn copy_resolv_conf(&self) -> Result<()> { + let src = Path::new("/etc/resolv.conf"); + if !src.exists() { + return Ok(()); + } + let dst = self.root.join("etc/resolv.conf"); + if let Some(parent) = dst.parent() { + let _ = std::fs::create_dir_all(parent); + } + let _ = std::fs::copy(src, &dst); + Ok(()) + } + + /// Copy the installer log into the target for post-mortem analysis. + pub fn export_log(&self) -> Result<()> { + let dst_dir = self.root.join("var/log/phoebus-installer"); + if std::fs::create_dir_all(&dst_dir).is_err() { + return Ok(()); + } + let _ = std::fs::copy(self.logger.path(), dst_dir.join("install.log")); + Ok(()) + } +} + +pub fn find_in_path(program: &str) -> Option { + if program.contains('/') { + let p = PathBuf::from(program); + return if is_executable(&p) { Some(p) } else { None }; + } + let path = std::env::var_os("PATH")?; + for dir in std::env::split_paths(&path) { + let candidate = dir.join(program); + if is_executable(&candidate) { + return Some(candidate); + } + } + None +} + +fn is_executable(path: &Path) -> bool { + use std::os::unix::fs::PermissionsExt; + match std::fs::metadata(path) { + Ok(meta) => meta.is_file() && meta.permissions().mode() & 0o111 != 0, + Err(_) => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::command::RecordingRunner; + use crate::log::Logger; + + fn exec(runner: RecordingRunner) -> Exec { + let dir = tempfile::tempdir().unwrap(); + // Leak the tempdir for the duration of the test process. + let path = dir.keep(); + let logger = Logger::open(path.join("install.log"), Redactor::new(), false); + Exec::new(Box::new(runner), logger, false, path.join("root"), path) + } + + #[test] + fn dry_run_does_not_execute() { + let runner = RecordingRunner::new(); + let mut e = exec(runner.clone()); + e.dry_run = true; + e.run(CommandSpec::new("s", "op", "sgdisk")).unwrap(); + assert!(runner.recorded().is_empty()); + } + + #[test] + fn failing_command_returns_error_with_stage() { + let runner = RecordingRunner::new(); + runner.fail("mkfs.btrfs", "no space"); + let e = exec(runner.clone()); + let err = e + .run(CommandSpec::new("storage_prepare", "mkfs", "mkfs.btrfs")) + .unwrap_err(); + let msg = err.to_string(); + assert!(msg.contains("storage_prepare")); + assert!(msg.contains("mkfs.btrfs")); + } + + #[test] + fn find_true_in_path() { + assert!(find_in_path("true").is_some()); + assert!(find_in_path("definitely-not-a-real-tool-xyz").is_none()); + } +} diff --git a/installer-rs/crates/phoebus-executor/src/kernel.rs b/installer-rs/crates/phoebus-executor/src/kernel.rs new file mode 100644 index 0000000..ba9d728 --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/kernel.rs @@ -0,0 +1,78 @@ +//! Kernel selection and configuration. +//! +//! The distribution kernel is used as a stable, complete base. The installer +//! applies conservative config fragments; it never generates a minimal kernel. + +use std::path::Path; + +use phoebus_core::policy::{PackagePolicyEngine, PolicyContext}; +use phoebus_core::system as sysgen; +use phoebus_core::{HardwareReport, InstallConfig}; + +use crate::error::{ExecError, Result}; +use crate::exec::Exec; +use crate::portage; + +pub fn write_profile(exec: &Exec, config: &InstallConfig) -> Result<()> { + exec.target().write( + "etc/kernel/config.d/00-phoebus-profile.config", + sysgen::kernel_profile_config(config), + )?; + exec.logger.info("wrote kernel profile fragment"); + Ok(()) +} + +pub fn write_cmdline( + exec: &Exec, + config: &InstallConfig, + luks_uuid: Option<&str>, + root_source: &str, +) -> Result<()> { + let cmdline = sysgen::kernel_cmdline(config, luks_uuid, root_source) + .map_err(|e| ExecError::operation("kernel_install", "cmdline", e))?; + exec.target().write("etc/kernel/cmdline", format!("{cmdline}\n"))?; + exec.logger + .info(format!("wrote /etc/kernel/cmdline: {cmdline}")); + Ok(()) +} + +pub fn install( + exec: &Exec, + config: &InstallConfig, + hardware: &HardwareReport, + engine: &PackagePolicyEngine, + ctx: &PolicyContext, +) -> Result<()> { + let mut packages = vec![config.kernel.selected_package()]; + for pkg in sysgen::kernel_extra_packages(&hardware.cpu) { + packages.push(pkg.to_string()); + } + exec.logger + .info(format!("installing kernel packages: {}", packages.join(" "))); + portage::emerge(exec, Path::new(&exec.root), &packages, engine, ctx) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::command::RecordingRunner; + use crate::log::Logger; + use phoebus_core::Redactor; + + fn make_exec(runner: RecordingRunner) -> Exec { + let path = tempfile::tempdir().unwrap().keep(); + let logger = Logger::open(path.join("l.log"), Redactor::new(), false); + Exec::new(Box::new(runner), logger, false, path.join("root"), path) + } + + #[test] + fn cmdline_written_with_rd_luks_name() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let cfg = InstallConfig::default(); + write_cmdline(&exec, &cfg, Some("uuid-1234"), "").unwrap(); + let text = std::fs::read_to_string(exec.root.join("etc/kernel/cmdline")).unwrap(); + assert!(text.contains("rd.luks.name=uuid-1234=cryptroot")); + assert!(text.contains("root=/dev/mapper/cryptroot")); + } +} diff --git a/installer-rs/crates/phoebus-executor/src/lib.rs b/installer-rs/crates/phoebus-executor/src/lib.rs new file mode 100644 index 0000000..8f4acab --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/lib.rs @@ -0,0 +1,31 @@ +//! Phoebus executor: privileged, deterministic system operations. +//! +//! Every external command goes through the `Exec` context, which centralises +//! logging, redaction and dry-run. Destructive operations require a +//! `DestructiveAuthorization` token produced only after explicit confirmation. + +pub mod actions; +pub mod admin; +pub mod auth; +pub mod boot; +pub mod command; +pub mod desktop; +pub mod encryption; +pub mod error; +pub mod exec; +pub mod kernel; +pub mod log; +pub mod portage; +pub mod probe; +pub mod services; +pub mod snapshot; +pub mod stage3; +pub mod storage; +pub mod update; +pub mod users; + +pub use auth::{authorize, AutoConfirm, Confirmation, DenyConfirm, DestructiveAuthorization}; +pub use command::{CommandOutput, CommandSpec, NeverRunner, ProcessRunner, RealRunner, RecordingRunner}; +pub use error::{ExecError, Result}; +pub use exec::Exec; +pub use log::Logger; diff --git a/installer-rs/crates/phoebus-executor/src/log.rs b/installer-rs/crates/phoebus-executor/src/log.rs new file mode 100644 index 0000000..baf32ee --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/log.rs @@ -0,0 +1,245 @@ +//! Installer logging with mandatory secret redaction. +//! +//! Every log line is passed through the shared `Redactor`, so a caller cannot +//! accidentally write a registered secret. Command output is captured and +//! logged through the same path. + +use std::fs::{File, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use phoebus_core::Redactor; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Level { + Debug, + Info, + Warn, + Error, +} + +impl Level { + fn as_str(self) -> &'static str { + match self { + Level::Debug => "DEBUG", + Level::Info => "INFO", + Level::Warn => "WARN", + Level::Error => "ERROR", + } + } +} + +pub struct Logger { + path: PathBuf, + file: Mutex>, + echo: bool, + redactor: Redactor, +} + +impl Logger { + /// Open (or create) the log file. Falls back to an in-memory logger when + /// the path cannot be opened, so logging never aborts the installer. + pub fn open(path: impl Into, redactor: Redactor, echo: bool) -> Self { + let path = path.into(); + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + let file = OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .ok(); + Self { + path, + file: Mutex::new(file), + echo, + redactor, + } + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub fn redactor(&self) -> &Redactor { + &self.redactor + } + + pub fn register_secret(&self, secret: &phoebus_core::SecretString) { + self.redactor.register(secret); + } + + fn write_line(&self, level: Level, message: &str) { + let message = self.redactor.redact(message); + let line = format!("{} [{}] {}\n", timestamp(), level.as_str(), message); + if let Ok(mut guard) = self.file.lock() { + if let Some(file) = guard.as_mut() { + let _ = file.write_all(line.as_bytes()); + let _ = file.flush(); + } + } + if self.echo { + let _ = std::io::stderr().write_all(line.as_bytes()); + } + } + + pub fn debug(&self, message: impl AsRef) { + self.write_line(Level::Debug, message.as_ref()); + } + pub fn info(&self, message: impl AsRef) { + self.write_line(Level::Info, message.as_ref()); + } + pub fn warn(&self, message: impl AsRef) { + self.write_line(Level::Warn, message.as_ref()); + } + pub fn error(&self, message: impl AsRef) { + self.write_line(Level::Error, message.as_ref()); + } + pub fn section(&self, name: &str) { + self.write_line(Level::Info, &format!("--- {name} ---")); + } + + /// Log a command with its exit status and duration (all redacted). + pub fn command( + &self, + stage: &str, + operation: &str, + program: &str, + args: &[String], + status: i32, + duration: Duration, + stdin_hidden: bool, + ) { + let mut line = format!("[{stage}] {operation} :: {program}"); + for arg in args { + line.push(' '); + line.push_str(&shell_quote(arg)); + } + if stdin_hidden { + line.push_str(" (stdin hidden)"); + } + line.push_str(&format!( + " :: exit {status} in {:.3}s", + duration.as_secs_f64() + )); + self.write_line(Level::Info, &line); + } + + /// Append raw command output (stdout/stderr) to the log, redacted. + pub fn output(&self, bytes: &[u8]) { + if bytes.is_empty() { + return; + } + let text = String::from_utf8_lossy(bytes); + let redacted = self.redactor.redact(&text); + if let Ok(mut guard) = self.file.lock() { + if let Some(file) = guard.as_mut() { + let _ = file.write_all(redacted.as_bytes()); + if !redacted.ends_with('\n') { + let _ = file.write_all(b"\n"); + } + let _ = file.flush(); + } + } + if self.echo { + let _ = std::io::stderr().write_all(redacted.as_bytes()); + } + } + + pub fn dry_run(&self, stage: &str, operation: &str, program: &str, args: &[String]) { + let mut line = format!("[{stage}] [dry-run] {operation} :: {program}"); + for arg in args { + line.push(' '); + line.push_str(&shell_quote(arg)); + } + self.write_line(Level::Info, &line); + } +} + +fn shell_quote(arg: &str) -> String { + if arg + .chars() + .all(|c| c.is_ascii_alphanumeric() || "-_./:=,@+".contains(c)) + { + arg.to_string() + } else { + format!("'{}'", arg.replace('\'', "'\\''")) + } +} + +/// Minimal UTC timestamp without pulling in a date crate. +fn timestamp() -> String { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default(); + let secs = now.as_secs() as i64; + let millis = now.subsec_millis(); + let days = secs.div_euclid(86_400); + let rem = secs.rem_euclid(86_400); + let (y, m, d) = civil_from_days(days); + let (hh, mm, ss) = (rem / 3600, (rem % 3600) / 60, rem % 60); + format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}.{millis:03}Z") +} + +/// Howard Hinnant's civil-from-days algorithm. +fn civil_from_days(z: i64) -> (i64, u32, u32) { + let z = z + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let doe = (z - era * 146_097) as i64; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = (doy - (153 * mp + 2) / 5 + 1) as u32; + let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; + (if m <= 2 { y + 1 } else { y }, m, d) +} + +#[cfg(test)] +mod tests { + use super::*; + use phoebus_core::SecretString; + + #[test] + fn secrets_are_redacted_in_log_file() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("install.log"); + let redactor = Redactor::new(); + let secret = SecretString::new("hunter2"); + redactor.register(&secret); + let logger = Logger::open(&path, redactor, false); + logger.info("passphrase is hunter2 here"); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("")); + assert!(!text.contains("hunter2")); + } + + #[test] + fn command_logging_includes_stage_and_status() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("install.log"); + let logger = Logger::open(&path, Redactor::new(), false); + logger.command( + "storage_prepare", + "create GPT", + "sgdisk", + &["--zap-all".into(), "/dev/vda".into()], + 0, + Duration::from_millis(12), + false, + ); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("[storage_prepare] create GPT :: sgdisk")); + assert!(text.contains("/dev/vda")); + assert!(text.contains("exit 0")); + } + + #[test] + fn timestamp_has_expected_shape() { + let ts = timestamp(); + assert_eq!(ts.len(), 24); + assert!(ts.ends_with('Z')); + } +} diff --git a/installer-rs/crates/phoebus-executor/src/portage.rs b/installer-rs/crates/phoebus-executor/src/portage.rs new file mode 100644 index 0000000..67c3336 --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/portage.rs @@ -0,0 +1,472 @@ +//! Portage configuration and base-system installation. +//! +//! Portage remains authoritative. The installer writes a sane initial config, +//! syncs the stable tree, sets up signed binary package verification, and runs +//! emerge inside the target chroot. + +use std::path::Path; + +use phoebus_core::policy::{InstallMethod, PackagePolicyEngine, PolicyContext}; +use phoebus_core::system as sysgen; +use phoebus_core::{HardwareReport, InstallConfig, TargetRoot}; + +use crate::command::CommandSpec; +use crate::error::{ExecError, Result}; +use crate::exec::Exec; + +pub fn write_config(exec: &Exec, config: &InstallConfig, hardware: &HardwareReport) -> Result<()> { + let root = exec.target(); + root.write("etc/portage/make.conf", sysgen::make_conf(config, hardware))?; + root.write("etc/portage/repos.conf/gentoo.conf", sysgen::repos_conf())?; + root.write( + "etc/portage/binrepos.conf/gentoo.conf", + sysgen::binrepos_conf(config), + )?; + root.write("etc/portage/package.use/phoebus", sysgen::package_use(config))?; + root.write( + "etc/portage/package.accept_keywords/phoebus", + sysgen::accept_keywords_policy(), + )?; + exec.logger.info("wrote Portage configuration"); + Ok(()) +} + +pub fn select_profile(exec: &Exec, config: &InstallConfig) -> Result<()> { + let root = exec.target(); + let link = root.etc("portage/make.profile")?; + if let Some(parent) = link.parent() { + std::fs::create_dir_all(parent).map_err(|e| ExecError::io(parent.to_path_buf(), e))?; + } + let _ = std::fs::remove_file(&link); + let target = format!( + "/var/db/repos/gentoo/profiles/{}", + sysgen::selected_profile(config) + ); + std::os::unix::fs::symlink(&target, &link) + .map_err(|e| ExecError::io(link.clone(), e))?; + exec.logger.info(format!("profile -> {target}")); + Ok(()) +} + +fn chroot_spec(stage: &str, operation: &str, root: &Path, program: &str, args: &[String]) -> CommandSpec { + let mut spec = CommandSpec::new(stage, operation, "chroot") + .arg(root.to_string_lossy().to_string()) + .args([ + "/usr/bin/env", + "-i", + "PATH=/usr/sbin:/usr/bin:/sbin:/bin", + "HOME=/root", + "TERM=xterm", + "LANG=C", + "TMPDIR=/tmp", + program, + ]) + .args(args.iter().cloned()); + spec.cwd = None; + spec +} + +pub fn chroot(exec: &Exec, root: &Path, program: &str, args: &[&str]) -> Result<()> { + let owned: Vec = args.iter().map(|s| (*s).to_string()).collect(); + let spec = chroot_spec( + "portage_configure", + &format!("chroot: {program}"), + root, + program, + &owned, + ); + exec.run(spec)?; + Ok(()) +} + +pub fn chroot_stdin( + exec: &Exec, + root: &Path, + program: &str, + args: &[&str], + input: &[u8], +) -> Result<()> { + let owned: Vec = args.iter().map(|s| (*s).to_string()).collect(); + let mut spec = chroot_spec( + "users_configure", + &format!("chroot: {program}"), + root, + program, + &owned, + ); + spec.stdin = Some(input.to_vec()); + exec.run(spec)?; + Ok(()) +} + +pub fn init_machine_id(exec: &Exec, root: &Path) -> Result<()> { + chroot(exec, root, "systemd-machine-id-setup", &[]) +} + +pub fn sync(exec: &Exec, root: &Path) -> Result<()> { + // A single rsync mirror can be mid-update, which makes Portage quarantine + // the tree ("Manifest verification failed"). Retry a few times. + let mut last_err = None; + for attempt in 1..=3 { + match chroot(exec, root, "emerge", &["--sync"]) { + Ok(()) => return Ok(()), + Err(e) => { + exec.logger + .warn(format!("emerge --sync attempt {attempt} failed: {e}")); + last_err = Some(e); + } + } + } + Err(last_err.unwrap_or_else(|| { + ExecError::operation("portage_configure", "emerge --sync", "sync failed") + })) +} + +pub fn verification_setup(exec: &Exec, root: &Path) -> Result<()> { + // getuto populates /etc/portage/gnupg with the Gentoo release key so that + // signed binary packages can be verified. Signature verification stays + // enabled; signing/verifying keys are public by definition. + chroot(exec, root, "getuto", &[])?; + if let Err(e) = relax_verify_keyring(exec) { + exec.logger + .warn(format!("could not make the GPG keyring accessible: {e}")); + } + Ok(()) +} + +/// Make the getuto keyring usable by Portage's dropped-privilege verifier. +/// +/// Portage verifies binary package signatures as `GPG_VERIFY_USER_DROP` +/// (default `nobody`), but getuto leaves `pubring.kbx` mode 0600 and the +/// directory non-writable. Public key material is not secret, so make the +/// public artifacts world-readable and let the verify user create its +/// `random_seed` file. `pass` and the private key directories stay 0600/0700. +pub fn relax_verify_keyring(exec: &Exec) -> Result<()> { + use std::os::unix::fs::{chown, PermissionsExt}; + + let dir = Path::new(&exec.root).join("etc/portage/gnupg"); + if !dir.is_dir() { + return Ok(()); + } + let gid = target_group_gid(&exec.root, "nogroup") + .or_else(|| target_group_gid(&exec.root, "nobody")); + + // Avoid gpg trying to write random_seed as the dropped user. + let gpg_conf = dir.join("gpg.conf"); + let mut conf = std::fs::read_to_string(&gpg_conf).unwrap_or_default(); + if !conf.contains("no-random-seed-file") { + if !conf.is_empty() && !conf.ends_with('\n') { + conf.push('\n'); + } + conf.push_str("no-random-seed-file\n"); + let _ = std::fs::write(&gpg_conf, conf); + } + + let skip = ["pass"]; + let skip_dirs = ["private-keys-v1.d", "openpgp-revocs.d"]; + if let Ok(entries) = std::fs::read_dir(&dir) { + for entry in entries.flatten() { + let path = entry.path(); + let name = entry.file_name().to_string_lossy().to_string(); + let meta = match entry.metadata() { + Ok(m) => m, + Err(_) => continue, + }; + if meta.is_dir() { + if skip_dirs.contains(&name.as_str()) { + continue; + } + let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)); + } else { + if skip.contains(&name.as_str()) { + continue; + } + let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)); + } + if let Some(gid) = gid { + let _ = chown(&path, None, Some(gid)); + } + } + } + + // The directory itself: readable/traversable, and writable by the verify + // group so gpg can create lock and random-seed files. + let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o775)); + if let Some(gid) = gid { + let _ = chown(&dir, None, Some(gid)); + } + exec.logger + .info("relaxed GPG keyring permissions for binary verification"); + Ok(()) +} + +fn target_group_gid(root: &Path, group: &str) -> Option { + let text = std::fs::read_to_string(root.join("etc/group")).ok()?; + for line in text.lines() { + let fields: Vec<&str> = line.split(':').collect(); + if fields.len() >= 3 && fields[0] == group { + return fields[2].parse::().ok(); + } + } + None +} + +pub fn base_packages() -> Vec<&'static str> { + sysgen::base_packages() +} + +pub fn write_locale_gen(exec: &Exec, config: &InstallConfig) -> Result<()> { + let root = exec.target(); + if config.system.locale.is_empty() { + return Ok(()); + } + let existing = root.read_to_string("etc/locale.gen").unwrap_or_default(); + let locale = &config.system.locale; + let already = existing + .lines() + .any(|l| l.trim_start().starts_with(&format!("{locale} "))); + if !already { + let mut text = existing; + if !text.is_empty() && !text.ends_with('\n') { + text.push('\n'); + } + text.push_str(&sysgen::locale_gen_line(locale)); + root.write("etc/locale.gen", text)?; + exec.logger.info(format!("locale.gen: enabled {locale}")); + } + Ok(()) +} + +/// Group packages by policy decision and run one emerge per group. +pub fn emerge( + exec: &Exec, + root: &Path, + packages: &[String], + engine: &PackagePolicyEngine, + ctx: &PolicyContext, +) -> Result<()> { + let mut source: Vec = Vec::new(); + let mut binary: Vec = Vec::new(); + for pkg in packages { + if pkg.is_empty() { + continue; + } + let decision = engine.decide(pkg, ctx); + exec.logger.info(format!( + "policy: {pkg} -> {} ({:?})", + decision.method.as_str(), + decision.reason + )); + match decision.method { + InstallMethod::Source => source.push(pkg.clone()), + InstallMethod::Binary => binary.push(pkg.clone()), + } + } + + if !source.is_empty() { + exec.logger + .info(format!("emerge (source): {}", source.join(" "))); + let mut args: Vec = vec![ + "--ask=n".into(), + "--quiet-build=y".into(), + "--binpkg-respect-use=y".into(), + ]; + args.extend(source.clone()); + let spec = chroot_spec("packages_base", "emerge source group", root, "emerge", &args); + exec.run(spec)?; + } + if !binary.is_empty() { + exec.logger + .info(format!("emerge (binary): {}", binary.join(" "))); + let mut args: Vec = vec![ + "--ask=n".into(), + "--quiet-build=y".into(), + "--getbinpkg".into(), + "--binpkg-respect-use=y".into(), + ]; + args.extend(binary.clone()); + let spec = chroot_spec("packages_base", "emerge binary group", root, "emerge", &args); + exec.run(spec)?; + } + Ok(()) +} + +/// Harvest measured compile times from the target's `emerge.log`. +/// +/// This records real measured durations; nothing is invented. +pub fn harvest_emerge_log(exec: &Exec, history_path: &Path) -> Result<()> { + let log_path = Path::new(&exec.root).join("var/log/emerge.log"); + let Ok(text) = std::fs::read_to_string(&log_path) else { + return Ok(()); + }; + let measured = phoebus_core::emergelog::parse_emerge_log(&text); + if measured.is_empty() { + return Ok(()); + } + let mut history = phoebus_core::policy::load_history(history_path); + for (atom, seconds) in measured { + history.insert(atom, seconds); + } + if let Err(e) = phoebus_core::policy::save_history(history_path, &history) { + exec.logger + .warn(format!("could not save compile-time history: {e}")); + return Ok(()); + } + exec.logger.info(format!( + "recorded {} measured compile times", + history.len() + )); + Ok(()) +} + +/// Convenience for a single package install outside the grouped path. +pub fn emerge_one( + exec: &Exec, + root: &Path, + pkg: &str, + engine: &PackagePolicyEngine, + ctx: &PolicyContext, +) -> Result<()> { + emerge(exec, root, &[pkg.to_string()], engine, ctx) +} + +pub fn target_root(exec: &Exec) -> TargetRoot { + exec.target() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::command::{CommandOutput, RecordingRunner}; + use crate::log::Logger; + use phoebus_core::Redactor; + + fn make_exec(runner: RecordingRunner) -> Exec { + let path = tempfile::tempdir().unwrap().keep(); + let logger = Logger::open(path.join("l.log"), Redactor::new(), false); + Exec::new(Box::new(runner), logger, false, path.join("root"), path) + } + + #[test] + fn chroot_command_separates_args_and_sets_tmpdir() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + chroot(&exec, Path::new("/mnt/t"), "emerge", &["--sync"]).unwrap(); + let recorded = runner.recorded(); + let spec = &recorded[0]; + assert_eq!(spec.program, "chroot"); + assert_eq!(spec.args[0], "/mnt/t"); + assert!(spec.args.iter().any(|a| a == "TMPDIR=/tmp")); + assert_eq!(spec.args.last().map(String::as_str), Some("--sync")); + assert!(spec.args.iter().any(|a| a == "emerge")); + } + + #[test] + fn emerge_groups_by_policy() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let cfg = InstallConfig::default(); + let engine = PackagePolicyEngine::new(); + let ctx = PolicyContext { + policy: cfg.packages.policy, + binhost_available: true, + memory_mib: 8192, + cores: 8, + }; + let pkgs = vec!["app-editors/vim".to_string(), "www-client/firefox".to_string()]; + emerge(&exec, Path::new("/mnt/t"), &pkgs, &engine, &ctx).unwrap(); + let programs: Vec = runner.programs(); + // Two chroot invocations: source group then binary group. + let emerges: Vec = runner + .recorded() + .into_iter() + .filter(|s| s.args.iter().any(|a| a == "emerge")) + .collect(); + assert_eq!(emerges.len(), 2); + assert!(programs.iter().all(|p| p == "chroot")); + } + + #[test] + fn locale_gen_appends_once() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let mut cfg = InstallConfig::default(); + cfg.system.locale = "en_US.UTF-8".into(); + write_locale_gen(&exec, &cfg).unwrap(); + write_locale_gen(&exec, &cfg).unwrap(); + let text = std::fs::read_to_string(exec.root.join("etc/locale.gen")).unwrap(); + assert_eq!(text.matches("en_US.UTF-8").count(), 1); + } + + #[test] + fn relax_keyring_makes_public_files_readable_but_not_secrets() { + use std::os::unix::fs::PermissionsExt; + let runner = RecordingRunner::new(); + let exec = make_exec(runner); + let dir = Path::new(&exec.root).join("etc/portage/gnupg"); + std::fs::create_dir_all(dir.join("private-keys-v1.d")).unwrap(); + for name in ["pubring.kbx", "pass", "gpg.conf", "trustdb.gpg"] { + let p = dir.join(name); + std::fs::write(&p, "x").unwrap(); + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + std::fs::set_permissions( + dir.join("private-keys-v1.d"), + std::fs::Permissions::from_mode(0o700), + ) + .unwrap(); + + relax_verify_keyring(&exec).unwrap(); + + let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(&dir.join("pubring.kbx")), 0o644); + assert_eq!(mode(&dir.join("trustdb.gpg")), 0o644); + assert_eq!(mode(&dir.join("pass")), 0o600, "secret pass file unchanged"); + assert_eq!( + mode(&dir.join("private-keys-v1.d")), + 0o700, + "private keys unchanged" + ); + assert_eq!(mode(&dir), 0o775); + assert!(std::fs::read_to_string(dir.join("gpg.conf")) + .unwrap() + .contains("no-random-seed-file")); + } + + #[test] + fn binary_group_requests_getbinpkg() { + let runner = RecordingRunner::new(); + runner.set_response( + "chroot", + CommandOutput { + status: 0, + success: true, + stdout: Vec::new(), + stderr: Vec::new(), + duration: std::time::Duration::from_millis(1), + }, + ); + let exec = make_exec(runner.clone()); + let engine = PackagePolicyEngine::new(); + let ctx = PolicyContext { + policy: phoebus_core::PackagePolicy::Balanced, + binhost_available: true, + memory_mib: 8192, + cores: 8, + }; + emerge( + &exec, + Path::new("/mnt/t"), + &["www-client/firefox".to_string()], + &engine, + &ctx, + ) + .unwrap(); + let recorded = runner.recorded(); + let spec = recorded + .iter() + .find(|s| s.args.iter().any(|a| a == "emerge")) + .unwrap(); + assert!(spec.args.iter().any(|a| a == "--getbinpkg")); + } +} diff --git a/installer-rs/crates/phoebus-executor/src/probe.rs b/installer-rs/crates/phoebus-executor/src/probe.rs new file mode 100644 index 0000000..ad66669 --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/probe.rs @@ -0,0 +1,468 @@ +//! Read-only hardware and disk probing. +//! +//! These functions never write. They take a `ProcessRunner` directly so they +//! still work in dry-run mode (mirroring the Bash prototype, where probing is +//! independent of `run_cmd`). + +use std::collections::HashMap; + +use phoebus_core::disk::{Disk, DiskKind}; +use phoebus_core::hardware::{CpuInfo, FirmwareMode, GpuInfo, GpuVendor, HardwareReport, NetworkDevice}; + +use crate::command::{CommandSpec, ProcessRunner}; + +fn capture(runner: &dyn ProcessRunner, program: &str, args: &[&str]) -> String { + let spec = CommandSpec::new("probe", program, program).args(args.iter().map(|s| s.to_string())); + match runner.execute(&spec) { + Ok(out) => out.stdout_lossy(), + Err(_) => String::new(), + } +} + +fn read_trim(path: &str) -> Option { + std::fs::read_to_string(path) + .ok() + .map(|s| s.trim().to_string()) +} + +// --------------------------------------------------------------------------- +// Hardware +// --------------------------------------------------------------------------- + +pub fn probe_firmware() -> FirmwareMode { + if std::path::Path::new("/sys/firmware/efi").is_dir() { + FirmwareMode::Uefi + } else { + FirmwareMode::Bios + } +} + +pub fn probe_cpu() -> CpuInfo { + let mut info = CpuInfo::default(); + if let Ok(text) = std::fs::read_to_string("/proc/cpuinfo") { + let mut threads = 0u32; + for line in text.lines() { + if line.starts_with("processor") { + threads += 1; + } + if let Some((key, value)) = line.split_once(':') { + let key = key.trim(); + let value = value.trim(); + match key { + "vendor_id" if info.vendor.is_empty() => info.vendor = value.into(), + "model name" if info.model.is_empty() => info.model = value.into(), + "flags" if info.features.is_empty() => { + info.features = value.split_whitespace().map(str::to_string).collect(); + } + _ => {} + } + } + } + info.threads = threads; + } + if let Ok(text) = std::fs::read_to_string("/sys/devices/system/cpu/online") { + // "0-7" or "0" + let text = text.trim(); + if let Some((a, b)) = text.split_once('-') { + if let (Ok(a), Ok(b)) = (a.parse::(), b.parse::()) { + info.cores = b - a + 1; + } + } else if let Ok(n) = text.parse::() { + info.cores = n + 1; + } + } + if info.cores == 0 { + info.cores = info.threads.max(1); + } + info +} + +pub fn probe_memory_mib() -> u64 { + if let Ok(text) = std::fs::read_to_string("/proc/meminfo") { + for line in text.lines() { + if let Some(rest) = line.strip_prefix("MemTotal:") { + if let Some(kb) = rest.split_whitespace().next() { + if let Ok(kb) = kb.parse::() { + return kb / 1024; + } + } + } + } + } + 0 +} + +fn classify_gpu(line: &str) -> GpuVendor { + let lower = line.to_ascii_lowercase(); + if lower.contains("nvidia") { + GpuVendor::Nvidia + } else if lower.contains("amd") || lower.contains("ati") || lower.contains("advanced micro") { + GpuVendor::Amd + } else if lower.contains("intel") { + GpuVendor::Intel + } else { + GpuVendor::Unknown + } +} + +fn lspci_filter(runner: &dyn ProcessRunner, pattern: &str) -> Vec { + let out = capture(runner, "lspci", &["-nn"]); + out.lines() + .filter(|l| { + let l = l.to_ascii_lowercase(); + pattern + .split('|') + .any(|p| l.contains(&p.to_ascii_lowercase())) + }) + .map(str::to_string) + .collect() +} + +pub fn probe_hardware(runner: &dyn ProcessRunner) -> HardwareReport { + let cpu = probe_cpu(); + let gpu_lines = lspci_filter( + runner, + "VGA compatible controller|3D controller|Display controller", + ); + let gpus = gpu_lines + .iter() + .map(|l| GpuInfo { + vendor: classify_gpu(l), + description: l.clone(), + }) + .collect(); + + let mut network = Vec::new(); + if let Ok(entries) = std::fs::read_dir("/sys/class/net") { + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + if name == "lo" { + continue; + } + let base = entry.path(); + let wireless = base.join("wireless").exists() || base.join("phy80211").exists(); + let operstate = read_trim(&base.join("operstate").to_string_lossy()).unwrap_or_default(); + network.push(NetworkDevice { + name, + wireless, + operstate, + }); + } + } + + let mut bluetooth = lspci_filter(runner, "Bluetooth"); + if let Ok(out) = std::process::Command::new("lsusb").output() { + let text = String::from_utf8_lossy(&out.stdout); + for line in text.lines().filter(|l| l.to_ascii_lowercase().contains("bluetooth")) { + bluetooth.push(line.to_string()); + } + } + + let input_devices = std::fs::read_to_string("/proc/bus/input/devices") + .map(|t| t.lines().filter(|l| l.starts_with("N: Name=")).count() as u32) + .unwrap_or(0); + + let laptop = std::fs::read_dir("/sys/class/power_supply") + .map(|entries| { + entries.flatten().any(|e| { + e.file_name() + .to_string_lossy() + .starts_with("BAT") + }) + }) + .unwrap_or(false); + + HardwareReport { + firmware: Some(probe_firmware()), + cpu, + memory_mib: probe_memory_mib(), + gpus, + network, + storage_controllers: lspci_filter(runner, "SATA controller|NVMe|RAID bus controller"), + audio: lspci_filter(runner, "Audio device"), + bluetooth, + usb_controllers: lspci_filter(runner, "USB controller"), + input_devices, + laptop, + } +} + +// --------------------------------------------------------------------------- +// Disks +// --------------------------------------------------------------------------- + +/// Parse `lsblk -P` output (`KEY="value" ...`) into a map. +pub fn parse_pairs(line: &str) -> HashMap { + let mut map = HashMap::new(); + let bytes = line.as_bytes(); + let mut i = 0; + while i < bytes.len() { + // skip whitespace + while i < bytes.len() && bytes[i].is_ascii_whitespace() { + i += 1; + } + let key_start = i; + while i < bytes.len() && bytes[i] != b'=' { + i += 1; + } + if i >= bytes.len() { + break; + } + let key = line[key_start..i].to_string(); + i += 1; // skip '=' + if i >= bytes.len() || bytes[i] != b'"' { + continue; + } + i += 1; + let mut value = String::new(); + while i < bytes.len() { + match bytes[i] { + b'\\' if i + 1 < bytes.len() => { + value.push(bytes[i + 1] as char); + i += 2; + } + b'"' => { + i += 1; + break; + } + c => { + value.push(c as char); + i += 1; + } + } + } + map.insert(key, value); + } + map +} + +fn read_mounts() -> Vec<(String, String)> { + let mut out = Vec::new(); + if let Ok(text) = std::fs::read_to_string("/proc/mounts") { + for line in text.lines() { + let mut parts = line.split_whitespace(); + if let (Some(src), Some(mp)) = (parts.next(), parts.next()) { + out.push((src.to_string(), mp.to_string())); + } + } + } + out +} + +fn read_cmdline() -> Vec { + std::fs::read_to_string("/proc/cmdline") + .map(|t| t.split_whitespace().map(str::to_string).collect()) + .unwrap_or_default() +} + +fn is_block_device(path: &str) -> bool { + use std::os::unix::fs::FileTypeExt; + std::fs::metadata(path) + .map(|m| m.file_type().is_block_device()) + .unwrap_or(false) +} + +fn disk_kind(name: &str, path: &str) -> DiskKind { + if name.starts_with("sr") || path.starts_with("/dev/sr") { + DiskKind::Optical + } else if name.starts_with("loop") || path.starts_with("/dev/loop") { + DiskKind::Loop + } else if name.starts_with("dm-") || path.starts_with("/dev/mapper") { + DiskKind::DeviceMapper + } else { + DiskKind::Physical + } +} + +/// List child partition device paths for a disk. +pub fn disk_partitions(runner: &dyn ProcessRunner, disk: &str) -> Vec { + let out = capture(runner, "lsblk", &["-rno", "NAME", disk]); + out.lines() + .skip(1) + .map(|l| l.trim()) + .filter(|l| !l.is_empty()) + .map(|name| format!("/dev/{name}")) + .collect() +} + +fn parent_disk(runner: &dyn ProcessRunner, dev: &str) -> String { + if dev.starts_with("/dev/loop") + || dev.starts_with("/dev/dm-") + || dev.starts_with("/dev/mapper") + || dev.starts_with("/dev/sr") + { + return dev.to_string(); + } + let out = capture(runner, "lsblk", &["-no", "PKNAME", dev]); + match out.lines().next().map(str::trim).filter(|s| !s.is_empty()) { + Some(pk) => format!("/dev/{pk}"), + None => dev.to_string(), + } +} + +fn live_source_disks(runner: &dyn ProcessRunner) -> Vec { + let mut sources: Vec = Vec::new(); + for tok in read_cmdline() { + if let Some((key, value)) = tok.split_once('=') { + if matches!(key, "root" | "cdroot" | "boot") { + sources.push(value.to_string()); + } + } + } + let mounts = read_mounts(); + for mp in ["/", "/run/initramfs", "/run/live", "/mnt/cdrom", "/mnt/live", "/lib/live"] { + if let Some((src, _)) = mounts.iter().find(|(_, m)| m == mp) { + sources.push(src.clone()); + } + } + let mut disks: Vec = Vec::new(); + for src in sources { + if !src.starts_with("/dev/") { + continue; + } + if !is_block_device(&src) { + continue; + } + let disk = parent_disk(runner, &src); + if !disks.contains(&disk) { + disks.push(disk); + } + } + disks +} + +pub fn probe_disks(runner: &dyn ProcessRunner) -> Vec { + let out = capture( + runner, + "lsblk", + &["-dn", "-P", "-o", "NAME,MODEL,SIZE,TRAN,RM,RO"], + ); + let mounts = read_mounts(); + let live = live_source_disks(runner); + + let mut disks = Vec::new(); + for line in out.lines() { + let pairs = parse_pairs(line); + let Some(name) = pairs.get("NAME") else { + continue; + }; + let path = format!("/dev/{name}"); + let kind = disk_kind(name, &path); + let size = pairs + .get("SIZE") + .and_then(|s| s.parse::().ok()) + .unwrap_or(0); + let read_only = pairs.get("RO").map(|v| v == "1").unwrap_or(false); + let removable = pairs.get("RM").map(|v| v == "1").unwrap_or(false); + let model = pairs + .get("MODEL") + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()); + let transport = pairs + .get("TRAN") + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()); + + // Mounted when the disk or any child partition is a mount source. + let mounted = mounts + .iter() + .any(|(src, _)| src == &path || is_partition_of(&path, src)); + + let live_media = live.iter().any(|d| d == &path); + disks.push(Disk { + path, + model, + size_bytes: size, + transport, + removable, + read_only, + mounted, + // lsblk only lists kernel block devices, so entries are block + // devices by construction. The explicit check remains available to + // callers that build a `Disk` from other sources. + is_block_device: true, + kind, + live_media, + }); + } + disks.sort_by(|a, b| a.path.cmp(&b.path)); + disks +} + +pub fn probe_disk_layout(runner: &dyn ProcessRunner, disk: &str) -> String { + capture( + runner, + "lsblk", + &["-o", "NAME,SIZE,TYPE,FSTYPE,LABEL,MOUNTPOINTS", disk], + ) +} + +/// True when `device` is a partition of `disk` (vda -> vda1, nvme0n1 -> nvme0n1p1). +pub fn is_partition_of(disk: &str, device: &str) -> bool { + let Some(rest) = device.strip_prefix(disk) else { + return false; + }; + if rest.is_empty() { + return false; + } + if rest.chars().all(|c| c.is_ascii_digit()) { + return true; + } + if let Some(digits) = rest.strip_prefix('p') { + return !digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()); + } + false +} + +pub fn blkid_uuid(runner: &dyn ProcessRunner, device: &str) -> Option { + let out = capture(runner, "blkid", &["-s", "UUID", "-o", "value", device]); + out.lines().next().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string) +} + +pub fn blkid_partlabel(runner: &dyn ProcessRunner, device: &str) -> Option { + let out = capture(runner, "blkid", &["-s", "PARTLABEL", "-o", "value", device]); + out.lines().next().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::command::{CommandOutput, RecordingRunner}; + + #[test] + fn parse_pairs_handles_quotes_and_escapes() { + let line = r#"NAME="vda" MODEL="QEMU HARDDISK" SIZE="32212254720" TRAN="virtio" RM="0" RO="0""#; + let pairs = parse_pairs(line); + assert_eq!(pairs.get("NAME").unwrap(), "vda"); + assert_eq!(pairs.get("SIZE").unwrap(), "32212254720"); + assert_eq!(pairs.get("MODEL").unwrap(), "QEMU HARDDISK"); + } + + #[test] + fn probe_disks_classifies_optical_as_protected() { + let runner = RecordingRunner::new(); + runner.set_response( + "lsblk", + CommandOutput { + status: 0, + success: true, + stdout: b"NAME=\"sr0\" MODEL=\"QEMU DVD-ROM\" SIZE=\"1073741824\" TRAN=\"sata\" RM=\"1\" RO=\"1\"\nNAME=\"vda\" MODEL=\"QEMU HARDDISK\" SIZE=\"32212254720\" TRAN=\"virtio\" RM=\"0\" RO=\"0\"\n".to_vec(), + stderr: Vec::new(), + duration: std::time::Duration::from_millis(1), + }, + ); + let disks = probe_disks(&runner); + let sr = disks.iter().find(|d| d.path == "/dev/sr0").unwrap(); + assert!(sr.is_protected()); + let vda = disks.iter().find(|d| d.path == "/dev/vda").unwrap(); + assert!(!vda.is_protected()); + } + + #[test] + fn disk_kind_classification() { + assert_eq!(disk_kind("sr0", "/dev/sr0"), DiskKind::Optical); + assert_eq!(disk_kind("loop0", "/dev/loop0"), DiskKind::Loop); + assert_eq!(disk_kind("dm-0", "/dev/dm-0"), DiskKind::DeviceMapper); + assert_eq!(disk_kind("vda", "/dev/vda"), DiskKind::Physical); + } +} diff --git a/installer-rs/crates/phoebus-executor/src/services.rs b/installer-rs/crates/phoebus-executor/src/services.rs new file mode 100644 index 0000000..5ea478b --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/services.rs @@ -0,0 +1,57 @@ +//! Target system services: hostname, keymap, timezone, locale and systemd +//! unit enablement. + +use std::path::Path; + +use phoebus_core::system as sysgen; +use phoebus_core::InstallConfig; + +use crate::error::{ExecError, Result}; +use crate::exec::Exec; +use crate::portage; + +pub fn configure(exec: &Exec, config: &InstallConfig) -> Result<()> { + write_network(exec, config)?; + let target = exec.target(); + target.write( + "etc/vconsole.conf", + format!("KEYMAP={}\n", config.system.keymap), + )?; + target.write( + "etc/locale.conf", + format!("LANG={}\n", config.system.locale), + )?; + set_timezone(exec, &config.system.timezone)?; + portage::write_locale_gen(exec, config)?; + + let root = Path::new(&exec.root); + let _ = portage::chroot(exec, root, "locale-gen", &[]); + + for svc in sysgen::target_services(config) { + if let Err(e) = portage::chroot(exec, root, "systemctl", &["enable", &svc]) { + exec.logger.warn(format!("could not enable {svc}: {e}")); + } + } + Ok(()) +} + +pub fn write_network(exec: &Exec, config: &InstallConfig) -> Result<()> { + let target = exec.target(); + target.write("etc/hostname", format!("{}\n", config.system.hostname))?; + let hosts = format!( + "127.0.0.1\tlocalhost\n::1\t\tlocalhost\n127.0.1.1\t{}\n", + config.system.hostname + ); + target.write("etc/hosts", hosts)?; + Ok(()) +} + +pub fn set_timezone(exec: &Exec, timezone: &str) -> Result<()> { + let target = exec.target(); + target.ensure_dir("etc")?; + let link = target.etc("localtime")?; + let _ = std::fs::remove_file(&link); + let dest = format!("/usr/share/zoneinfo/{timezone}"); + std::os::unix::fs::symlink(&dest, &link).map_err(|e| ExecError::io(link.clone(), e))?; + Ok(()) +} diff --git a/installer-rs/crates/phoebus-executor/src/snapshot.rs b/installer-rs/crates/phoebus-executor/src/snapshot.rs new file mode 100644 index 0000000..453d113 --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/snapshot.rs @@ -0,0 +1,160 @@ +//! Btrfs snapshot creation and transaction history. +//! +//! Snapshots are read-only and live under the `@snapshots` subvolume +//! (`/.snapshots`). A record is appended to the history before the operation +//! and marked committed only afterwards. Real rollback (default-subvolume +//! switching plus `/boot` handling) is deliberately *not* implemented here; the +//! foundations are. +//! +//! `/home` is a separate subvolume and is intentionally not snapshotted by +//! default, so a future system rollback cannot discard user documents. + +use std::path::{Path, PathBuf}; + +use phoebus_core::snapshot::{snapshot_name, SnapshotHistory, SnapshotRecord, SnapshotStatus}; + +use crate::auth::DestructiveAuthorization; +use crate::command::CommandSpec; +use crate::error::{ExecError, Result}; +use crate::exec::Exec; + +pub const SNAPSHOT_DIR: &str = ".snapshots"; +pub const HISTORY_REL: &str = "var/lib/phoebus/snapshot-history.toml"; + +pub fn snapshots_path(root: &Path) -> PathBuf { + root.join(SNAPSHOT_DIR) +} + +pub fn history_path(root: &Path) -> PathBuf { + root.join(HISTORY_REL) +} + +pub fn read_history(root: &Path) -> SnapshotHistory { + SnapshotHistory::load(&history_path(root)).unwrap_or_default() +} + +pub fn write_history(root: &Path, history: &SnapshotHistory) -> Result<()> { + history + .save(&history_path(root)) + .map_err(ExecError::Core) +} + +fn now_unix() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +/// Create a read-only snapshot of `source_subvol` (usually the mounted root). +pub fn create( + exec: &Exec, + _auth: &DestructiveAuthorization, + root: &Path, + source_subvol: &str, + operation: &str, +) -> Result { + let dir = snapshots_path(root); + std::fs::create_dir_all(&dir).map_err(|e| ExecError::io(dir.clone(), e))?; + let unix = now_unix(); + let name = snapshot_name("@", unix, operation); + let dest = dir.join(&name); + + exec.run( + CommandSpec::new("snapshot", format!("create snapshot {name}"), "btrfs") + .args(["subvolume", "snapshot", "-r"]) + .arg(source_subvol) + .arg(dest.to_string_lossy().to_string()), + )?; + + let record = SnapshotRecord { + id: name.clone(), + created_unix: unix, + operation: operation.to_string(), + source_subvol: source_subvol.to_string(), + snapshot_subvol: name, + status: SnapshotStatus::Created, + }; + Ok(record) +} + +/// Create a snapshot and record it as committed in the history. +pub fn create_and_record( + exec: &Exec, + auth: &DestructiveAuthorization, + root: &Path, + source_subvol: &str, + operation: &str, +) -> Result { + let mut record = create(exec, auth, root, source_subvol, operation)?; + record.status = SnapshotStatus::Committed; + let mut history = read_history(root); + history.append(record.clone()); + write_history(root, &history)?; + exec.logger + .info(format!("snapshot committed: {}", record.id)); + Ok(record) +} + +pub fn list(_exec: &Exec, root: &Path) -> Result> { + let dir = snapshots_path(root); + if !dir.is_dir() { + return Ok(Vec::new()); + } + let mut names: Vec = std::fs::read_dir(&dir) + .map_err(|e| ExecError::io(dir.clone(), e))? + .flatten() + .map(|e| e.file_name().to_string_lossy().to_string()) + .collect(); + names.sort(); + Ok(names) +} + +pub fn delete(exec: &Exec, _auth: &DestructiveAuthorization, root: &Path, id: &str) -> Result<()> { + let target = snapshots_path(root).join(id); + exec.run( + CommandSpec::new("snapshot", format!("delete snapshot {id}"), "btrfs") + .args(["subvolume", "delete"]) + .arg(target.to_string_lossy().to_string()), + )?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::command::RecordingRunner; + use crate::log::Logger; + use phoebus_core::Redactor; + + fn make_exec(runner: RecordingRunner) -> Exec { + let path = tempfile::tempdir().unwrap().keep(); + let logger = Logger::open(path.join("l.log"), Redactor::new(), false); + Exec::new(Box::new(runner), logger, false, path.join("root"), path) + } + + #[test] + fn create_uses_readonly_btrfs_snapshot() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap(); + let record = create(&exec, &auth, Path::new(&exec.root), "/", "sys update").unwrap(); + assert_eq!(record.status, SnapshotStatus::Created); + let spec = &runner.recorded()[0]; + assert_eq!(spec.program, "btrfs"); + assert_eq!(&spec.args[0..3], &["subvolume", "snapshot", "-r"]); + assert!(spec.args.iter().any(|a| a.contains(".snapshots"))); + } + + #[test] + fn create_and_record_commits_history() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap(); + let record = create_and_record(&exec, &auth, Path::new(&exec.root), "/", "risk").unwrap(); + assert_eq!(record.status, SnapshotStatus::Committed); + let history = read_history(Path::new(&exec.root)); + assert_eq!(history.records.len(), 1); + assert_eq!(history.latest().unwrap().id, record.id); + } +} diff --git a/installer-rs/crates/phoebus-executor/src/stage3.rs b/installer-rs/crates/phoebus-executor/src/stage3.rs new file mode 100644 index 0000000..0d95b7f --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/stage3.rs @@ -0,0 +1,193 @@ +//! Gentoo stage3 acquisition and verification. +//! +//! The stage3 tarball may be pinned (URL + SHA-256) or resolved from the +//! Gentoo mirror. Unpinned downloads verify the signed DIGESTS file and its +//! SHA-512 entry. Signature verification fails closed when gpg and the Gentoo +//! release key are available. + +use std::path::{Path, PathBuf}; + +use phoebus_core::InstallConfig; + +use crate::command::{CommandOutput, CommandSpec}; +use crate::error::{ExecError, Result}; +use crate::exec::Exec; + +pub fn require_tools(exec: &Exec) -> Result<()> { + exec.require_tools(&["curl", "tar"]) +} + +/// Resolve the stage3 download URL. +pub fn resolve_url(exec: &Exec, config: &InstallConfig) -> Result { + if !config.stage3.url.is_empty() { + return Ok(config.stage3.url.clone()); + } + let base = config.stage3.mirror.trim_end_matches('/'); + let latest = format!("{base}/current-stage3-amd64-systemd/latest-stage3-amd64-systemd.txt"); + let out = exec.runner.execute( + &CommandSpec::new("stage_install", "resolve latest stage3", "curl") + .args(["-fsSL", &latest]), + )?; + let text = out.stdout_lossy(); + for line in text.lines() { + let mut fields = line.split_whitespace(); + if let Some(name) = fields.next() { + if name.starts_with("stage3-amd64-systemd-") && name.ends_with(".tar.xz") { + return Ok(format!("{base}/current-stage3-amd64-systemd/{name}")); + } + } + } + Err(ExecError::operation( + "stage_install", + "resolve stage3", + "could not resolve the latest stage3; set STAGE3_URL explicitly", + )) +} + +fn hash_file(exec: &Exec, program: &str, path: &Path) -> Result { + let out = exec.runner.execute( + &CommandSpec::new("stage_install", "hash stage3", program).arg(path.to_string_lossy()), + )?; + out.stdout_lossy() + .split_whitespace() + .next() + .map(str::to_string) + .ok_or_else(|| ExecError::operation("stage_install", "hash", "empty hash output")) +} + +/// Download and verify the stage3 tarball into `state_dir`. +pub fn fetch(exec: &Exec, config: &InstallConfig, state_dir: &Path) -> Result { + let url = resolve_url(exec, config)?; + let dest = state_dir.join("stage3-systemd.tar.xz"); + std::fs::create_dir_all(state_dir).map_err(|e| ExecError::io(state_dir.to_path_buf(), e))?; + exec.logger.info(format!("stage3 URL: {url}")); + + exec.run( + CommandSpec::new("stage_install", "download stage3", "curl") + .args(["-fL", "--retry", "3", "-o"]) + .arg(dest.to_string_lossy().to_string()) + .arg(&url), + )?; + + if !config.stage3.sha256.is_empty() { + let got = hash_file(exec, "sha256sum", &dest)?; + if got != config.stage3.sha256 { + return Err(ExecError::operation( + "stage_install", + "verify stage3", + format!("SHA-256 mismatch (expected {}, got {})", config.stage3.sha256, got), + )); + } + exec.logger.info("stage3 checksum verified (pinned SHA-256)"); + return Ok(dest); + } + + verify_digests(exec, &url, &dest)?; + Ok(dest) +} + +fn verify_digests(exec: &Exec, url: &str, dest: &Path) -> Result<()> { + let digests = dest.with_extension("xz.DIGESTS"); + let spec = CommandSpec::new("stage_install", "download stage3 DIGESTS", "curl") + .args(["-fsSL", "-o"]) + .arg(digests.to_string_lossy().to_string()) + .arg(format!("{url}.DIGESTS")); + if exec.run(spec).is_err() { + exec.logger + .warn("could not fetch stage3 DIGESTS; checksum not verified"); + return Ok(()); + } + if let Err(e) = verify_signature(exec, &digests) { + let _ = std::fs::remove_file(&digests); + return Err(e); + } + let base = url.rsplit('/').next().unwrap_or_default(); + let text = std::fs::read_to_string(&digests) + .map_err(|e| ExecError::io(digests.clone(), e))?; + let want = text.lines().find_map(|line| { + let mut f = line.split_whitespace(); + let hash = f.next()?; + let name = f.next()?; + if hash.len() == 128 && name == base { + Some(hash.to_string()) + } else { + None + } + }); + let _ = std::fs::remove_file(&digests); + let Some(want) = want else { + exec.logger.warn("no SHA-512 entry found in DIGESTS; checksum not verified"); + return Ok(()); + }; + let got = hash_file(exec, "sha512sum", dest)?; + if got != want { + return Err(ExecError::operation( + "stage_install", + "verify stage3", + "SHA-512 mismatch against signed DIGESTS", + )); + } + exec.logger + .info("stage3 SHA-512 verified against signed DIGESTS"); + Ok(()) +} + +fn verify_signature(exec: &Exec, digests: &Path) -> Result<()> { + let key = "/usr/share/openpgp-keys/gentoo-release.asc"; + if crate::exec::find_in_path("gpg").is_none() || !Path::new(key).is_file() { + exec.logger + .warn("gpg or Gentoo release key unavailable; skipping signature check"); + return Ok(()); + } + let home = tempfile::tempdir().map_err(|e| ExecError::io(std::env::temp_dir(), e))?; + let home_str = home.path().to_string_lossy().to_string(); + let import = CommandSpec::new("stage_install", "import Gentoo release key", "gpg") + .args(["--batch", "--quiet", "--import", key]) + .env("GNUPGHOME", &home_str); + if exec.runner.execute(&import).is_err() { + exec.logger + .warn("could not import Gentoo release key; skipping signature check"); + return Ok(()); + } + let verify = CommandSpec::new("stage_install", "verify stage3 DIGESTS signature", "gpg") + .args(["--batch", "--verify"]) + .arg(digests.to_string_lossy().to_string()) + .env("GNUPGHOME", &home_str); + match exec.runner.execute(&verify) { + Ok(out) => { + exec.logger.output(&out.stdout); + exec.logger.output(&out.stderr); + if out.success { + Ok(()) + } else { + Err(ExecError::operation( + "stage_install", + "verify stage3 DIGESTS signature", + "signature verification FAILED", + )) + } + } + Err(_) => Ok(()), + } +} + +pub fn extract(exec: &Exec, root: &Path, tarball: &Path) -> Result<()> { + exec.run( + CommandSpec::new("stage_install", "extract stage3", "tar") + .args([ + "--xattrs", + "--xattrs-include=*.*", + "--numeric-owner", + "-xpf", + ]) + .arg(tarball.to_string_lossy().to_string()) + .args(["-C"]) + .arg(root.to_string_lossy().to_string()), + )?; + Ok(()) +} + +/// Convenience used by tests. +pub fn dry_output() -> CommandOutput { + CommandOutput::dry_run() +} diff --git a/installer-rs/crates/phoebus-executor/src/storage.rs b/installer-rs/crates/phoebus-executor/src/storage.rs new file mode 100644 index 0000000..b3b490b --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/storage.rs @@ -0,0 +1,526 @@ +//! GPT partitioning, filesystems, Btrfs layout, fstab/crypttab generation. +//! +//! The order is the proven one: partition, create ESP, LUKS format/open, +//! mkfs.btrfs, mount top-level, create subvolumes, unmount top-level, mount the +//! subvolume layout. fstab/crypttab are written *after* stage3 extraction. + +use phoebus_core::system as sysgen; +use phoebus_core::{Encryption, InstallConfig, SecretString}; + +use crate::auth::DestructiveAuthorization; +use crate::command::{CommandSpec, ProcessRunner}; +use crate::encryption; +use crate::error::{ExecError, Result}; +use crate::exec::Exec; +use crate::probe; + +#[derive(Debug, Clone, Default)] +pub struct StorageState { + pub efi_part: String, + pub root_part: String, + pub root_source: String, + pub luks_uuid: Option, + pub efi_uuid: Option, +} + +pub fn require_tools(exec: &Exec) -> Result<()> { + exec.require_tools(&["sgdisk", "partprobe", "blkid", "wipefs", "mkfs.fat", "mount", "umount"]) +} + +fn disk_transport(runner: &dyn ProcessRunner, disk: &str) -> String { + let spec = CommandSpec::new("storage_prepare", "disk transport", "lsblk") + .args(["-dn", "-o", "TRAN", disk]); + match runner.execute(&spec) { + Ok(out) => out.stdout_lossy().trim().to_string(), + Err(_) => String::new(), + } +} + +/// The full storage preparation for a whole-disk install. +pub fn prepare( + exec: &Exec, + config: &InstallConfig, + auth: &DestructiveAuthorization, + passphrase: Option<&SecretString>, + state: &mut StorageState, +) -> Result<()> { + let disk = &config.storage.disk; + let root = exec.target(); + + wipe(exec, auth, disk)?; + create_gpt(exec, auth, config, disk)?; + identify_partitions(exec, disk, state)?; + if state.efi_part.is_empty() || state.root_part.is_empty() { + return Err(ExecError::operation( + "storage_prepare", + "identify partitions", + "could not identify the created partitions", + )); + } + + mkfs_efi(exec, auth, &state.efi_part)?; + prepare_root(exec, auth, config, passphrase, state)?; + create_layout(exec, auth, config, &state.root_source, exec.root.as_path())?; + mount_efi(exec, config, &state.efi_part, exec.root.as_path())?; + create_swapfile(exec, config, &root, &state.root_source)?; + Ok(()) +} + +pub fn wipe(exec: &Exec, _auth: &DestructiveAuthorization, disk: &str) -> Result<()> { + exec.run( + CommandSpec::new("storage_prepare", "wipe partition signatures", "wipefs") + .arg("-a") + .arg(disk), + )?; + exec.run( + CommandSpec::new("storage_prepare", "zap GPT/MBR", "sgdisk") + .arg("--zap-all") + .arg(disk), + )?; + Ok(()) +} + +pub fn create_gpt( + exec: &Exec, + _auth: &DestructiveAuthorization, + config: &InstallConfig, + disk: &str, +) -> Result<()> { + let root_type = if config.is_encrypted() { "8309" } else { "8300" }; + let efi = config.storage.efi_size_mib; + let mut spec = CommandSpec::new("storage_prepare", "create GPT", "sgdisk") + .arg("--set-alignment=2048") + .arg(format!("--new=1:0:+{efi}M")) + .arg("--typecode=1:ef00") + .arg("--change-name=1:EFI") + .arg("--new=2:0:0") + .arg(format!("--typecode=2:{root_type}")) + .arg("--change-name=2:phoebus-root") + .arg(disk); + // The final positional disk must come last; CommandSpec preserves order. + spec.stage = "storage_prepare".into(); + exec.run(spec)?; + + exec.run( + CommandSpec::new("storage_prepare", "re-read partition table", "partprobe").arg(disk), + )?; + if crate::exec::find_in_path("udevadm").is_some() { + exec.run(CommandSpec::new("storage_prepare", "settle udev", "udevadm").arg("settle"))?; + } + Ok(()) +} + +/// Identify the EFI and root partitions by GPT label, falling back to order. +pub fn identify_partitions(exec: &Exec, disk: &str, state: &mut StorageState) -> Result<()> { + let runner = exec.runner.as_ref(); + let parts = probe::disk_partitions(runner, disk); + state.efi_part.clear(); + state.root_part.clear(); + for part in &parts { + match probe::blkid_partlabel(runner, part).as_deref() { + Some("EFI") => state.efi_part = part.clone(), + Some("phoebus-root") => state.root_part = part.clone(), + _ => {} + } + } + if state.efi_part.is_empty() { + if let Some(p) = parts.first() { + state.efi_part = p.clone(); + } + } + if state.root_part.is_empty() { + if let Some(p) = parts.get(1) { + state.root_part = p.clone(); + } + } + Ok(()) +} + +pub fn mkfs_efi(exec: &Exec, _auth: &DestructiveAuthorization, part: &str) -> Result<()> { + exec.run( + CommandSpec::new("storage_prepare", "create FAT32 EFI filesystem", "mkfs.fat") + .args(["-F32", "-n", "EFI"]) + .arg(part), + )?; + Ok(()) +} + +pub fn prepare_root( + exec: &Exec, + auth: &DestructiveAuthorization, + config: &InstallConfig, + passphrase: Option<&SecretString>, + state: &mut StorageState, +) -> Result<()> { + state.root_part = state.root_part.clone(); + if config.encryption.mode == Encryption::None { + mkfs_btrfs(exec, auth, config, &state.root_part)?; + state.root_source = state.root_part.clone(); + state.luks_uuid = None; + } else { + let passphrase = passphrase.ok_or_else(|| { + ExecError::operation("storage_prepare", "encrypt root", "no passphrase configured") + })?; + encryption::luks_format(exec, auth, config, &state.root_part, passphrase)?; + encryption::luks_open(exec, config, &state.root_part, passphrase)?; + let mapper = encryption::mapper_path(config); + mkfs_btrfs(exec, auth, config, &mapper)?; + state.root_source = mapper; + state.luks_uuid = probe::blkid_uuid(exec.runner.as_ref(), &state.root_part); + } + exec.logger.info(format!( + "root filesystem source: {}", + state.root_source + )); + Ok(()) +} + +pub fn mkfs_btrfs( + exec: &Exec, + _auth: &DestructiveAuthorization, + config: &InstallConfig, + device: &str, +) -> Result<()> { + exec.run( + CommandSpec::new("storage_prepare", "create Btrfs filesystem", "mkfs.btrfs") + .args(["-f", "-L", &config.storage.btrfs_label]) + .arg(device), + )?; + Ok(()) +} + +/// Create the subvolume layout and mount it. +/// +/// The top-level (subvolid=5) must be mounted to create @, @home, ...; only +/// afterwards can the individual subvolumes be mounted. +pub fn create_layout( + exec: &Exec, + _auth: &DestructiveAuthorization, + config: &InstallConfig, + device: &str, + root: &std::path::Path, +) -> Result<()> { + std::fs::create_dir_all(root).map_err(|e| ExecError::io(root.to_path_buf(), e))?; + exec.run( + CommandSpec::new("storage_prepare", "mount Btrfs top-level", "mount") + .args(["-o", "subvolid=5"]) + .arg(device) + .arg(root.to_string_lossy().to_string()), + )?; + + let mut created = true; + for sv in &config.storage.subvols { + let target = root.join(sv); + let res = exec.run( + CommandSpec::new("storage_prepare", format!("create subvolume {sv}"), "btrfs") + .args(["subvolume", "create"]) + .arg(target.to_string_lossy().to_string()), + ); + if res.is_err() { + created = false; + break; + } + } + if !created { + let _ = exec.run( + CommandSpec::new("storage_prepare", "unmount top-level", "umount") + .arg(root.to_string_lossy().to_string()), + ); + return Err(ExecError::operation( + "storage_prepare", + "create subvolumes", + "a subvolume could not be created", + )); + } + + set_default_subvolume(exec, root).ok(); + + exec.run( + CommandSpec::new("storage_prepare", "unmount top-level", "umount") + .arg(root.to_string_lossy().to_string()), + )?; + + mount_layout(exec, config, device, root) +} + +fn set_default_subvolume(exec: &Exec, root: &std::path::Path) -> Result<()> { + let spec = CommandSpec::new("storage_prepare", "list subvolumes", "btrfs") + .args(["subvolume", "list", "-o"]) + .arg(root.to_string_lossy().to_string()); + let out = exec.runner.execute(&spec)?; + let mut id: Option = None; + for line in out.stdout_lossy().lines() { + let fields: Vec<&str> = line.split_whitespace().collect(); + if fields.last() == Some(&"@") && fields.len() >= 2 { + id = Some(fields[1].to_string()); + } + } + if let Some(id) = id { + exec.run( + CommandSpec::new("storage_prepare", "set @ as default", "btrfs") + .args(["subvolume", "set-default", &id]) + .arg(root.to_string_lossy().to_string()), + )?; + } + Ok(()) +} + +fn ssd_for(exec: &Exec, config: &InstallConfig) -> bool { + let transport = disk_transport(exec.runner.as_ref(), &config.storage.disk); + transport == "nvme" || transport == "sata" +} + +pub fn btrfs_mount_opts(exec: &Exec, config: &InstallConfig) -> String { + sysgen::btrfs_mount_opts(&config.storage.compress, ssd_for(exec, config)) +} + +pub fn mount_layout( + exec: &Exec, + config: &InstallConfig, + device: &str, + root: &std::path::Path, +) -> Result<()> { + let opts = btrfs_mount_opts(exec, config); + std::fs::create_dir_all(root).map_err(|e| ExecError::io(root.to_path_buf(), e))?; + let root_sv = config.storage.root_subvolume(); + exec.run( + CommandSpec::new("storage_prepare", "mount root subvolume", "mount") + .arg("-o") + .arg(format!("{opts},subvol={root_sv}")) + .arg(device) + .arg(root.to_string_lossy().to_string()), + )?; + for (sv, target) in [ + ("@home", "home"), + ("@var", "var"), + ("@snapshots", ".snapshots"), + ("@swap", "swap"), + ] { + if !config.storage.subvols.iter().any(|s| s == sv) { + continue; + } + let mp = root.join(target); + std::fs::create_dir_all(&mp).map_err(|e| ExecError::io(mp.clone(), e))?; + exec.run( + CommandSpec::new("storage_prepare", format!("mount {sv}"), "mount") + .arg("-o") + .arg(format!("{opts},subvol={sv}")) + .arg(device) + .arg(mp.to_string_lossy().to_string()), + )?; + } + Ok(()) +} + +pub fn mount_efi( + exec: &Exec, + config: &InstallConfig, + part: &str, + root: &std::path::Path, +) -> Result<()> { + let mp = root.join(config.storage.efi_mount.trim_start_matches('/')); + std::fs::create_dir_all(&mp).map_err(|e| ExecError::io(mp.clone(), e))?; + exec.run( + CommandSpec::new("storage_prepare", "mount EFI", "mount") + .arg(part) + .arg(mp.to_string_lossy().to_string()), + )?; + Ok(()) +} + +pub fn create_swapfile( + exec: &Exec, + config: &InstallConfig, + root: &phoebus_core::TargetRoot, + _root_source: &str, +) -> Result<()> { + let swapdir = root.ensure_dir("swap")?; + let swapfile = swapdir.join("swapfile"); + let size_mib = swap_size_mib(exec); + let spec = CommandSpec::new("storage_prepare", "create Btrfs swapfile", "btrfs") + .args(["filesystem", "mkswapfile", "--size", &format!("{size_mib}m")]) + .arg(swapfile.to_string_lossy().to_string()); + if exec.run(spec).is_ok() { + return Ok(()); + } + // Fallback for older btrfs-progs. + exec.run( + CommandSpec::new("storage_prepare", "create swapfile container", "truncate") + .args(["-s", &format!("{size_mib}M")]) + .arg(swapfile.to_string_lossy().to_string()), + )?; + exec.run( + CommandSpec::new("storage_prepare", "disable CoW on swapfile", "chattr") + .arg("+C") + .arg(swapfile.to_string_lossy().to_string()), + )?; + exec.run( + CommandSpec::new("storage_prepare", "make swap", "mkswap") + .arg(swapfile.to_string_lossy().to_string()), + )?; + let _ = config; + Ok(()) +} + +fn swap_size_mib(_exec: &Exec) -> u64 { + let mem = read_mem_mib(); + let swap = if mem == 0 { 4096 } else { mem / 2 }; + swap.clamp(1024, 8192) +} + +fn read_mem_mib() -> u64 { + std::fs::read_to_string("/proc/meminfo") + .ok() + .and_then(|text| { + text.lines().find_map(|l| { + l.strip_prefix("MemTotal:") + .and_then(|r| r.split_whitespace().next()) + .and_then(|kb| kb.parse::().ok()) + .map(|kb| kb / 1024) + }) + }) + .unwrap_or(0) +} + +// --------------------------------------------------------------------------- +// fstab / crypttab +// --------------------------------------------------------------------------- + +/// The stable fstab source reference: the mapper path when encrypted, +/// otherwise `UUID=`. +pub fn root_source_ref(exec: &Exec, _config: &InstallConfig, state: &StorageState) -> String { + if state.root_source.starts_with("/dev/mapper/") { + state.root_source.clone() + } else { + probe::blkid_uuid(exec.runner.as_ref(), &state.root_source) + .map(|u| format!("UUID={u}")) + .unwrap_or_else(|| state.root_source.clone()) + } +} + +pub fn write_fstab( + exec: &Exec, + config: &InstallConfig, + state: &mut StorageState, +) -> Result<()> { + let root = exec.target(); + let src = root_source_ref(exec, config, state); + let opts = btrfs_mount_opts(exec, config); + if state.efi_uuid.is_none() { + state.efi_uuid = probe::blkid_uuid(exec.runner.as_ref(), &state.efi_part); + } + let text = sysgen::fstab(config, &src, state.efi_uuid.as_deref(), &opts); + root.write("etc/fstab", text)?; + exec.logger.info("wrote /etc/fstab"); + Ok(()) +} + +pub fn write_crypttab(exec: &Exec, config: &InstallConfig, state: &StorageState) -> Result<()> { + if !config.is_encrypted() { + return Ok(()); + } + let text = encryption::crypttab_line(exec, config, &state.root_part)?; + exec.target().write("etc/crypttab", text)?; + exec.logger.info("wrote /etc/crypttab"); + Ok(()) +} + +/// Unmount children first, the root last. +pub fn unmount_all(exec: &Exec, config: &InstallConfig, root: &std::path::Path) -> Result<()> { + let mut mounts = vec![ + config.storage.efi_mount.clone(), + "/.snapshots".to_string(), + "/var".to_string(), + "/home".to_string(), + "/swap".to_string(), + String::new(), + ]; + mounts.dedup(); + for m in mounts { + let target = root.join(m.trim_start_matches('/')); + let spec = CommandSpec::new("finalize", format!("unmount {m}"), "umount") + .args(["-R"]) + .arg(target.to_string_lossy().to_string()); + // Best effort. + let _ = exec.run(spec); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::command::RecordingRunner; + use crate::log::Logger; + use phoebus_core::Redactor; + + fn make_exec(runner: RecordingRunner) -> Exec { + let path = tempfile::tempdir().unwrap().keep(); + let logger = Logger::open(path.join("l.log"), Redactor::new(), false); + Exec::new(Box::new(runner), logger, false, path.join("root"), path) + } + + #[test] + fn gpt_uses_luks_type_when_encrypted() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let cfg = InstallConfig::default(); + let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap(); + create_gpt(&exec, &auth, &cfg, "/dev/vda").unwrap(); + let recorded = runner.recorded(); + let gpt = recorded.iter().find(|s| s.program == "sgdisk").unwrap(); + assert!(gpt.args.iter().any(|a| a == "--typecode=2:8309")); + assert!(gpt.args.iter().any(|a| a == "--typecode=1:ef00")); + assert_eq!(gpt.args.last().map(String::as_str), Some("/dev/vda")); + } + + #[test] + fn create_layout_creates_subvolumes_before_mounting_root() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let cfg = InstallConfig::default(); + let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap(); + let root = std::path::PathBuf::from(exec.root.clone()); + create_layout(&exec, &auth, &cfg, "/dev/mapper/cryptroot", &root).unwrap(); + let recorded = runner.recorded(); + // Find the first subvolume create and the first subvol=@ mount. + let create_idx = recorded + .iter() + .position(|s| s.program == "btrfs" && s.args.first().map(String::as_str) == Some("subvolume") && s.args.get(1).map(String::as_str) == Some("create")) + .expect("subvolume create"); + let mount_idx = recorded + .iter() + .position(|s| s.program == "mount" && s.args.iter().any(|a| a.contains("subvol=@"))) + .expect("subvol mount"); + assert!(create_idx < mount_idx, "subvolumes must be created before mounting @"); + } + + #[test] + fn fstab_and_crypttab_written_into_target() { + let runner = RecordingRunner::new(); + runner.set_response( + "blkid", + crate::command::CommandOutput { + status: 0, + success: true, + stdout: b"1111-2222\n".to_vec(), + stderr: Vec::new(), + duration: std::time::Duration::from_millis(1), + }, + ); + let exec = make_exec(runner.clone()); + let cfg = InstallConfig::default(); + let mut state = StorageState { + efi_part: "/dev/vda1".into(), + root_part: "/dev/vda2".into(), + root_source: "/dev/mapper/cryptroot".into(), + ..Default::default() + }; + write_fstab(&exec, &cfg, &mut state).unwrap(); + write_crypttab(&exec, &cfg, &state).unwrap(); + let fstab = std::fs::read_to_string(exec.root.join("etc/fstab")).unwrap(); + assert!(fstab.contains("subvol=@swap")); + let crypttab = std::fs::read_to_string(exec.root.join("etc/crypttab")).unwrap(); + assert!(crypttab.contains("cryptroot UUID=1111-2222 none luks,discard")); + } +} diff --git a/installer-rs/crates/phoebus-executor/src/update.rs b/installer-rs/crates/phoebus-executor/src/update.rs new file mode 100644 index 0000000..30302e7 --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/update.rs @@ -0,0 +1,189 @@ +//! Background update preparation. +//! +//! Fetches distfiles and builds reusable local binary packages without +//! installing them. Activation stays explicit. Uses only real Portage flags. + +use std::path::{Path, PathBuf}; + +use phoebus_core::update::{build_args, fetch_args, should_prepare, PowerState, PrepareState, PrepareStatus}; + +use crate::error::{ExecError, Result}; +use crate::exec::Exec; +use crate::portage; + +pub struct PrepareOutcome { + pub started: bool, + pub note: String, +} + +pub fn state_path(root: &Path) -> PathBuf { + root.join("var/lib/phoebus/update-state.toml") +} + +pub fn load_state(root: &Path) -> PrepareState { + let path = state_path(root); + if !path.exists() { + return PrepareState::default(); + } + std::fs::read_to_string(&path) + .ok() + .and_then(|t| toml::from_str(&t).ok()) + .unwrap_or_default() +} + +pub fn save_state(exec: &Exec, root: &Path, state: &PrepareState) -> Result<()> { + let path = state_path(root); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|e| ExecError::io(parent.to_path_buf(), e))?; + } + let text = toml::to_string_pretty(state) + .map_err(|e| ExecError::operation("update", "serialize state", e.to_string()))?; + std::fs::write(&path, text).map_err(|e| ExecError::io(path.clone(), e))?; + exec.logger.info(format!("update state -> {}", path.display())); + Ok(()) +} + +/// Read the current power source from sysfs. +pub fn read_power_state() -> PowerState { + let Ok(entries) = std::fs::read_dir("/sys/class/power_supply") else { + return PowerState::Unknown; + }; + let mut saw_battery = false; + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + let base = entry.path(); + if name.starts_with("AC") || name.starts_with("ADP") || name.starts_with("Mains") { + if let Ok(v) = std::fs::read_to_string(base.join("online")) { + if v.trim() == "1" { + return PowerState::Ac; + } + } + } + if name.starts_with("BAT") { + saw_battery = true; + } + } + if saw_battery { + PowerState::Battery + } else { + PowerState::Unknown + } +} + +fn read_load_average() -> f32 { + std::fs::read_to_string("/proc/loadavg") + .ok() + .and_then(|t| t.split_whitespace().next().and_then(|v| v.parse().ok())) + .unwrap_or(0.0) +} + +/// Prepare updates: fetch distfiles, then build reusable binary packages. +pub fn prepare( + exec: &Exec, + root: &Path, + cores: u32, + force: bool, +) -> Result { + let power = read_power_state(); + let load = read_load_average(); + if !force && !should_prepare(power, load, cores, false) { + let note = format!("deferred (power={power:?}, load={load:.2})"); + exec.logger.info(format!("background prepare {note}")); + return Ok(PrepareOutcome { + started: false, + note, + }); + } + + let mut state = PrepareState { + status: PrepareStatus::Running, + note: "fetching distfiles".into(), + ..load_state(root) + }; + save_state(exec, root, &state)?; + + let result = (|| -> Result<()> { + portage::chroot(exec, root, "emerge", &fetch_args())?; + state.note = "building binary packages".into(); + let _ = save_state(exec, root, &state); + portage::chroot(exec, root, "emerge", &build_args())?; + Ok(()) + })(); + + match result { + Ok(()) => { + state.status = PrepareStatus::Ready; + state.note = "updates prepared (not activated)".into(); + state.last_prepared_unix = now_unix(); + save_state(exec, root, &state)?; + exec.logger + .info("background update preparation complete (not activated)"); + Ok(PrepareOutcome { + started: true, + note: state.note.clone(), + }) + } + Err(e) => { + state.status = PrepareStatus::Failed; + state.note = format!("{e}"); + let _ = save_state(exec, root, &state); + Err(e) + } + } +} + +fn now_unix() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::command::RecordingRunner; + use crate::log::Logger; + use phoebus_core::Redactor; + + fn make_exec(runner: RecordingRunner) -> Exec { + let path = tempfile::tempdir().unwrap().keep(); + let logger = Logger::open(path.join("l.log"), Redactor::new(), false); + Exec::new(Box::new(runner), logger, false, path.join("root"), path) + } + + #[test] + fn prepare_forces_fetch_and_build_without_install() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + let root = Path::new(&exec.root); + let outcome = prepare(&exec, root, 8, true).unwrap(); + assert!(outcome.started); + let specs = runner.recorded(); + let emerge_specs: Vec<_> = specs + .iter() + .filter(|s| s.args.iter().any(|a| a == "emerge")) + .collect(); + assert_eq!(emerge_specs.len(), 2); + assert!(emerge_specs[0].args.iter().any(|a| a == "--fetchonly")); + assert!(emerge_specs[1].args.iter().any(|a| a == "--buildpkgonly")); + assert!(!emerge_specs.iter().any(|s| s.args.iter().any(|a| a == "@world" && false))); + let state = load_state(root); + assert_eq!(state.status, PrepareStatus::Ready); + } + + #[test] + fn state_roundtrip() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner); + let root = Path::new(&exec.root); + let state = PrepareState { + last_prepared_unix: 123, + status: PrepareStatus::Ready, + prepared_packages: 5, + note: "ok".into(), + }; + save_state(&exec, root, &state).unwrap(); + assert_eq!(load_state(root), state); + } +} diff --git a/installer-rs/crates/phoebus-executor/src/users.rs b/installer-rs/crates/phoebus-executor/src/users.rs new file mode 100644 index 0000000..e3c2251 --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/users.rs @@ -0,0 +1,184 @@ +//! User account configuration. +//! +//! Passwords are hashed immediately and only hashes travel to the target. +//! Plaintext never touches the config, the log or a command line. + +use std::path::Path; + +use phoebus_core::{InstallConfig, SecretString}; + +use crate::command::CommandSpec; +use crate::error::{ExecError, Result}; +use crate::exec::Exec; +use crate::portage; + +/// SHA-512 crypt hash via `openssl passwd -6 -stdin`. +pub fn hash_password(exec: &Exec, password: &SecretString) -> Result { + let spec = CommandSpec::new("users_configure", "hash password", "openssl") + .args(["passwd", "-6", "-stdin"]) + .stdin(password.expose().as_bytes().to_vec()); + let out = exec.runner.execute(&spec)?; + let hash = out.stdout_lossy().trim().to_string(); + if hash.is_empty() { + return Err(ExecError::operation( + "users_configure", + "hash password", + "empty hash", + )); + } + Ok(hash) +} + +fn group_exists(root: &Path, group: &str) -> bool { + let path = root.join("etc/group"); + std::fs::read_to_string(path) + .map(|text| text.lines().any(|l| l.starts_with(&format!("{group}:")))) + .unwrap_or(false) +} + +/// Create missing supplementary groups and return the subset that exists. +pub fn ensure_groups(exec: &Exec, root: &Path, groups: &[String]) -> Result> { + let mut out = Vec::new(); + for group in groups { + if group.is_empty() { + continue; + } + if !group_exists(root, group) { + if let Err(e) = portage::chroot(exec, root, "groupadd", &["-r", group]) { + exec.logger + .warn(format!("could not create group {group}: {e}")); + } + } + if group_exists(root, group) { + out.push(group.clone()); + } else { + exec.logger + .warn(format!("group {group} not available; skipping")); + } + } + Ok(out) +} + +pub fn create( + exec: &Exec, + config: &InstallConfig, + user_password: Option<&SecretString>, + root_password: Option<&SecretString>, +) -> Result<()> { + let username = &config.user.username; + if username.is_empty() { + return Err(ExecError::operation( + "users_configure", + "create user", + "no username configured", + )); + } + let root = Path::new(&exec.root); + let groups = ensure_groups(exec, root, &config.user.groups)?; + + let mut args: Vec<&str> = vec![ + "-m", + "-U", + "-s", + &config.system.root_shell, + "-c", + &config.user.fullname, + ]; + let group_list = groups.join(","); + if !group_list.is_empty() { + args.push("-G"); + args.push(&group_list); + } + args.push(username); + portage::chroot(exec, root, "useradd", &args)?; + + if let Some(password) = user_password { + if !password.is_empty() { + let hash = hash_password(exec, password)?; + let input = format!("{username}:{hash}\n"); + portage::chroot_stdin(exec, root, "chpasswd", &["-e"], input.as_bytes())?; + exec.logger.info(format!("password set for {username}")); + } + } else { + exec.logger + .warn(format!("no password set for {username} (account locked)")); + } + + match root_password { + Some(password) if !password.is_empty() => { + let hash = hash_password(exec, password)?; + let input = format!("root:{hash}\n"); + portage::chroot_stdin(exec, root, "chpasswd", &["-e"], input.as_bytes())?; + exec.logger.info("root password set"); + } + _ => { + let _ = portage::chroot(exec, root, "passwd", &["-l", "root"]); + exec.logger + .info("root account locked (no root password supplied)"); + } + } + Ok(()) +} + +pub fn configure_sudo(exec: &Exec) -> Result<()> { + let target = exec.target(); + target.write("etc/sudoers.d/10-wheel", "# Members of the wheel group may run commands as root.\n%wheel ALL=(ALL:ALL) ALL\n")?; + let path = target.etc("sudoers.d/10-wheel")?; + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o440)) + .map_err(|e| ExecError::io(path.clone(), e))?; + let root = Path::new(&exec.root); + if root.join("usr/sbin/visudo").exists() || root.join("sbin/visudo").exists() { + portage::chroot(exec, root, "visudo", &["-cf", "/etc/sudoers.d/10-wheel"])?; + } + exec.logger.info("sudo configured for wheel"); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::command::{CommandOutput, RecordingRunner}; + use crate::log::Logger; + use phoebus_core::Redactor; + + fn make_exec(runner: RecordingRunner) -> Exec { + let path = tempfile::tempdir().unwrap().keep(); + let logger = Logger::open(path.join("l.log"), Redactor::new(), false); + Exec::new(Box::new(runner), logger, false, path.join("root"), path) + } + + #[test] + fn password_hash_goes_over_stdin() { + let runner = RecordingRunner::new(); + runner.set_response( + "openssl", + CommandOutput { + status: 0, + success: true, + stdout: b"$6$abc$hash\n".to_vec(), + stderr: Vec::new(), + duration: std::time::Duration::from_millis(1), + }, + ); + let exec = make_exec(runner.clone()); + let secret = SecretString::new("pw"); + let hash = hash_password(&exec, &secret).unwrap(); + assert_eq!(hash, "$6$abc$hash"); + let spec = &runner.recorded()[0]; + assert!(!spec.args.iter().any(|a| a.contains("pw"))); + assert_eq!(spec.stdin.as_deref(), Some(b"pw".as_slice())); + } + + #[test] + fn ensure_groups_creates_missing() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + // No /etc/group present -> groupadd attempted, then still missing -> + // excluded from the returned list. + let groups = vec!["render".to_string()]; + let out = ensure_groups(&exec, Path::new(&exec.root), &groups).unwrap(); + assert!(out.is_empty()); + assert!(runner.programs().iter().any(|p| p == "chroot")); + } +} diff --git a/installer-rs/crates/phoebus-installer/Cargo.toml b/installer-rs/crates/phoebus-installer/Cargo.toml new file mode 100644 index 0000000..6f40a92 --- /dev/null +++ b/installer-rs/crates/phoebus-installer/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "phoebus-installer" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[[bin]] +name = "phoebus-installer" +path = "src/main.rs" + +[dependencies] +phoebus-core.workspace = true +phoebus-executor.workspace = true +phoebus-tui = { path = "../phoebus-tui" } +clap.workspace = true +serde.workspace = true +toml.workspace = true +serde_json.workspace = true +sha2 = "0.10" + +[dev-dependencies] +tempfile.workspace = true diff --git a/installer-rs/crates/phoebus-installer/src/bin/phoebus-release.rs b/installer-rs/crates/phoebus-installer/src/bin/phoebus-release.rs new file mode 100644 index 0000000..3084201 --- /dev/null +++ b/installer-rs/crates/phoebus-installer/src/bin/phoebus-release.rs @@ -0,0 +1,139 @@ +//! Release manifest tool. +//! +//! Produces and verifies the checksummed manifest for a candidate ISO. The +//! publish flow must refuse to replace `latest.iso` unless `verify` passes. + +use std::path::PathBuf; +use std::process::ExitCode; + +use clap::{Parser, Subcommand}; +use phoebus_core::VERSION; +use phoebus_installer::release::{ + artifact_for, default_manifest_path, sha256_file, ReleaseManifest, +}; + +#[derive(Parser)] +#[command(name = "phoebus-release", version = VERSION, about = "Phoebus release tooling")] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand)] +enum Command { + /// Build a manifest for every artifact in a directory. + Manifest { + #[arg(long)] + dir: PathBuf, + #[arg(long)] + output: Option, + #[arg(long, default_value = "")] + base: String, + #[arg(long, default_value = "")] + stage3: String, + #[arg(long, default_value = "")] + opencode: String, + }, + /// Verify a directory against a manifest. Exits non-zero on any mismatch. + Verify { + #[arg(long)] + dir: PathBuf, + #[arg(long)] + manifest: Option, + }, + /// Print the xorriso command that assembles the candidate ISO. + Assemble { + #[arg(long)] + base: PathBuf, + #[arg(long)] + payload: PathBuf, + #[arg(long)] + output: PathBuf, + }, + /// Print the sha256 of a single file. + Sha256 { file: PathBuf }, +} + +fn main() -> ExitCode { + match run() { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("phoebus-release: {e}"); + ExitCode::FAILURE + } + } +} + +fn run() -> std::result::Result<(), Box> { + match Cli::parse().command { + Command::Manifest { + dir, + output, + base, + stage3, + opencode, + } => { + let mut manifest = ReleaseManifest { + installer_base: base, + stage3, + opencode_version: opencode, + created_unix: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0), + ..Default::default() + }; + for entry in std::fs::read_dir(&dir)? { + let entry = entry?; + let path = entry.path(); + if path.is_file() { + manifest.artifacts.push(artifact_for(&path)?); + } + } + manifest.artifacts.sort_by(|a, b| a.name.cmp(&b.name)); + let out = output.unwrap_or_else(|| default_manifest_path(&dir)); + manifest.save(&out)?; + println!("wrote {} ({} artifacts)", out.display(), manifest.artifacts.len()); + Ok(()) + } + Command::Verify { dir, manifest } => { + let path = manifest.unwrap_or_else(|| default_manifest_path(&dir)); + let manifest = ReleaseManifest::load(&path)?; + let mut failed = 0; + for artifact in &manifest.artifacts { + let file = dir.join(&artifact.name); + if !file.is_file() { + eprintln!("MISSING {}", artifact.name); + failed += 1; + } else if manifest.verify(&artifact.name, &file) { + println!("OK {}", artifact.name); + } else { + eprintln!("MISMATCH {}", artifact.name); + failed += 1; + } + } + if failed > 0 { + return Err(format!("{failed} artifact(s) failed verification; not publishing").into()); + } + println!("all {} artifacts verified", manifest.artifacts.len()); + Ok(()) + } + Command::Assemble { + base, + payload, + output, + } => { + let cmd = ReleaseManifest::assemble_command(&base, &payload, &output); + println!("{}", cmd.join(" ")); + eprintln!( + "note: requires xorriso; verify the candidate with `phoebus-release verify` \ + before replacing latest.iso" + ); + Ok(()) + } + Command::Sha256 { file } => { + println!("{}", sha256_file(&file)?); + Ok(()) + } + } +} diff --git a/installer-rs/crates/phoebus-installer/src/bin/sys.rs b/installer-rs/crates/phoebus-installer/src/bin/sys.rs new file mode 100644 index 0000000..e26757c --- /dev/null +++ b/installer-rs/crates/phoebus-installer/src/bin/sys.rs @@ -0,0 +1,169 @@ +//! `sys ` - proposed Phoebus system interface. +//! +//! The normal path is deterministic: a phrase is parsed into a closed, +//! validated `SystemAction`, shown for approval, and executed by the +//! privileged broker. The AI path emits the same typed schema via +//! `--action-file`; it never receives a shell or the sudo password. + +use std::io::Write; +use std::path::PathBuf; +use std::process::ExitCode; + +use clap::Parser; +use phoebus_core::action::{parse_action, parse_natural, SystemAction}; +use phoebus_core::Redactor; +use phoebus_executor::{ + actions, authorize, AutoConfirm, Confirmation, DestructiveAuthorization, Exec, Logger, + RealRunner, Result, +}; + +#[derive(Parser, Debug)] +#[command(name = "sys", about = "Phoebus system interface")] +struct Cli { + /// Natural-language instruction, e.g. `enable sshd`. + text: Vec, + + /// A typed action as JSON, e.g. '{"action":"enable_service","name":"sshd"}'. + #[arg(long)] + action: Option, + + /// Read a typed action from a JSON file (used by the AI path). + #[arg(long)] + action_file: Option, + + /// Auto-approve (unattended); still requires root. + #[arg(long, short = 'y')] + yes: bool, + + /// Root directory of the target system. + #[arg(long, default_value = "/")] + root: PathBuf, +} + +struct SysConfirm { + action: SystemAction, + assume_yes: bool, +} + +impl Confirmation for SysConfirm { + fn confirm_erase(&self, preview: &str) -> Result { + if self.assume_yes { + println!("{preview}"); + return Ok(true); + } + println!("\n{preview}"); + print!("\nProceed? [y/N] "); + std::io::stdout().flush().ok(); + let mut line = String::new(); + std::io::stdin().read_line(&mut line).map_err(|e| { + phoebus_executor::ExecError::operation("sys", "confirm", e.to_string()) + })?; + Ok(matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes")) + } + + fn confirm_final(&self, _message: &str) -> Result { + let _ = &self.action; + Ok(true) + } +} + +fn effective_uid() -> u32 { + std::process::Command::new("id") + .arg("-u") + .output() + .ok() + .and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse().ok()) + .unwrap_or(1) +} + +fn main() -> ExitCode { + match run() { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("sys: {e}"); + ExitCode::FAILURE + } + } +} + +fn run() -> std::result::Result<(), Box> { + let cli = Cli::parse(); + + let action = if let Some(json) = &cli.action { + parse_action(json)? + } else if let Some(path) = &cli.action_file { + let text = std::fs::read_to_string(path)?; + parse_action(&text)? + } else { + let phrase = cli.text.join(" "); + match parse_natural(&phrase) { + Some(a) => a, + None => { + eprintln!("sys: could not parse `{phrase}` deterministically."); + eprintln!("Examples: sys enable sshd | sys disable bluetooth | sys history"); + eprintln!("Or provide a typed action with --action/--action-file."); + return Err("unsupported instruction".into()); + } + } + }; + + let mut state_dir = PathBuf::from("/run/phoebus-installer"); + if std::fs::create_dir_all(&state_dir).is_err() { + state_dir = std::env::temp_dir().join("phoebus-installer"); + std::fs::create_dir_all(&state_dir).ok(); + } + let logger = Logger::open(state_dir.join("sys.log"), Redactor::new(), false); + let exec = Exec::new( + Box::new(RealRunner), + logger, + false, + cli.root.clone(), + state_dir, + ); + + println!("{}", actions::preview(&action)); + + if action.is_mutating() && effective_uid() != 0 { + return Err("mutating actions require root; run `sudo sys ...`".into()); + } + + let auth: Option = if action.is_mutating() { + let confirmation = SysConfirm { + action: action.clone(), + assume_yes: cli.yes, + }; + Some(authorize( + &confirmation, + &actions::preview(&action), + "execute", + )?) + } else { + None + }; + + // High-risk operations are preceded by a snapshot when the root is Btrfs. + if action.risk() == phoebus_core::action::Risk::High + && cli.root.join(".snapshots").is_dir() + && auth.is_some() + { + match phoebus_executor::snapshot::create_and_record( + &exec, + auth.as_ref().unwrap(), + &cli.root, + "/", + &action.describe(), + ) { + Ok(record) => println!("created snapshot: {}", record.id), + Err(e) => eprintln!("warning: could not create snapshot: {e}"), + } + } + + let outcome = actions::execute(&exec, &action, auth.as_ref(), &cli.root)?; + println!("{}", outcome.output); + Ok(()) +} + +#[allow(dead_code)] +fn _auto() -> AutoConfirm { + AutoConfirm +} diff --git a/installer-rs/crates/phoebus-installer/src/lib.rs b/installer-rs/crates/phoebus-installer/src/lib.rs new file mode 100644 index 0000000..61aee2f --- /dev/null +++ b/installer-rs/crates/phoebus-installer/src/lib.rs @@ -0,0 +1,6 @@ +//! Phoebus installer orchestration and CLI support. + +pub mod orchestrate; +pub mod release; + +pub use orchestrate::Installer; diff --git a/installer-rs/crates/phoebus-installer/src/main.rs b/installer-rs/crates/phoebus-installer/src/main.rs new file mode 100644 index 0000000..8f33b1a --- /dev/null +++ b/installer-rs/crates/phoebus-installer/src/main.rs @@ -0,0 +1,242 @@ +//! Phoebus OS installer CLI. +//! +//! With no mode flags on a terminal, the text UI starts. The deterministic +//! backend is available directly with `--plan`, `--dry-run` and `--install`. +//! Secrets are supplied through files, never on the command line. + +use std::io::Write; +use std::path::PathBuf; +use std::process::ExitCode; + +use clap::Parser; +use phoebus_core::{InstallConfig, Redactor, SecretString}; +use phoebus_executor::{ + authorize, AutoConfirm, Confirmation, DestructiveAuthorization, Exec, Logger, RealRunner, + Result, +}; +use phoebus_installer::Installer; +use phoebus_tui::TuiOutcome; + +#[derive(Parser, Debug)] +#[command( + name = "phoebus-installer", + version, + about = "Phoebus OS installer (deterministic backend + TUI)" +)] +struct Cli { + /// Load configuration from a file (TOML or the legacy flat format). + #[arg(long)] + config: Option, + + /// Render the installation plan and exit. + #[arg(long)] + plan: bool, + + /// Do not execute commands or modify the target. + #[arg(long)] + dry_run: bool, + + /// Run the deterministic backend without the TUI. + #[arg(long)] + install: bool, + + /// Skip interactive confirmations (for unattended installs). + #[arg(long, short = 'y')] + yes: bool, + + /// Read the LUKS passphrase from a 0600 file. + #[arg(long)] + luks_passphrase_file: Option, + + /// Read the user password from a 0600 file. + #[arg(long)] + user_password_file: Option, + + /// Read the root password from a 0600 file. + #[arg(long)] + root_password_file: Option, + + /// Write the effective configuration as TOML and exit. + #[arg(long)] + save_config: Option, +} + +struct TerminalConfirm; + +impl Confirmation for TerminalConfirm { + fn confirm_erase(&self, preview: &str) -> Result { + println!("\n{preview}"); + print!("\nType ERASE to continue: "); + std::io::stdout().flush().ok(); + let mut line = String::new(); + std::io::stdin() + .read_line(&mut line) + .map_err(|e| phoebus_executor::ExecError::operation("confirm", "erase", e.to_string()))?; + Ok(line.trim() == "ERASE") + } + + fn confirm_final(&self, message: &str) -> Result { + print!("{message} [y/N] "); + std::io::stdout().flush().ok(); + let mut line = String::new(); + std::io::stdin() + .read_line(&mut line) + .map_err(|e| phoebus_executor::ExecError::operation("confirm", "final", e.to_string()))?; + Ok(matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes")) + } +} + +fn read_secret(path: &PathBuf) -> std::io::Result { + let value = std::fs::read_to_string(path)?; + Ok(SecretString::new(value.trim_end_matches(['\n', '\r']))) +} + +fn main() -> ExitCode { + match run() { + Ok(code) => code, + Err(e) => { + eprintln!("error: {e}"); + ExitCode::FAILURE + } + } +} + +fn run() -> std::result::Result> { + let cli = Cli::parse(); + + let mut config = if let Some(path) = &cli.config { + InstallConfig::load_from_path(path)? + } else { + InstallConfig::default() + }; + if cli.dry_run { + config.runtime.dry_run = true; + } + if cli.yes { + config.runtime.assume_yes = true; + } + + // Secrets may come from CLI files or the TUI. + let mut luks = cli.luks_passphrase_file.as_ref().map(read_secret).transpose()?; + let mut user_pw = cli.user_password_file.as_ref().map(read_secret).transpose()?; + let root_pw = cli.root_password_file.as_ref().map(read_secret).transpose()?; + let mut tui_confirmed = false; + let mut do_install = cli.install; + + // TUI when no explicit mode and a terminal is present. + if !cli.plan && !cli.install && !cli.dry_run && phoebus_tui::is_tty() { + match phoebus_tui::run(config.clone())? { + TuiOutcome::Exit => return Ok(ExitCode::SUCCESS), + TuiOutcome::Save(saved) => { + let path = cli + .config + .clone() + .unwrap_or_else(|| PathBuf::from("phoebus-install.toml")); + std::fs::write(&path, saved.to_toml_string()?)?; + println!("wrote {}", path.display()); + return Ok(ExitCode::SUCCESS); + } + TuiOutcome::Install(saved, tui_luks, tui_user) => { + config = saved; + if luks.is_none() { + luks = tui_luks; + } + if user_pw.is_none() { + user_pw = tui_user; + } + do_install = true; + tui_confirmed = true; + } + } + } + + if let Some(path) = &cli.save_config { + std::fs::write(path, config.to_toml_string()?)?; + println!("wrote {}", path.display()); + } + + let mut state_dir = PathBuf::from(&config.runtime.state_dir); + if std::fs::create_dir_all(&state_dir).is_err() { + state_dir = PathBuf::from("/tmp/phoebus-installer"); + std::fs::create_dir_all(&state_dir).ok(); + } + let log_path = state_dir.join("install.log"); + + let echo = std::env::var("PHOEBUS_LOG_ECHO") + .map(|v| matches!(v.to_ascii_lowercase().as_str(), "yes" | "1" | "true")) + .unwrap_or(false); + let logger = Logger::open(&log_path, Redactor::new(), echo); + + let root = if config.runtime.dry_run { + let sandbox = state_dir.join("dry-run-root"); + std::fs::create_dir_all(&sandbox).ok(); + sandbox + } else { + PathBuf::from(&config.storage.install_root) + }; + + let exec = Exec::new( + Box::new(RealRunner), + logger, + config.runtime.dry_run, + root, + state_dir.clone(), + ); + for secret in [&luks, &user_pw, &root_pw].into_iter().flatten() { + exec.register_secret(secret); + } + + let mut installer = Installer::new(config, exec); + + // Plan / default mode. + if cli.plan || !do_install { + print!("{}", installer.render_plan()); + let issues = installer.validate(); + println!("\nValidation:"); + if issues.is_empty() { + println!(" OK"); + } else { + for issue in &issues { + println!(" - {issue}"); + } + } + return Ok(ExitCode::SUCCESS); + } + + // Install mode. + let issues = installer.validate(); + if !issues.is_empty() { + eprintln!("configuration is incomplete:"); + for issue in &issues { + eprintln!(" - {issue}"); + } + return Ok(ExitCode::FAILURE); + } + + print!("{}", installer.render_plan()); + + let auth: DestructiveAuthorization = if tui_confirmed || installer.config.runtime.assume_yes { + authorize(&AutoConfirm, &installer.destructive_preview(), "Start installation?")? + } else { + let preview = installer.destructive_preview(); + authorize( + &TerminalConfirm, + &preview, + "Start the installation now? This can take a long time.", + )? + }; + + installer.install(&auth, luks.as_ref(), user_pw.as_ref(), root_pw.as_ref())?; + if installer.config.runtime.dry_run { + println!( + "dry-run complete; log: {}", + installer.exec.log_path().display() + ); + } else { + println!( + "installation complete; log: {}", + installer.exec.log_path().display() + ); + } + Ok(ExitCode::SUCCESS) +} diff --git a/installer-rs/crates/phoebus-installer/src/orchestrate.rs b/installer-rs/crates/phoebus-installer/src/orchestrate.rs new file mode 100644 index 0000000..b3b2c6d --- /dev/null +++ b/installer-rs/crates/phoebus-installer/src/orchestrate.rs @@ -0,0 +1,420 @@ +//! Installation orchestration. +//! +//! The only place destructive authorization is required, and only after the +//! plan has been shown and confirmed. Stages run in the proven order and stop +//! on the first failure. + +use std::path::PathBuf; + +use phoebus_core::policy::{load_history, PackagePolicyEngine, PolicyContext}; +use phoebus_core::validate::ValidationIssue; +use phoebus_core::{validate, HardwareReport, InstallConfig, InstallPlan, SecretString}; +use phoebus_executor::storage::StorageState; +use phoebus_executor::{ + boot, desktop, encryption, kernel, portage, probe, services, stage3, storage, users, Exec, + Result, +}; + +pub struct Installer { + pub config: InstallConfig, + pub hardware: HardwareReport, + pub disks: Vec, + pub exec: Exec, + pub engine: PackagePolicyEngine, + pub policy_ctx: PolicyContext, + pub state: StorageState, +} + +impl Installer { + pub fn new(config: InstallConfig, exec: Exec) -> Self { + let hardware = probe::probe_hardware(exec.runner.as_ref()); + let disks = probe::probe_disks(exec.runner.as_ref()); + // Prefer measured history installed on the target, then the installer's + // ephemeral state directory. + let persistent = exec.root.join("var/lib/phoebus/compile-times.tsv"); + let volatile = exec.state_dir.join("compile-times.tsv"); + let history = if persistent.exists() { + load_history(&persistent) + } else { + load_history(&volatile) + }; + let engine = PackagePolicyEngine::new().with_history(history); + let binhost_available = + config.packages.binary_packages && !config.stage3.binhost_uri.is_empty(); + let policy_ctx = PolicyContext { + policy: config.packages.policy, + binhost_available, + memory_mib: hardware.memory_mib, + cores: hardware.cpu.cores, + }; + Self { + config, + hardware, + disks, + exec, + engine, + policy_ctx, + state: StorageState::default(), + } + } + + pub fn plan(&self) -> InstallPlan { + InstallPlan::for_config(&self.config) + } + + pub fn render_plan(&self) -> String { + self.plan().render_human(&self.config, Some(&self.hardware)) + } + + pub fn destructive_preview(&self) -> String { + let disk = &self.config.storage.disk; + let layout = probe::probe_disk_layout(self.exec.runner.as_ref(), disk); + self.plan().destructive_preview(&self.config, &layout) + } + + pub fn disk_layout(&self) -> String { + probe::probe_disk_layout(self.exec.runner.as_ref(), &self.config.storage.disk) + } + + /// Configuration plus target-disk validation. + pub fn validate(&self) -> Vec { + let mut issues = validate::validate_config(&self.config); + let disk = &self.config.storage.disk; + if !disk.is_empty() { + match self.disks.iter().find(|d| &d.path == disk) { + Some(d) => { + if let Some(reason) = d.protection() { + issues.push(ValidationIssue::new( + "target_disk", + format!("refusing target {disk}: {}", reason.describe()), + )); + } + } + None => issues.push(ValidationIssue::new( + "target_disk", + format!("target disk {disk} was not detected on this system"), + )), + } + } + issues + } + + /// Run the staged installation. `auth` must have been produced only after + /// the destructive preview and final confirmation. + pub fn install( + &mut self, + auth: &phoebus_executor::DestructiveAuthorization, + luks_passphrase: Option<&SecretString>, + user_password: Option<&SecretString>, + root_password: Option<&SecretString>, + ) -> Result<()> { + let steps = self.plan().steps.clone(); + for step in steps { + let name = step.name(); + self.exec.logger.section(name); + let result = self.run_step(step, auth, luks_passphrase, user_password, root_password); + if let Err(e) = result { + self.exec.logger.error(format!("stage failed: {name}: {e}")); + if !self.exec.dry_run { + let _ = self.exec.export_log(); + let _ = self.exec.umount_chroot(); + } + return Err(e); + } + self.exec.logger.info(format!("stage complete: {name}")); + } + Ok(()) + } + + fn run_step( + &mut self, + step: phoebus_core::InstallStep, + auth: &phoebus_executor::DestructiveAuthorization, + luks_passphrase: Option<&SecretString>, + user_password: Option<&SecretString>, + root_password: Option<&SecretString>, + ) -> Result<()> { + use phoebus_core::InstallStep::*; + match step { + StoragePrepare => self.storage_prepare(auth, luks_passphrase), + StageInstall => self.stage_install(), + FstabGenerate => self.fstab_generate(), + PortageConfigure => self.portage_configure(), + PackagesBase => self.packages_base(), + KernelInstall => self.kernel_install(), + BootInstall => self.boot_install(), + UsersConfigure => self.users_configure(user_password, root_password), + ServicesConfigure => self.services_configure(), + DesktopInstall => self.desktop_install(), + Finalize => self.finalize(auth), + } + } + + fn storage_prepare( + &mut self, + auth: &phoebus_executor::DestructiveAuthorization, + luks_passphrase: Option<&SecretString>, + ) -> Result<()> { + if self.exec.dry_run { + self.exec.logger.info(format!( + "[dry-run] would partition and format {}", + self.config.storage.disk + )); + self.state.root_source = format!("/dev/mapper/{}", self.config.encryption.name); + self.state.luks_uuid = Some("".into()); + return Ok(()); + } + storage::prepare( + &self.exec, + &self.config, + auth, + luks_passphrase, + &mut self.state, + ) + } + + fn stage_install(&self) -> Result<()> { + if self.exec.dry_run { + self.exec + .logger + .info("[dry-run] would fetch and extract the stage3"); + return Ok(()); + } + stage3::fetch(&self.exec, &self.config, &self.exec.state_dir)?; + let tarball = self.exec.state_dir.join("stage3-systemd.tar.xz"); + stage3::extract(&self.exec, std::path::Path::new(&self.exec.root), &tarball) + } + + fn fstab_generate(&mut self) -> Result<()> { + if self.exec.dry_run { + self.exec + .logger + .info("[dry-run] would write fstab and crypttab"); + return Ok(()); + } + storage::write_fstab(&self.exec, &self.config, &mut self.state)?; + storage::write_crypttab(&self.exec, &self.config, &self.state)?; + let target = self.exec.target(); + for dir in ["var/tmp", "tmp", "root", "home"] { + target.ensure_dir(dir)?; + } + use std::os::unix::fs::PermissionsExt; + for dir in ["var/tmp", "tmp"] { + if let Ok(p) = target.resolve(dir) { + let _ = std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o1777)); + } + } + if let Ok(p) = target.resolve("root") { + let _ = std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o700)); + } + Ok(()) + } + + fn portage_configure(&self) -> Result<()> { + if self.exec.dry_run { + self.exec + .logger + .info("[dry-run] would write Portage config and sync"); + return Ok(()); + } + portage::write_config(&self.exec, &self.config, &self.hardware)?; + self.exec.copy_resolv_conf()?; + self.exec.mount_chroot()?; + let root = PathBuf::from(&self.exec.root); + if let Err(e) = portage::init_machine_id(&self.exec, &root) { + self.exec.logger.warn(format!("could not initialise machine-id: {e}")); + } + let result: Result<()> = (|| { + portage::sync(&self.exec, &root)?; + if let Err(e) = portage::verification_setup(&self.exec, &root) { + self.exec + .logger + .warn(format!("getuto failed; binary verification may fail: {e}")); + } + Ok(()) + })(); + self.exec.umount_chroot()?; + result?; + portage::select_profile(&self.exec, &self.config) + } + + fn packages_base(&self) -> Result<()> { + if self.exec.dry_run { + self.exec + .logger + .info("[dry-run] would install base packages"); + return Ok(()); + } + self.exec.mount_chroot()?; + let packages: Vec = portage::base_packages() + .into_iter() + .map(str::to_string) + .collect(); + let result = portage::emerge( + &self.exec, + std::path::Path::new(&self.exec.root), + &packages, + &self.engine, + &self.policy_ctx, + ); + self.exec.umount_chroot()?; + if result.is_ok() { + self.harvest_compile_times(); + } + result + } + + /// Record measured compile times from the target's emerge.log into the + /// installed system so the data survives reboot. + fn harvest_compile_times(&self) { + let history = match self.exec.target().var("lib/phoebus/compile-times.tsv") { + Ok(p) => p, + Err(_) => self.exec.state_dir.join("compile-times.tsv"), + }; + if let Err(e) = portage::harvest_emerge_log(&self.exec, &history) { + self.exec + .logger + .warn(format!("compile-time instrumentation failed: {e}")); + } + } + + fn kernel_install(&self) -> Result<()> { + if self.exec.dry_run { + self.exec + .logger + .info("[dry-run] would configure and install the kernel"); + return Ok(()); + } + kernel::write_profile(&self.exec, &self.config)?; + boot::write_install_conf(&self.exec)?; + boot::write_dracut_conf(&self.exec, &self.config)?; + let root_source = storage::root_source_ref(&self.exec, &self.config, &self.state); + kernel::write_cmdline( + &self.exec, + &self.config, + self.state.luks_uuid.as_deref(), + &root_source, + )?; + self.exec.mount_chroot()?; + let result = kernel::install( + &self.exec, + &self.config, + &self.hardware, + &self.engine, + &self.policy_ctx, + ); + self.exec.umount_chroot()?; + if result.is_ok() { + self.harvest_compile_times(); + } + result + } + + fn boot_install(&self) -> Result<()> { + if self.exec.dry_run { + self.exec + .logger + .info("[dry-run] would install systemd-boot"); + return Ok(()); + } + self.exec.mount_chroot()?; + if let Err(e) = boot::install_systemd_boot(&self.exec, &self.config) { + self.exec + .logger + .warn(format!("bootctl install failed; relying on EFI fallback: {e}")); + } + if let Err(e) = boot::generate_entries(&self.exec) { + self.exec + .logger + .warn(format!("kernel-install reported an issue: {e}")); + } + self.exec.umount_chroot()?; + boot::write_loader_conf(&self.exec, &self.config)?; + if let Err(e) = boot::write_recovery_entry(&self.exec, &self.config) { + self.exec + .logger + .warn(format!("could not write recovery entry: {e}")); + } + if let Err(e) = boot::install_fallback(&self.exec, &self.config) { + self.exec.logger.warn(format!("EFI fallback not installed: {e}")); + } + let _ = boot::random_seed(&self.exec, &self.config); + boot::verify(&self.exec, &self.config) + } + + fn users_configure( + &self, + user_password: Option<&SecretString>, + root_password: Option<&SecretString>, + ) -> Result<()> { + if self.exec.dry_run { + self.exec + .logger + .info("[dry-run] would create the user account"); + return Ok(()); + } + self.exec.mount_chroot()?; + let result: Result<()> = (|| { + users::create(&self.exec, &self.config, user_password, root_password)?; + users::configure_sudo(&self.exec)?; + Ok(()) + })(); + self.exec.umount_chroot()?; + result + } + + fn services_configure(&self) -> Result<()> { + if self.exec.dry_run { + self.exec + .logger + .info("[dry-run] would configure locale/timezone/services"); + return Ok(()); + } + self.exec.mount_chroot()?; + let result = services::configure(&self.exec, &self.config); + self.exec.umount_chroot()?; + result + } + + fn desktop_install(&self) -> Result<()> { + if self.config.desktop.profile == phoebus_core::DesktopProfile::None { + self.exec.logger.info("no desktop profile selected"); + return Ok(()); + } + if self.exec.dry_run { + self.exec + .logger + .info("[dry-run] would install the desktop profile"); + return Ok(()); + } + self.exec.mount_chroot()?; + let result: Result<()> = (|| { + desktop::install(&self.exec, &self.config, &self.engine, &self.policy_ctx)?; + desktop::write_session_script(&self.exec, &self.config)?; + desktop::configure_flatpak(&self.exec, &self.config)?; + Ok(()) + })(); + self.exec.umount_chroot()?; + if result.is_ok() { + self.harvest_compile_times(); + } + result + } + + fn finalize(&self, auth: &phoebus_executor::DestructiveAuthorization) -> Result<()> { + if self.exec.dry_run { + self.exec.logger.info("[dry-run] finalize"); + return Ok(()); + } + let _ = self.exec.export_log(); + let _ = self.exec.umount_chroot(); + storage::unmount_all(&self.exec, &self.config, std::path::Path::new(&self.exec.root))?; + if self.config.is_encrypted() { + if let Err(e) = encryption::luks_close(&self.exec, auth, &self.config) { + self.exec.logger.warn(format!("could not close LUKS device: {e}")); + } + } + self.exec.logger.info("installation finished"); + Ok(()) + } +} diff --git a/installer-rs/crates/phoebus-installer/src/release.rs b/installer-rs/crates/phoebus-installer/src/release.rs new file mode 100644 index 0000000..8a76a05 --- /dev/null +++ b/installer-rs/crates/phoebus-installer/src/release.rs @@ -0,0 +1,159 @@ +//! Release/ISO automation foundations. +//! +//! A biweekly release should not require a small VPS to rebuild the Gentoo +//! world. The model is: take a known-good installer-base ISO, overlay the +//! Phoebus installer + configs + pinned OpenCode, verify checksums, smoke test, +//! then publish atomically. This module produces and verifies the manifest that +//! makes that reproducible. +//! +//! Actual ISO assembly needs `xorriso`; this module emits the intended command +//! and refuses to publish without a passing verification. + +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Artifact { + pub name: String, + pub sha256: String, + pub size_bytes: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct ReleaseManifest { + pub version: String, + pub created_unix: u64, + pub installer_base: String, + pub stage3: String, + pub opencode_version: String, + pub artifacts: Vec, +} + +impl Default for ReleaseManifest { + fn default() -> Self { + Self { + version: env!("CARGO_PKG_VERSION").to_string(), + created_unix: 0, + installer_base: String::new(), + stage3: String::new(), + opencode_version: String::new(), + artifacts: Vec::new(), + } + } +} + +pub fn sha256_file(path: &Path) -> std::io::Result { + let mut file = std::fs::File::open(path)?; + let mut hasher = Sha256::new(); + std::io::copy(&mut file, &mut hasher)?; + Ok(format!("{:x}", hasher.finalize())) +} + +pub fn artifact_for(path: &Path) -> std::io::Result { + let meta = std::fs::metadata(path)?; + Ok(Artifact { + name: path + .file_name() + .map(|s| s.to_string_lossy().to_string()) + .unwrap_or_default(), + sha256: sha256_file(path)?, + size_bytes: meta.len(), + }) +} + +impl ReleaseManifest { + pub fn save(&self, path: &Path) -> std::io::Result<()> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(path, serde_json::to_string_pretty(self).unwrap()) + } + + pub fn load(path: &Path) -> std::io::Result { + let text = std::fs::read_to_string(path)?; + serde_json::from_str(&text) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e)) + } + + /// Verify a candidate artifact against the manifest. + pub fn verify(&self, name: &str, path: &Path) -> bool { + match self.artifacts.iter().find(|a| a.name == name) { + Some(expected) => sha256_file(path) + .map(|got| got == expected.sha256) + .unwrap_or(false), + None => false, + } + } + + /// The xorriso command that would assemble the candidate ISO. + /// + /// The base ISO is remastered with the Phoebus payload; nothing in the base + /// system is rebuilt. + pub fn assemble_command(base_iso: &Path, payload_dir: &Path, output: &Path) -> Vec { + vec![ + "xorriso".into(), + "-indev".into(), + base_iso.to_string_lossy().to_string(), + "-outdev".into(), + output.to_string_lossy().to_string(), + "-map".into(), + payload_dir.to_string_lossy().to_string(), + "/phoebus".into(), + "-boot_image".into(), + "any".into(), + "keep".into(), + ] + } +} + +pub fn default_manifest_path(dir: &Path) -> PathBuf { + dir.join("phoebus-release.json") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sha256_of_known_bytes() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("f"); + std::fs::write(&path, b"abc").unwrap(); + // SHA-256("abc") + assert_eq!( + sha256_file(&path).unwrap(), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + } + + #[test] + fn manifest_roundtrip_and_verify() { + let dir = tempfile::tempdir().unwrap(); + let iso = dir.path().join("phoebus.iso"); + std::fs::write(&iso, b"iso-bytes").unwrap(); + let mut manifest = ReleaseManifest::default(); + manifest.artifacts.push(artifact_for(&iso).unwrap()); + manifest.installer_base = "installer-base-2026.iso".into(); + let path = default_manifest_path(dir.path()); + manifest.save(&path).unwrap(); + let loaded = ReleaseManifest::load(&path).unwrap(); + assert_eq!(loaded, manifest); + assert!(loaded.verify("phoebus.iso", &iso)); + assert!(!loaded.verify("missing.iso", &iso)); + } + + #[test] + fn assemble_command_targets_payload() { + let cmd = ReleaseManifest::assemble_command( + Path::new("/base.iso"), + Path::new("/payload"), + Path::new("/out.iso"), + ); + assert_eq!(cmd[0], "xorriso"); + assert!(cmd.iter().any(|a| a == "/phoebus")); + assert!(cmd.iter().any(|a| a == "/base.iso")); + } +} diff --git a/installer-rs/crates/phoebus-installer/tests/parity.rs b/installer-rs/crates/phoebus-installer/tests/parity.rs new file mode 100644 index 0000000..59dd782 --- /dev/null +++ b/installer-rs/crates/phoebus-installer/tests/parity.rs @@ -0,0 +1,96 @@ +//! Bash/Rust plan parity. +//! +//! Runs the same configuration through the reference Bash `--plan` and the +//! Rust `--plan` and checks that the semantically important facts agree. +//! Formatting is allowed to differ; behavior is not. + +use std::path::PathBuf; +use std::process::Command; + +fn bash_installer() -> Option { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../installer/bin/ai-installer"); + if path.is_file() { + Some(path) + } else { + None + } +} + +fn write_config(dir: &std::path::Path) -> PathBuf { + let path = dir.join("parity.conf"); + let text = "\ +HOSTNAME='paritybox'\n\ +USERNAME='parityuser'\n\ +LOCALE='en_US.UTF-8'\n\ +TIMEZONE='UTC'\n\ +KEYMAP='us'\n\ +TARGET_DISK='/dev/vda'\n\ +EFI_SIZE_MIB='1024'\n\ +FILESYSTEM='btrfs'\n\ +ENCRYPTION='luks2'\n\ +COMPRESS='zstd:3'\n\ +KERNEL_PROFILE='safe'\n\ +KERNEL_CONSOLE='console=tty0'\n\ +PACKAGE_POLICY='balanced'\n\ +DESKTOP_PROFILE='dwl'\n\ +BTRFS_SUBVOLS='@ @home @var @snapshots @swap'\n"; + std::fs::write(&path, text).unwrap(); + path +} + +#[test] +fn rust_plan_matches_bash_plan_on_key_facts() { + let Some(bash) = bash_installer() else { + eprintln!("skipping: reference Bash installer not found"); + return; + }; + let dir = tempfile::tempdir().unwrap(); + let config = write_config(dir.path()); + + let bash_out = Command::new("bash") + .arg(&bash) + .arg("--config") + .arg(&config) + .arg("--plan") + .output() + .expect("run bash installer"); + if !bash_out.status.success() { + eprintln!("skipping: Bash installer could not run"); + return; + } + let bash_text = String::from_utf8_lossy(&bash_out.stdout).to_string(); + + let rust_out = Command::new(env!("CARGO_BIN_EXE_phoebus-installer")) + .arg("--config") + .arg(&config) + .arg("--plan") + .output() + .expect("run rust installer"); + assert!(rust_out.status.success()); + let rust_text = String::from_utf8_lossy(&rust_out.stdout).to_string(); + + // Facts both renderings must agree on. + for fact in [ + "paritybox", + "parityuser", + "en_US.UTF-8", + "UTC", + "/dev/vda", + "luks2", + "btrfs", + "@snapshots", + "sys-kernel/gentoo-kernel-bin", + "balanced", + "dwl", + ] { + assert!( + bash_text.contains(fact), + "Bash plan missing `{fact}`:\n{bash_text}" + ); + assert!( + rust_text.contains(fact), + "Rust plan missing `{fact}`:\n{rust_text}" + ); + } +} diff --git a/installer-rs/crates/phoebus-tui/Cargo.toml b/installer-rs/crates/phoebus-tui/Cargo.toml new file mode 100644 index 0000000..853de0f --- /dev/null +++ b/installer-rs/crates/phoebus-tui/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "phoebus-tui" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +phoebus-core.workspace = true +ratatui = "0.29" +crossterm = "0.28" diff --git a/installer-rs/crates/phoebus-tui/src/lib.rs b/installer-rs/crates/phoebus-tui/src/lib.rs new file mode 100644 index 0000000..7a014cd --- /dev/null +++ b/installer-rs/crates/phoebus-tui/src/lib.rs @@ -0,0 +1,507 @@ +//! Phoebus installer text UI. +//! +//! A simple, keyboard-driven configuration screen in the spirit of +//! `void-installer`. It edits the typed `InstallConfig` and returns an outcome; +//! privileged execution stays in the CLI so there is a single place that can +//! run the destructive backend. + +use std::io; + +use crossterm::event::{self, Event, KeyCode, KeyEventKind}; +use crossterm::execute; +use crossterm::terminal::{ + disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen, +}; +use phoebus_core::{DesktopProfile, Encryption, Filesystem, InstallConfig, KernelProfile, PackagePolicy, SecretString}; +use ratatui::backend::CrosstermBackend; +use ratatui::layout::{Constraint, Direction, Layout, Rect}; +use ratatui::style::{Color, Modifier, Style}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap}; +use ratatui::Terminal; + +pub enum TuiOutcome { + Exit, + Install(InstallConfig, Option, Option), + Save(InstallConfig), +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum EditTarget { + Keymap, + Hostname, + Locale, + Timezone, + Username, + Disk, + UserPassword, + Passphrase, +} + +struct EditState { + label: String, + value: String, + target: EditTarget, + secret: bool, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Choice { + Filesystem, + Encryption, + KernelProfile, + PackagePolicy, + DesktopProfile, +} + +enum Mode { + Browse, + Edit(EditState), + Choice(Choice, usize), + Plan(String, u16), + ConfirmErase, + Message(String), +} + +struct App { + config: InstallConfig, + passphrase: Option, + user_password: Option, + cursor: usize, + mode: Mode, + confirm_input: String, +} + +impl App { + fn new(config: InstallConfig) -> Self { + Self { + config, + passphrase: None, + user_password: None, + cursor: 0, + mode: Mode::Browse, + confirm_input: String::new(), + } + } + + fn entries(&self) -> Vec<(String, String)> { + let c = &self.config; + vec![ + ("Keyboard".into(), c.system.keymap.clone()), + ("Hostname".into(), c.system.hostname.clone()), + ("Locale".into(), c.system.locale.clone()), + ("Timezone".into(), c.system.timezone.clone()), + ("User".into(), c.user.username.clone()), + ("Disk".into(), c.storage.disk.clone()), + ("Filesystem".into(), c.storage.filesystem.to_string()), + ("Encryption".into(), c.encryption.mode.to_string()), + ( + "Kernel profile".into(), + c.kernel.profile.to_string(), + ), + ("Package policy".into(), c.packages.policy.to_string()), + ("Desktop".into(), c.desktop.profile.to_string()), + ( + "Flatpak".into(), + if c.desktop.flatpak { "yes" } else { "no" }.into(), + ), + ( + "Passphrase".into(), + if self.passphrase.is_some() { "set" } else { "unset" }.into(), + ), + ( + "User password".into(), + if self.user_password.is_some() { "set" } else { "unset" }.into(), + ), + ("Review plan".into(), String::new()), + ("Install".into(), String::new()), + ("Exit".into(), String::new()), + ] + } + + fn activate(&mut self) { + let idx = self.cursor; + match idx { + 0 => self.mode = Mode::Edit(self.edit("Keyboard", &self.config.system.keymap.clone(), EditTarget::Keymap, false)), + 1 => self.mode = Mode::Edit(self.edit("Hostname", &self.config.system.hostname.clone(), EditTarget::Hostname, false)), + 2 => self.mode = Mode::Edit(self.edit("Locale", &self.config.system.locale.clone(), EditTarget::Locale, false)), + 3 => self.mode = Mode::Edit(self.edit("Timezone", &self.config.system.timezone.clone(), EditTarget::Timezone, false)), + 4 => self.mode = Mode::Edit(self.edit("User", &self.config.user.username.clone(), EditTarget::Username, false)), + 5 => self.mode = Mode::Edit(self.edit("Disk", &self.config.storage.disk.clone(), EditTarget::Disk, false)), + 6 => self.mode = Mode::Choice(Choice::Filesystem, 0), + 7 => self.mode = Mode::Choice(Choice::Encryption, 0), + 8 => self.mode = Mode::Choice(Choice::KernelProfile, 0), + 9 => self.mode = Mode::Choice(Choice::PackagePolicy, 0), + 10 => self.mode = Mode::Choice(Choice::DesktopProfile, 0), + 11 => self.config.desktop.flatpak = !self.config.desktop.flatpak, + 12 => self.mode = Mode::Edit(self.edit("Encryption passphrase", "", EditTarget::Passphrase, true)), + 13 => self.mode = Mode::Edit(self.edit("User password", "", EditTarget::UserPassword, true)), + 14 => self.mode = Mode::Plan(self.render_plan(), 0), + 15 => self.mode = Mode::ConfirmErase, + 16 => self.mode = Mode::Message("__exit__".into()), + _ => {} + } + } + + fn edit(&self, label: &str, value: &str, target: EditTarget, secret: bool) -> EditState { + EditState { + label: label.to_string(), + value: value.to_string(), + target, + secret, + } + } + + fn render_plan(&self) -> String { + let plan = phoebus_core::InstallPlan::for_config(&self.config); + let text = plan.render_human(&self.config, None); + let issues = phoebus_core::validate_config(&self.config); + let mut out = text; + out.push_str("\nValidation:\n"); + if issues.is_empty() { + out.push_str(" OK\n"); + } else { + for i in &issues { + out.push_str(&format!(" - {i}\n")); + } + } + out + } + + fn commit_edit(state: &EditState, config: &mut InstallConfig, passphrase: &mut Option, user_password: &mut Option) { + match state.target { + EditTarget::Keymap => config.system.keymap = state.value.clone(), + EditTarget::Hostname => config.system.hostname = state.value.clone(), + EditTarget::Locale => config.system.locale = state.value.clone(), + EditTarget::Timezone => config.system.timezone = state.value.clone(), + EditTarget::Username => config.user.username = state.value.clone(), + EditTarget::Disk => config.storage.disk = state.value.clone(), + EditTarget::Passphrase => *passphrase = Some(SecretString::new(state.value.clone())), + EditTarget::UserPassword => *user_password = Some(SecretString::new(state.value.clone())), + } + } +} + +fn draw(frame: &mut ratatui::Frame, app: &mut App) { + let chunks = Layout::default() + .direction(Direction::Vertical) + .constraints([Constraint::Min(3), Constraint::Length(3)]) + .split(frame.area()); + + let items: Vec = app + .entries() + .into_iter() + .map(|(name, value)| { + let line = if value.is_empty() { + Line::from(vec![Span::raw(name)]) + } else { + Line::from(vec![ + Span::styled(format!("{name:<18}"), Style::default().fg(Color::Cyan)), + Span::raw(value), + ]) + }; + ListItem::new(line) + }) + .collect(); + let list = List::new(items) + .block(Block::default().borders(Borders::ALL).title(" Phoebus OS Installer ")) + .highlight_style(Style::default().add_modifier(Modifier::REVERSED)) + .highlight_symbol("> "); + let mut state = ListState::default(); + state.select(Some(app.cursor)); + frame.render_stateful_widget(list, chunks[0], &mut state); + + let help = "Enter: edit p: plan i: install s: save q: quit"; + frame.render_widget( + Paragraph::new(help).block(Block::default().borders(Borders::ALL).title(" Help ")), + chunks[1], + ); + + match &app.mode { + Mode::Edit(edit) => { + let area = centered(60, 3, frame.area()); + frame.render_widget(Clear, area); + let shown = if edit.secret { + "*".repeat(edit.value.len()) + } else { + edit.value.clone() + }; + frame.render_widget( + Paragraph::new(shown).block( + Block::default() + .borders(Borders::ALL) + .title(format!(" {} ", edit.label)), + ), + area, + ); + } + Mode::Choice(choice, selected) => { + let options = choice_options(*choice, &app.config); + let items: Vec = options + .iter() + .enumerate() + .map(|(i, o)| { + let style = if i == *selected { + Style::default().add_modifier(Modifier::REVERSED) + } else { + Style::default() + }; + ListItem::new(Span::styled(o.clone(), style)) + }) + .collect(); + let height = (options.len() as u16 + 2).min(frame.area().height); + let area = centered(40, height, frame.area()); + frame.render_widget(Clear, area); + frame.render_widget( + List::new(items).block(Block::default().borders(Borders::ALL).title(" Select ")), + area, + ); + } + Mode::Plan(text, scroll) => { + let area = frame.area(); + frame.render_widget(Clear, area); + let lines: Vec = text.lines().map(|l| Line::from(l.to_string())).collect(); + frame.render_widget( + Paragraph::new(lines) + .scroll((*scroll, 0)) + .wrap(Wrap { trim: false }) + .block(Block::default().borders(Borders::ALL).title(" Installation plan (q to close) ")), + area, + ); + } + Mode::ConfirmErase => { + let area = centered(60, 7, frame.area()); + frame.render_widget(Clear, area); + frame.render_widget( + Paragraph::new(format!( + "This will ERASE the target disk.\n\nType ERASE then press Enter to confirm, Esc to cancel.\n\n> {}", + app.confirm_input + )) + .block(Block::default().borders(Borders::ALL).title(" DESTRUCTIVE ")), + area, + ); + } + Mode::Message(msg) => { + if msg == "__exit__" { + return; + } + let area = centered(60, 5, frame.area()); + frame.render_widget(Clear, area); + frame.render_widget( + Paragraph::new(msg.clone()).block(Block::default().borders(Borders::ALL).title(" Message ")), + area, + ); + } + Mode::Browse => {} + } +} + +fn choice_options(choice: Choice, _config: &InstallConfig) -> Vec { + match choice { + Choice::Filesystem => vec![ + Filesystem::Btrfs.to_string(), + Filesystem::Ext4.to_string(), + ], + Choice::Encryption => vec![ + Encryption::Luks2.to_string(), + Encryption::None.to_string(), + ], + Choice::KernelProfile => vec![ + KernelProfile::Optimized.to_string(), + KernelProfile::Safe.to_string(), + KernelProfile::Aggressive.to_string(), + ], + Choice::PackagePolicy => vec![ + PackagePolicy::Balanced.to_string(), + PackagePolicy::SourceFirst.to_string(), + PackagePolicy::BinaryFirst.to_string(), + ], + Choice::DesktopProfile => vec![ + DesktopProfile::None.to_string(), + DesktopProfile::Dwl.to_string(), + DesktopProfile::Minimal.to_string(), + DesktopProfile::Full.to_string(), + ], + } +} + +fn centered(width: u16, height: u16, area: Rect) -> Rect { + let w = width.min(area.width); + let h = height.min(area.height); + Rect { + x: area.x + (area.width.saturating_sub(w)) / 2, + y: area.y + (area.height.saturating_sub(h)) / 2, + width: w, + height: h, + } +} + +fn apply_choice(choice: Choice, index: usize, config: &mut InstallConfig) { + match choice { + Choice::Filesystem => { + config.storage.filesystem = if index == 0 { Filesystem::Btrfs } else { Filesystem::Ext4 }; + } + Choice::Encryption => { + config.encryption.mode = if index == 0 { Encryption::Luks2 } else { Encryption::None }; + } + Choice::KernelProfile => { + config.kernel.profile = [KernelProfile::Optimized, KernelProfile::Safe, KernelProfile::Aggressive][index.min(2)]; + } + Choice::PackagePolicy => { + config.packages.policy = [PackagePolicy::Balanced, PackagePolicy::SourceFirst, PackagePolicy::BinaryFirst][index.min(2)]; + } + Choice::DesktopProfile => { + config.desktop.profile = [DesktopProfile::None, DesktopProfile::Dwl, DesktopProfile::Minimal, DesktopProfile::Full][index.min(3)]; + } + } +} + +pub fn run(mut config: InstallConfig) -> io::Result { + enable_raw_mode()?; + let mut stdout = io::stdout(); + execute!(stdout, EnterAlternateScreen)?; + let backend = CrosstermBackend::new(stdout); + let mut terminal = Terminal::new(backend)?; + let mut app = App::new(config.clone()); + + let outcome = loop { + terminal.draw(|f| draw(f, &mut app))?; + + let ev = event::read()?; + if let Event::Key(key) = ev { + if key.kind != KeyEventKind::Press { + continue; + } + let mut exit = None; + match &mut app.mode { + Mode::Browse => match key.code { + KeyCode::Char('q') | KeyCode::Esc => exit = Some(TuiOutcome::Exit), + KeyCode::Down | KeyCode::Char('j') => { + app.cursor = (app.cursor + 1).min(app.entries().len() - 1) + } + KeyCode::Up | KeyCode::Char('k') => app.cursor = app.cursor.saturating_sub(1), + KeyCode::Enter => app.activate(), + KeyCode::Char('p') => app.mode = Mode::Plan(app.render_plan(), 0), + KeyCode::Char('s') => exit = Some(TuiOutcome::Save(app.config.clone())), + KeyCode::Char('i') => { + app.confirm_input.clear(); + app.mode = Mode::ConfirmErase; + } + _ => {} + }, + Mode::Edit(_) => match key.code { + KeyCode::Esc => app.mode = Mode::Browse, + KeyCode::Enter => { + if let Mode::Edit(edit) = std::mem::replace(&mut app.mode, Mode::Browse) { + App::commit_edit(&edit, &mut app.config, &mut app.passphrase, &mut app.user_password); + } + } + KeyCode::Backspace => { + if let Mode::Edit(edit) = &mut app.mode { + edit.value.pop(); + } + } + KeyCode::Char(c) => { + if let Mode::Edit(edit) = &mut app.mode { + edit.value.push(c); + } + } + _ => {} + }, + Mode::Choice(choice, selected) => { + let count = choice_options(*choice, &app.config).len(); + match key.code { + KeyCode::Esc => app.mode = Mode::Browse, + KeyCode::Down | KeyCode::Char('j') => { + *selected = (*selected + 1).min(count.saturating_sub(1)) + } + KeyCode::Up | KeyCode::Char('k') => *selected = selected.saturating_sub(1), + KeyCode::Enter => { + if let Mode::Choice(choice, selected) = std::mem::replace(&mut app.mode, Mode::Browse) { + apply_choice(choice, selected, &mut app.config); + } + } + _ => {} + } + } + Mode::Plan(_, scroll) => match key.code { + KeyCode::Esc | KeyCode::Char('q') => app.mode = Mode::Browse, + KeyCode::Down | KeyCode::Char('j') => *scroll = scroll.saturating_add(1), + KeyCode::Up | KeyCode::Char('k') => *scroll = scroll.saturating_sub(1), + _ => {} + }, + Mode::ConfirmErase => match key.code { + KeyCode::Esc => { + app.confirm_input.clear(); + app.mode = Mode::Browse; + } + KeyCode::Backspace => { + app.confirm_input.pop(); + } + KeyCode::Enter => { + if app.confirm_input == "ERASE" { + exit = Some(TuiOutcome::Install( + app.config.clone(), + app.passphrase.clone(), + app.user_password.clone(), + )); + } else { + let msg = "Type ERASE exactly (case sensitive)."; + app.confirm_input.clear(); + app.mode = Mode::Message(msg.into()); + } + } + KeyCode::Char(c) => app.confirm_input.push(c), + _ => {} + }, + Mode::Message(msg) => { + if msg == "__exit__" { + exit = Some(TuiOutcome::Exit); + } else if key.code == KeyCode::Enter || key.code == KeyCode::Esc { + app.mode = Mode::Browse; + } + } + } + if let Some(o) = exit { + break o; + } + } + }; + + disable_raw_mode()?; + execute!(terminal.backend_mut(), LeaveAlternateScreen)?; + terminal.show_cursor()?; + config = app.config.clone(); + Ok(match outcome { + TuiOutcome::Exit => TuiOutcome::Exit, + TuiOutcome::Save(_) => TuiOutcome::Save(config), + TuiOutcome::Install(_, p, u) => TuiOutcome::Install(config, p, u), + }) +} + +/// Whether stdout is a terminal. +pub fn is_tty() -> bool { + use std::io::IsTerminal; + io::stdout().is_terminal() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn entries_and_actions_are_bounded() { + let app = App::new(InstallConfig::default()); + let entries = app.entries(); + assert!(entries.len() >= 17); + } + + #[test] + fn apply_choice_sets_values() { + let mut config = InstallConfig::default(); + apply_choice(Choice::DesktopProfile, 1, &mut config); + assert_eq!(config.desktop.profile, DesktopProfile::Dwl); + apply_choice(Choice::Encryption, 1, &mut config); + assert_eq!(config.encryption.mode, Encryption::None); + } +} diff --git a/installer/README.md b/installer/README.md new file mode 100644 index 0000000..448a151 --- /dev/null +++ b/installer/README.md @@ -0,0 +1,124 @@ +# Phoebus OS installer + +A deterministic, text-mode installer for Phoebus OS, inspired by +`void-installer`. It is usable entirely without an LLM; AI only augments it. + +## Goals + +- Simple keyboard-driven TUI. +- Logical, revisitable configuration stages. +- A complete installation plan and explicit confirmation before anything + destructive happens. +- Logs for every backend operation. +- No magical hidden disk modifications. + +## Two layers + +``` +tui/ front-end: menus, dialogs, screens + menu.sh main loop, review and install flow + screens.sh one function per configuration stage + ui.sh dialog/whiptail abstraction + +lib/ deterministic backend (usable without the TUI) + state.sh structured configuration state + logging.sh logging + run_cmd + dry-run + confirm.sh destructive-operation authorization gates + hardware.sh read-only hardware probing + disks.sh read-only disk discovery and protection rules + partitions.sh GPT partitioning + filesystem.sh mkfs, mount, fstab/crypttab generation + encryption.sh LUKS2 + btrfs.sh subvolume layout + network.sh live networking + target hostname + portage.sh Portage configuration and stage3 + pkgpolicy.sh compile-vs-binary policy + kernel.sh kernel profile and installation + boot.sh systemd-boot (BLS entries) + dracut initramfs + users.sh accounts, passwords, sudo + desktop.sh desktop profiles + ai.sh assistant and structured proposals + opencode.sh pinned, checksum-verified OpenCode + plan.sh installation plan generation + validation.sh configuration validation + install.sh staged orchestration + +config/ + defaults.conf all defaults + opencode.manifest pinned OpenCode release + SHA-256 + +tests/ unit tests, no root or disks required +``` + +## Running in a Gentoo Live environment + +The LiveGUI reference (or any Gentoo live medium with `dialog`, Portage and the +disk tools listed in `doc/FINDINGS.md`) can run the installer directly: + +```sh +sudo /path/to/installer/bin/ai-installer +``` + +Useful non-interactive modes (the backend works without the TUI): + +```sh +# Print the generated installation plan and validate the configuration +ai-installer --plan + +# Load a saved configuration +ai-installer --config /root/phoebus-install.conf + +# Dry run: every command is logged, nothing is executed +ai-installer --dry-run + +# Run the backend without a TUI (still requires explicit ERASE confirmation) +ai-installer --config /root/phoebus-install.conf --install + +# Fetch and verify the pinned OpenCode release +ai-installer --bootstrap-opencode +``` + +### Typical flow + +1. Network (connect Wi-Fi if needed). +2. Keyboard, hostname, locale, timezone, user. +3. Disk: pick a target (protected devices are never offered). +4. Filesystem / encryption: LUKS2 is the default; set a passphrase. +5. Boot / kernel / packages / desktop as desired. +6. Review configuration -> inspect the plan. +7. Install -> read the destructive summary, type `ERASE`, confirm again. + +## Safety model + +- Detection never modifies a disk. +- The target disk must be explicitly selected from candidates. +- Disks that are mounted, read-only, optical/loop, or back the live medium are + marked **PROTECTED** and cannot be selected. +- All destructive commands go through `run_destructive`, which refuses to run + unless `PHOEBUS_DESTRUCTIVE_AUTHORIZED=yes`. Only `install.sh` grants this, + only after the plan is approved. +- Whole-disk erase additionally requires typing `ERASE`. +- Dry-run mode redirects all file writes to a temporary sandbox and runs no + commands. +- Passwords, passphrases and API keys are never written to the config or logs. + +## Package policy + +`lib/pkgpolicy.sh` implements the rule "compile when cheap or beneficial, use a +binary when expensive and the benefit is negligible". It is deterministic and +uses a curated table plus optional historical compile times +(`$STATE_DIR/compile-times.tsv`). No model is consulted to guess performance. + +## AI policy + +- The normal install path is fully deterministic and LLM-free. +- The AI assistant explains hardware, disks, filesystems, kernel and package + choices, and can translate a natural-language request into a **structured + proposal** (flat JSON with a fixed key whitelist). +- Every proposed field is validated by `lib/validation.sh`. The LLM never + receives secrets, never touches a disk and never runs a command. +- Proposal flow: request -> proposal -> validation -> preview -> confirmation -> + backend. + +See `doc/FINDINGS.md` for environment findings and `doc/TESTING.md` for safe +testing instructions. diff --git a/installer/bin/ai-installer b/installer/bin/ai-installer new file mode 100755 index 0000000..afc1369 --- /dev/null +++ b/installer/bin/ai-installer @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Phoebus OS installer entry point. +# +# Usage: +# ai-installer start the text UI +# ai-installer --dry-run start the UI with no disk changes +# ai-installer --config FILE load a saved configuration +# ai-installer --plan print the installation plan and exit +# ai-installer --install run the deterministic backend (no TUI) +# ai-installer --yes skip interactive confirmations (unattended) +# ai-installer --luks-passphrase-file FILE +# ai-installer --user-password-file FILE +# ai-installer --root-password-file FILE +# ai-installer --bootstrap-opencode +# +# The deterministic backend can be used without the TUI. The TUI is only a +# front-end over the same configuration state and backend functions. +# Secret files must be mode 0600; their contents are never logged. + +PHOEBUS_VERSION="0.1.0" + +set -uo pipefail + +# Locate the project root (the directory containing lib/, tui/, config/). +_self="${BASH_SOURCE[0]}" +while [[ -L "$_self" ]]; do + _self="$(readlink "$_self")" +done +PHOEBUS_ROOT="$(cd "$(dirname "$_self")/.." && pwd)" +export PHOEBUS_ROOT + +CONFIG_FILE="" +MODE="tui" +UI_BACKEND="${UI_BACKEND:-auto}" +STATE_DIR="${STATE_DIR:-/run/ai-installer}" +LUKS_PW_FILE="" +USER_PW_FILE="" +ROOT_PW_FILE="" + +# read_secret_file FILE - read a secret without echoing it; returns non-zero +# when the file is missing or unreadable. The value is never logged. +read_secret_file() { + local file="$1" + [[ -r "$file" ]] || { printf 'cannot read secret file: %s\n' "$file" >&2; return 1; } + local value + value="$(cat -- "$file")" + printf '%s' "${value%$'\n'}" +} + +# --- argument parsing ------------------------------------------------------- +while (($#)); do + case "$1" in + --dry-run) CLI_DRY_RUN=yes ;; + --yes|-y) CLI_ASSUME_YES=yes ;; + --config) shift; CONFIG_FILE="${1:-}" ;; + --plan) MODE="plan" ;; + --install) MODE="install" ;; + --backend) MODE="plan" ;; + --ui) shift; UI_BACKEND="${1:-}" ;; + --luks-passphrase-file) shift; LUKS_PW_FILE="${1:-}" ;; + --user-password-file) shift; USER_PW_FILE="${1:-}" ;; + --root-password-file) shift; ROOT_PW_FILE="${1:-}" ;; + --bootstrap-opencode) MODE="opencode" ;; + --version|-V) printf '%s %s\n' "Phoebus installer" "$PHOEBUS_VERSION"; exit 0 ;; + --help|-h) + sed -n '3,20p' "$_self" | sed 's/^# \{0,1\}//' + exit 0 ;; + *) printf 'Unknown option: %s\n' "$1" >&2; exit 2 ;; + esac + shift +done + +export UI_BACKEND + +# --- load libraries --------------------------------------------------------- +# shellcheck source=/dev/null +for lib in state logging confirm hardware disks validation plan pkgpolicy \ + portage partitions filesystem encryption btrfs network kernel boot \ + users desktop opencode ai install; do + source "$PHOEBUS_ROOT/lib/$lib.sh" +done +# shellcheck source=/dev/null +for tui in ui screens menu; do + source "$PHOEBUS_ROOT/tui/$tui.sh" +done + +# --- initialize state ------------------------------------------------------- +mkdir -p "$STATE_DIR" 2>/dev/null || STATE_DIR="/tmp/ai-installer" +export STATE_DIR + +config_load_defaults "$PHOEBUS_ROOT/config/defaults.conf" +[[ -n "$CONFIG_FILE" ]] && config_load_file "$CONFIG_FILE" + +[[ -n "${CLI_DRY_RUN:-}" ]] && config_set DRY_RUN "$CLI_DRY_RUN" +[[ -n "${CLI_ASSUME_YES:-}" ]] && config_set ASSUME_YES "$CLI_ASSUME_YES" + +log_init + +# --- load secrets from files (unattended installs only) --------------------- +if [[ -n "$LUKS_PW_FILE" ]]; then + LUKS_PASSPHRASE="$(read_secret_file "$LUKS_PW_FILE")" || exit 1 + secret_register "$LUKS_PASSPHRASE" +fi +if [[ -n "$USER_PW_FILE" ]]; then + USER_PASSWORD="$(read_secret_file "$USER_PW_FILE")" || exit 1 + secret_register "$USER_PASSWORD" +fi +if [[ -n "$ROOT_PW_FILE" ]]; then + ROOT_PASSWORD="$(read_secret_file "$ROOT_PW_FILE")" || exit 1 + secret_register "$ROOT_PASSWORD" +fi + +# --- run -------------------------------------------------------------------- +case "$MODE" in + plan) + plan_generate + plan_render + printf '\n' + printf 'Validation:\n' + problems="$(validate_config)" + if [[ -z "$problems" ]]; then printf ' OK\n'; else printf '%s\n' "$problems" | sed 's/^/ - /'; fi + exit 0 + ;; + install) + plan_generate + if [[ -n "$(validate_config)" ]]; then + log_error "configuration is incomplete; run --plan to inspect" + exit 1 + fi + if ! confirm_erase "$(plan_destructive_preview)"; then + log_error "installation not confirmed" + exit 1 + fi + destructive_grant + rc=0 + install_run || rc=$? + destructive_revoke + exit "$rc" + ;; + opencode) + if opencode_ensure; then + printf 'OpenCode ready at %s\n' "$(opencode_detect)" + exit 0 + fi + exit 1 + ;; + tui) + if ! ui_init; then + printf 'No dialog/whiptail found. Use --plan or --install for the backend.\n' >&2 + exit 1 + fi + menu_main + exit 0 + ;; +esac diff --git a/installer/config/defaults.conf b/installer/config/defaults.conf new file mode 100644 index 0000000..7aae67f --- /dev/null +++ b/installer/config/defaults.conf @@ -0,0 +1,83 @@ +# Phoebus OS installer defaults. +# +# This file is sourced by lib/state.sh. Only settings that are not already +# defined are applied, so a user-supplied config file always wins. +# +# Do NOT put secrets (passwords, passphrases, API keys) in this file. + +# --- identity --------------------------------------------------------------- +config_default DISTRO_NAME "Phoebus OS" +config_default DISTRO_ID "phoebus" +config_default ARCH "x86_64" + +# --- general installation --------------------------------------------------- +config_default HOSTNAME "phoebus" +config_default KEYMAP "us" +config_default LOCALE "en_US.UTF-8" +config_default TIMEZONE "UTC" +config_default ROOT_SHELL "/bin/bash" + +# --- user account ----------------------------------------------------------- +config_default USERNAME "" +config_default USER_FULLNAME "Phoebus User" +config_default USER_GROUPS "wheel,audio,video,input,render,plugdev,libinput,network,power" +config_default USER_HOME "/home" + +# --- target / storage ------------------------------------------------------- +config_default TARGET_DISK "" +config_default PARTITION_SCHEME "whole_disk" +config_default EFI_SIZE_MIB "1024" +config_default EFI_MOUNT "/efi" +config_default SWAP_SIZE_MIB "0" # 0 = swapfile sized from RAM +config_default FILESYSTEM "btrfs" +config_default BTRFS_LABEL "phoebus" +config_default COMPRESS "zstd:3" +config_default INSTALL_ROOT "/mnt/phoebus" +config_default BTRFS_SUBVOLS "@ @home @var @snapshots @swap" + +# --- encryption ------------------------------------------------------------- +config_default ENCRYPTION "luks2" +config_default LUKS_NAME "cryptroot" +config_default LUKS_CIPHER "aes-xts-plain64" +config_default LUKS_KEY_SIZE "512" +config_default LUKS_PBKDF "argon2id" + +# --- Gentoo base installation ---------------------------------------------- +# Pin STAGE3_URL/STAGE3_SHA256 for reproducible installs. When empty the +# installer resolves the current stable systemd stage3 from the mirror. +config_default STAGE3_URL "" +config_default STAGE3_SHA256 "" +config_default STAGE3_MIRROR "https://distfiles.gentoo.org/releases/amd64/autobuilds" +config_default GENTOO_PROFILE "default/linux/amd64/23.0/systemd" +config_default BINHOST_URI "https://distfiles.gentoo.org/releases/amd64/binpackages/23.0/x86-64" + +# --- boot / kernel ---------------------------------------------------------- +config_default BOOTLOADER "systemd-boot" +config_default KERNEL_PROFILE "optimized" # safe | optimized | aggressive +config_default KERNEL_PACKAGE "sys-kernel/gentoo-kernel" +config_default KERNEL_UKI "no" +config_default KERNEL_CONSOLE "console=tty0" +config_default KEEP_KERNELS "3" +config_default SECUREBOOT "no" + +# --- software --------------------------------------------------------------- +config_default PACKAGE_POLICY "balanced" # source_first | balanced | binary_first +config_default FEATURES_BINPKG "yes" +config_default ACCEPT_LICENSE "@FREE @BINARY-REDISTRIBUTABLE" +config_default DESKTOP_PROFILE "none" # none | minimal | dwl | full +config_default FLATPAK "no" +config_default AUDIO_STACK "pipewire" +config_default INIT_SYSTEM "systemd" + +# --- AI --------------------------------------------------------------------- +config_default AI_ENABLED "no" +config_default AI_PROVIDER "" +config_default AI_MODEL "" +config_default AI_ENDPOINT "" +config_default OPENCODE_VERSION "" +config_default OPENCODE_VERIFY "yes" + +# --- runtime (not persisted by default) ------------------------------------ +config_default DRY_RUN "no" +config_default ASSUME_YES "no" +config_default LOG_DIR "/var/log/ai-installer" diff --git a/installer/config/example.conf b/installer/config/example.conf new file mode 100644 index 0000000..74c0805 --- /dev/null +++ b/installer/config/example.conf @@ -0,0 +1,46 @@ +# Example Phoebus OS installer configuration. +# +# Load with: ai-installer --config example.conf +# Inspect: ai-installer --config example.conf --plan +# Install: ai-installer --config example.conf --install +# +# NEVER put passwords, passphrases or API keys in this file. They are prompted +# for interactively and are never persisted. + +# Identity +HOSTNAME='phoebus' +KEYMAP='us' +LOCALE='en_US.UTF-8' +TIMEZONE='UTC' + +# User +USERNAME='phoebus' +USER_FULLNAME='Phoebus User' + +# Storage +TARGET_DISK='/dev/nvme0n1' +PARTITION_SCHEME='whole_disk' +EFI_SIZE_MIB='1024' +FILESYSTEM='btrfs' +ENCRYPTION='luks2' +COMPRESS='zstd:3' + +# Boot and kernel +BOOTLOADER='systemd-boot' +KERNEL_PROFILE='optimized' +KERNEL_UKI='yes' +KEEP_KERNELS='3' + +# Packages +PACKAGE_POLICY='balanced' +FEATURES_BINPKG='yes' +ACCEPT_LICENSE='@FREE @BINARY-REDISTRIBUTABLE' + +# Desktop +DESKTOP_PROFILE='dwl' +FLATPAK='yes' + +# AI (credentials are provided separately, never here) +AI_ENABLED='no' +AI_PROVIDER='' +AI_MODEL='' diff --git a/installer/config/opencode.manifest b/installer/config/opencode.manifest new file mode 100644 index 0000000..130eff9 --- /dev/null +++ b/installer/config/opencode.manifest @@ -0,0 +1,23 @@ +# Pinned OpenCode release for the Phoebus OS installer. +# +# We deliberately do NOT use the vendor's curl|sh installer. The artifacts are +# fetched from the official GitHub release and verified against the SHA-256 +# digests below before anything is executed. +# +# Update procedure: +# 1. pick a release: https://github.com/anomalyco/opencode/releases +# 2. download the linux tarball for the architecture +# 3. sha256sum the tarball and update this file +# 4. test in a throwaway VM before shipping a new ISO + +VERSION=v1.18.31 + +# x86_64 (glibc) +x86_64.url=https://github.com/anomalyco/opencode/releases/download/v1.18.31/opencode-linux-x64.tar.gz +x86_64.sha256=e9312be75ed803b7415fc2aeabda1f4fe938912a39673762dc0c38c0e11ebde4 +x86_64.binary=opencode + +# aarch64 (glibc) +aarch64.url=https://github.com/anomalyco/opencode/releases/download/v1.18.31/opencode-linux-arm64.tar.gz +aarch64.sha256=0000000000000000000000000000000000000000000000000000000000000000 +aarch64.binary=opencode diff --git a/installer/doc/FINDINGS.md b/installer/doc/FINDINGS.md new file mode 100644 index 0000000..01012c8 --- /dev/null +++ b/installer/doc/FINDINGS.md @@ -0,0 +1,103 @@ +# Environment findings + +This document records what was actually found in the reference environment +before any installer code was written. Nothing here is assumed just because +"Gentoo usually has it". + +## Reference media + +- Repository: `/home/dominic/Source/phoebus_os` +- Reference image: `livegui-amd64-20260913T163055Z.iso` + - Volume label: `gentoo-amd64-livegui` + - 4.3 GiB ISO 9660 (El Torito, UEFI + BIOS bootable) +- Root filesystem: `image.squashfs` (4.1 GiB) inside the ISO +- Base system: `Gentoo Base System release 2.18` +- Reference profile: `default/linux/amd64/23.0/desktop/plasma` + (i.e. the LiveGUI is a **KDE Plasma / OpenRC** image) + +Inspection was done by extracting `image.squashfs` with `7z` and listing it +with `unsquashfs -l` (365,567 entries); individual config files were extracted +read-only. The host used for development is Ubuntu 26.04; the reference is used +strictly as read-only data. + +## Init system mismatch (important) + +The LiveGUI reference boots **OpenRC/sysvinit** (`/etc/inittab` present, no +`systemctl`, `/usr/lib/systemd/systemd-sysctl`/`systemd-udevd` come from +`sys-apps/systemd-utils`). Phoebus OS itself is **systemd-based**. + +Consequence: the installer runs on an OpenRC live medium but installs a +systemd target. Inside the target chroot, `systemctl` is available after the +stage3, and service enablement is performed there. The installer must not +assume the live environment can `systemctl`. + +## Tools found in the live environment + +Present (`usr/bin`, `usr/sbin`, `bin`, `sbin`): + +- Shell: `bash`, coreutils, `sed`, `awk`, `grep` +- TUI: **`dialog`** (and `whiptail`), `libdialog`, `libncurses`, `tput` +- Portage: `emerge`, `portageq`, `eselect`, `locale-gen` +- Disk: `lsblk`, `blkid`, `findmnt`, `parted`, `sgdisk`, `gdisk`, `fdisk`, + `sfdisk`, `wipefs`, `partprobe`, `udevadm`, `losetup`, `dmsetup` +- Filesystems: `mkfs.btrfs`, `btrfs`, `btrfsck`, `mkfs.fat`, `mkfs.ext4`, + `mkswap`, `swapon` +- Encryption: `cryptsetup`, `gocryptfs` +- Network: `NetworkManager`/`nmcli`/`nmtui`, `iw`, `wpa_supplicant`, `dhcpcd`, + `ip`, `ping`, `rfkill` +- Boot: `efibootmgr`, `grub-install`, `dracut`; `arch-chroot` +- Compiler/toolchain: `gcc`, `make`, `git`, `rsync`, `curl`, `wget`, `openssl`, + `gpg`, `sha256sum` +- Misc: `lspci`, `lsusb`, `lscpu`, `dmidecode`, `smartctl`, `tmux`, `vim` + +Absent / not available in the live environment: + +- `systemctl`, `bootctl`, `kernel-install`, `ukify`, `localectl`, + `timedatectl`, `hostnamectl`, `systemd-cryptenroll` +- `genkernel`, `jq` (so all parsing is done in pure bash) +- `opencode`, `node`, `npm`, `flatpak` + +## Portage configuration found + +- `/etc/portage/make.conf`: catalyst stage defaults, `COMMON_FLAGS="-O2 -pipe"`, + `LC_MESSAGES=C.UTF-8` +- `/etc/portage/make.profile` -> `.../desktop/plasma` +- `/etc/portage/binrepos.conf/gentoo.conf`: + `https://distfiles.gentoo.org/releases/amd64/binpackages/23.0/x86-64`, + `verify-signature = true` - confirms Gentoo binary packages are usable and + signed, which the package policy relies on +- `/etc/portage/package.license/package.license`: `*/* @BINARY-REDISTRIBUTABLE` +- Kernel package `sys-kernel/gentoo-kernel` with `experimental` USE flag in the + live image; `sys-fs/lvm2 thin` +- **No Portage tree is present** (`/var/db/repos` exists but is empty) + +Consequence: the installer must sync Portage and/or fetch a stage3 itself; it +cannot rely on a pre-populated tree in the live image. + +## Goop / prior installer scripts + +The reference image contains no Gentoo installer script that overlaps with what +we are building (only unrelated `*installer` binaries from KDE/rust). There was +nothing to reuse or avoid duplicating in-tree. + +## OpenCode + +OpenCode is **not** present in the live image. It is downloaded by the installer +from a pinned GitHub release (`anomalyco/opencode`, currently `v1.18.31`) and +verified by SHA-256 against `config/opencode.manifest` before use. The vendor +`curl | sh` installer is deliberately not used. (During development OpenCode +`v1.18.31` was fetched and hashed; the live image provides no Node.js, so the +standalone `opencode-linux-x64.tar.gz` binary is used.) + +## Design decisions driven by these findings + +1. **Bash + dialog**, not a heavier stack: both are present in the live image and + `dialog` gives a clean Void-style TUI with no extra dependencies. +2. **No `jq`**: all JSON-ish parsing (AI proposals) is implemented in pure bash. +3. **systemd target**: services are enabled inside the target chroot, not in the + live environment. +4. **Binhost enabled by default**: Gentoo signed binary packages are already + configured in the reference, so the balanced package policy can use them. +5. **Installer fetches its own stage3**: the live image has no Portage tree. +6. **systemd-boot + UKI are target-side operations** (`bootctl`, + `kernel-install`), performed after the stage3 is installed. diff --git a/installer/doc/TESTING.md b/installer/doc/TESTING.md new file mode 100644 index 0000000..521a3d4 --- /dev/null +++ b/installer/doc/TESTING.md @@ -0,0 +1,67 @@ +# Testing the installer safely + +Never test destructive paths on a real machine. There are three levels, from +cheapest to most realistic. + +## 1. Unit tests (no root, no disks) + +```sh +installer/tests/run_tests.sh +``` + +These cover configuration state, validation, plan generation, package policy, +OpenCode checksum verification, AI proposal parsing/whitelisting, the +destructive authorization gate, and the dry-run storage/sandbox behaviour. +They run on any Linux machine with Bash 4+; the development host has neither +`dialog` nor any Portage tooling, which is exactly the point. + +## 2. Dry-run + +```sh +installer/bin/ai-installer --dry-run --config my.conf +# or, without the TUI: +installer/bin/ai-installer --dry-run --config my.conf --plan +``` + +In dry-run mode: + +- `run_cmd` logs every command as `[dry-run]` and executes nothing; +- the target root becomes `$STATE_DIR/dry-run-root`, so even file generation + cannot touch the host; +- `install_preflight` still refuses incomplete or unsafe configurations. + +## 3. Full VM test (recommended before release) + +`tests/vm/run-vm.sh` boots the reference ISO with a **disposable** qcow2 disk: + +```sh +# defaults: 32 GiB disk, 4 GiB RAM, 4 CPUs, UEFI (OVMF) +installer/tests/vm/run-vm.sh --iso /path/to/livegui-amd64.iso + +# see all options +installer/tests/vm/run-vm.sh --help +``` + +Inside the VM: + +1. Boot the live medium and get a shell. +2. Copy or mount the `installer/` tree into the VM. +3. Run `bin/ai-installer`. +4. Select the virtio disk (`/dev/vda`) as the target. The ISO device is + protected and will not be offered. +5. Complete the review, type `ERASE`, and install. +6. Reboot the VM from the disk (`-boot c`) to verify UEFI boot, LUKS unlock and + the login. + +The script keeps the disk image in a working directory you choose, so a test +can be discarded by deleting that directory. It never touches host disks and +uses QEMU user-mode networking by default. + +## Additional checks + +- `bash -n` over every script is part of the unit suite (`test_syntax.sh`). +- `shellcheck` is optional and not required; several modules use constructs + that trip naive shellcheck rules, so treat its output as advisory. +- To exercise the backend without a VM, point `--config` at a file with + `TARGET_DISK` unset and use `--plan`; the safety tests already cover the + sandbox and authorization logic. diff --git a/installer/doc/VM-BOOT-VERIFICATION.md b/installer/doc/VM-BOOT-VERIFICATION.md new file mode 100644 index 0000000..93f2432 --- /dev/null +++ b/installer/doc/VM-BOOT-VERIFICATION.md @@ -0,0 +1,177 @@ +# Disposable UEFI VM boot verification + +This records the first successful end-to-end install and boot of Phoebus OS +against a disposable qcow2 disk. No physical disk was ever touched. + +## Exact tested path + +Host (Ubuntu, no root required): + +- QEMU `qemu-system-x86_64` (extracted locally under `/tmp/opencode/qemudeb`), + OVMF (`OVMF_CODE_4M.fd` + `OVMF_VARS_4M.fd`). +- Target disk: `/tmp/opencode/vm/work/target.qcow2`, 30 GiB, virtio-blk + (`/dev/vda` in the guest). +- Live boot: the reference ISO's own `boot/gentoo` + `boot/gentoo.igz`, with + `-append "root=live:CDLABEL=gentoo-amd64-livegui rd.live.dir=/ + rd.live.squashimg=image.squashfs cdroot console=ttyS0,115200"`. +- A host `python3 -m http.server` serves the installer tarball, the pinned + stage3 and the test config to the guest over QEMU user networking. + +Phase 1 (install): + +1. Boot the live ISO headless; get a root shell on the serial console. +2. Download the installer and test config from the host. +3. Write secrets to `0600` files and run: + `installer/bin/ai-installer --config test.conf --install --yes + --luks-passphrase-file FILE --user-password-file FILE` +4. Stages executed in order: `preflight, storage, stage3, fstab, + portage, base packages, kernel, bootloader, users, services, desktop, + finalize`. + +Phase 2 (boot the disk alone, ISO detached): + +5. Power off, then start a new QEMU with **no ISO and no `-kernel`**, boot + `order=c`, same OVMF NVRAM. +6. Firmware runs `\EFI\systemd\systemd-bootx64.efi`; systemd-boot boots the + "Gentoo Linux" BLS entry from the ESP. +7. `systemd-cryptsetup` prompts for the LUKS2 passphrase, unlocks + `/dev/vda2`, mounts the Btrfs `@` subvolume as `/`. +8. systemd (PID 1) starts, serial getty appears, user login succeeds. + +## Verified results + +- Firmware booted the disk's own systemd-boot (Boot000C "Linux Boot Manager"). +- LUKS2 passphrase prompt and successful unlock. +- Btrfs subvolumes mounted: `/`, `/home`, `/var`, `/.snapshots`, `/swap` + (later fix), ESP at `/efi`. +- `cat /proc/1/comm` -> `systemd`. +- `systemd-analyze`: 1.442s kernel + 5.755s initrd + 2.942s userspace. +- Login as `phoebus` with the configured password; groups: + `wheel audio video render input plugdev power network libinput`. +- Networking up (`enp0s2 10.0.2.15/24`). +- `systemctl --failed`: exactly one unit, `swap-swapfile.swap` (fixed after + this run; see below). + +## Bugs found and fixed during this work + +1. **Subvolumes created after mounting `@`** - `storage_prepare` mounted + `subvol=@` before `@` existed (mount exit 32). Added `btrfs_create_layout` + (mount top-level, create subvols, unmount, then mount layout) and a + regression test (`tests/test_btrfs_order.sh`). +2. **Generated fstab overwritten by stage3** - fstab/crypttab were generated + during storage, then the stage3 tarball replaced `/etc/fstab`. Moved + generation to a new `fstab_generate` stage after extraction. +3. **`/var/tmp` absent in the target** - systemd's `kernel-install` needs a + temporary directory; `/var/tmp` was missing. The fstab stage now creates + `/var/tmp`, `/tmp`, `/root`, `/home`, and chroot commands set + `TMPDIR=/tmp`. +4. **installkernel needs `uki_generator` even for BLS** - with an explicit + `/etc/kernel/install.conf`, `05-check-config.install` always requires a + `uki_generator`. BLS now writes `uki_generator=none`. +5. **dracut could not build the `crypt` module** - the target lacked + `sys-fs/cryptsetup`. Added `sys-fs/cryptsetup` and `sys-fs/btrfs-progs` to + the base package set. +6. **No `systemd-cryptsetup`** - `sys-apps/systemd` was built without the + `cryptsetup` USE flag, so the encrypted root could not be unlocked. Added + `cryptsetup` (and `policykit`) to the systemd package.use entry. +7. **Kernel command line used unnamed LUKS** - `rd.luks.uuid` yields + `luks-`, not the configured name. Switched to + `rd.luks.name==`. +8. **Dracut UKI did not embed the command line** - the dracut `uki_generator` + produced a UKI with no `.cmdline`, so it booted with no `root=`. Deferred + UKI in favour of a reliable BLS entry carrying `options`. UKI remains + future work. +9. **fstab did not mount `@swap`** - the swapfile unit failed because `/swap` + was never the `@swap` subvolume. Added the `subvol=@swap` fstab entry. +10. **`local root="$1" dir="$root/..."` class bug** - reintroduced in + `boot_write_dracut_conf`; split into two `local` statements. This class of + bug is now covered by the regression suite. +11. **Wrong package atoms** - `gui-apps/fuzzel` (not in Gentoo) -> `gui-apps/wofi`, + `app-misc/brightnessctl` (not packaged) removed, + `app-crypt/gnome-keyring` -> `gnome-base/gnome-keyring`, + `gui-apps/polkit-gnome` -> `gnome-extra/polkit-gnome`. +12. **Package policy compiled too much** - unknown packages defaulted to + source. `balanced` now compiles cheap builds and uses signed Gentoo + binaries for everything else, which cut installer time substantially. + +## Rust installer parity (same VM path) + +The Rust installer (`installer-rs`) reproduced the entire path on a fresh +disposable qcow2 disk using the static binary +`phoebus-installer` (`x86_64-unknown-linux-gnu`, crt-static): + +- Same config (legacy flat format), same pinned stage3 URL + SHA-256. +- `INSTALL_RC=0`; stages: storage, stage3, fstab, portage, base packages, + kernel, bootloader, users, services, desktop (none), finalize. +- Policy decisions matched Bash: `sudo`/`networkmanager`/`polkit` binary, + `cryptsetup`/`btrfs-progs` source. +- The installer recorded **81 then 97 measured compile times** from Portage's + `emerge.log` (real data, not estimates). +- `NO_SECRET_LEAK` from the log secret scan. + +Booted with the ISO detached: + +- UEFI firmware ran systemd-boot; BLS entry booted. +- LUKS2 unlock, Btrfs `@` root, `/home`, `/var`, `/swap`, ESP at `/efi`. +- `cat /proc/1/comm` -> `systemd`. +- `systemctl is-system-running` -> **running** (not degraded). +- `systemctl --failed` -> **0 loaded units listed**. +- `systemd-analyze`: 1.378s kernel + 5.238s initrd + 4.114s userspace = + 10.730s. +- Login as `phoebus` succeeded; networking up (`10.0.2.15/24`). + +This is the point at which the Rust installer satisfies the parity criteria and +may become the primary installer. The Bash implementation remains the +reference/fallback until the desktop milestone is also verified. + +## Desktop and Flatpak (Rust installer, verified) + +The Rust installer, running the desktop profile, installed the full Wayland +desktop and Flatpak successfully (`INSTALL_RC=0`; 326 measured compile times +recorded). Key change: a desktop install now selects the supported stable +Gentoo profile `default/linux/amd64/23.0/desktop/systemd` instead of +reconstructing X/Wayland/dbus USE by hand from the minimal systemd profile. +This resolved the earlier `cairo[X]`/`libglvnd[X]`/`libxkbcommon[X]` +conflicts, and `sys-fs/{btrfs-progs,cryptsetup} -man` avoided a +Sphinx/Pillow circular dependency. + +Booted with the ISO detached and logged in: + +- `systemctl is-system-running` -> `running`; `systemctl --failed` -> 0 units. +- `flatpak --version` -> **Flatpak 1.18.1**; `flatpak remotes` -> **flathub + configured**. +- Binaries present and runnable: `dwl 0.7`, `Waybar v0.15.0`, `wofi 1.4.1`, + `mako`, `swaybg`, `pipewire`, `wireplumber`, `grim`, `wl-clipboard`. + +Session verification. The VM's serial session has **no logind seat**, so +wlroots' DRM backend correctly refuses (`Failed to start a DRM session`). This +is a headless-harness limitation, not an installer defect. Using +`WLR_BACKENDS=headless WLR_RENDERER=pixman`: + +- `dwl` started (pid observed), created the `wayland-0` socket. +- `mako`, `waybar`, and `swaybg` started and connected (`swaybg` found output + `HEADLESS-1`). +- `wl-copy`/`wl-paste` round-tripped `phoebus-clip`. +- `grim /tmp/shot.png` produced a **14401-byte PNG**, proving the compositor + renders and captures. +- `wpctl status` reported the PipeWire graph; `systemctl --user --failed` -> 0. +- `waybar` logged a non-fatal warning about a missing power-menu file and + power-profiles-daemon. + +The installer writes `/usr/local/bin/phoebus-session`, which starts waybar, +mako and swaybg and then execs dwl, with a software-render fallback when no +render node is present. + +## Known remaining work + +- The graphical session was verified with the **headless** wlroots backend + (no logind seat in the serial harness). A physical VT / seat path is + architected (`phoebus-session`) but was not exercised on real hardware. +- NVIDIA proprietary support is architecturally allowed but **NOT VERIFIED**. +- UKI is deferred (BLS is used). +- The installer rebuilds `sys-apps/systemd` from source because + boot/policykit/cryptsetup USE differ from the binhost. Shipping a matching + systemd binpkg is a future optimization. +- Desktop USE still does not match the signed binhost, so the desktop + transaction compiles a large amount from source (~26 minutes for the desktop + package set on 8 vCPUs in the test VM). diff --git a/installer/lib/ai.sh b/installer/lib/ai.sh new file mode 100644 index 0000000..e245380 --- /dev/null +++ b/installer/lib/ai.sh @@ -0,0 +1,301 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# AI assistant integration. +# +# Design rule: the LLM NEVER manipulates disks and NEVER runs privileged +# commands. It may only produce a structured proposal (a flat JSON object). +# The deterministic backend validates every field, the change is previewed and +# the user must confirm. Most assistant features work with no LLM at all. +# +# Secrets (API keys, passphrases, passwords) are never passed to the model and +# never written to the installation log. + +# --------------------------------------------------------------------------- +# Deterministic (offline) assistance +# --------------------------------------------------------------------------- + +ai_explain_hardware() { + { + printf 'Detected hardware\n' + printf '=================\n\n' + hw_report + printf '\nRecommended kernel profile: %s\n' "$(hw_recommended_kernel_profile)" + printf 'Suggested VIDEO_CARDS: %s\n' "$(portage_detect_video_cards)" + } 2>&1 +} + +ai_explain_disks() { + { + printf 'Disk summary\n' + printf '============\n\n' + local d + for d in "${DISK_LIST[@]}"; do + printf '%s\n' "$(disk_display_line "$d")" + done + printf '\nReading (read-only):\n' + if [[ -n "$(config_get TARGET_DISK)" && -b "$(config_get TARGET_DISK)" ]]; then + disk_layout_text "$(config_get TARGET_DISK)" + else + printf ' no target disk selected yet\n' + fi + } 2>&1 +} + +ai_explain_plan() { + plan_generate + plan_render +} + +ai_explain_encryption() { + cat <<'EOF' +Encryption and filesystem choices +================================= + +LUKS2 (default) + The whole root partition is encrypted. Unlocking happens at boot with a + passphrase. TPM2 enrollment is planned but not required. + +Btrfs subvolumes + @ the root filesystem + @home /home, snapshotted independently + @var /var, kept separate so root snapshots stay small + @snapshots /.snapshots, where rollback snapshots live + @swap holds the swapfile + + Separate subvolumes let snapshots and rollbacks target only the parts of + the system you care about, and keep user data out of root snapshots. + +zstd compression + Transparent compression at level 3. A good balance of CPU and space. +EOF +} + +# ai_offline_response QUERY - small deterministic help based on keywords +ai_offline_response() { + local q + q="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')" + case "$q" in + *partition*|*disk*|*layout*) ai_explain_disks ;; + *encrypt*|*luks*|*btrfs*|*filesystem*) ai_explain_encryption ;; + *hardware*|*cpu*|*gpu*|*wifi*|*bluetooth*) ai_explain_hardware ;; + *kernel*) printf 'Kernel policy\n=============\n\nProfile: %s\nPackage: %s\n\n%s\n' \ + "$(config_get KERNEL_PROFILE)" "$(kernel_select_package)" \ + "The distribution kernel is used as a stable, complete base. The installer applies conservative config fragments; it never generates a minimal kernel that only boots the current hardware." ;; + *package*|*compile*|*binary*) pkgpolicy_report ;; + *plan*|*summary*) ai_explain_plan ;; + *log*|*error*|*fail*) log_tail 60 ;; + *network*|*internet*) network_status_text ;; + *desktop*|*wayland*|*dwl*) printf 'Desktop\n=======\nProfile: %s\n\nBase: dwl (Wayland tiling). Audio: PipeWire + Wireplumber.\nFlatpak: %s\n' \ + "$(config_get DESKTOP_PROFILE)" "$(config_get FLATPAK)" ;; + *) printf 'I can explain (offline, no model required):\n' + printf ' - hardware: detected CPU/GPU/storage/network\n' + printf ' - disks: devices and read-only layout\n' + printf ' - encryption: LUKS2 and Btrfs subvolumes\n' + printf ' - kernel: kernel policy\n' + printf ' - packages: compile vs binary policy\n' + printf ' - plan: the generated installation plan\n' + printf ' - logs: recent installer log lines\n' + printf '\nAsk about any of these, or configure a model for free-form help.\n' + ;; + esac +} + +# --------------------------------------------------------------------------- +# Structured proposals +# --------------------------------------------------------------------------- +# Only these keys may be changed by an AI proposal, and every value is +# validated by validation.sh before it is accepted. +AI_PROPOSAL_KEYS=(TARGET_DISK ENCRYPTION FILESYSTEM DESKTOP_PROFILE + PACKAGE_POLICY KERNEL_PROFILE HOSTNAME TIMEZONE LOCALE KEYMAP USERNAME) + +# ai_parse_json_kv TEXT - flatten a flat JSON object into key=value lines +ai_parse_json_kv() { + local text="$1" match + while IFS= read -r match; do + [[ -z "$match" ]] && continue + if [[ "$match" =~ ^\"([A-Za-z_][A-Za-z0-9_]*)\"[[:space:]]*:[[:space:]]*\"([^\"]*)\"$ ]]; then + printf '%s=%s\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" + elif [[ "$match" =~ ^\"([A-Za-z_][A-Za-z0-9_]*)\"[[:space:]]*:[[:space:]]*([0-9]+|true|false)$ ]]; then + printf '%s=%s\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" + fi + done < <(grep -oE '"[A-Za-z_][A-Za-z0-9_]*"[[:space:]]*:[[:space:]]*("[^"]*"|[0-9]+|true|false)' <<<"$text") +} + +ai_key_allowed() { + local key="$1" k + for k in "${AI_PROPOSAL_KEYS[@]}"; do + [[ "$k" == "$key" ]] && return 0 + done + return 1 +} + +# ai_validate_field KEY VALUE - non-empty error string when invalid +ai_validate_field() { + local key="$1" value="$2" + case "$key" in + TARGET_DISK) validate_target_disk "$value" ;; + ENCRYPTION) [[ "$value" =~ ^(none|luks2)$ ]] || printf 'encryption must be none or luks2\n' ;; + FILESYSTEM) [[ "$value" =~ ^(btrfs|ext4)$ ]] || printf 'filesystem must be btrfs or ext4\n' ;; + DESKTOP_PROFILE) [[ " $(desktop_profiles) " == *" $value "* ]] || printf 'unknown desktop profile\n' ;; + PACKAGE_POLICY) [[ "$value" =~ ^(source_first|balanced|binary_first)$ ]] || printf 'unknown package policy\n' ;; + KERNEL_PROFILE) [[ "$value" =~ ^(safe|optimized|aggressive)$ ]] || printf 'unknown kernel profile\n' ;; + HOSTNAME) validate_hostname "$value" ;; + TIMEZONE) validate_timezone "$value" ;; + LOCALE) validate_locale "$value" ;; + KEYMAP) validate_keymap "$value" ;; + USERNAME) validate_username "$value" ;; + *) printf 'key not permitted\n' ;; + esac +} + +# ai_apply_proposal TEXT - validate and apply; print accepted/rejected lines. +# Nothing is executed; only configuration state is changed. +ai_apply_proposal() { + local text="$1" line key value err accepted=0 rejected=0 + printf 'AI proposal review\n==================\n\n' + while IFS= read -r line; do + key="${line%%=*}"; value="${line#*=}" + key="${key^^}" + if ! ai_key_allowed "$key"; then + printf 'REJECTED %-16s %s (not a permitted setting)\n' "$key" "$value" + rejected=$((rejected+1)); continue + fi + err="$(ai_validate_field "$key" "$value")" + if [[ -n "$err" ]]; then + printf 'REJECTED %-16s %s (%s)\n' "$key" "$value" "${err%%$'\n'*}" + rejected=$((rejected+1)); continue + fi + printf 'ACCEPTED %-16s %s\n' "$key" "$value" + config_set "$key" "$value" + accepted=$((accepted+1)) + done < <(ai_parse_json_kv "$text") + printf '\n%d accepted, %d rejected.\n' "$accepted" "$rejected" + log_info "AI proposal applied: $accepted accepted, $rejected rejected" + ((rejected == 0)) +} + +# ai_propose_offline QUERY - deterministic translator for common requests +ai_propose_offline() { + local q + q="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')" + local json="{" + local sep="" + if [[ "$q" == *encrypt* || "$q" == *luks* ]]; then + json+="${sep}\"encryption\":\"luks2\""; sep="," + fi + if [[ "$q" == *btrfs* ]]; then + json+="${sep}\"filesystem\":\"btrfs\""; sep="," + fi + if [[ "$q" == *desktop* ]]; then + json+="${sep}\"desktop_profile\":\"dwl\""; sep="," + elif [[ "$q" == *minimal* ]]; then + json+="${sep}\"desktop_profile\":\"minimal\""; sep="," + fi + local disk + disk="$(printf '%s' "$q" | grep -oE '/dev/(nvme[0-9]+n[0-9]+|[sv]d[a-z])' | head -n1)" + if [[ -n "$disk" ]]; then + if disks_is_protected "$disk"; then + printf 'Offline assistant: %s looks protected, not proposing it.\n' "$disk" >&2 + else + json+="${sep}\"target_disk\":\"$disk\""; sep="," + fi + fi + json+="}" + printf '%s\n' "$json" +} + +# ai_propose_llm QUERY - ask OpenCode for a flat JSON proposal. +# The result is only ever fed to ai_apply_proposal, which validates everything. +ai_propose_llm() { + local query="$1" bin prompt out + bin="$(opencode_detect)" || { log_warn "OpenCode not available"; return 1; } + prompt="You are the Phoebus OS installer assistant. Reply with ONLY a flat JSON object of installer settings. Allowed keys: ${AI_PROPOSAL_KEYS[*]}. Allowed values: encryption=none|luks2, filesystem=btrfs|ext4, desktop_profile=none|minimal|dwl|full, package_policy=source_first|balanced|binary_first, kernel_profile=safe|optimized|aggressive. Do not include markdown, explanations, commands, shell code or secrets. User request: $query" + log_info "AI: requesting structured proposal from OpenCode" + out="$("$bin" run --pure "$prompt" 2>>"$PHOEBUS_LOG_FILE")" || { + log_error "OpenCode run failed"; return 1; } + printf '%s\n' "$out" +} + +# ai_propose_interactive - choose engine, then apply validated proposal +ai_propose_interactive() { + local query engine text + if declare -F ui_inputbox >/dev/null 2>&1; then + ui_inputbox "AI proposal" "Describe the installation you want (e.g. 'whole nvme, encrypt everything, desktop')." "" || return 1 + query="$UI_RESULT" + else + printf 'Describe the installation you want: ' >&2 + read -r query || return 1 + fi + [[ -n "$query" ]] || return 1 + + engine="offline" + if opencode_available && config_bool AI_ENABLED; then + if declare -F ui_menu >/dev/null 2>&1; then + ui_menu "AI proposal" "Which engine should translate the request?" 10 60 2 \ + offline "Deterministic rules (no model)" \ + model "OpenCode model (validated proposal)" || return 1 + engine="$UI_RESULT" + fi + fi + + if [[ "$engine" == "model" ]]; then + text="$(ai_propose_llm "$query")" || return 1 + else + text="$(ai_propose_offline "$query")" + fi + log_info "AI proposal text: $text" + ai_apply_proposal "$text" || log_warn "some proposed settings were rejected" + return 0 +} + +# ai_store_api_key KEY - store a provider key with restrictive permissions +ai_store_api_key() { + local key="$1" dir file + dir="${STATE_DIR:-/tmp/ai-installer}/ai" + file="$dir/credentials" + mkdir -p "$dir" + secret_register "$key" + umask 077 + printf '%s\n' "$key" >"$file" + chmod 0600 "$file" + log_info "API credential stored at $file (value not logged)" +} + +# ai_configure - provider/model setup; secrets never logged +ai_configure() { + local provider model endpoint key + if declare -F ui_inputbox >/dev/null 2>&1; then + ui_inputbox "AI configuration" "Provider (e.g. anthropic, openai, ollama):" "$(config_get AI_PROVIDER)" || return 1 + provider="$UI_RESULT" + ui_inputbox "AI configuration" "Model (e.g. claude-sonnet-4, gpt-5, llama3):" "$(config_get AI_MODEL)" || return 1 + model="$UI_RESULT" + ui_inputbox "AI configuration" "Custom endpoint / base URL (optional, for local models):" "$(config_get AI_ENDPOINT)" || return 1 + endpoint="$UI_RESULT" + config_set AI_PROVIDER "$provider" + config_set AI_MODEL "$model" + config_set AI_ENDPOINT "$endpoint" + config_set AI_ENABLED "yes" + opencode_write_config + + if declare -F ui_yesno >/dev/null 2>&1; then + if ui_yesno "AI credentials" "Store an API key now? It is saved with mode 0600 and never logged."; then + ui_passwordbox "AI credentials" "Paste API key (input hidden):" || return 0 + key="$UI_RESULT" + ai_store_api_key "$key" + fi + fi + else + printf 'AI configuration requires the TUI or a config file.\n' + fi + return 0 +} + +# ai_status_text +ai_status_text() { + printf 'AI assistant: %s\n' "$(config_bool AI_ENABLED && echo enabled || echo disabled)" + printf 'OpenCode: %s\n' "$(opencode_detect || echo 'not installed')" + printf 'Provider: %s\n' "$(config_get AI_PROVIDER)" + printf 'Model: %s\n' "$(config_get AI_MODEL)" + printf 'Endpoint: %s\n' "$(config_get AI_ENDPOINT)" +} diff --git a/installer/lib/boot.sh b/installer/lib/boot.sh new file mode 100644 index 0000000..184af05 --- /dev/null +++ b/installer/lib/boot.sh @@ -0,0 +1,150 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Bootloader installation (UEFI + systemd-boot, Unified Kernel Images). +# +# The ESP is mounted in the target at EFI_MOUNT. systemd-boot is installed and +# configured to boot UKIs produced by kernel-install. Secure Boot is scaffolded +# but not enforced in v0.1. + +boot_esp_path() { + printf '%s%s' "$1" "$(config_get EFI_MOUNT)" +} + +# boot_install ROOT - install systemd-boot into the ESP +boot_install() { + local root="$1" esp + esp="$(config_get EFI_MOUNT)" + portage_chroot "$root" bootctl --esp-path="$esp" install +} + +# boot_write_loader_conf ROOT +boot_write_loader_conf() { + local root="$1" esp dir + esp="$(boot_esp_path "$root")" + dir="$esp/loader" + mkdir -p "$dir" + { + printf '# systemd-boot configuration\n' + printf 'default *\n' + printf 'timeout %s\n' "3" + printf 'console-mode keep\n' + printf 'editor no\n' + } >"$dir/loader.conf" + log_info "wrote $dir/loader.conf" +} + +# boot_write_install_conf ROOT +# Configure Gentoo installkernel. v0.1 uses layout=bls (Boot Loader +# Specification): the kernel and dracut initramfs are placed on the ESP and +# systemd-boot entry files carry the kernel command line. The dracut UKI +# generator does not embed /etc/kernel/cmdline, which produced an unbootable +# image (no root=), so UKI is deferred until that path is verified. +boot_write_install_conf() { + local root="$1" dir + dir="$root/etc/kernel" + mkdir -p "$dir" + { + printf '# /etc/kernel/install.conf - Gentoo installkernel\n' + printf '# When /etc/kernel/install.conf exists it is used INSTEAD of the\n' + printf '# package default in /usr/lib/kernel/install.conf, so every required\n' + printf '# generator must be listed here.\n' + printf '# installkernel always requires uki_generator when dracut generates\n' + printf '# the initramfs; "none" disables UKI assembly for the BLS layout.\n' + printf 'layout=bls\n' + printf 'initrd_generator=dracut\n' + printf 'uki_generator=none\n' + } >"$dir/install.conf" + log_info "wrote $dir/install.conf (layout=bls)" +} + +# boot_write_dracut_conf ROOT +# A generic initramfs with the storage/crypto modules forced in. This keeps +# the encrypted Btrfs root unlockable and survives kernel updates. +boot_write_dracut_conf() { + local root="$1" + local dir="$root/etc/dracut.conf.d" + mkdir -p "$dir" + { + printf '# %s dracut configuration\n' "$(config_get DISTRO_NAME)" + printf '# Generic (non-hostonly) initramfs for predictable boot behaviour.\n' + printf 'hostonly="no"\n' + printf 'compress="zstd"\n' + printf 'add_dracutmodules+=" crypt btrfs "\n' + } >"$dir/10-phoebus.conf" + log_info "wrote $dir/10-phoebus.conf" +} + +# boot_generate_uki ROOT - trigger kernel-install for every installed kernel +boot_generate_uki() { + local root="$1" + portage_chroot "$root" kernel-install add-all +} + +# boot_install_fallback ROOT - ensure the default EFI fallback path works even +# when writing the UEFI boot variable failed. +boot_install_fallback() { + local root="$1" esp src + esp="$(boot_esp_path "$root")" + mkdir -p "$esp/EFI/BOOT" "$esp/EFI/systemd" + src="$esp/EFI/systemd/systemd-bootx64.efi" + if [[ ! -e "$src" ]]; then + # Boot loader provided by sys-apps/systemd[boot] inside the target. + local vendor="$root/usr/lib/systemd/boot/efi/systemd-bootx64.efi" + if [[ -e "$vendor" ]]; then + src="$vendor" + else + log_warn "systemd-boot binary not found; EFI fallback not installed" + return 1 + fi + fi + run_cmd "install fallback bootloader" cp -f "$src" "$esp/EFI/BOOT/BOOTX64.EFI" +} + +# boot_random_seed ROOT - enable systemd random seed persistence +boot_random_seed() { + local root="$1" esp + esp="$(boot_esp_path "$root")" + mkdir -p "$esp/loader" + if [[ ! -e "$esp/loader/random-seed" ]]; then + run_cmd "create random seed" \ + dd if=/dev/urandom of="$esp/loader/random-seed" bs=512 count=1 status=none + fi +} + +# boot_verify ROOT - confirm bootloader artifacts exist +boot_verify() { + local root="$1" esp + esp="$(boot_esp_path "$root")" + if [[ ! -e "$esp/EFI/systemd/systemd-bootx64.efi" && \ + ! -e "$esp/EFI/BOOT/BOOTX64.EFI" ]]; then + log_error "no systemd-boot loader found in $esp" + return 1 + fi + [[ -e "$esp/loader/loader.conf" ]] || { + log_error "loader.conf not found"; return 1; } + return 0 +} + +# boot_secureboot_status - report, never change firmware state +boot_secureboot_status() { + if [[ -d /sys/firmware/efi/efivars ]]; then + if command -v mokutil >/dev/null 2>&1; then + mokutil --sb-state 2>/dev/null || printf 'unknown' + else + printf 'Secure Boot state unknown (mokutil not installed)' + fi + else + printf 'not booted in UEFI mode' + fi +} + +# boot_secureboot_scaffold ROOT - placeholders for future enrollment +boot_secureboot_scaffold() { + local root="$1" + mkdir -p "$root/etc/secureboot" + { + printf '# Secure Boot is not enabled by this version of the installer.\n' + printf '# Future: sbctl / systemd-sbsign key enrollment and UKI signing.\n' + } >"$root/etc/secureboot/README" +} diff --git a/installer/lib/btrfs.sh b/installer/lib/btrfs.sh new file mode 100644 index 0000000..0511e4a --- /dev/null +++ b/installer/lib/btrfs.sh @@ -0,0 +1,109 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Btrfs layout backend. +# +# Default layout (see config/defaults.conf): +# @ / root +# @home /home +# @var /var +# @snapshots /.snapshots +# @swap /swap holds the swapfile +# +# Top-level (subvolid=5) is only mounted temporarily to create subvolumes. + +btrfs_require_tools() { + require_cmd btrfs mkfs.btrfs || return 1 +} + +btrfs_mount_opts() { + local opts + opts="noatime,compress=$(config_get COMPRESS),space_cache=v2" + if [[ "$(disk_transport "$(config_get TARGET_DISK)")" == "nvme" || \ + "$(disk_transport "$(config_get TARGET_DISK)")" == "sata" ]]; then + opts+=",ssd" + fi + printf '%s' "$opts" +} + +# btrfs_mkfs DEVICE +btrfs_mkfs() { + local dev="$1" label + label="$(config_get BTRFS_LABEL)" + run_destructive "create Btrfs filesystem on $dev" \ + mkfs.btrfs -f -L "$label" "$dev" +} + +# btrfs_mount_top DEVICE MOUNTPOINT +btrfs_mount_top() { + local dev="$1" mp="$2" + mkdir -p "$mp" + run_cmd "mount Btrfs top-level" mount -o "subvolid=5" "$dev" "$mp" +} + +# btrfs_create_subvolumes MOUNTPOINT +btrfs_create_subvolumes() { + local mp="$1" sv + for sv in $(config_get BTRFS_SUBVOLS); do + run_destructive "create subvolume $sv" btrfs subvolume create "$mp/$sv" || return 1 + done +} + +# btrfs_set_default MOUNTPOINT - make @ the default subvolume +btrfs_set_default() { + local mp="$1" id + id="$(btrfs subvolume list -o "$mp" 2>/dev/null | awk '$NF=="@"{print $2; exit}')" + [[ -n "$id" ]] || return 0 + run_cmd "set @ as default subvolume" btrfs subvolume set-default "$id" "$mp" +} + +# btrfs_mount_layout DEVICE ROOT +btrfs_mount_layout() { + local dev="$1" root="$2" opts + opts="$(btrfs_mount_opts)" + mkdir -p "$root" + run_cmd "mount @ at $root" mount -o "${opts},subvol=@" "$dev" "$root" || return 1 + local pair sv target + for pair in "@home:home" "@var:var" "@snapshots:.snapshots" "@swap:swap"; do + sv="${pair%%:*}"; target="${pair##*:}" + mkdir -p "$root/$target" + run_cmd "mount $sv at /$target" mount -o "${opts},subvol=$sv" "$dev" "$root/$target" || return 1 + done +} + +# btrfs_create_layout DEVICE ROOT +# Create the subvolume layout on a freshly created filesystem, then mount it. +# The top-level (subvolid=5) must be mounted to create @, @home, ...; only +# afterwards can the individual subvolumes be mounted. +btrfs_create_layout() { + local dev="$1" root="$2" + btrfs_mount_top "$dev" "$root" || return 1 + if ! btrfs_create_subvolumes "$root"; then + run_cmd "unmount top-level" umount "$root" || true + return 1 + fi + btrfs_set_default "$root" || true + run_cmd "unmount top-level" umount "$root" || return 1 + btrfs_mount_layout "$dev" "$root" +} + +# btrfs_create_swapfile ROOT [MIB] +btrfs_create_swapfile() { + local root="$1" mib="${2:-$(plan_swap_mib)}" + local swapdir="$root/swap" + mkdir -p "$swapdir" + if btrfs filesystem mkswapfile --help >/dev/null 2>&1; then + run_cmd "create Btrfs swapfile" \ + btrfs filesystem mkswapfile --size "${mib}m" "$swapdir/swapfile" + else + run_cmd "create swapfile container" \ + truncate -s "${mib}M" "$swapdir/swapfile" || return 1 + run_cmd "disable CoW on swapfile" chattr +C "$swapdir/swapfile" + run_cmd "make swap" mkswap "$swapdir/swapfile" + fi +} + +# btrfs_scrub_device DEVICE - verify checksums (non-destructive) +btrfs_scrub_device() { + run_cmd "scrub $1" btrfs scrub start -B "$1" +} diff --git a/installer/lib/confirm.sh b/installer/lib/confirm.sh new file mode 100644 index 0000000..d76fa50 --- /dev/null +++ b/installer/lib/confirm.sh @@ -0,0 +1,93 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Destructive-operation confirmation infrastructure. +# +# There are two independent gates: +# +# 1. PHOEBUS_DESTRUCTIVE_AUTHORIZED must be "yes" before run_destructive will +# execute anything. Only install.sh sets it, and only after the user has +# approved the generated plan. +# 2. Whole-disk erase additionally requires the user to type the word ERASE. +# +# This means a bug in the TUI cannot silently wipe a disk: every destructive +# command goes through run_destructive. + +declare -g PHOEBUS_DESTRUCTIVE_AUTHORIZED="${PHOEBUS_DESTRUCTIVE_AUTHORIZED:-no}" + +destructive_authorized() { [[ "$PHOEBUS_DESTRUCTIVE_AUTHORIZED" == "yes" ]]; } + +# destructive_grant / destructive_revoke +destructive_grant() { PHOEBUS_DESTRUCTIVE_AUTHORIZED="yes"; log_warn "destructive operations AUTHORIZED for this session"; } +destructive_revoke() { PHOEBUS_DESTRUCTIVE_AUTHORIZED="no"; log_info "destructive operations revoked"; } + +# _prompt_yesno MESSAGE - returns 0 for yes +_prompt_yesno() { + local message="$1" + if declare -F ui_yesno >/dev/null 2>&1; then + ui_yesno "Confirm" "$message" + return $? + fi + local answer + printf '%s [y/N] ' "$message" >&2 + read -r answer || return 1 + [[ "$answer" =~ ^[Yy] ]] +} + +# _prompt_word PROMPT EXPECTED - returns 0 when the typed word matches +_prompt_word() { + local prompt="$1" expected="$2" answer + if declare -F ui_inputbox >/dev/null 2>&1; then + ui_inputbox "Destructive operation" "$prompt" "" || return 1 + answer="$UI_RESULT" + else + printf '%s ' "$prompt" >&2 + read -r answer || return 1 + fi + [[ "$answer" == "$expected" ]] +} + +# confirm_action MESSAGE - plain yes/no confirmation +confirm_action() { + if config_bool ASSUME_YES; then + log_warn "auto-approving (ASSUME_YES): $1" + return 0 + fi + _prompt_yesno "$1" +} + +# confirm_erase PREVIEW - strong confirmation for whole-disk destruction. +# Displays PREVIEW and requires the user to type ERASE. +confirm_erase() { + local preview="$1" + if config_bool ASSUME_YES; then + log_warn "auto-approving ERASE confirmation (ASSUME_YES)" + return 0 + fi + if declare -F ui_msgbox >/dev/null 2>&1; then + ui_msgbox "DESTRUCTIVE OPERATION" "$preview + +Type ERASE to continue." + else + printf '%s\n\n' "$preview" >&2 + fi + _prompt_word "Type ERASE to confirm:" "ERASE" +} + +# require_destructive_authorization CALLER - hard gate used by run_destructive +require_destructive_authorization() { + if ! destructive_authorized; then + log_error "blocked destructive operation from ${1:-unknown}: not authorized" + return 1 + fi + return 0 +} + +# run_destructive DESCRIPTION ARGS... +# Execute a previously approved destructive command. Honours DRY_RUN via +# run_cmd. Refuses to run without authorization. +run_destructive() { + local desc="${1:-destructive operation}"; shift + require_destructive_authorization "$desc" || return 1 + run_cmd "$desc" "$@" +} diff --git a/installer/lib/desktop.sh b/installer/lib/desktop.sh new file mode 100644 index 0000000..cd9d402 --- /dev/null +++ b/installer/lib/desktop.sh @@ -0,0 +1,93 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Desktop profile installation. +# +# The flagship desktop is a small Wayland tiling environment centred on dwl. +# Full desktop installation is future work; this module defines the profile and +# the package sets so the installer can grow into it cleanly. + +desktop_profiles() { + printf '%s\n' none minimal dwl full +} + +# desktop_packages PROFILE +desktop_packages() { + local profile="$1" + case "$profile" in + none) + ;; + minimal) + printf '%s\n' \ + gui-libs/wayland \ + gui-libs/wayland-protocols \ + x11-base/xwayland + ;; + dwl|full) + printf '%s\n' \ + gui-wm/dwl \ + gui-apps/waybar \ + gui-apps/wofi \ + gui-apps/mako \ + gui-apps/swayidle \ + gui-apps/swaylock \ + gui-apps/swaybg \ + gui-apps/wl-clipboard \ + gui-apps/grim \ + gui-apps/slurp \ + gui-libs/gtk-layer-shell \ + x11-base/xwayland \ + x11-terms/kitty \ + net-misc/networkmanager \ + sys-auth/polkit \ + gnome-extra/polkit-gnome + ;; + esac + if [[ "$profile" == "full" ]]; then + printf '%s\n' \ + sys-apps/flatpak \ + net-wireless/bluez \ + gnome-base/gnome-keyring + fi +} + +# desktop_audio_packages - PipeWire is always the audio stack +desktop_audio_packages() { + printf '%s\n' media-video/pipewire media-video/wireplumber +} + +# desktop_install ROOT +desktop_install() { + local root="$1" profile + profile="$(config_get DESKTOP_PROFILE)" + [[ "$profile" == "none" ]] && { log_info "no desktop profile selected"; return 0; } + + local -a packages=() + mapfile -t packages < <(desktop_packages "$profile") + mapfile -t -O "${#packages[@]}" packages < <(desktop_audio_packages) + if config_bool FLATPAK; then + packages+=(sys-apps/flatpak) + fi + log_info "installing desktop profile '$profile' (${#packages[@]} packages)" + portage_emerge "$root" "${packages[@]}" +} + +# desktop_configure_flatpak ROOT +desktop_configure_flatpak() { + local root="$1" + config_bool FLATPAK || return 0 + # Flathub is a third-party catalogue; adding it is opt-in via the profile. + portage_chroot "$root" flatpak remote-add --if-not-exists flathub \ + https://flathub.org/repo/flathub.flatpakrepo || { + log_warn "could not add flathub remote (network?)"; return 0; } + log_info "flatpak configured with flathub" +} + +# desktop_services ROOT - system services needed by the desktop +desktop_services() { + local profile + profile="$(config_get DESKTOP_PROFILE)" + printf '%s\n' NetworkManager systemd-resolved + [[ "$profile" == "full" ]] && printf '%s\n' bluetooth + return 0 +} diff --git a/installer/lib/disks.sh b/installer/lib/disks.sh new file mode 100644 index 0000000..7c59e0e --- /dev/null +++ b/installer/lib/disks.sh @@ -0,0 +1,177 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Read-only disk and partition discovery. +# +# This module never writes to a disk. It exists so the installer can present +# accurate information and so destructive operations can refuse to touch the +# live medium, mounted filesystems or optical drives. + +declare -ga DISK_LIST=() + +# disks_available_tool +disks_tool_ok() { command -v lsblk >/dev/null 2>&1; } + +# disks_refresh - populate DISK_LIST with whole-disk device paths +disks_refresh() { + DISK_LIST=() + disks_tool_ok || return 1 + local name path + while IFS= read -r name; do + path="/dev/$name" + [[ -b "$path" ]] && DISK_LIST+=("$path") + done < <(lsblk -dn -o NAME 2>/dev/null | sort) + ((${#DISK_LIST[@]})) +} + +# _disk_attr PATH COLUMN - single value for a whole disk +_disk_attr() { + local path="$1" col="$2" + lsblk -dn -o "$col" "$path" 2>/dev/null | head -n1 | sed 's/[[:space:]]*$//' +} + +disk_size_bytes() { + lsblk -bdn -o SIZE "$1" 2>/dev/null | head -n1 | tr -d ' ' +} +disk_size_human() { + local b="${1:-0}" + numfmt --to=iec --suffix=B "$b" 2>/dev/null || printf '%s bytes' "$b" +} +disk_model() { _disk_attr "$1" MODEL; } +disk_transport() { _disk_attr "$1" TRAN; } +disk_is_removable() { [[ "$(_disk_attr "$1" RM)" == "1" ]]; } +disk_is_readonly() { [[ "$(_disk_attr "$1" RO)" == "1" ]]; } + +# disk_partitions PATH - print child device paths one per line +disk_partitions() { + local path="$1" name + while IFS= read -r name; do + [[ -n "$name" ]] && printf '/dev/%s\n' "$name" + done < <(lsblk -rno NAME "$path" 2>/dev/null | tail -n +2) +} + +disk_partition_count() { + disk_partitions "$1" | grep -c . || true +} + +# disk_is_mounted PATH - true when the disk or any child is mounted +disk_is_mounted() { + local path="$1" dev + while IFS= read -r dev; do + [[ -n "$dev" ]] || continue + if grep -q "^${dev} " /proc/mounts 2>/dev/null; then + return 0 + fi + done < <(printf '%s\n' "$path"; disk_partitions "$path") + return 1 +} + +# _parent_disk DEV - resolve a device (possibly a partition) to its whole disk +_parent_disk() { + local dev="$1" pk + dev="$(readlink -f "$dev" 2>/dev/null || printf '%s' "$dev")" + case "$dev" in + /dev/loop*|/dev/dm-*|/dev/mapper/*|/dev/sr*) printf '%s' "$dev"; return ;; + esac + pk="$(lsblk -no PKNAME "$dev" 2>/dev/null | head -n1)" + if [[ -n "$pk" ]]; then printf '/dev/%s' "$pk"; else printf '%s' "$dev"; fi +} + +# _live_source_disks - whole disks that back the running live system +_live_source_disks() { + local src disk + local -a sources=() + # Sources directly referenced by the kernel command line. + if [[ -r /proc/cmdline ]]; then + while IFS= read -r tok; do + case "$tok" in + root=*|cdroot=*|boot=*) sources+=("${tok#*=}") ;; + esac + done < <(tr ' ' '\n' /dev/null)" + [[ -n "$src" ]] && sources+=("$src") + done + fi + local seen="" + for src in "${sources[@]}"; do + [[ -b "$src" ]] || continue + disk="$(_parent_disk "$src")" + case "$seen" in *" $disk "*) continue ;; esac + seen+=" $disk " + printf '%s\n' "$disk" + done +} + +# disk_protected_reason PATH - non-empty when the disk must not be a target +disk_protected_reason() { + local path="$1" live + if disk_is_readonly "$path"; then + printf 'read-only device' + return + fi + case "$path" in + /dev/sr*|/dev/loop*|/dev/dm-*|/dev/mapper/*) + printf 'not a whole disk' + return ;; + esac + if disk_is_mounted "$path"; then + printf 'contains mounted filesystems' + return + fi + while IFS= read -r live; do + if [[ "$live" == "$path" ]]; then + printf 'live installation medium' + return + fi + done < <(_live_source_disks) +} + +# disks_is_protected PATH +disks_is_protected() { [[ -n "$(disk_protected_reason "$1")" ]]; } + +# disks_candidates - device paths that may be chosen as installation target +disks_candidates() { + local d + for d in "${DISK_LIST[@]}"; do + disks_is_protected "$d" || printf '%s\n' "$d" + done +} + +# disk_display_line PATH - one line description for menus +disk_display_line() { + local path="$1" size model tran flag="" reason + size="$(disk_size_human "$(disk_size_bytes "$path")")" + model="$(disk_model "$path")" + tran="$(disk_transport "$path")" + reason="$(disk_protected_reason "$path")" + if [[ -n "$reason" ]]; then + flag=" [PROTECTED: $reason]" + fi + printf '%-16s %8s %-8s %s%s' "$path" "$size" "${tran:-?}" "${model:-disk}" "$flag" +} + +# disk_partition_table PATH - GPT/MBR/unknown via parted (read-only) +disk_partition_table() { + command -v parted >/dev/null 2>&1 || { printf 'unknown'; return; } + local out + out="$(parted -s "$1" print 2>/dev/null | awk -F': ' '/Partition Table/{print $2; exit}')" + printf '%s' "${out:-unknown}" +} + +# disk_free_space_bytes PATH - unpartitioned space, best effort +disk_free_space_bytes() { + command -v parted >/dev/null 2>&1 || return 1 + parted -s -m "$1" unit B print free 2>/dev/null | \ + awk -F: '$5=="free"{sum+=$4} END{printf "%d", sum}' +} + +# disk_layout_text PATH - read-only partition listing +disk_layout_text() { + local path="$1" + lsblk -o NAME,SIZE,TYPE,FSTYPE,LABEL,MOUNTPOINTS "$path" 2>/dev/null +} diff --git a/installer/lib/encryption.sh b/installer/lib/encryption.sh new file mode 100644 index 0000000..eedbc87 --- /dev/null +++ b/installer/lib/encryption.sh @@ -0,0 +1,109 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# LUKS2 encryption backend. +# +# Passphrases are held in memory only (LUKS_PASSPHRASE), never written to the +# config, never passed on a command line and never logged. cryptsetup reads the +# passphrase from stdin via --key-file -. +# +# TPM2 enrollment is intentionally not implemented in v0.1; the function +# stubs document where it will hook in. + +declare -g LUKS_PASSPHRASE="${LUKS_PASSPHRASE:-}" + +encryption_require_tools() { + require_cmd cryptsetup blkid || return 1 +} + +# encryption_configure - prompt for and remember the passphrase (TUI or tty) +encryption_configure() { + local first second + if declare -F ui_passwordbox >/dev/null 2>&1; then + ui_passwordbox "Encryption passphrase" "Enter a LUKS2 passphrase for the root volume:" || return 1 + first="$UI_RESULT" + ui_passwordbox "Encryption passphrase" "Repeat the passphrase:" || return 1 + second="$UI_RESULT" + else + read -r -s -p "LUKS passphrase: " first; printf '\n' >&2 + read -r -s -p "Repeat: " second; printf '\n' >&2 + fi + if [[ -z "$first" ]]; then + log_error "empty encryption passphrase refused" + return 1 + fi + if [[ "$first" != "$second" ]]; then + log_error "passphrases did not match" + return 1 + fi + LUKS_PASSPHRASE="$first" + secret_register "$first" + log_info "encryption passphrase set (value not logged)" + return 0 +} + +# _run_cryptsetup_stdin DESCRIPTION COMMAND... - feeds LUKS_PASSPHRASE on stdin +_run_cryptsetup_stdin() { + local desc="$1"; shift + if config_bool DRY_RUN; then + log_line INFO "[dry-run] $desc :: $(_cmd_to_string "$@")" + return 0 + fi + log_line INFO "$desc :: $(_cmd_to_string "$@")" + printf '%s' "$LUKS_PASSPHRASE" | "$@" >>"$PHOEBUS_LOG_FILE" 2>&1 + local status=$? + log_line INFO "$desc :: exit status $status" + return $status +} + +# encryption_format PARTITION +encryption_format() { + local part="$1" cipher keysize pbkdf + cipher="$(config_get LUKS_CIPHER)" + keysize="$(config_get LUKS_KEY_SIZE)" + pbkdf="$(config_get LUKS_PBKDF)" + [[ -n "$LUKS_PASSPHRASE" ]] || { log_error "no passphrase configured"; return 1; } + _run_cryptsetup_stdin "format LUKS2 on $part" \ + cryptsetup luksFormat --batch-mode --type luks2 \ + --cipher "$cipher" --key-size "$keysize" --pbkdf "$pbkdf" \ + --key-file - "$part" +} + +# encryption_open PARTITION NAME +encryption_open() { + local part="$1" name="${2:-$(config_get LUKS_NAME)}" + [[ -n "$LUKS_PASSPHRASE" ]] || { log_error "no passphrase configured"; return 1; } + _run_cryptsetup_stdin "open LUKS2 $part as $name" \ + cryptsetup open --type luks --key-file - "$part" "$name" +} + +# encryption_close NAME +encryption_close() { + local name="${1:-$(config_get LUKS_NAME)}" + run_destructive "close LUKS device $name" cryptsetup close "$name" +} + +# encryption_mapper_path NAME +encryption_mapper_path() { + printf '/dev/mapper/%s' "${1:-$(config_get LUKS_NAME)}" +} + +# encryption_crypttab_line PARTITION [NAME] +# Produces a crypttab line using the partition UUID (stable across reboots). +encryption_crypttab_line() { + local part="$1" name="${2:-$(config_get LUKS_NAME)}" uuid + uuid="$(blkid -s UUID -o value "$part" 2>/dev/null)" + [[ -n "$uuid" ]] || return 1 + printf '%s UUID=%s none luks,discard\n' "$name" "$uuid" +} + +# encryption_tpm2_enroll - future work; never made mandatory +encryption_tpm2_enroll() { + log_warn "TPM2 enrollment is not implemented in this version" + return 1 +} + +# encryption_tpm2_available - best-effort capability probe +encryption_tpm2_available() { + [[ -e /sys/class/tpm/tpm0 ]] && command -v systemd-cryptenroll >/dev/null 2>&1 +} diff --git a/installer/lib/filesystem.sh b/installer/lib/filesystem.sh new file mode 100644 index 0000000..e506cf2 --- /dev/null +++ b/installer/lib/filesystem.sh @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Filesystem creation, mounting and fstab/crypttab generation. +# +# fstab is generated deterministically from the plan rather than scraping the +# live system, so no host state leaks into the installed system. + +declare -g FS_ROOT_SOURCE="" +declare -g FS_EFI_PART="" +declare -g FS_ROOT_PART="" + +filesystem_require_tools() { + require_cmd mkfs.fat mount umount blkid || return 1 +} + +# filesystem_mkfs_efi PARTITION +filesystem_mkfs_efi() { + local part="$1" + run_destructive "create FAT32 EFI filesystem on $part" \ + mkfs.fat -F32 -n EFI "$part" +} + +# filesystem_mount_efi PARTITION ROOT +filesystem_mount_efi() { + local part="$1" root="$2" mp + mp="$(config_get EFI_MOUNT)" + mkdir -p "$root$mp" + run_cmd "mount EFI" mount "$part" "$root$mp" +} + +# filesystem_prepare_root DISK +# Create the root filesystem, applying encryption when configured. +# Sets FS_ROOT_SOURCE to the device that carries the Btrfs filesystem. +filesystem_prepare_root() { + local disk="$1" part="$2" + FS_ROOT_PART="$part" + if [[ "$(config_get ENCRYPTION)" == "none" ]]; then + btrfs_mkfs "$part" || return 1 + FS_ROOT_SOURCE="$part" + else + encryption_format "$part" || return 1 + encryption_open "$part" "$(config_get LUKS_NAME)" || return 1 + local mapper + mapper="$(encryption_mapper_path)" + btrfs_mkfs "$mapper" || return 1 + FS_ROOT_SOURCE="$mapper" + fi + log_info "root filesystem source: $FS_ROOT_SOURCE" +} + +# filesystem_mount_root ROOT +filesystem_mount_root() { + local root="$1" + btrfs_mount_layout "$FS_ROOT_SOURCE" "$root" +} + +# filesystem_source_ref - stable reference for fstab (UUID when unencrypted) +filesystem_source_ref() { + if [[ "$FS_ROOT_SOURCE" == /dev/mapper/* ]]; then + printf '%s' "$FS_ROOT_SOURCE" + else + local uuid + uuid="$(blkid -s UUID -o value "$FS_ROOT_SOURCE" 2>/dev/null)" + if [[ -n "$uuid" ]]; then printf 'UUID=%s' "$uuid"; else printf '%s' "$FS_ROOT_SOURCE"; fi + fi +} + +# filesystem_generate_fstab ROOT +filesystem_generate_fstab() { + local root="$1" + local fstab="$root/etc/fstab" + local opts src + src="$(filesystem_source_ref)" + opts="$(btrfs_mount_opts)" + mkdir -p "$root/etc" + + { + printf '# /etc/fstab: %s\n' "$(config_get DISTRO_NAME)" + printf '# Generated by the installer. Use `findmnt --verify` to check.\n' + printf '#\n' + printf '# \t\t\t\t\t\n' + local efi_uuid + efi_uuid="$(blkid -s UUID -o value "$FS_EFI_PART" 2>/dev/null)" + if [[ -n "$efi_uuid" ]]; then + printf 'UUID=%s\t%s\tvfat\tumask=0077,shortname=winnt\t0\t2\n' "$efi_uuid" "$(config_get EFI_MOUNT)" + fi + printf '%s\t/\tbtrfs\t%s,subvol=@\t0\t1\n' "$src" "$opts" + printf '%s\t/home\tbtrfs\t%s,subvol=@home\t0\t2\n' "$src" "$opts" + printf '%s\t/var\tbtrfs\t%s,subvol=@var\t0\t2\n' "$src" "$opts" + printf '%s\t/.snapshots\tbtrfs\t%s,subvol=@snapshots\t0\t2\n' "$src" "$opts" + printf '%s\t/swap\tbtrfs\t%s,subvol=@swap\t0\t2\n' "$src" "$opts" + printf '/swap/swapfile\tnone\tswap\tdefaults\t0\t0\n' + } >"$fstab" + log_info "wrote $fstab" +} + +# filesystem_generate_crypttab ROOT +filesystem_generate_crypttab() { + local root="$1" + local crypttab="$root/etc/crypttab" + local line + [[ "$(config_get ENCRYPTION)" == "none" ]] && return 0 + line="$(encryption_crypttab_line "$FS_ROOT_PART" "$(config_get LUKS_NAME)")" || { + log_error "could not determine LUKS UUID for crypttab" + return 1 + } + mkdir -p "$root/etc" + { + printf '# /etc/crypttab: unlock the root volume at boot.\n' + printf '# \t\t\t\n' + printf '%s\n' "$line" + } >"$crypttab" + log_info "wrote $crypttab" +} + +# filesystem_verify ROOT - basic post-mount checks +filesystem_verify() { + local root="$1" + [[ -d "$root/etc" ]] || { log_error "$root/etc missing"; return 1; } + findmnt -n "$root" >/dev/null 2>&1 || { log_error "$root is not a mountpoint"; return 1; } + return 0 +} + +# filesystem_unmount_all ROOT - best effort teardown (used on rollback) +filesystem_unmount_all() { + local root="$1" + # Unmount children first, the root last. + local -a mounts=("$(config_get EFI_MOUNT)" "/.snapshots" "/var" "/home" "/swap" "") + local m + for m in "${mounts[@]}"; do + run_cmd "unmount $root$m" umount -R "$root$m" 2>/dev/null || true + done +} diff --git a/installer/lib/hardware.sh b/installer/lib/hardware.sh new file mode 100644 index 0000000..7cb73d1 --- /dev/null +++ b/installer/lib/hardware.sh @@ -0,0 +1,128 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Read-only hardware probing. +# +# Nothing in this file modifies the system: it only reads /proc, /sys and the +# output of read-only inventory tools. Results feed the installation plan and +# the kernel/profile decisions. + +hw_cpu_vendor() { + awk -F': ' '/^vendor_id/{print $2; exit}' /proc/cpuinfo 2>/dev/null +} + +hw_cpu_model() { + awk -F': ' '/^model name/{print $2; exit}' /proc/cpuinfo 2>/dev/null +} + +hw_cpu_cores() { + local n + n="$(nproc --all 2>/dev/null || echo 1)" + printf '%s' "$n" +} + +hw_cpu_threads() { + local n + n="$(grep -c '^processor' /proc/cpuinfo 2>/dev/null || echo 1)" + printf '%s' "$n" +} + +hw_cpu_has() { + grep -qw "$1" /proc/cpuinfo 2>/dev/null +} + +# hw_cpu_virt - print a human readable virtualisation capability summary +hw_cpu_virt() { + local out=() + hw_cpu_has vmx && out+=("Intel VT-x") + hw_cpu_has svm && out+=("AMD-V") + hw_cpu_has avx2 && out+=("AVX2") + hw_cpu_has avx512f && out+=("AVX-512") + hw_cpu_has aes && out+=("AES-NI") + ((${#out[@]})) && printf '%s' "${out[*]}" +} + +hw_mem_total_mib() { + awk '/^MemTotal:/{printf "%d", $2/1024; exit}' /proc/meminfo 2>/dev/null +} + +hw_firmware_mode() { + if [[ -d /sys/firmware/efi ]]; then printf 'UEFI'; else printf 'BIOS'; fi +} + +_is_laptop() { + local p + for p in /sys/class/power_supply/BAT*; do + [[ -e "$p" ]] && return 0 + done + [[ -d /sys/firmware/acpi/tables ]] && \ + grep -qi 'laptop' /sys/class/dmi/id/chassis_type 2>/dev/null + return 1 +} + +# _hw_lspci_filter REGEX - matching lspci lines, if lspci is available +_hw_lspci_filter() { + command -v lspci >/dev/null 2>&1 || return 0 + lspci -nn 2>/dev/null | grep -iE "$1" || true +} + +_hw_lsusb_filter() { + command -v lsusb >/dev/null 2>&1 || return 0 + lsusb 2>/dev/null | grep -iE "$1" || true +} + +hw_gpus() { _hw_lspci_filter 'VGA compatible controller|3D controller|Display controller'; } +hw_network_hw() { _hw_lspci_filter 'Ethernet controller|Network controller|Wireless'; } +hw_bluetooth() { { _hw_lspci_filter 'Bluetooth'; _hw_lsusb_filter 'Bluetooth'; } | sort -u; } +hw_audio() { _hw_lspci_filter 'Audio device'; } +hw_usb() { _hw_lspci_filter 'USB controller'; } +hw_storage_hw() { _hw_lspci_filter 'SATA controller|NVMe|RAID bus controller'; } + +# hw_gpu_vendors - space separated vendor tags, used for driver policy +hw_gpu_vendors() { + local gpus vendors=() + gpus="$(hw_gpus)" + grep -qi 'nvidia' <<<"$gpus" && vendors+=("nvidia") + grep -qi 'amd\|advanced micro devices\|ati technologies' <<<"$gpus" && vendors+=("amd") + grep -qi 'intel' <<<"$gpus" && vendors+=("intel") + printf '%s' "${vendors[*]:-unknown}" +} + +hw_input_devices() { + local count=0 + [[ -r /proc/bus/input/devices ]] && \ + count="$(grep -c '^N: Name=' /proc/bus/input/devices 2>/dev/null)" + printf '%s' "$count" +} + +# hw_report - human readable report for the TUI / hardware screen +hw_report() { + local virt + virt="$(hw_cpu_virt)" + printf 'Firmware: %s\n' "$(hw_firmware_mode)" + printf 'CPU: %s\n' "$(hw_cpu_model)" + printf 'CPU cores: %s threads / %s logical CPUs\n' \ + "$(hw_cpu_threads)" "$(hw_cpu_cores)" + printf 'CPU features: %s\n' "${virt:-none detected}" + printf 'Memory: %s MiB\n' "$(hw_mem_total_mib)" + printf 'Machine type: %s\n' "$(_is_laptop && echo laptop || echo desktop/server)" + printf 'Input devices: %s\n' "$(hw_input_devices)" + printf '\n' + printf 'GPUs:\n%s\n\n' "$(hw_gpus | sed 's/^/ /' | grep . || echo ' (none detected)')" + printf 'Storage controllers:\n%s\n\n' "$(hw_storage_hw | sed 's/^/ /' | grep . || echo ' (none detected)')" + printf 'Network:\n%s\n\n' "$(hw_network_hw | sed 's/^/ /' | grep . || echo ' (none detected)')" + printf 'Bluetooth:\n%s\n\n' "$(hw_bluetooth | sed 's/^/ /' | grep . || echo ' (none detected)')" + printf 'Audio:\n%s\n\n' "$(hw_audio | sed 's/^/ /' | grep . || echo ' (none detected)')" + printf 'USB controllers:\n%s\n' "$(hw_usb | sed 's/^/ /' | grep . || echo ' (none detected)')" +} + +# hw_recommended_kernel_profile - conservative recommendation +hw_recommended_kernel_profile() { + local mem + mem="$(hw_mem_total_mib)" + if [[ -n "$mem" ]] && ((mem < 2048)); then + printf 'safe' + else + printf 'optimized' + fi +} diff --git a/installer/lib/install.sh b/installer/lib/install.sh new file mode 100644 index 0000000..03e54b9 --- /dev/null +++ b/installer/lib/install.sh @@ -0,0 +1,330 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Installation orchestration. +# +# This is the only place that grants destructive authorization, and only after +# the plan has been displayed and explicitly approved. Each stage checks the +# return status of the one before it and stops on failure rather than +# continuing blindly. + +declare -g INSTALL_TARGET_ROOT="" +declare -g INSTALL_FAILED_STAGE="" + +# install_effective_root - the directory the installed system lives in. +# In dry-run mode this is a sandbox so file writes never touch the host. +install_effective_root() { + if config_bool DRY_RUN; then + printf '%s/dry-run-root' "${STATE_DIR:-/tmp/ai-installer}" + else + printf '%s' "$(config_get INSTALL_ROOT)" + fi +} + +install_require_root() { + if config_bool DRY_RUN; then return 0; fi + if [[ "$(id -u)" -ne 0 ]]; then + log_error "the installer must run as root" + return 1 + fi + return 0 +} + +# install_preflight - non-destructive checks before anything is touched +install_preflight() { + log_section "preflight" + install_require_root || return 1 + if ! config_bool DRY_RUN && [[ ! -d /sys/firmware/efi ]]; then + log_error "system was not booted in UEFI mode; v0.1 supports UEFI only" + return 1 + fi + local problems + problems="$(validate_config)" + if [[ -n "$problems" ]]; then + log_error "configuration is incomplete:" + while IFS= read -r problems; do log_error " $problems"; done <<<"$problems" + return 1 + fi + partitions_require_tools || return 1 + filesystem_require_tools || return 1 + btrfs_require_tools || return 1 + if [[ "$(config_get ENCRYPTION)" != "none" ]]; then + encryption_require_tools || return 1 + fi + if [[ -z "$LUKS_PASSPHRASE" && "$(config_get ENCRYPTION)" != "none" ]]; then + log_error "encryption selected but no passphrase configured" + return 1 + fi + return 0 +} + +# install_chroot_mount ROOT / install_chroot_umount ROOT +install_chroot_mount() { + local root="$1" + run_cmd "mount proc" mount -t proc proc "$root/proc" || return 1 + run_cmd "mount sysfs" mount --rbind /sys "$root/sys" || return 1 + run_cmd "mount devtmpfs" mount --rbind /dev "$root/dev" || return 1 + run_cmd "mount devpts" mount --make-rslave "$root/dev" 2>/dev/null || true + [[ -d "$root/run" ]] && run_cmd "mount tmpfs on /run" mount -t tmpfs tmpfs "$root/run" || true + return 0 +} + +install_chroot_umount() { + local root="$1" + run_cmd "unmount $root/proc" umount -l "$root/proc" 2>/dev/null || true + run_cmd "unmount $root/sys" umount -l "$root/sys" 2>/dev/null || true + run_cmd "unmount $root/dev" umount -l "$root/dev" 2>/dev/null || true +} + +# install_stage_storage - create partitions, filesystems and mount the target +install_stage_storage() { + local disk root + disk="$(config_get TARGET_DISK)" + root="$INSTALL_TARGET_ROOT" + log_section "storage: $disk" + + if config_bool DRY_RUN; then + log_info "[dry-run] would partition and format $disk at $root" + mkdir -p "$root" + return 0 + fi + + partitions_wipe "$disk" || return 1 + partitions_create_gpt "$disk" || return 1 + partitions_verify "$disk" || return 1 + FS_EFI_PART="$EFI_PART" + + filesystem_mkfs_efi "$EFI_PART" || return 1 + filesystem_prepare_root "$disk" "$ROOT_PART" || return 1 + # Create the subvolume layout and mount the root; mounting the ESP afterwards + # avoids covering the ESP mount with the root filesystem. + btrfs_create_layout "$FS_ROOT_SOURCE" "$root" || return 1 + filesystem_mount_efi "$EFI_PART" "$root" || return 1 + btrfs_create_swapfile "$root" || return 1 + # NOTE: /etc/fstab and /etc/crypttab are generated after the stage3 is + # extracted (install_stage_fstab); generating them here would be undone by + # the stage3 tarball, which ships its own /etc/fstab. + return 0 +} + +# install_stage_fstab - write fstab, crypttab and required runtime directories. +# Runs after the stage3 has been extracted so nothing overwrites these files. +install_stage_fstab() { + local root="$INSTALL_TARGET_ROOT" + log_section "fstab / crypttab" + if config_bool DRY_RUN; then + log_info "[dry-run] would write fstab and crypttab into $root" + return 0 + fi + filesystem_generate_fstab "$root" || return 1 + filesystem_generate_crypttab "$root" || return 1 + # Some stage3 media omit /var/tmp; systemd's kernel-install needs it. + mkdir -p "$root/var/tmp" "$root/tmp" "$root/root" "$root/home" + chmod 1777 "$root/var/tmp" "$root/tmp" 2>/dev/null || true + chmod 0700 "$root/root" 2>/dev/null || true + return 0 +} + +# install_stage_base - extract the Gentoo systemd stage3 +install_stage_base() { + local root="$INSTALL_TARGET_ROOT" tarball + log_section "base system (stage3)" + mkdir -p "$root" "${STATE_DIR:-/tmp/ai-installer}" + tarball="${STATE_DIR:-/tmp/ai-installer}/stage3-systemd.tar.xz" + if config_bool DRY_RUN; then + log_info "[dry-run] would fetch stage3 and extract into $root" + return 0 + fi + portage_fetch_stage3 "$tarball" || return 1 + portage_extract_stage3 "$root" "$tarball" || return 1 + return 0 +} + +# install_stage_portage - configure Portage and sync +install_stage_portage() { + local root="$INSTALL_TARGET_ROOT" + log_section "portage configuration" + if config_bool DRY_RUN; then + log_info "[dry-run] would write Portage config and sync" + return 0 + fi + portage_write_make_conf "$root" || return 1 + portage_write_repos_conf "$root" || return 1 + portage_write_binrepos "$root" || return 1 + portage_write_package_files "$root" || return 1 + cp -L /etc/resolv.conf "$root/etc/resolv.conf" 2>/dev/null || true + install_chroot_mount "$root" || return 1 + portage_init_machine_id "$root" || log_warn "could not initialise machine-id" + portage_sync "$root" || { install_chroot_umount "$root"; return 1; } + portage_verification_setup "$root" || log_warn "getuto failed; binary package verification may fail" + install_chroot_umount "$root" + # Select the profile only after the tree exists, so the symlink is never + # dangling while Portage runs. + portage_select_profile "$root" || return 1 + return 0 +} + +# install_stage_packages - base packages beyond the stage3 +install_stage_packages() { + local root="$INSTALL_TARGET_ROOT" + local -a packages=() + log_section "base packages" + mapfile -t packages < <(portage_base_packages) + install_chroot_mount "$root" || return 1 + portage_emerge "$root" "${packages[@]}" || { install_chroot_umount "$root"; return 1; } + install_chroot_umount "$root" + return 0 +} + +# install_stage_kernel +install_stage_kernel() { + local root="$INSTALL_TARGET_ROOT" + log_section "kernel" + kernel_write_profile "$root" || return 1 + boot_write_install_conf "$root" || return 1 + boot_write_dracut_conf "$root" || return 1 + kernel_write_cmdline "$root" || return 1 + install_chroot_mount "$root" || return 1 + kernel_install "$root" || { install_chroot_umount "$root"; return 1; } + install_chroot_umount "$root" + return 0 +} + +# install_stage_boot +install_stage_boot() { + local root="$INSTALL_TARGET_ROOT" + log_section "bootloader" + install_chroot_mount "$root" || return 1 + boot_install "$root" || log_warn "bootctl install failed; will rely on the EFI fallback path" + boot_generate_uki "$root" || log_warn "kernel-install add-all reported an issue" + install_chroot_umount "$root" + boot_write_loader_conf "$root" || return 1 + boot_install_fallback "$root" || log_warn "EFI fallback bootloader not installed" + boot_random_seed "$root" || true + boot_verify "$root" || return 1 + return 0 +} + +# install_stage_users +install_stage_users() { + local root="$INSTALL_TARGET_ROOT" + log_section "users" + install_chroot_mount "$root" || return 1 + users_create "$root" || { install_chroot_umount "$root"; return 1; } + users_configure_sudo "$root" || { install_chroot_umount "$root"; return 1; } + install_chroot_umount "$root" + return 0 +} + +# install_stage_services - locale, timezone, keymap, systemd services +install_stage_services() { + local root="$INSTALL_TARGET_ROOT" tz locale keymap + log_section "system services" + tz="$(config_get TIMEZONE)" + locale="$(config_get LOCALE)" + keymap="$(config_get KEYMAP)" + + network_configure_target "$root" || return 1 + mkdir -p "$root/etc" + { + printf 'KEYMAP=%s\n' "$keymap" + } >"$root/etc/vconsole.conf" + ln -sf "/usr/share/zoneinfo/$tz" "$root/etc/localtime" + { + printf 'LANG=%s\n' "$locale" + } >"$root/etc/locale.conf" + portage_write_locale_gen "$root" "$locale" + + install_chroot_mount "$root" || return 1 + portage_chroot "$root" locale-gen || log_warn "locale-gen failed (continuing)" + local svc + local -a services=() + mapfile -t services < <(network_target_services) + mapfile -t -O "${#services[@]}" services < <(desktop_services) + printf '%s\n' "${services[@]}" | sort -u >"$root/etc/.phoebus-services" + while IFS= read -r svc; do + [[ -z "$svc" ]] && continue + portage_chroot "$root" systemctl enable "$svc" || log_warn "could not enable $svc" + done <"$root/etc/.phoebus-services" + rm -f "$root/etc/.phoebus-services" + install_chroot_umount "$root" + return 0 +} + +# install_stage_desktop +install_stage_desktop() { + local root="$INSTALL_TARGET_ROOT" profile + profile="$(config_get DESKTOP_PROFILE)" + log_section "desktop: $profile" + [[ "$profile" == "none" ]] && return 0 + install_chroot_mount "$root" || return 1 + desktop_install "$root" || { install_chroot_umount "$root"; return 1; } + desktop_configure_flatpak "$root" || true + install_chroot_umount "$root" + return 0 +} + +# install_export_logs ROOT - copy the installer log into the target so a +# failed installation can be diagnosed after reboot. +install_export_logs() { + local root="$1" dest + dest="$root/var/log/ai-installer" + [[ -r "${PHOEBUS_LOG_FILE:-}" ]] || return 0 + mkdir -p "$dest" 2>/dev/null || return 0 + cp -f "$PHOEBUS_LOG_FILE" "$dest/install.log" 2>/dev/null || true +} + +# install_stage_finalize +install_stage_finalize() { + local root="$INSTALL_TARGET_ROOT" + log_section "finalize" + if ! config_bool DRY_RUN; then + install_export_logs "$root" + install_chroot_umount "$root" + filesystem_unmount_all "$root" + if [[ "$(config_get ENCRYPTION)" != "none" ]]; then + encryption_close "$(config_get LUKS_NAME)" || log_warn "could not close LUKS device" + fi + fi + log_info "installation finished" + return 0 +} + +# install_run - execute the staged installation, stopping on first failure +install_run() { + INSTALL_TARGET_ROOT="$(install_effective_root)" + INSTALL_FAILED_STAGE="" + mkdir -p "$INSTALL_TARGET_ROOT" 2>/dev/null || true + + install_preflight || { INSTALL_FAILED_STAGE="preflight"; return 1; } + + local stage rc + for stage in "${PLAN_STEPS[@]}"; do + rc=0 + case "$stage" in + storage_prepare) install_stage_storage || rc=1 ;; + stage_install) install_stage_base || rc=1 ;; + fstab_generate) install_stage_fstab || rc=1 ;; + portage_configure) install_stage_portage || rc=1 ;; + packages_base) install_stage_packages || rc=1 ;; + kernel_install) install_stage_kernel || rc=1 ;; + boot_install) install_stage_boot || rc=1 ;; + users_configure) install_stage_users || rc=1 ;; + services_configure) install_stage_services || rc=1 ;; + desktop_install) install_stage_desktop || rc=1 ;; + finalize) install_stage_finalize || rc=1 ;; + *) log_warn "unknown stage: $stage" ;; + esac + if ((rc != 0)); then + INSTALL_FAILED_STAGE="$stage" + log_error "stage failed: $stage" + if ! config_bool DRY_RUN; then + install_export_logs "$INSTALL_TARGET_ROOT" + install_chroot_umount "$INSTALL_TARGET_ROOT" + fi + return 1 + fi + log_info "stage complete: $stage" + done + return 0 +} diff --git a/installer/lib/kernel.sh b/installer/lib/kernel.sh new file mode 100644 index 0000000..0d665e4 --- /dev/null +++ b/installer/lib/kernel.sh @@ -0,0 +1,139 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Kernel selection and configuration. +# +# Policy: compile an "optimized but conservative" kernel. We start from the +# Gentoo distribution kernel (sys-kernel/gentoo-kernel), which is a stable, +# well-tested configuration, and apply a small, safe set of profile fragments. +# We never generate a minimal config that only boots the installer's hardware. + +kernel_profile_file() { + printf '%s/etc/kernel/config.d/00-phoebus-profile.config' "$1" +} + +# kernel_modules_for_hardware - extra kernel packages suggested by hardware +kernel_extra_packages() { + printf '%s\n' sys-kernel/linux-firmware + if hw_cpu_has vmx; then + printf '%s\n' sys-firmware/intel-microcode + fi + if hw_cpu_has svm; then + printf '%s\n' sys-firmware/amd-ucode + fi +} + +# kernel_select_package - final kernel package respecting the profile +kernel_select_package() { + local pkg profile + pkg="$(config_get KERNEL_PACKAGE)" + profile="$(config_get KERNEL_PROFILE)" + case "$profile" in + safe) + # Safe profile prefers the prebuilt distribution kernel. + printf '%s' "sys-kernel/gentoo-kernel-bin" ;; + optimized) + printf '%s' "${pkg:-sys-kernel/gentoo-kernel}" ;; + aggressive) + # Aggressive still uses the distribution sources but may take a + # locally tuned savedconfig fragment. + printf '%s' "${pkg:-sys-kernel/gentoo-kernel}" ;; + *) + printf '%s' "${pkg:-sys-kernel/gentoo-kernel}" ;; + esac +} + +# kernel_write_profile ROOT - safe config fragments (never minimal) +kernel_write_profile() { + local root="$1" profile file + profile="$(config_get KERNEL_PROFILE)" + file="$(kernel_profile_file "$root")" + mkdir -p "$(dirname "$file")" + { + printf '# %s kernel profile: %s\n' "$(config_get DISTRO_NAME)" "$profile" + printf '# Applied on top of the Gentoo distribution kernel configuration.\n' + printf '# The base configuration is intentionally kept: it supports common\n' + printf '# peripherals the user may attach later.\n' + printf '\n' + printf '# Storage / modern filesystems and encryption\n' + printf 'CONFIG_BTRFS_FS=y\n' + printf 'CONFIG_BTRFS_FS_POSIX_ACL=y\n' + printf 'CONFIG_DM_CRYPT=y\n' + printf 'CONFIG_DM_INTEGRITY=y\n' + printf 'CONFIG_NVME_CORE=y\n' + printf 'CONFIG_BLK_DEV_NVME=y\n' + printf '\n' + printf '# Input / USB / common buses\n' + printf 'CONFIG_HID_GENERIC=y\n' + printf 'CONFIG_USB_HID=y\n' + printf 'CONFIG_USB_XHCI_HCD=y\n' + printf '\n' + printf '# systemd / containers / virtualisation guests\n' + printf 'CONFIG_CGROUPS=y\n' + printf 'CONFIG_NAMESPACES=y\n' + printf 'CONFIG_VIRTIO=y\n' + printf 'CONFIG_VIRTIO_PCI=y\n' + printf 'CONFIG_VIRTIO_BLK=y\n' + printf 'CONFIG_VIRTIO_NET=y\n' + printf '\n' + printf '# Compression used by Btrfs\n' + printf 'CONFIG_ZSTD_COMPRESS=y\n' + printf 'CONFIG_ZSTD_DECOMPRESS=y\n' + } >"$file" + log_info "wrote kernel profile fragment $file" +} + +# kernel_write_cmdline ROOT - kernel command line for UKI/systemd-boot +kernel_write_cmdline() { + local root="$1" cmdline="" enc name uuid + enc="$(config_get ENCRYPTION)" + name="$(config_get LUKS_NAME)" + if [[ "$enc" != "none" ]]; then + uuid="$(blkid -s UUID -o value "$FS_ROOT_PART" 2>/dev/null)" + if [[ -z "$uuid" ]]; then + if config_bool DRY_RUN; then + uuid="" + else + log_error "cannot determine LUKS UUID for kernel command line" + return 1 + fi + fi + # rd.luks.name== makes dracut/systemd create the mapper under + # the configured name; rd.luks.uuid alone would produce luks- and the + # root= below would not exist. + cmdline+="rd.luks.name=$uuid=$name " + cmdline+="root=/dev/mapper/$name " + else + cmdline+="root=$(filesystem_source_ref) " + fi + cmdline+="rootfstype=btrfs rootflags=subvol=@ rw quiet" + local console + console="$(config_get KERNEL_CONSOLE)" + [[ -n "$console" ]] && cmdline+=" $console" + mkdir -p "$root/etc/kernel" + printf '%s\n' "$cmdline" >"$root/etc/kernel/cmdline" + log_info "wrote /etc/kernel/cmdline: $cmdline" +} + +# kernel_install ROOT - emerge the kernel and firmware +kernel_install() { + local root="$1" pkg + pkg="$(kernel_select_package)" + local -a packages=("$pkg") + mapfile -t -O "${#packages[@]}" packages < <(kernel_extra_packages) + log_info "installing kernel packages: ${packages[*]}" + portage_emerge "$root" "${packages[@]}" +} + +# kernel_update ROOT - rebuild the distribution kernel via emerge @module-rebuild +kernel_update() { + local root="$1" + portage_chroot "$root" emerge --ask=n --quiet-build=y @module-rebuild +} + +# kernel_available_list ROOT - kernels present in the ESP +kernel_available_list() { + local root="$1" esp + esp="$root$(config_get EFI_MOUNT)" + find "$esp" -maxdepth 4 -name 'vmlinuz*' -o -name '*.efi' 2>/dev/null | sed "s#^$root##" +} diff --git a/installer/lib/logging.sh b/installer/lib/logging.sh new file mode 100644 index 0000000..fe3dcd3 --- /dev/null +++ b/installer/lib/logging.sh @@ -0,0 +1,139 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Installer logging and command execution. +# +# Every operation performed by the deterministic backend goes through run_cmd +# (or run_cmd_capture), which records the command, its output and its exit +# status. This makes failures diagnosable and keeps destructive behaviour +# auditable. +# +# Secrets are scrubbed from all log output. + +declare -g PHOEBUS_LOG_FILE="${PHOEBUS_LOG_FILE:-}" +declare -g PHOEBUS_LOG_ECHO="${PHOEBUS_LOG_ECHO:-no}" +declare -ga SECRET_VALUES=() + +# secret_register VALUE - remember a secret so it is never written to logs +secret_register() { + [[ -n "${1-}" ]] && SECRET_VALUES+=("$1") +} + +# redact_scrub TEXT - replace every known secret with +redact_scrub() { + local text="$1" secret + for secret in "${SECRET_VALUES[@]}"; do + [[ -n "$secret" ]] && text="${text//"$secret"/}" + done + printf '%s' "$text" +} + +log_init() { + local dir + dir="${LOG_DIR:-/var/log/ai-installer}" + if ! mkdir -p "$dir" 2>/dev/null || [[ ! -w "$dir" ]]; then + dir="${STATE_DIR:-/tmp/ai-installer}/logs" + mkdir -p "$dir" 2>/dev/null || true + fi + PHOEBUS_LOG_FILE="${PHOEBUS_LOG_FILE:-$dir/install.log}" + : >"$PHOEBUS_LOG_FILE" 2>/dev/null || PHOEBUS_LOG_FILE=/dev/null + log_line INFO "=== ${DISTRO_NAME:-Phoebus OS} installer started ===" + log_line INFO "log file: $PHOEBUS_LOG_FILE" +} + +log_line() { + local level="$1" message="${2-}" + local ts + ts="$(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date)" + message="$(redact_scrub "$message")" + printf '%s [%s] %s\n' "$ts" "$level" "$message" >>"$PHOEBUS_LOG_FILE" 2>/dev/null || true + if [[ "$PHOEBUS_LOG_ECHO" == "yes" ]]; then + printf '%s [%s] %s\n' "$ts" "$level" "$message" >&2 + fi +} + +log_debug() { log_line DEBUG "$@"; } +log_info() { log_line INFO "$@"; } +log_warn() { log_line WARN "$@"; } +log_error() { log_line ERROR "$@"; } +log_section() { log_line INFO "--- $* ---"; } + +# _cmd_to_string ARGS... - printable, redacted representation of a command +_cmd_to_string() { + local out="" arg + for arg in "$@"; do + out+="$(printf '%q' "$arg") " + done + redact_scrub "${out% }" +} + +# run_cmd DESCRIPTION ARGS... +# Execute a command, streaming stdout/stderr to the log. Honours DRY_RUN. +run_cmd() { + local desc="$1"; shift + local printable status + printable="$(_cmd_to_string "$@")" + if config_bool DRY_RUN; then + log_line INFO "[dry-run] $desc :: $printable" + return 0 + fi + log_line INFO "$desc :: $printable" + "$@" >>"$PHOEBUS_LOG_FILE" 2>&1 + status=$? + log_line INFO "$desc :: exit status $status" + return $status +} + +# run_cmd_capture DESCRIPTION ARGS... +# Like run_cmd but stdout is stored in RUN_OUTPUT and not streamed. stderr +# still goes to the log. Never logs the captured stdout (may contain secrets). +run_cmd_capture() { + local desc="$1"; shift + local printable status + RUN_OUTPUT="" + printable="$(_cmd_to_string "$@")" + if config_bool DRY_RUN; then + log_line INFO "[dry-run] $desc (capture) :: $printable" + return 0 + fi + log_line DEBUG "$desc (capture) :: $printable" + RUN_OUTPUT="$("$@" 2>>"$PHOEBUS_LOG_FILE")" + status=$? + log_line DEBUG "$desc :: exit status $status" + return $status +} + +# run_cmd_quiet DESCRIPTION ARGS... - output fully suppressed +run_cmd_quiet() { + local desc="$1"; shift + local printable status + printable="$(_cmd_to_string "$@")" + if config_bool DRY_RUN; then + log_line INFO "[dry-run] $desc :: $printable" + return 0 + fi + log_line DEBUG "$desc (quiet) :: $printable" + "$@" >>"$PHOEBUS_LOG_FILE" 2>&1 + status=$? + log_line DEBUG "$desc :: exit status $status" + return $status +} + +# require_cmd NAME... - fail fast when a required tool is unavailable +require_cmd() { + local missing=() name + for name in "$@"; do + command -v "$name" >/dev/null 2>&1 || missing+=("$name") + done + if ((${#missing[@]})); then + log_error "missing required command(s): ${missing[*]}" + return 1 + fi + return 0 +} + +# log_tail [N] - last N lines of the log (for the TUI) +log_tail() { + local n="${1:-40}" + tail -n "$n" "$PHOEBUS_LOG_FILE" 2>/dev/null +} diff --git a/installer/lib/network.sh b/installer/lib/network.sh new file mode 100644 index 0000000..b6cca78 --- /dev/null +++ b/installer/lib/network.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Networking for the live environment and for the installed system. +# +# In the live environment we drive NetworkManager (present in the Gentoo +# LiveGUI reference) because it works for both wired and wireless. The installed +# system also uses NetworkManager, which matches the desktop profile. + +WIFI_PASSPHRASE="" + +network_interfaces() { + local iface + for iface in /sys/class/net/*; do + iface="${iface##*/}" + [[ "$iface" == "lo" ]] && continue + printf '%s\n' "$iface" + done +} + +network_is_wireless() { + local iface="$1" + [[ -d "/sys/class/net/$iface/wireless" ]] || \ + [[ -d "/sys/class/net/$iface/phy80211" ]] +} + +network_interface_state() { + cat "/sys/class/net/$1/operstate" 2>/dev/null || printf 'unknown' +} + +network_online() { + command -v ip >/dev/null 2>&1 || return 1 + ip route show default 2>/dev/null | grep -q 'default' && return 0 + if command -v ping >/dev/null 2>&1; then + ping -c1 -W2 1.1.1.1 >/dev/null 2>&1 && return 0 + fi + return 1 +} + +network_status_text() { + local iface + printf 'Connectivity: %s\n\n' "$(network_online && echo online || echo offline)" + for iface in $(network_interfaces); do + local kind state + kind="$(network_is_wireless "$iface" && echo wireless || echo wired)" + state="$(network_interface_state "$iface")" + printf ' %-12s %-8s %s\n' "$iface" "$kind" "$state" + done +} + +# network_live_start - best effort start of the live network manager +network_live_start() { + if command -v rc-service >/dev/null 2>&1; then + run_cmd "start NetworkManager (OpenRC)" rc-service NetworkManager start 2>/dev/null || true + fi + if command -v nmcli >/dev/null 2>&1; then + run_cmd "ensure NetworkManager running" nmcli general status >/dev/null 2>&1 || true + fi + if command -v rfkill >/dev/null 2>&1; then + run_cmd "unblock wifi" rfkill unblock wifi 2>/dev/null || true + fi +} + +# network_connect_wifi SSID PASSPHRASE - live environment helper +network_connect_wifi() { + local ssid="$1" pass="$2" + command -v nmcli >/dev/null 2>&1 || { log_error "nmcli not available"; return 1; } + secret_register "$pass" + if [[ -n "$pass" ]]; then + run_cmd "connect to wifi '$ssid'" nmcli device wifi connect "$ssid" password "$pass" + else + run_cmd "connect to wifi '$ssid'" nmcli device wifi connect "$ssid" + fi +} + +# network_wifi_scan - print "SSID SIGNAL SECURITY" lines +network_wifi_scan() { + command -v nmcli >/dev/null 2>&1 || return 1 + nmcli -t -f SSID,SIGNAL,SECURITY device wifi list 2>/dev/null | \ + awk -F: 'NF && $1!=""{printf "%-32s %3s%% %s\n", $1, $2, $3}' +} + +# network_configure_target ROOT +# Write the target hostname and enable the networking services. Service +# enablement itself happens inside the chroot during install. +network_configure_target() { + local root="$1" hostname + hostname="$(config_get HOSTNAME)" + mkdir -p "$root/etc" + printf '%s\n' "$hostname" >"$root/etc/hostname" + { + printf '127.0.0.1\tlocalhost\n' + printf '::1\t\tlocalhost\n' + printf '127.0.1.1\t%s\n' "$hostname" + } >"$root/etc/hosts" + log_info "configured hostname '$hostname' in target" +} + +# network_target_service_names - services to enable in the installed system +network_target_services() { + printf '%s\n' NetworkManager systemd-resolved +} diff --git a/installer/lib/opencode.sh b/installer/lib/opencode.sh new file mode 100644 index 0000000..865af10 --- /dev/null +++ b/installer/lib/opencode.sh @@ -0,0 +1,156 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Reproducible OpenCode provisioning. +# +# The vendor installer (curl | sh) is never used. We fetch a pinned release +# tarball from the official GitHub release and verify its SHA-256 against the +# local manifest before extracting it. The binary is never executed during +# verification. + +opencode_manifest_file() { + printf '%s/config/opencode.manifest' "$PHOEBUS_ROOT" +} + +opencode_manifest_get() { + local arch="$1" key="$2" file out + file="$(opencode_manifest_file)" + [[ -r "$file" ]] || return 1 + out="$(awk -F= -v a="$arch" -v k="$key" '$1==a"."k{sub(/^[^=]*=/,""); print; exit}' "$file")" + [[ -n "$out" ]] || return 1 + printf '%s' "$out" +} + +opencode_version_manifest() { + local file + file="$(opencode_manifest_file)" + awk -F= '$1=="VERSION"{print $2; exit}' "$file" 2>/dev/null +} + +opencode_arch() { + case "$(uname -m)" in + x86_64|amd64) printf 'x86_64' ;; + aarch64|arm64) printf 'aarch64' ;; + *) printf 'unsupported' ;; + esac +} + +# opencode_bin_dir - where the verified binary lives +opencode_bin_dir() { + if [[ -n "${PHOEBUS_OPENCODE_DIR:-}" ]]; then + printf '%s' "$PHOEBUS_OPENCODE_DIR" + elif [[ -w /opt ]]; then + printf '/opt/phoebus/opencode' + else + printf '%s/opencode' "${STATE_DIR:-/tmp/ai-installer}" + fi +} + +# opencode_detect - print the path to a usable opencode binary, if any +opencode_detect() { + local candidate + if command -v opencode >/dev/null 2>&1; then + command -v opencode + return 0 + fi + for candidate in "$(opencode_bin_dir)/opencode" /usr/local/bin/opencode; do + [[ -x "$candidate" ]] && { printf '%s' "$candidate"; return 0; } + done + return 1 +} + +opencode_available() { opencode_detect >/dev/null 2>&1; } + +# opencode_checksum_ok FILE EXPECTED - false for placeholders or mismatches +opencode_checksum_ok() { + local file="$1" expected="$2" got + [[ -n "$expected" ]] || return 1 + [[ "$expected" =~ ^0+$ ]] && return 1 + got="$(sha256sum "$file" | awk '{print $1}')" + [[ "$got" == "$expected" ]] +} + +# opencode_bootstrap [DESTDIR] - download, verify and extract a pinned release +opencode_bootstrap() { + local dest="${1:-$(opencode_bin_dir)}" + local arch url sha binary tmp + arch="$(opencode_arch)" + if [[ "$arch" == "unsupported" ]]; then + log_error "OpenCode: unsupported architecture $(uname -m)" + return 1 + fi + url="$(opencode_manifest_get "$arch" url)" + sha="$(opencode_manifest_get "$arch" sha256)" + binary="$(opencode_manifest_get "$arch" binary)" + binary="${binary:-opencode}" + + if [[ -z "$url" || -z "$sha" ]]; then + log_error "OpenCode: no pinned manifest entry for $arch" + return 1 + fi + if [[ "$sha" =~ ^0+$ ]]; then + log_error "OpenCode: manifest has a placeholder checksum for $arch; refusing" + return 1 + fi + require_cmd curl sha256sum tar || return 1 + + mkdir -p "$dest" || return 1 + tmp="$(mktemp "${TMPDIR:-/tmp}/opencode.XXXXXX.tar.gz")" || return 1 + # shellcheck disable=SC2064 + trap "rm -f '$tmp'" RETURN + log_info "OpenCode: fetching $url" + if ! run_cmd "download OpenCode" curl -fL --retry 3 -o "$tmp" "$url"; then + return 1 + fi + if ! opencode_checksum_ok "$tmp" "$sha"; then + log_error "OpenCode: SHA-256 verification FAILED; discarding download" + rm -f "$tmp" + return 1 + fi + log_info "OpenCode: checksum verified" + run_cmd "extract OpenCode" tar -xzf "$tmp" -C "$dest" || return 1 + [[ -f "$dest/$binary" ]] || { log_error "OpenCode: expected binary '$binary' not found"; return 1; } + chmod 0755 "$dest/$binary" + ln -sf "$dest/$binary" "$dest/opencode" 2>/dev/null || true + log_info "OpenCode installed at $dest/$binary ($(opencode_version_manifest))" + return 0 +} + +# opencode_ensure - ensure a binary is present, bootstrapping if needed +opencode_ensure() { + opencode_available && return 0 + log_info "OpenCode not found; bootstrapping pinned release" + opencode_bootstrap +} + +# opencode_print_version BIN +opencode_print_version() { + local bin="$1" + "$bin" --version 2>/dev/null | head -n1 +} + +# opencode_ai_config_path - where the installer keeps AI provider config +opencode_ai_config_path() { + printf '%s/ai/opencode.json' "${STATE_DIR:-/tmp/ai-installer}" +} + +# opencode_write_config - write provider/model config (never secrets) +opencode_write_config() { + local path dir provider model endpoint + path="$(opencode_ai_config_path)" + dir="$(dirname "$path")" + mkdir -p "$dir" + provider="$(config_get AI_PROVIDER)" + model="$(config_get AI_MODEL)" + endpoint="$(config_get AI_ENDPOINT)" + { + printf '{\n' + printf ' "$schema": "https://opencode.ai/config.json"\n' + if [[ -n "$provider" ]]; then printf ' ,"provider": "%s"\n' "$provider"; fi + if [[ -n "$model" ]]; then printf ' ,"model": "%s"\n' "$model"; fi + if [[ -n "$endpoint" ]]; then printf ' ,"baseURL": "%s"\n' "$endpoint"; fi + printf '}\n' + } >"$path" + chmod 0600 "$path" + log_info "wrote OpenCode config to $path (credentials are never stored here)" +} diff --git a/installer/lib/partitions.sh b/installer/lib/partitions.sh new file mode 100644 index 0000000..8b824b3 --- /dev/null +++ b/installer/lib/partitions.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# GPT partition creation for the installation target. +# +# Every function here is destructive and must be invoked through +# run_destructive, which enforces prior authorization. + +# partitions_require_tools +partitions_require_tools() { + require_cmd sgdisk partprobe blkid wipefs || return 1 +} + +# partitions_wipe DISK - zap all existing partition signatures +partitions_wipe() { + local disk="$1" + run_destructive "wipe partition signatures on $disk" wipefs -a "$disk" || return 1 + run_destructive "zap GPT/MBR on $disk" sgdisk --zap-all "$disk" +} + +# partitions_create_gpt DISK - EFI + root (LUKS or plain btrfs) +partitions_create_gpt() { + local disk="$1" + local efi_mib root_type=8309 + efi_mib="$(config_get EFI_SIZE_MIB)" + [[ "$efi_mib" =~ ^[0-9]+$ ]] || efi_mib=1024 + if [[ "$(config_get ENCRYPTION)" == "none" ]]; then + root_type=8300 + fi + + run_destructive "create GPT on $disk" sgdisk --set-alignment=2048 \ + --new=1:0:+${efi_mib}M --typecode=1:ef00 --change-name=1:EFI \ + --new=2:0:0 --typecode=2:${root_type} --change-name=2:phoebus-root \ + "$disk" || return 1 + run_destructive "re-read partition table on $disk" partprobe "$disk" + command -v udevadm >/dev/null 2>&1 && run_cmd "settle udev" udevadm settle +} + +# partitions_named DISK - first EFI and root partition paths via blkid +partitions_named() { + local disk="$1" + EFI_PART="" ROOT_PART="" + # Prefer explicit GPT names when available. + if command -v blkid >/dev/null 2>&1; then + local dev label + while IFS= read -r dev; do + label="$(blkid -s PARTLABEL -o value "$dev" 2>/dev/null)" + case "$label" in + EFI) EFI_PART="$dev" ;; + phoebus-root) ROOT_PART="$dev" ;; + esac + done < <(disk_partitions "$disk") + fi + # Fallback by order. + local -a parts=() + mapfile -t parts < <(disk_partitions "$disk") + [[ -z "$EFI_PART" && ${#parts[@]} -ge 1 ]] && EFI_PART="${parts[0]}" + [[ -z "$ROOT_PART" && ${#parts[@]} -ge 2 ]] && ROOT_PART="${parts[1]}" + [[ -n "$EFI_PART" && -n "$ROOT_PART" ]] +} + +# partitions_verify DISK - sanity check after creation +partitions_verify() { + local disk="$1" + partitions_named "$disk" || { log_error "could not identify created partitions on $disk"; return 1; } + [[ -b "$EFI_PART" && -b "$ROOT_PART" ]] || { log_error "partition devices missing"; return 1; } + log_info "partitions: EFI=$EFI_PART root=$ROOT_PART" + return 0 +} diff --git a/installer/lib/pkgpolicy.sh b/installer/lib/pkgpolicy.sh new file mode 100644 index 0000000..dc1f67b --- /dev/null +++ b/installer/lib/pkgpolicy.sh @@ -0,0 +1,156 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Package compilation policy. +# +# The rule is deliberately deterministic: +# +# compile when compilation is cheap OR gives a meaningful benefit; +# use a binary when compilation is expensive AND the benefit is negligible. +# +# Decisions are driven by a small curated table plus optional historical +# compile-time data. An LLM is never consulted to guess performance. +# +# Historical data format (tab separated), one package per line: +# category/packagesecondsupdates-per-year +# Overrides the built-in estimate. + +declare -gA PKGPOLICY_COMPILE_SECONDS=( + [app-editors/vim]=45 + [app-misc/tmux]=20 + [app-shells/zsh]=60 + [dev-lang/python]=900 + [dev-lang/rust]=3600 + [dev-libs/glib]=120 + [dev-util/cmake]=300 + [dev-vcs/git]=120 + [media-video/ffmpeg]=900 + [net-misc/curl]=90 + [sys-apps/busybox]=60 + [sys-apps/coreutils]=120 + [sys-apps/systemd]=420 + [sys-devel/gcc]=3600 + [sys-kernel/gentoo-kernel]=1800 + [sys-kernel/gentoo-sources]=120 + [sys-libs/glibc]=900 + [www-client/firefox]=4200 + [www-client/chromium]=7200 + [app-office/libreoffice]=5400 + [dev-qt/qtbase]=900 + [kde-plasma/plasma-desktop]=600 + [net-im/discord-bin]=0 + [games-util/steam-launcher]=0 +) + +# Packages where a binary package is strongly preferred (huge + frequent +# updates + negligible local optimisation benefit + runtime CPU dispatch). +declare -gA PKGPOLICY_BINARY_PREFERRED=( + [www-client/firefox]=1 + [www-client/chromium]=1 + [app-office/libreoffice]=1 + [mail-client/thunderbird]=1 + [dev-lang/rust]=1 + [dev-lang/llvm]=1 + [dev-qt/qtwebengine]=1 + [sys-devel/gcc]=1 + [sys-libs/glibc]=1 + [net-im/discord-bin]=1 + [games-util/steam-launcher]=1 +) + +# Packages that genuinely benefit from local optimisation or USE customisation. +declare -gA PKGPOLICY_SOURCE_PREFERRED=( + [sys-kernel/gentoo-kernel]=1 + [sys-kernel/gentoo-sources]=1 + [sys-apps/systemd]=1 + [app-shells/zsh]=1 + [sys-apps/busybox]=1 + [sys-fs/btrfs-progs]=1 + [sys-fs/cryptsetup]=1 +) + +PKGPOLICY_HISTORY_FILE="" + +pkgpolicy_history_file() { + printf '%s' "${PKGPOLICY_HISTORY_FILE:-${STATE_DIR:-/tmp/ai-installer}/compile-times.tsv}" +} + +pkgpolicy_compile_seconds() { + local pkg="$1" hist line + hist="$(pkgpolicy_history_file)" + if [[ -r "$hist" ]]; then + line="$(awk -F'\t' -v p="$pkg" '$1==p{print $2; exit}' "$hist")" + if [[ "$line" =~ ^[0-9]+$ ]]; then printf '%s' "$line"; return; fi + fi + printf '%s' "${PKGPOLICY_COMPILE_SECONDS[$pkg]:-300}" +} + +pkgpolicy_updates_per_year() { + local pkg="$1" hist line + hist="$(pkgpolicy_history_file)" + if [[ -r "$hist" ]]; then + line="$(awk -F'\t' -v p="$pkg" '$1==p{print $3; exit}' "$hist")" + if [[ "$line" =~ ^[0-9]+$ ]]; then printf '%s' "$line"; return; fi + fi + printf '6' +} + +# pkgpolicy_binary_available PKG - a binary can plausibly be fetched +pkgpolicy_binary_available() { + [[ -n "$(config_get BINHOST_URI)" ]] || return 1 + config_bool FEATURES_BINPKG +} + +# pkgpolicy_decide PKG - prints "source" or "binary" +pkgpolicy_decide() { + local pkg="$1" policy seconds mem cores + policy="$(config_get PACKAGE_POLICY)" + seconds="$(pkgpolicy_compile_seconds "$pkg")" + mem="$(hw_mem_total_mib)"; [[ -n "$mem" ]] || mem=4096 + cores="$(hw_cpu_cores)"; [[ -n "$cores" ]] || cores=2 + + case "$policy" in + source_first) + printf 'source'; return ;; + binary_first) + if pkgpolicy_binary_available; then printf 'binary'; else printf 'source'; fi + return ;; + esac + + # balanced: + # - explicit preferences win; + # - cheap builds are compiled locally; + # - everything else uses a signed Gentoo binary when one is available. + # This is deterministic and avoids guessing performance where no data + # exists. Portage still builds from source whenever USE does not match the + # binary (--binpkg-respect-use=y). + if [[ -n "${PKGPOLICY_BINARY_PREFERRED[$pkg]:-}" ]]; then + pkgpolicy_binary_available && { printf 'binary'; return; } + fi + if [[ -n "${PKGPOLICY_SOURCE_PREFERRED[$pkg]:-}" ]]; then + printf 'source'; return + fi + if ((seconds <= 120)); then printf 'source'; return; fi + if pkgpolicy_binary_available; then printf 'binary'; return; fi + printf 'source' +} + +# pkgpolicy_emerge_flags PKG - extra emerge flags for a package +pkgpolicy_emerge_flags() { + local pkg="$1" decision + decision="$(pkgpolicy_decide "$pkg")" + if [[ "$decision" == "binary" ]]; then + printf '%s\n' --getbinpkg --binpkg-respect-use=y + fi +} + +# pkgpolicy_report [PKGS...] - human readable policy decisions +pkgpolicy_report() { + local -a pkgs=("$@") pkg + ((${#pkgs[@]})) || pkgs=(sys-apps/systemd sys-devel/gcc www-client/firefox sys-kernel/gentoo-kernel app-editors/vim) + printf 'Policy: %s\n\n' "$(config_get PACKAGE_POLICY)" + printf '%-32s %8s %s\n' "package" "est(s)" "decision" + for pkg in "${pkgs[@]}"; do + printf '%-32s %8s %s\n' "$pkg" "$(pkgpolicy_compile_seconds "$pkg")" "$(pkgpolicy_decide "$pkg")" + done +} diff --git a/installer/lib/plan.sh b/installer/lib/plan.sh new file mode 100644 index 0000000..a944399 --- /dev/null +++ b/installer/lib/plan.sh @@ -0,0 +1,147 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Installation plan generation. +# +# The plan is a deterministic, human-readable description of the operations the +# backend will perform. Nothing is executed until the plan has been displayed +# and explicitly approved (see install.sh). + +declare -ga PLAN_LINES=() +declare -ga PLAN_STEPS=() + +_plan_add() { PLAN_LINES+=("$@"); } +_step() { PLAN_STEPS+=("$*"); } + +# plan_swap_mib - swapfile size in MiB derived from installed RAM +plan_swap_mib() { + local mem + mem="$(hw_mem_total_mib)" + [[ -n "$mem" ]] || mem=4096 + local swap=$((mem / 2)) + ((swap < 1024)) && swap=1024 + ((swap > 8192)) && swap=8192 + printf '%s' "$swap" +} + +# plan_storage_sizes - sets PLAN_EFI_MIB and PLAN_LUKS_MIB +plan_storage_sizes() { + local disk="${1:-$(config_get TARGET_DISK)}" total efi + PLAN_EFI_MIB="$(config_get EFI_SIZE_MIB)" + [[ "$PLAN_EFI_MIB" =~ ^[0-9]+$ ]] || PLAN_EFI_MIB=1024 + total=0 + if [[ -b "$disk" ]]; then + total="$(disk_size_bytes "$disk")" + fi + PLAN_LUKS_MIB=$(( (total / 1048576) - PLAN_EFI_MIB - 2 )) + ((PLAN_LUKS_MIB < 0)) && PLAN_LUKS_MIB=0 +} + +# plan_generate - build PLAN_LINES and PLAN_STEPS from CFG +plan_generate() { + PLAN_LINES=() + PLAN_STEPS=() + + local disk hostname locale tz username fs enc kprofile desktop policy + disk="$(config_get TARGET_DISK)" + hostname="$(config_get HOSTNAME)" + locale="$(config_get LOCALE)" + tz="$(config_get TIMEZONE)" + username="$(config_get USERNAME)" + fs="$(config_get FILESYSTEM)" + enc="$(config_get ENCRYPTION)" + kprofile="$(config_get KERNEL_PROFILE)" + desktop="$(config_get DESKTOP_PROFILE)" + policy="$(config_get PACKAGE_POLICY)" + + _plan_add "Installation plan" + _plan_add "=================" + _plan_add "" + _plan_add "System:" + _plan_add " Distribution : $(config_get DISTRO_NAME)" + _plan_add " Architecture : $(config_get ARCH)" + _plan_add " Init system : $(config_get INIT_SYSTEM)" + _plan_add " Firmware : $(hw_firmware_mode)" + _plan_add "" + _plan_add "Identity:" + _plan_add " Hostname : $hostname" + _plan_add " Keymap : $(config_get KEYMAP)" + _plan_add " Locale : $locale" + _plan_add " Timezone : $tz" + _plan_add " User : ${username:-}" + _plan_add "" + _plan_add "Storage:" + _plan_add " Target disk : ${disk:-}" + if [[ -n "$disk" && -b "$disk" ]]; then + _plan_add " Disk model : $(disk_model "$disk")" + _plan_add " Disk size : $(disk_size_human "$(disk_size_bytes "$disk")")" + fi + _plan_add " Partitioning : GPT (${PARTITION_SCHEME:-whole_disk})" + _plan_add " Encryption : ${enc:-none}" + _plan_add " Filesystem : $fs" + _plan_add "" + _plan_add " Layout:" + _plan_add " EFI System Partition (FAT32) $(config_get EFI_SIZE_MIB) MiB -> $(config_get EFI_MOUNT)" + _plan_add " $(printf '%-36s' "${enc^^} container") remainder" + _plan_add " $(printf '%-34s' "$fs")" + local subvol + for subvol in $(config_get BTRFS_SUBVOLS); do + _plan_add " $subvol" + done + _plan_add "" + _plan_add "Boot and kernel:" + _plan_add " Bootloader : $(config_get BOOTLOADER) (BLS entries)" + _plan_add " Unified UKI : $(config_get KERNEL_UKI) (deferred; BLS used)" + _plan_add " Kernel : $(kernel_select_package 2>/dev/null || config_get KERNEL_PACKAGE) ($kprofile profile)" + _plan_add " Keep kernels : $(config_get KEEP_KERNELS)" + _plan_add "" + _plan_add "Software:" + _plan_add " Package policy : $policy" + _plan_add " Binary pkgs : $(config_get FEATURES_BINPKG)" + _plan_add " Accept license : $(config_get ACCEPT_LICENSE)" + _plan_add " Desktop : $desktop" + _plan_add " Flatpak : $(config_get FLATPAK)" + _plan_add " Audio : $(config_get AUDIO_STACK)" + _plan_add " AI assistant : $(config_get AI_ENABLED)" + + # Ordered execution steps (names map to backend functions in install.sh). + _step "storage_prepare" + _step "stage_install" + _step "fstab_generate" + _step "portage_configure" + _step "packages_base" + _step "kernel_install" + _step "boot_install" + _step "users_configure" + _step "services_configure" + _step "desktop_install" + _step "finalize" +} + +# plan_render - print the full plan +plan_render() { printf '%s\n' "${PLAN_LINES[@]}"; } + +# plan_destructive_preview - the scary, explicit summary shown before wiping +plan_destructive_preview() { + local disk enc fs + disk="$(config_get TARGET_DISK)" + enc="$(config_get ENCRYPTION)" + fs="$(config_get FILESYSTEM)" + printf 'TARGET: %s\n' "$disk" + printf '\n' + printf 'ALL DATA ON THIS DEVICE WILL BE DESTROYED.\n' + printf 'This cannot be undone.\n' + printf '\n' + printf ' EFI (FAT32): %s MiB\n' "$(config_get EFI_SIZE_MIB)" + if [[ "$enc" != "none" && -n "$enc" ]]; then + printf ' %s (passphrase): remainder\n' "${enc^^}" + fi + printf ' %s:\n' "$fs" + local subvol + for subvol in $(config_get BTRFS_SUBVOLS); do + printf ' %s\n' "$subvol" + done + printf '\n' + printf 'Existing partitions on the target:\n' + disk_layout_text "$disk" 2>/dev/null | sed 's/^/ /' +} diff --git a/installer/lib/portage.sh b/installer/lib/portage.sh new file mode 100644 index 0000000..54c3cd3 --- /dev/null +++ b/installer/lib/portage.sh @@ -0,0 +1,363 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Portage configuration and base-system installation. +# +# Portage stays the authoritative package manager. This module writes a +# sensible initial configuration, resolves the stable systemd stage3 and runs +# emerge inside the target chroot. + +# portage_detect_cpu_flags - CPU_FLAGS_X86 from /proc/cpuinfo (deterministic) +portage_detect_cpu_flags() { + local -a wanted=(aes avx avx2 avx512f avx512bw avx512cd avx512dq avx512vl + bmi1 bmi2 f16c fma mmx mmxext pclmul popcnt rdrand sha sse sse2 sse3 + sse4_1 sse4_2 ssse3 xop) + local -A flags=() + local f w + for f in $(awk -F': ' '/^flags/{print $2; exit}' /proc/cpuinfo 2>/dev/null); do + flags[$f]=1 + done + local out=() + for w in "${wanted[@]}"; do + [[ -n "${flags[$w]:-}" ]] && out+=("$w") + done + printf '%s' "${out[*]}" +} + +portage_detect_video_cards() { + local vendors cards=() + vendors="$(hw_gpu_vendors)" + [[ "$vendors" == *intel* ]] && cards+=(intel) + [[ "$vendors" == *amd* ]] && cards+=(amdgpu radeonsi) + [[ "$vendors" == *nvidia* ]] && cards+=(nvidia) + ((${#cards[@]})) || cards+=(dummy) + printf '%s' "${cards[*]}" +} + +# portage_makeopts - parallel build width bounded by RAM +portage_makeopts() { + local cores mem jobs load + cores="$(hw_cpu_cores)"; [[ "$cores" =~ ^[0-9]+$ ]] || cores=4 + mem="$(hw_mem_total_mib)"; [[ "$mem" =~ ^[0-9]+$ ]] || mem=4096 + jobs=$((cores + 1)) + local mem_jobs=$((mem / 2048)) + ((mem_jobs < 1)) && mem_jobs=1 + ((jobs > mem_jobs)) && jobs=$mem_jobs + ((jobs < 1)) && jobs=1 + load="$cores" + printf -- '-j%s -l%s' "$jobs" "$load" +} + +portage_write_make_conf() { + local root="$1" + local mac="$root/etc/portage/make.conf" + mkdir -p "$(dirname "$mac")" + { + printf '# %s Portage configuration\n' "$(config_get DISTRO_NAME)" + printf '# Generated by the installer. Safe to edit.\n\n' + printf 'COMMON_FLAGS="-O2 -pipe -march=native"\n' + printf 'CFLAGS="${COMMON_FLAGS}"\n' + printf 'CXXFLAGS="${COMMON_FLAGS}"\n' + printf 'FCFLAGS="${COMMON_FLAGS}"\n' + printf 'FFLAGS="${COMMON_FLAGS}"\n\n' + printf 'MAKEOPTS="%s"\n' "$(portage_makeopts)" + printf 'EMERGE_DEFAULT_OPTS="--binpkg-respect-use=y --with-bdeps=y"\n\n' + printf 'ACCEPT_KEYWORDS="amd64"\n' + printf 'ACCEPT_LICENSE="%s"\n\n' "$(config_get ACCEPT_LICENSE)" + printf '# Keep the global USE set close to the profile/binhost baseline so that\n' + printf '# signed binaries can be reused; per-package USE lives in package.use.\n' + printf '# dbus/policykit are part of the standard systemd desktop baseline and\n' + printf '# are required by NetworkManager/wpa_supplicant and polkit respectively.\n' + printf 'USE="systemd dbus policykit"\n' + printf 'VIDEO_CARDS="%s"\n' "$(portage_detect_video_cards)" + printf 'INPUT_DEVICES="libinput"\n' + printf 'LINGUAS="en"\n' + } >"$mac" + log_info "wrote $mac" +} + +portage_write_repos_conf() { + local root="$1" + local dir="$root/etc/portage/repos.conf" + mkdir -p "$dir" + { + printf '[gentoo]\n' + printf 'location = /var/db/repos/gentoo\n' + printf 'sync-type = rsync\n' + printf 'sync-uri = rsync://rsync.gentoo.org/gentoo-portage\n' + printf 'auto-sync = yes\n' + } >"$dir/gentoo.conf" + log_info "wrote $dir/gentoo.conf" +} + +portage_write_binrepos() { + local root="$1" + local dir="$root/etc/portage/binrepos.conf" + mkdir -p "$dir" + { + printf '[gentoo]\n' + printf 'priority = 1\n' + printf 'sync-uri = %s\n' "$(config_get BINHOST_URI)" + printf 'location = /var/cache/binhost/gentoo\n' + printf 'verify-signature = true\n' + } >"$dir/gentoo.conf" + log_info "wrote $dir/gentoo.conf" +} + +portage_write_package_files() { + local root="$1" + local dir="$root/etc/portage/package.use" + mkdir -p "$dir" + { + printf '# %s installer policy\n' "$(config_get DISTRO_NAME)" + printf '# Core system: systemd is the init system.\n' + printf '# policykit is required by sys-auth/polkit[systemd];\n' + printf '# cryptsetup builds systemd-cryptsetup for the encrypted root initramfs.\n' + printf 'sys-apps/systemd boot policykit cryptsetup\n' + printf '# Distribution kernel + systemd-boot UKI generation.\n' + printf '# installkernel REQUIRED_USE: systemd-boot? ( systemd ), ukify? ( uki )\n' + printf 'sys-kernel/installkernel dracut systemd systemd-boot uki\n' + printf 'sys-apps/dbus systemd\n' + printf 'sys-auth/polkit systemd\n' + printf 'sys-apps/util-linux systemd\n' + printf '# Networking\n' + printf 'net-misc/networkmanager systemd\n' + printf '# Audio (PipeWire + WirePlumber are the standard stack)\n' + printf 'media-video/pipewire sound-server\n' + printf 'media-video/wireplumber\n' + if [[ "$(config_get DESKTOP_PROFILE)" != "none" ]]; then + # Wayland-first, but GTK3/polkit-gnome still need cairo/gtk built with + # X support (XWayland and the GTK X11 backend). Keep Wayland enabled too. + printf '# Desktop (Wayland-first, XWayland compatibility)\n' + printf 'x11-libs/cairo X\n' + printf 'x11-libs/gtk+ X wayland\n' + printf 'gui-libs/gtk wayland\n' + printf 'media-libs/libglvnd X\n' + printf 'x11-terms/kitty wayland\n' + printf 'media-video/pipewire systemd\n' + fi + } >"$dir/phoebus" + log_info "wrote $dir/phoebus" + + # Narrowly scoped testing keywords. Gentoo currently keywords linux-firmware + # and some Wayland components as testing-only; these are hardware/desktop + # enablement and are justified explicitly rather than globally enabling + # ~amd64. + local ak="$root/etc/portage/package.accept_keywords" + mkdir -p "$ak" + { + printf '# Phoebus: scoped testing keywords for hardware/desktop enablement.\n' + printf '# This is NOT a global ~amd64 switch.\n' + printf 'sys-kernel/linux-firmware\n' + printf 'gui-wm/dwl\n' + } >"$ak/phoebus" + log_info "wrote $ak/phoebus" +} + +# portage_select_profile ROOT +portage_select_profile() { + local root="$1" profile + profile="$(config_get GENTOO_PROFILE)" + local link="$root/etc/portage/make.profile" + mkdir -p "$(dirname "$link")" + rm -f "$link" + ln -s "/var/db/repos/gentoo/profiles/$profile" "$link" + log_info "profile -> $profile" +} + +# portage_stage3_url - resolve the stable systemd stage3 URL +portage_stage3_url() { + local pinned + pinned="$(config_get STAGE3_URL)" + if [[ -n "$pinned" ]]; then printf '%s' "$pinned"; return 0; fi + local base latest rel + base="$(config_get STAGE3_MIRROR)" + latest="$base/current-stage3-amd64-systemd/latest-stage3-amd64-systemd.txt" + if command -v curl >/dev/null 2>&1; then + # The latest-*.txt file is PGP-clearsigned and contains a line such as: + # stage3-amd64-systemd-20260913T163055Z.tar.xz 290634984 + rel="$(curl -fsSL "$latest" 2>/dev/null | \ + awk '$1 ~ /^stage3-amd64-systemd-.*\.tar\.xz$/{print $1; exit}')" + fi + if [[ -z "$rel" ]]; then + log_warn "could not resolve latest stage3 (offline?); set STAGE3_URL explicitly" + return 1 + fi + printf '%s/current-stage3-amd64-systemd/%s' "$base" "$rel" +} + +# portage_verify_stage3_signature FILE +# Verifies the clearsigned DIGESTS file with the Gentoo release key that the +# stage3 ships. Fails closed when gpg and the key are available. +portage_verify_stage3_signature() { + local digests="$1" key="/usr/share/openpgp-keys/gentoo-release.asc" home rc=0 + command -v gpg >/dev/null 2>&1 || { log_warn "gpg unavailable; skipping signature check"; return 0; } + [[ -r "$key" ]] || { log_warn "Gentoo release key not found; skipping signature check"; return 0; } + home="$(mktemp -d)" + if ! GNUPGHOME="$home" gpg --batch --quiet --import "$key" >/dev/null 2>>"$PHOEBUS_LOG_FILE" 2>&1; then + log_warn "could not import Gentoo release key; skipping signature check" + rm -rf "$home" + return 0 + fi + if GNUPGHOME="$home" gpg --batch --verify "$digests" >>"$PHOEBUS_LOG_FILE" 2>&1; then + log_info "stage3 DIGESTS signature verified" + else + log_error "stage3 DIGESTS signature verification FAILED" + rc=1 + fi + rm -rf "$home" + return $rc +} + +# portage_fetch_stage3 DESTDIR - download and verify the stage3 tarball +portage_fetch_stage3() { + local dest="$1" url base expected got want digests + url="$(portage_stage3_url)" || return 1 + base="${url##*/}" + expected="$(config_get STAGE3_SHA256)" + log_info "stage3 URL: $url" + run_cmd "download stage3" curl -fL --retry 3 -o "$dest" "$url" || return 1 + + if [[ -n "$expected" ]]; then + got="$(sha256sum "$dest" | awk '{print $1}')" + if [[ "$got" != "$expected" ]]; then + log_error "stage3 checksum mismatch (expected $expected, got $got)" + return 1 + fi + log_info "stage3 checksum verified (pinned SHA-256)" + return 0 + fi + + digests="${dest}.DIGESTS" + if ! run_cmd "download stage3 DIGESTS" curl -fsSL -o "$digests" "$url.DIGESTS"; then + log_warn "could not fetch stage3 DIGESTS; checksum not verified" + return 0 + fi + portage_verify_stage3_signature "$digests" || return 1 + want="$(awk -v f="$base" 'length($1)==128 && $2==f{print $1; exit}' "$digests")" + if [[ -z "$want" ]]; then + log_warn "no SHA-512 entry for $base in DIGESTS" + rm -f "$digests" + return 0 + fi + got="$(sha512sum "$dest" | awk '{print $1}')" + rm -f "$digests" + if [[ "$got" != "$want" ]]; then + log_error "stage3 SHA-512 mismatch (expected $want, got $got)" + return 1 + fi + log_info "stage3 SHA-512 verified against signed DIGESTS" + return 0 +} + +# portage_extract_stage3 ROOT TARBALL +portage_extract_stage3() { + local root="$1" tarball="$2" + run_destructive "extract stage3 into $root" \ + tar --xattrs --xattrs-include='*.*' --numeric-owner -xpf "$tarball" -C "$root" +} + +# portage_chroot ROOT CMD... - run a command inside the target +portage_chroot() { + local root="$1"; shift + run_cmd "chroot: $*" chroot "$root" \ + /usr/bin/env -i \ + PATH=/usr/sbin:/usr/bin:/sbin:/bin \ + HOME=/root TERM="${TERM:-xterm}" LANG=C TMPDIR=/tmp \ + "$@" +} + +# portage_chroot_stdin ROOT INPUT CMD... - chroot with INPUT on stdin. +# Used for secrets such as password hashes; INPUT is never logged. +portage_chroot_stdin() { + local root="$1" input="$2"; shift 2 + if config_bool DRY_RUN; then + log_line INFO "[dry-run] chroot: $* (stdin hidden)" + return 0 + fi + log_line INFO "chroot: $* (stdin hidden)" + printf '%s\n' "$input" | chroot "$root" \ + /usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root LANG=C TMPDIR=/tmp \ + "$@" >>"$PHOEBUS_LOG_FILE" 2>&1 + local status=$? + log_line INFO "chroot: $* :: exit status $status" + return $status +} + +# portage_base_packages - packages every Phoebus system needs beyond stage3. +# cryptsetup and btrfs-progs are required by dracut to build an initramfs that +# can unlock and mount the encrypted Btrfs root. +portage_base_packages() { + printf '%s\n' \ + app-admin/sudo \ + net-misc/networkmanager \ + sys-auth/polkit \ + sys-fs/cryptsetup \ + sys-fs/btrfs-progs +} + +# portage_sync ROOT - initialise the repository over rsync (rsync ships in the +# stage3; curl/wget do not). +portage_sync() { + local root="$1" + portage_chroot "$root" emerge --sync +} + +# portage_verification_setup ROOT +# Populate /etc/portage/gnupg with the Gentoo release key so that signed +# binary packages can be verified. getuto ships in the stage3. +portage_verification_setup() { + local root="$1" + portage_chroot "$root" getuto +} + +# portage_init_machine_id ROOT +# The systemd stage3 ships no /etc/machine-id. Generate one before the kernel +# is installed so kernel-install has stable machine identification. +portage_init_machine_id() { + local root="$1" + portage_chroot "$root" systemd-machine-id-setup +} + +# portage_write_locale_gen ROOT LOCALE - ensure the chosen locale is generated +portage_write_locale_gen() { + local root="$1" locale="$2" file="$1/etc/locale.gen" + [[ -n "$locale" ]] || return 0 + [[ -f "$file" ]] || { mkdir -p "$root/etc"; : >"$file"; } + if ! grep -qE "^[[:space:]]*${locale//./\\.}[[:space:]]" "$file"; then + printf '%s UTF-8\n' "$locale" >>"$file" + log_info "locale.gen: enabled $locale" + fi +} + +# portage_emerge ROOT PACKAGES... +# Group packages by policy decision and run one emerge per group. This keeps +# the dependency graph solve to a minimum and passes --getbinpkg only to the +# group that should prefer binaries. +portage_emerge() { + local root="$1"; shift + local pkg decision + local -a bin_pkgs=() src_pkgs=() + for pkg in "$@"; do + [[ -n "$pkg" ]] || continue + decision="$(pkgpolicy_decide "$pkg")" + log_info "policy: $pkg -> $decision" + if [[ "$decision" == "binary" ]]; then + bin_pkgs+=("$pkg") + else + src_pkgs+=("$pkg") + fi + done + local status=0 + if ((${#src_pkgs[@]})); then + log_info "emerge (source): ${src_pkgs[*]}" + portage_chroot "$root" emerge --ask=n --quiet-build=y \ + --binpkg-respect-use=y "${src_pkgs[@]}" || { log_error "source emerge failed"; status=1; } + fi + if ((status == 0 && ${#bin_pkgs[@]})); then + log_info "emerge (binary): ${bin_pkgs[*]}" + portage_chroot "$root" emerge --ask=n --quiet-build=y \ + --getbinpkg --binpkg-respect-use=y "${bin_pkgs[@]}" || { log_error "binary emerge failed"; status=1; } + fi + return $status +} diff --git a/installer/lib/state.sh b/installer/lib/state.sh new file mode 100644 index 0000000..cd4c680 --- /dev/null +++ b/installer/lib/state.sh @@ -0,0 +1,135 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Installer configuration state. +# +# All user choices live in the associative array CFG. The state is deliberately +# kept separate from the UI so that an unattended installation can be driven +# from a plain configuration file. + +declare -gA CFG=() +declare -g CONFIG_FILE="${CONFIG_FILE:-}" + +# config_default KEY VALUE +# Set KEY to VALUE only when it has not been set yet. This lets a user +# config file loaded later override the shipped defaults. +config_default() { + local key="$1" value="${2-}" + if [[ -z "${CFG[$key]+set}" ]]; then + CFG[$key]="$value" + fi +} + +# config_set KEY VALUE +config_set() { + local key="$1" value="${2-}" + CFG[$key]="$value" +} + +# config_get KEY [DEFAULT] +config_get() { + local key="$1" default="${2-}" + if [[ -n "${CFG[$key]+set}" ]]; then + printf '%s' "${CFG[$key]}" + else + printf '%s' "$default" + fi +} + +# config_is KEY VALUE - boolean helper +config_is() { + [[ "$(config_get "$1")" == "$2" ]] +} + +config_bool() { + case "$(config_get "$1")" in + yes|true|1|on) return 0 ;; + *) return 1 ;; + esac +} + +# config_load_defaults [FILE] +config_load_defaults() { + local file="${1:-$PHOEBUS_ROOT/config/defaults.conf}" + [[ -r "$file" ]] || return 1 + # shellcheck source=/dev/null + source "$file" +} + +# Decode a value from a config file. Supports plain, single- and double-quoted +# values. This is not a general shell evaluator on purpose: configuration files +# are data, and must never execute code. +config_decode_value() { + local raw="$1" + case "$raw" in + \'*\') + raw="${raw#\'}" + raw="${raw%\'}" + raw="${raw//\'\\\'\'/\'}" + ;; + \"*\") + raw="${raw#\"}" + raw="${raw%\"}" + ;; + esac + printf '%s' "$raw" +} + +# config_load_file FILE +config_load_file() { + local file="$1" line key value + [[ -r "$file" ]] || return 1 + while IFS= read -r line || [[ -n "$line" ]]; do + [[ "$line" =~ ^[[:space:]]*# ]] && continue + [[ "$line" =~ ^[[:space:]]*$ ]] && continue + if [[ "$line" =~ ^([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then + key="${BASH_REMATCH[1]}" + value="$(config_decode_value "${BASH_REMATCH[2]}")" + CFG[$key]="$value" + fi + done <"$file" + CONFIG_FILE="$file" +} + +# config_save_file FILE +config_save_file() { + local file="$1" key + local dir + dir="$(dirname -- "$file")" + mkdir -p "$dir" + { + printf '# Phoebus OS installer configuration\n' + printf '# Generated: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || echo unknown)" + printf '# NOTE: never place passwords, passphrases or API keys in this file.\n\n' + local -a keys + mapfile -t keys < <(printf '%s\n' "${!CFG[@]}" | sort) + for key in "${keys[@]}"; do + case "$key" in + LUKS_PASSPHRASE|ROOT_PASSWORD|USER_PASSWORD|AI_API_KEY) + continue ;; + esac + printf "%s='%s'\n" "$key" "${CFG[$key]//\'/\'\\\'\'}" + done + } >"$file" +} + +# config_summary - stable, sorted KEY=value dump (for logs, values redacted) +config_dump() { + local key + local -a keys + mapfile -t keys < <(printf '%s\n' "${!CFG[@]}" | sort) + for key in "${keys[@]}"; do + printf '%s=%s\n' "$key" "$(redact_value "$key" "${CFG[$key]}")" + done +} + +# redact_value KEY VALUE - never emit secret material +redact_value() { + local key="$1" value="$2" + case "$key" in + *PASSWORD*|*PASSPHRASE*|*API_KEY*|*TOKEN*|*SECRET*) + if [[ -n "$value" ]]; then printf ''; else printf ''; fi + ;; + *) printf '%s' "$value" ;; + esac +} diff --git a/installer/lib/users.sh b/installer/lib/users.sh new file mode 100644 index 0000000..63c1443 --- /dev/null +++ b/installer/lib/users.sh @@ -0,0 +1,127 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# User account configuration. +# +# Passwords are hashed immediately and held only as hashes. Plaintext is never +# written to disk, the config file or the log. + +declare -g USER_PASSWORD="${USER_PASSWORD:-}" +declare -g ROOT_PASSWORD="${ROOT_PASSWORD:-}" + +# users_hash PASSWORD - SHA-512 crypt hash (openssl present in the live image) +users_hash() { + local pw="$1" hash + if command -v openssl >/dev/null 2>&1; then + hash="$(printf '%s' "$pw" | openssl passwd -6 -stdin 2>/dev/null)" + fi + [[ -n "$hash" ]] || return 1 + printf '%s' "$hash" +} + +# users_prompt_passwords - collect and hash passwords (TUI or tty) +users_prompt_passwords() { + local user rootpw + if declare -F ui_passwordbox >/dev/null 2>&1; then + ui_passwordbox "User password" "Password for $(config_get USERNAME):" || return 1 + user="$UI_RESULT" + ui_passwordbox "User password" "Repeat password:" || return 1 + [[ "$user" == "$UI_RESULT" ]] || { log_error "user passwords did not match"; return 1; } + ui_passwordbox "Root password" "Password for root (leave blank to lock root):" || return 1 + rootpw="$UI_RESULT" + else + read -r -s -p "User password: " user; printf '\n' >&2 + read -r -s -p "Root password (blank to lock): " rootpw; printf '\n' >&2 + fi + secret_register "$user" + secret_register "$rootpw" + USER_PASSWORD="$user" + ROOT_PASSWORD="$rootpw" + return 0 +} + +# users_create ROOT - create the primary account and lock root by default +# users_ensure_groups ROOT GROUPS +# Create missing supplementary groups and return the subset that now exists. +# A minimal stage3 does not define render/libinput/plugdev/power, and +# useradd -G fails outright if any listed group is absent. +users_ensure_groups() { + local root="$1" groups="$2" g out="" + local saved_ifs="$IFS" + IFS=, + for g in $groups; do + [[ -z "$g" ]] && continue + if ! grep -q "^$g:" "$root/etc/group" 2>/dev/null; then + portage_chroot "$root" groupadd -r "$g" || log_warn "could not create group $g" + fi + if grep -q "^$g:" "$root/etc/group" 2>/dev/null; then + out="${out:+$out,}$g" + else + log_warn "group $g not available; skipping" + fi + done + IFS="$saved_ifs" + printf '%s' "$out" +} + +users_create() { + local root="$1" username fullname groups shell userhash roothash + username="$(config_get USERNAME)" + fullname="$(config_get USER_FULLNAME)" + shell="$(config_get ROOT_SHELL)" + [[ -n "$username" ]] || { log_error "no username configured"; return 1; } + + groups="$(users_ensure_groups "$root" "$(config_get USER_GROUPS)")" + local -a uargs=(-m -U -s "$shell" -c "$fullname") + [[ -n "$groups" ]] && uargs+=(-G "$groups") + uargs+=("$username") + portage_chroot "$root" useradd "${uargs[@]}" || { + log_error "useradd failed"; return 1; } + + userhash="$(users_hash "$USER_PASSWORD")" + if [[ -n "$userhash" ]]; then + portage_chroot_stdin "$root" "$username:$userhash" chpasswd -e || { + log_error "could not set password for $username"; return 1; } + log_info "password set for $username" + else + log_warn "no password set for $username (account locked)" + fi + + if [[ -n "$ROOT_PASSWORD" ]]; then + roothash="$(users_hash "$ROOT_PASSWORD")" + portage_chroot_stdin "$root" "root:$roothash" chpasswd -e || { + log_warn "could not set root password"; } + log_info "root password set" + else + portage_chroot "$root" passwd -l root || true + log_info "root account locked (no root password supplied)" + fi + USER_PASSWORD="" ROOT_PASSWORD="" +} + +# users_configure_sudo ROOT - wheel group may sudo, with a password +users_configure_sudo() { + local root="$1" + local dir="$root/etc/sudoers.d" + mkdir -p "$dir" + { + printf '# Members of the wheel group may run commands as root.\n' + printf '%%wheel ALL=(ALL:ALL) ALL\n' + } >"$dir/10-wheel" + chmod 0440 "$dir/10-wheel" + if [[ -x "$root/usr/sbin/visudo" || -x "$root/sbin/visudo" ]]; then + portage_chroot "$root" visudo -cf /etc/sudoers.d/10-wheel || { + log_error "invalid sudoers file"; return 1; } + fi + log_info "sudo configured for wheel" +} + +# users_verify ROOT +users_verify() { + local root="$1" username + username="$(config_get USERNAME)" + grep -q "^$username:" "$root/etc/passwd" || { + log_error "user $username missing from target"; return 1; } + [[ -d "$root/home/$username" ]] || log_warn "home directory for $username not found" + return 0 +} diff --git a/installer/lib/validation.sh b/installer/lib/validation.sh new file mode 100644 index 0000000..039176b --- /dev/null +++ b/installer/lib/validation.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Configuration validation. +# +# Pure(ish) decision logic, separated from the TUI so it can be unit tested and +# reused for unattended installs. validate_config prints one problem per line +# and returns the number of problems found. + +validate_hostname() { + local h="$1" + [[ ${#h} -ge 1 && ${#h} -le 63 ]] || { printf 'hostname must be 1-63 characters\n'; return 1; } + [[ "$h" =~ ^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?$ ]] || { + printf 'hostname may only contain letters, digits and internal hyphens\n'; return 1; } + return 0 +} + +validate_username() { + local u="$1" + [[ -n "$u" ]] || { printf 'username is required\n'; return 1; } + [[ "$u" != "root" ]] || { printf 'refusing to create an account named root\n'; return 1; } + [[ ${#u} -le 32 ]] || { printf 'username must be at most 32 characters\n'; return 1; } + [[ "$u" =~ ^[a-z_][a-z0-9_-]*$ ]] || { + printf 'username must start with a lowercase letter and contain only [a-z0-9_-]\n'; return 1; } + return 0 +} + +validate_locale() { + local l="$1" + [[ -n "$l" ]] || { printf 'locale is required\n'; return 1; } + local base="${l%%.*}" + if [[ -r /usr/share/i18n/locales/$base ]] || \ + [[ -d /usr/lib/locale && -e /usr/lib/locale/locale-archive ]]; then + return 0 + fi + [[ "$l" =~ ^[A-Za-z_]+\.?[A-Za-z0-9-]*$ ]] && return 0 + printf 'locale looks malformed: %s\n' "$l" + return 1 +} + +validate_timezone() { + local tz="$1" + [[ -n "$tz" ]] || { printf 'timezone is required\n'; return 1; } + if [[ -d /usr/share/zoneinfo ]]; then + [[ -e "/usr/share/zoneinfo/$tz" && ! -d "/usr/share/zoneinfo/$tz" ]] && return 0 + printf 'unknown timezone: %s\n' "$tz" + return 1 + fi + return 0 +} + +validate_keymap() { + local km="$1" + [[ -n "$km" ]] || { printf 'keymap is required\n'; return 1; } + return 0 +} + +validate_target_disk() { + local disk="$1" + [[ -n "$disk" ]] || { printf 'no target disk selected\n'; return 1; } + [[ -b "$disk" ]] || { printf 'target is not a block device: %s\n' "$disk"; return 1; } + local reason + reason="$(disk_protected_reason "$disk")" + if [[ -n "$reason" ]]; then + printf 'refusing target %s: %s\n' "$disk" "$reason" + return 1 + fi + return 0 +} + +# validate_config [KEYS...] - print problems; return problem count +validate_config() { + local -a keys=("$@") + local problems=0 msg + ((${#keys[@]})) || keys=(HOSTNAME USERNAME LOCALE TIMEZONE KEYMAP TARGET_DISK) + + local key + for key in "${keys[@]}"; do + case "$key" in + HOSTNAME) validate_hostname "$(config_get HOSTNAME)" && true || { problems=$((problems+1)); } ;; + USERNAME) validate_username "$(config_get USERNAME)" && true || { problems=$((problems+1)); } ;; + LOCALE) validate_locale "$(config_get LOCALE)" && true || { problems=$((problems+1)); } ;; + TIMEZONE) validate_timezone "$(config_get TIMEZONE)" && true || { problems=$((problems+1)); } ;; + KEYMAP) validate_keymap "$(config_get KEYMAP)" && true || { problems=$((problems+1)); } ;; + TARGET_DISK) validate_target_disk "$(config_get TARGET_DISK)" && true || { problems=$((problems+1)); } ;; + esac + done + return "$problems" +} + +# validate_password_strength PASSWORD - print a short assessment +validate_password_strength() { + local pw="$1" score=0 + ((${#pw} >= 8)) && score=$((score+1)) + ((${#pw} >= 12)) && score=$((score+1)) + [[ "$pw" =~ [A-Z] ]] && score=$((score+1)) + [[ "$pw" =~ [a-z] ]] && score=$((score+1)) + [[ "$pw" =~ [0-9] ]] && score=$((score+1)) + [[ "$pw" =~ [^A-Za-z0-9] ]] && score=$((score+1)) + if ((score <= 2)); then printf 'weak' + elif ((score <= 4)); then printf 'fair' + else printf 'strong'; fi +} diff --git a/installer/tests/lib.sh b/installer/tests/lib.sh new file mode 100644 index 0000000..0f6f41b --- /dev/null +++ b/installer/tests/lib.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Minimal test harness. No external test framework is required (the live image +# has none, and the backend must be testable on any machine). + +TESTS_RUN=0 +TESTS_FAILED=0 +TEST_NAME="unknown" + +phoebus_test_setup() { + # shellcheck source=/dev/null + PHOEBUS_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + export PHOEBUS_ROOT + STATE_DIR="$(mktemp -d "${TMPDIR:-/tmp}/phoebus-test.XXXXXX")" + export STATE_DIR + PHOEBUS_LOG_FILE="$STATE_DIR/test.log" + export PHOEBUS_LOG_FILE + : >"$PHOEBUS_LOG_FILE" + PHOEBUS_LOG_ECHO=no + export PHOEBUS_LOG_ECHO + + local lib + for lib in state logging confirm hardware disks validation plan pkgpolicy \ + portage partitions filesystem encryption btrfs network kernel \ + boot users desktop opencode ai install; do + # shellcheck source=/dev/null + source "$PHOEBUS_ROOT/lib/$lib.sh" + done + config_load_defaults "$PHOEBUS_ROOT/config/defaults.conf" +} + +_assert() { + local ok="$1" message="$2" + TESTS_RUN=$((TESTS_RUN + 1)) + if [[ "$ok" == "1" ]]; then + printf ' ok %s\n' "$message" + else + TESTS_FAILED=$((TESTS_FAILED + 1)) + printf ' FAIL %s\n' "$message" + fi +} + +assert_eq() { + local expected="$1" actual="$2" message="${3:-equal}" + if [[ "$expected" == "$actual" ]]; then _assert 1 "$message"; else + _assert 0 "$message (expected '$expected', got '$actual')"; fi +} + +assert_neq() { + local a="$1" b="$2" message="${3:-not equal}" + if [[ "$a" != "$b" ]]; then _assert 1 "$message"; else + _assert 0 "$message (both '$a')"; fi +} + +assert_contains() { + local haystack="$1" needle="$2" message="${3:-contains}" + if [[ "$haystack" == *"$needle"* ]]; then _assert 1 "$message"; else + _assert 0 "$message (missing '$needle')"; fi +} + +assert_not_contains() { + local haystack="$1" needle="$2" message="${3:-not contains}" + if [[ "$haystack" != *"$needle"* ]]; then _assert 1 "$message"; else + _assert 0 "$message (unexpectedly found '$needle')"; fi +} + +assert_success() { + local message="$1"; shift + if "$@" >/dev/null 2>&1; then _assert 1 "$message"; else _assert 0 "$message"; fi +} + +assert_failure() { + local message="$1"; shift + if "$@" >/dev/null 2>&1; then _assert 0 "$message"; else _assert 1 "$message"; fi +} + +phoebus_test_report() { + printf '\n%s: %d run, %d failed\n' "$TEST_NAME" "$TESTS_RUN" "$TESTS_FAILED" + [[ "$TESTS_FAILED" -eq 0 ]] +} diff --git a/installer/tests/run_tests.sh b/installer/tests/run_tests.sh new file mode 100755 index 0000000..186a7aa --- /dev/null +++ b/installer/tests/run_tests.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Run all installer tests. No root privileges and no block devices required. + +set -uo pipefail +TEST_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PHOEBUS_ROOT="$(cd "$TEST_DIR/.." && pwd)" +export PHOEBUS_ROOT + +total_failed=0 +total_run=0 +failed_tests=() + +for test in "$TEST_DIR"/test_*.sh; do + [[ -f "$test" ]] || continue + printf '\n== %s ==\n' "$(basename "$test")" + if bash "$test"; then + : + else + failed_tests+=("$(basename "$test")") + total_failed=$((total_failed + 1)) + fi +done + +printf '\n========================================\n' +if ((${#failed_tests[@]})); then + printf 'FAILED test files (%d):\n' "${#failed_tests[@]}" + printf ' %s\n' "${failed_tests[@]}" + exit 1 +fi +printf 'All tests passed.\n' +exit 0 diff --git a/installer/tests/test_ai.sh b/installer/tests/test_ai.sh new file mode 100644 index 0000000..12c6be6 --- /dev/null +++ b/installer/tests/test_ai.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" +TEST_NAME="test_ai" +phoebus_test_setup + +parsed="$(ai_parse_json_kv '{"hostname":"foo","encryption":"luks2","count":3}')" +assert_contains "$parsed" "hostname=foo" "flat JSON parser: string" +assert_contains "$parsed" "encryption=luks2" "flat JSON parser: string 2" +assert_contains "$parsed" "count=3" "flat JSON parser: number" + +assert_success "HOSTNAME permitted" ai_key_allowed HOSTNAME +assert_failure "EVIL key refused" ai_key_allowed EVIL +assert_failure "LUKS_PASSPHRASE refused" ai_key_allowed LUKS_PASSPHRASE + +assert_eq "" "$(ai_validate_field ENCRYPTION luks2)" "valid encryption accepted" +assert_neq "" "$(ai_validate_field ENCRYPTION bogus)" "invalid encryption rejected" +assert_neq "" "$(ai_validate_field HOSTNAME 'bad host')" "invalid hostname rejected" +assert_neq "" "$(ai_validate_field TARGET_DISK /dev/nonexistent)" "invalid disk rejected" + +# applying a proposal with an out-of-whitelist key still validates known keys +before="$(config_get HOSTNAME)" +ai_apply_proposal '{"hostname":"good-host","evil":"rm -rf /"}' >/dev/null 2>&1 || true +assert_eq "good-host" "$(config_get HOSTNAME)" "valid proposal field applied" +assert_eq "" "$(config_get EVIL)" "unknown proposal field ignored" + +# offline translator +offline="$(ai_propose_offline "encrypt everything with btrfs and a desktop")" +assert_contains "$offline" '"encryption":"luks2"' "offline proposal sets luks2" +assert_contains "$offline" '"filesystem":"btrfs"' "offline proposal sets btrfs" +assert_contains "$offline" '"desktop_profile":"dwl"' "offline proposal sets desktop" + +# offline assistance never needs a model +assert_contains "$(ai_offline_response "encryption")" "LUKS2" "offline encryption help" + +phoebus_test_report diff --git a/installer/tests/test_btrfs_order.sh b/installer/tests/test_btrfs_order.sh new file mode 100644 index 0000000..41930b1 --- /dev/null +++ b/installer/tests/test_btrfs_order.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Regression test: subvolumes must be created before any subvol=@ mount is +# attempted. The first VM install failed because the layout was mounted before +# the subvolumes existed (mount exit 32). +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" +TEST_NAME="test_btrfs_order" +phoebus_test_setup +source "$PHOEBUS_ROOT/lib/confirm.sh" + +# Authorize destructive pseudo-commands for the fake environment. +PHOEBUS_DESTRUCTIVE_AUTHORIZED="yes" +config_set DRY_RUN "no" + +fakebin="$STATE_DIR/bin" +mkdir -p "$fakebin" +export FAKE_LOG="$STATE_DIR/calls.log" +: >"$FAKE_LOG" + +cat >"$fakebin/mount" <<'EOF' +#!/usr/bin/env bash +printf 'mount %s\n' "$*" >>"$FAKE_LOG" +exit 0 +EOF +cat >"$fakebin/umount" <<'EOF' +#!/usr/bin/env bash +printf 'umount %s\n' "$*" >>"$FAKE_LOG" +exit 0 +EOF +cat >"$fakebin/btrfs" <<'EOF' +#!/usr/bin/env bash +printf 'btrfs %s\n' "$*" >>"$FAKE_LOG" +exit 0 +EOF +chmod +x "$fakebin/mount" "$fakebin/umount" "$fakebin/btrfs" +PATH="$fakebin:$PATH" + +config_set BTRFS_SUBVOLS "@ @home @var @snapshots @swap" +btrfs_create_layout /dev/fake "$STATE_DIR/root" >/dev/null 2>&1 +rc=$? + +assert_eq "0" "$rc" "btrfs_create_layout succeeds with fake tools" + +# The first subvolume creation must precede the first subvol=@ mount. +create_line="$(grep -n 'btrfs subvolume create' "$FAKE_LOG" | head -n1 | cut -d: -f1)" +mount_line="$(grep -n 'subvol=@ ' "$FAKE_LOG" | head -n1 | cut -d: -f1)" +assert_success "subvolume create recorded" test -n "$create_line" +assert_success "subvol=@ mount recorded" test -n "$mount_line" +if [[ -n "$create_line" && -n "$mount_line" ]]; then + assert_success "subvolumes created before mounting @" test "$create_line" -lt "$mount_line" +fi + +# All five subvolumes are created. +assert_eq "5" "$(grep -c 'btrfs subvolume create' "$FAKE_LOG")" "all subvolumes created" + +phoebus_test_report diff --git a/installer/tests/test_install_dryrun.sh b/installer/tests/test_install_dryrun.sh new file mode 100644 index 0000000..1c8ba08 --- /dev/null +++ b/installer/tests/test_install_dryrun.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" +TEST_NAME="test_install_dryrun" +phoebus_test_setup +source "$PHOEBUS_ROOT/lib/confirm.sh" +source "$PHOEBUS_ROOT/lib/install.sh" + +# A dry-run must never write to the configured install root. +config_set DRY_RUN "yes" +config_set TARGET_DISK "/dev/definitely-not-a-real-disk" +config_set INSTALL_ROOT "$STATE_DIR/host-root-should-stay-empty" +config_set USERNAME "tester" +install_effective_root >/dev/null +INSTALL_TARGET_ROOT="$(install_effective_root)" + +assert_success "dry-run storage stage" install_stage_storage +assert_success "sandbox root created" test -d "$INSTALL_TARGET_ROOT" +assert_failure "host install root untouched" test -e "$(config_get INSTALL_ROOT)" + +assert_success "dry-run base stage" install_stage_base +assert_success "dry-run portage stage" install_stage_portage + +# scripts created by later stages stay inside the sandbox +assert_success "dry-run kernel profile writes to sandbox" install_stage_kernel +assert_success "kernel fragment in sandbox" test -e "$INSTALL_TARGET_ROOT/etc/kernel/config.d/00-phoebus-profile.config" + +# preflight refuses an incomplete configuration (no real target disk) +config_set DRY_RUN "no" +assert_failure "preflight rejects incomplete config" install_preflight + +phoebus_test_report diff --git a/installer/tests/test_opencode.sh b/installer/tests/test_opencode.sh new file mode 100644 index 0000000..64a4e57 --- /dev/null +++ b/installer/tests/test_opencode.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" +TEST_NAME="test_opencode" +phoebus_test_setup + +url="$(opencode_manifest_get x86_64 url)" +sha="$(opencode_manifest_get x86_64 sha256)" +assert_contains "$url" "opencode-linux-x64.tar.gz" "manifest has x86_64 url" +assert_eq "64" "${#sha}" "manifest sha256 is 64 hex chars" +assert_eq "v1.18.31" "$(opencode_version_manifest)" "manifest pins a version" + +# checksum verification +f="$STATE_DIR/artifact" +printf 'hello phoebus\n' >"$f" +good="$(sha256sum "$f" | awk '{print $1}')" +assert_success "correct checksum accepted" opencode_checksum_ok "$f" "$good" +assert_failure "wrong checksum rejected" opencode_checksum_ok "$f" "deadbeef" +assert_failure "placeholder checksum rejected" opencode_checksum_ok "$f" "0000000000000000000000000000000000000000000000000000000000000000" +assert_failure "empty checksum rejected" opencode_checksum_ok "$f" "" + +# unknown arch has no usable entry +assert_failure "unknown arch refused" opencode_manifest_get sparc url + +phoebus_test_report diff --git a/installer/tests/test_pkgpolicy.sh b/installer/tests/test_pkgpolicy.sh new file mode 100644 index 0000000..6a5f1ac --- /dev/null +++ b/installer/tests/test_pkgpolicy.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" +TEST_NAME="test_pkgpolicy" +phoebus_test_setup + +# Default is balanced and a binary source is configured. +config_set PACKAGE_POLICY "balanced" +config_set FEATURES_BINPKG "yes" +config_set BINHOST_URI "https://example.invalid/binpkgs" + +assert_eq "45" "$(pkgpolicy_compile_seconds app-editors/vim)" "known compile time (vim)" +assert_eq "300" "$(pkgpolicy_compile_seconds dev-libs/unknown)" "unknown defaults to 300s" + +assert_eq "source" "$(pkgpolicy_decide app-editors/vim)" "cheap package compiles" +assert_eq "binary" "$(pkgpolicy_decide www-client/firefox)" "huge package uses binary" +assert_eq "source" "$(pkgpolicy_decide sys-kernel/gentoo-kernel)" "kernel always compiles" + +# policy overrides +config_set PACKAGE_POLICY "source_first" +assert_eq "source" "$(pkgpolicy_decide www-client/firefox)" "source_first compiles everything" + +config_set PACKAGE_POLICY "binary_first" +assert_eq "binary" "$(pkgpolicy_decide app-editors/vim)" "binary_first prefers binaries" + +# history override +config_set PACKAGE_POLICY "balanced" +printf 'app-editors/vim\t7\t25\n' >"${STATE_DIR}/compile-times.tsv" +assert_eq "7" "$(pkgpolicy_compile_seconds app-editors/vim)" "history overrides estimate" + +# no binary host -> source even in binary_first +config_set BINHOST_URI "" +config_set PACKAGE_POLICY "binary_first" +assert_eq "source" "$(pkgpolicy_decide www-client/firefox)" "no binhost means compile" + +phoebus_test_report diff --git a/installer/tests/test_plan.sh b/installer/tests/test_plan.sh new file mode 100644 index 0000000..cbfc473 --- /dev/null +++ b/installer/tests/test_plan.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" +TEST_NAME="test_plan" +phoebus_test_setup + +config_set HOSTNAME "phoebus-test" +config_set USERNAME "tester" +config_set DESKTOP_PROFILE "dwl" +config_set PACKAGE_POLICY "balanced" + +plan_generate +plan="$(plan_render)" + +assert_contains "$plan" "Installation plan" "plan has header" +assert_contains "$plan" "phoebus-test" "plan includes hostname" +assert_contains "$plan" "tester" "plan includes username" +assert_contains "$plan" "dwl" "plan includes desktop profile" +assert_contains "$plan" "systemd" "plan includes init system" +assert_contains "$plan" "@snapshots" "plan includes snapshot subvolume" + +assert_eq "storage_prepare" "${PLAN_STEPS[0]}" "first step is storage_prepare" +assert_eq "finalize" "${PLAN_STEPS[${#PLAN_STEPS[@]}-1]}" "last step is finalize" + +# subvolume list is configurable +config_set BTRFS_SUBVOLS "@ @home @var @snapshots @swap @log" +plan_generate +assert_contains "$(plan_render)" "@log" "plan reflects configured subvolumes" + +# swap sizing is bounded +swap="$(plan_swap_mib)" +assert_success "swap size is numeric" test "$swap" -ge 1024 + +phoebus_test_report diff --git a/installer/tests/test_regressions.sh b/installer/tests/test_regressions.sh new file mode 100644 index 0000000..21bb543 --- /dev/null +++ b/installer/tests/test_regressions.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Regression tests for bugs found during the first real VM installation. +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" +TEST_NAME="test_regressions" +phoebus_test_setup + +# --- kernel cmdline: encrypted root must use rd.luks.name== ----- +config_set ENCRYPTION "luks2" +config_set LUKS_NAME "cryptroot" +FS_ROOT_PART="/dev/fake" +blkid() { printf '%s\n' "00000000-1111-2222-3333-444444444444"; } +root="$STATE_DIR/target" +mkdir -p "$root" +kernel_write_cmdline "$root" +cmdline="$(cat "$root/etc/kernel/cmdline")" +assert_contains "$cmdline" "rd.luks.name=00000000-1111-2222-3333-444444444444=cryptroot" \ + "cmdline names the LUKS mapper" +assert_contains "$cmdline" "root=/dev/mapper/cryptroot" "cmdline root is the mapper" +assert_not_contains "$cmdline" "rd.luks.uuid=" "cmdline does not use un-named rd.luks.uuid" + +# --- install.conf must declare every generator (it replaces the default) ---- +boot_write_install_conf "$root" +iconf="$(cat "$root/etc/kernel/install.conf")" +assert_contains "$iconf" "layout=bls" "install.conf uses BLS layout" +assert_contains "$iconf" "initrd_generator=dracut" "install.conf sets initrd generator" +assert_contains "$iconf" "uki_generator=none" "install.conf disables UKI for BLS" + +# dracut must be forced to include crypt/btrfs for the encrypted root +boot_write_dracut_conf "$root" +dconf="$(cat "$root/etc/dracut.conf.d/10-phoebus.conf")" +assert_contains "$dconf" "add_dracutmodules" "dracut config adds modules" +assert_contains "$dconf" "crypt" "dracut includes crypt" +assert_contains "$dconf" "btrfs" "dracut includes btrfs" + +# --- fstab must be generated after the stage3 extraction -------------------- +plan_generate +sig="" fgi="" pci="" +for i in "${!PLAN_STEPS[@]}"; do + case "${PLAN_STEPS[$i]}" in + stage_install) sig="$i" ;; + fstab_generate) fgi="$i" ;; + portage_configure) pci="$i" ;; + esac +done +assert_success "fstab_generate is a plan step" test -n "$fgi" +assert_success "stage_install precedes fstab_generate" test "$sig" -lt "$fgi" +assert_success "fstab_generate precedes portage_configure" test "$fgi" -lt "$pci" + +__fn_contains() { declare -f "$1" | grep -q "$2"; } +assert_failure "storage stage does not generate fstab" \ + __fn_contains install_stage_storage filesystem_generate_fstab +assert_success "fstab stage generates fstab" \ + __fn_contains install_stage_fstab filesystem_generate_fstab +assert_success "fstab stage creates /var/tmp" \ + __fn_contains install_stage_fstab "/var/tmp" + +# --- chroot commands set TMPDIR (systemd kernel-install requires it) -------- +assert_success "portage_chroot sets TMPDIR" \ + __fn_contains portage_chroot "TMPDIR=/tmp" +assert_success "portage_chroot_stdin sets TMPDIR" \ + __fn_contains portage_chroot_stdin "TMPDIR=/tmp" + +# --- initial cmdline includes the configured console ------------------------ +config_set KERNEL_CONSOLE "console=tty0 console=ttyS0,115200" +kernel_write_cmdline "$root" +assert_contains "$(cat "$root/etc/kernel/cmdline")" "console=ttyS0,115200" \ + "cmdline includes configured console" +config_set KERNEL_CONSOLE "console=tty0" + +# --- base packages must include the storage userspace needed by dracut ------ +basepkgs="$(portage_base_packages)" +assert_contains "$basepkgs" "sys-fs/cryptsetup" "base packages include cryptsetup" +assert_contains "$basepkgs" "sys-fs/btrfs-progs" "base packages include btrfs-progs" + +# --- systemd must be built with cryptsetup for the initramfs --------------- +pkgroot="$STATE_DIR/pkgroot" +mkdir -p "$pkgroot/etc/portage" +config_set DESKTOP_PROFILE "dwl" +portage_write_package_files "$pkgroot" +pupkg="$(cat "$pkgroot/etc/portage/package.use/phoebus")" +assert_contains "$pupkg" "sys-apps/systemd boot policykit cryptsetup" \ + "systemd built with boot/policykit/cryptsetup" +assert_contains "$pupkg" "sys-kernel/installkernel" "installkernel policy present" +assert_contains "$pupkg" "x11-libs/cairo X" "desktop enables cairo X for GTK3" +config_set DESKTOP_PROFILE "none" + +# --- fstab must mount @swap so the swapfile can be activated ---------------- +FS_EFI_PART="/dev/fake-efi" +FS_ROOT_SOURCE="/dev/fake-root" +mkdir -p "$root/etc" +filesystem_generate_fstab "$root" +fstab="$(cat "$root/etc/fstab")" +assert_contains "$fstab" "subvol=@swap" "fstab mounts @swap subvolume" +assert_contains "$fstab" "/swap/swapfile" "fstab enables the swapfile" + +# --- secrets never reach the log ------------------------------------------- +secret_register "topsecretvalue123" +run_cmd "secret test" /bin/true "topsecretvalue123" >/dev/null 2>&1 +logtext="$(cat "$PHOEBUS_LOG_FILE")" +assert_not_contains "$logtext" "topsecretvalue123" "secret is scrubbed from the log" + +phoebus_test_report diff --git a/installer/tests/test_safety.sh b/installer/tests/test_safety.sh new file mode 100644 index 0000000..88020c3 --- /dev/null +++ b/installer/tests/test_safety.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" +TEST_NAME="test_safety" +phoebus_test_setup +# confirm.sh and install.sh are not loaded by lib.sh; load them explicitly. +source "$PHOEBUS_ROOT/lib/confirm.sh" +source "$PHOEBUS_ROOT/lib/install.sh" + +# destructive commands are blocked until authorized +destructive_revoke +assert_failure "run_destructive blocked when unauthorized" run_destructive "test op" true + +# after authorization, dry-run still prevents execution +config_set DRY_RUN "yes" +destructive_grant +assert_success "run_destructive allowed after grant (dry-run)" run_destructive "test op" /bin/true +destructive_revoke + +# effective root is a sandbox in dry-run, never the configured target +config_set INSTALL_ROOT "/mnt/do-not-touch" +config_set DRY_RUN "yes" +root="$(install_effective_root)" +assert_neq "/mnt/do-not-touch" "$root" "dry-run uses a sandbox root" +assert_contains "$root" "dry-run-root" "sandbox root name is explicit" + +# in a real run the configured root is used +config_set DRY_RUN "no" +assert_eq "/mnt/do-not-touch" "$(install_effective_root)" "real root used when not dry-run" + +phoebus_test_report diff --git a/installer/tests/test_state.sh b/installer/tests/test_state.sh new file mode 100644 index 0000000..3f44747 --- /dev/null +++ b/installer/tests/test_state.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" +TEST_NAME="test_state" +phoebus_test_setup + +assert_eq "phoebus" "$(config_get HOSTNAME)" "default hostname" + +config_set HOSTNAME "testbox" +assert_eq "testbox" "$(config_get HOSTNAME)" "config_set updates value" + +config_default HOSTNAME "should-not-apply" +assert_eq "testbox" "$(config_get HOSTNAME)" "config_default does not override" + +config_set SECRET_KEY "s3cr3t" +config_set USERNAME "alice" + +local_file="$STATE_DIR/state.conf" +config_save_file "$local_file" +assert_success "config file written" test -s "$local_file" + +config_set HOSTNAME "changed" +config_load_file "$local_file" +assert_eq "testbox" "$(config_get HOSTNAME)" "round-trip restores value" +assert_eq "alice" "$(config_get USERNAME)" "round-trip restores username" + +assert_not_contains "$(cat "$local_file")" "PASSWORD" "secret keys with PASSWORD are not saved" + +# redaction +secret_register "hunter2" +secret_register "topsecret" +assert_eq "pw=" "$(redact_scrub "pw=hunter2")" "registered secret is scrubbed" +assert_eq "x" "$(redact_scrub "x")" "normal text unchanged" +assert_eq "" "$(redact_value USER_PASSWORD "abc")" "redact_value hides password" +assert_eq "abc" "$(redact_value HOSTNAME "abc")" "redact_value keeps non-secret" + +phoebus_test_report diff --git a/installer/tests/test_syntax.sh b/installer/tests/test_syntax.sh new file mode 100644 index 0000000..17f0dff --- /dev/null +++ b/installer/tests/test_syntax.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" +TEST_NAME="test_syntax" +PHOEBUS_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +failures=0 +count=0 +while IFS= read -r file; do + count=$((count + 1)) + if bash -n "$file" 2>/dev/null; then + printf ' ok syntax %s\n' "${file#"$PHOEBUS_ROOT"/}" + else + printf ' FAIL syntax %s\n' "${file#"$PHOEBUS_ROOT"/}" + bash -n "$file" 2>&1 | sed 's/^/ /' + failures=$((failures + 1)) + fi +done < <(find "$PHOEBUS_ROOT" -type f \( -name '*.sh' -o -path '*/bin/*' \) | sort) + +TESTS_RUN=$count +TESTS_FAILED=$failures +phoebus_test_report diff --git a/installer/tests/test_validation.sh b/installer/tests/test_validation.sh new file mode 100644 index 0000000..2fc34e8 --- /dev/null +++ b/installer/tests/test_validation.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" +TEST_NAME="test_validation" +phoebus_test_setup + +assert_success "valid hostname" validate_hostname "phoebus" +assert_success "hostname with hyphen" validate_hostname "my-box" +assert_failure "hostname with space" validate_hostname "bad host" +assert_failure "empty hostname" validate_hostname "" +assert_failure "hostname leading -" validate_hostname "-bad" + +assert_success "valid username" validate_username "alice" +assert_failure "root refused" validate_username "root" +assert_failure "uppercase username" validate_username "Alice" +assert_failure "empty username" validate_username "" + +assert_success "valid timezone" validate_timezone "UTC" +assert_failure "empty timezone" validate_timezone "" + +assert_failure "target not a block device" validate_target_disk "/dev/does-not-exist-xyz" +assert_failure "empty target" validate_target_disk "" + +assert_success "sr0 protected" disks_is_protected "/dev/sr0" +assert_success "loop protected" disks_is_protected "/dev/loop0" + +assert_eq "weak" "$(validate_password_strength "abc")" "short password weak" +assert_eq "weak" "$(validate_password_strength "abcdefghij")" "10 lowercase chars weak" +assert_eq "fair" "$(validate_password_strength "Abcdefghij")" "mixed-case password fair" +assert_eq "strong" "$(validate_password_strength "Abcdef1!ghijk")" "complex password strong" + +# validate_config reports missing required fields +config_set HOSTNAME "ok-host" +config_set USERNAME "" +problems="$(validate_config HOSTNAME USERNAME)" +assert_contains "$problems" "username" "validate_config flags missing username" + +phoebus_test_report diff --git a/installer/tests/vm/README.md b/installer/tests/vm/README.md new file mode 100644 index 0000000..3b531fd --- /dev/null +++ b/installer/tests/vm/README.md @@ -0,0 +1,63 @@ +# Disposable UEFI VM harness + +Proves that the installer produces a bootable encrypted system without ever +touching a physical disk. The target is always a qcow2 file. + +## Files + +- `run-vm.sh` interactive QEMU launcher (manual testing). +- `install.sh` guest-side, non-interactive installation (run in the VM). +- `serial-driver.py` host-side pexpect driver (`install` and `boot` modes). +- `test.conf.example` installer configuration used by the driver. + +## Host prerequisites + +- `qemu-system-x86_64`, `qemu-img`, OVMF firmware, Python `pexpect`. +- The reference Gentoo ISO. + +## Procedure + +Serve the installer, the stage3 and the config to the guest: + +```sh +cd /path/to/serve +tar czf installer.tar.gz -C /path/to/phoebus_os installer +cp installer/tests/vm/install.sh . +cp installer/tests/vm/test.conf.example test.conf # edit TARGET_DISK etc. +sha256sum stage3.tar.xz # set STAGE3_SHA256 +python3 -m http.server 8000 --bind 127.0.0.1 +``` + +Run the installation (driver boots the ISO kernel/initrd directly and drives +the serial console): + +```sh +QEMU_BIN=/path/to/qemu-system-x86_64 \ +QEMU_LIBDIR=/path/to/qemu/libs \ +QEMU_DATADIR=/path/to/qemu/share \ +OVMF_CODE=/path/to/OVMF_CODE_4M.fd \ +OVMF_VARS=/path/to/OVMF_VARS.fd \ +DISK=/tmp/phoebus/target.qcow2 \ +ISO=/path/to/livegui-amd64.iso \ +KERNEL=/tmp/live/boot/gentoo INITRD=/tmp/live/boot/gentoo.igz \ +INSTALL_URL=http://10.0.2.2:8000/install.sh \ +python3 installer/tests/vm/serial-driver.py install +``` + +Then boot the disk alone (ISO detached) and verify: + +```sh +DISK=/tmp/phoebus/target.qcow2 OVMF_CODE=... OVMF_VARS=... \ +python3 installer/tests/vm/serial-driver.py boot +``` + +To patch a console into an existing entry for observation, the BLS entry in +`/efi/loader/entries/*.conf` takes an `options` line; the installer can also +embed a console via `KERNEL_CONSOLE` (`GENTOO_KERNEL_CONSOLE` equivalent). + +## Safety + +- `DISK` must be a qcow2 image; never point it at `/dev/*`. +- The installer itself classifies the ISO's device as protected. +- Secrets are passed through 0600 files and are checked for leakage in the + installer log by `install.sh`. diff --git a/installer/tests/vm/install.sh b/installer/tests/vm/install.sh new file mode 100755 index 0000000..dadf249 --- /dev/null +++ b/installer/tests/vm/install.sh @@ -0,0 +1,60 @@ +#!/bin/bash +# Guest-side automation for a disposable VM installation. +# +# Run inside the Gentoo live environment. It fetches the installer and a test +# configuration from a host HTTP server (QEMU user networking reaches the host +# at 10.0.2.2), supplies secrets from 0600 files, and drives the deterministic +# backend with --install. It never uses the TUI. +# +# Environment: +# PHOEBUS_BASE_URL host base URL (default http://10.0.2.2:8000) +# PHOEBUS_CONFIG config file name on the server (default test.conf) +# LUKS_PASSPHRASE LUKS passphrase (kept in a 0600 temp file, never logged) +# USER_PASSWORD user password +# +# The test configuration pins STAGE3_URL to the same HTTP server so the +# stage3 checksum is verified without re-downloading from the internet. + +set -u +export PATH=/usr/sbin:/usr/bin:/sbin:/bin +export PHOEBUS_LOG_ECHO=yes + +BASE="${PHOEBUS_BASE_URL:-http://10.0.2.2:8000}" +CONF="${PHOEBUS_CONFIG:-test.conf}" + +echo "===PHOEBUS-DRIVER-START===" +umask 077 +printf '%s' "${LUKS_PASSPHRASE:-phoebus-luks-test}" >/tmp/luks.pw +printf '%s' "${USER_PASSWORD:-phoebus-user-test}" >/tmp/user.pw +chmod 600 /tmp/luks.pw /tmp/user.pw + +cd /tmp || exit 1 +if ! curl -fsSL "$BASE/installer.tar.gz" -o installer.tar.gz; then + echo "===FETCH-FAIL==="; poweroff -f; exit 1 +fi +rm -rf installer && tar xzf installer.tar.gz +curl -fsSL "$BASE/$CONF" -o /tmp/test.conf + +echo "=== DISKS BEFORE ===" +lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINTS + +bash installer/bin/ai-installer --config /tmp/test.conf --install --yes \ + --luks-passphrase-file /tmp/luks.pw --user-password-file /tmp/user.pw +rc=$? +echo "===INSTALL-RC=$rc===" + +LOG=/var/log/ai-installer/install.log +[ -r "$LOG" ] || LOG=/tmp/ai-installer/logs/install.log +echo "=== LOG TAIL ===" +tail -n 60 "$LOG" 2>/dev/null + +echo "===SECRET-SCAN===" +if grep -a -e "${LUKS_PASSPHRASE:-phoebus-luks-test}" \ + -e "${USER_PASSWORD:-phoebus-user-test}" "$LOG" 2>/dev/null; then + echo "SECRET_LEAK_FOUND" +else + echo "NO_SECRET_LEAK" +fi +sync +echo "===POWEROFF===" +poweroff -f diff --git a/installer/tests/vm/run-vm.sh b/installer/tests/vm/run-vm.sh new file mode 100755 index 0000000..b483a0c --- /dev/null +++ b/installer/tests/vm/run-vm.sh @@ -0,0 +1,115 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Boot a disposable UEFI VM with a scratch disk for installer testing. +# +# run-vm.sh --iso /path/to/livegui.iso --disk-size 32G --workdir /tmp/phoebus-vm +# +# The VM disk is a qcow2 file inside the work directory. No host disk is ever +# touched. Delete the work directory to discard the test. + +set -euo pipefail + +ISO="" +DISK_SIZE="32G" +WORKDIR="${TMPDIR:-/tmp}/phoebus-vm" +MEM="4096" +CPUS="4" +BOOT="d" +EXTRA=() + +usage() { + cat <<'EOF' +Usage: run-vm.sh --iso PATH [options] + +Options: + --iso PATH Live ISO to boot (required) + --disk-size SIZE Scratch disk size (default 32G) + --workdir DIR Directory for the scratch disk (default /tmp/phoebus-vm) + --mem MiB RAM in MiB (default 4096) + --cpus N vCPUs (default 4) + --disk-boot Boot from the scratch disk instead of the ISO + --help Show this help + +Requires qemu-system-x86_64 and OVMF (edk2) firmware. +EOF +} + +while (($#)); do + case "$1" in + --iso) shift; ISO="${1:-}" ;; + --disk-size) shift; DISK_SIZE="${1:-}" ;; + --workdir) shift; WORKDIR="${1:-}" ;; + --mem) shift; MEM="${1:-}" ;; + --cpus) shift; CPUS="${1:-}" ;; + --disk-boot) BOOT="c" ;; + --help|-h) usage; exit 0 ;; + *) echo "unknown option: $1" >&2; usage; exit 2 ;; + esac + shift +done + +[[ -n "$ISO" ]] || { echo "error: --iso is required" >&2; usage; exit 2; } +[[ -r "$ISO" ]] || { echo "error: cannot read ISO: $ISO" >&2; exit 2; } +command -v qemu-system-x86_64 >/dev/null 2>&1 || { + echo "error: qemu-system-x86_64 not found" >&2; exit 1; } + +# Locate OVMF firmware. +OVMF_CODE="" +OVMF_VARS_SRC="" +for cand in \ + /usr/share/OVMF/OVMF_CODE.fd \ + /usr/share/OVMF/OVMF_CODE_4M.fd \ + /usr/share/edk2/x64/OVMF_CODE.fd \ + /usr/share/edk2-ovmf/x64/OVMF_CODE.fd; do + if [[ -r "$cand" ]]; then OVMF_CODE="$cand"; fi +done +for cand in \ + /usr/share/OVMF/OVMF_VARS.fd \ + /usr/share/OVMF/OVMF_VARS_4M.fd \ + /usr/share/edk2/x64/OVMF_VARS.fd \ + /usr/share/edk2-ovmf/x64/OVMF_VARS.fd; do + if [[ -r "$cand" ]]; then OVMF_VARS_SRC="$cand"; fi +done + +[[ -n "$OVMF_CODE" ]] || { echo "error: OVMF firmware not found" >&2; exit 1; } + +mkdir -p "$WORKDIR" +DISK="$WORKDIR/phoebus-test.qcow2" +VARS="$WORKDIR/OVMF_VARS.fd" + +if [[ ! -f "$DISK" ]]; then + echo "creating scratch disk $DISK ($DISK_SIZE)" + qemu-img create -f qcow2 "$DISK" "$DISK_SIZE" >/dev/null +fi +if [[ ! -f "$VARS" ]]; then + cp "$OVMF_VARS_SRC" "$VARS" +fi + +ACCEL=() +if [[ -w /dev/kvm ]]; then ACCEL=(-enable-kvm); fi + +echo "ISO: $ISO" +echo "Disk: $DISK" +echo "Workdir: $WORKDIR" +echo "Firmware:$OVMF_CODE" +echo +echo "Inside the VM run: /path/to/installer/bin/ai-installer" +echo "Remember: the scratch disk is disposable." + +QEMU=(qemu-system-x86_64 + -machine q35 + "${ACCEL[@]}" + -m "$MEM" + -smp "$CPUS" + -cpu host + -drive if=pflash,format=raw,readonly=on,file="$OVMF_CODE" + -drive if=pflash,format=raw,file="$VARS" + -drive file="$DISK",if=virtio,format=qcow2 + -netdev user,id=n0 -device virtio-net-pci,netdev=n0 + -device virtio-vga + -boot "order=$BOOT" + -cdrom "$ISO" +) + +exec "${QEMU[@]}" "${EXTRA[@]}" diff --git a/installer/tests/vm/serial-driver.py b/installer/tests/vm/serial-driver.py new file mode 100644 index 0000000..961fdbf --- /dev/null +++ b/installer/tests/vm/serial-driver.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Headless serial driver for the disposable UEFI VM. + +Two modes: + + install : boot the live ISO kernel/initrd, run a guest script that installs + Phoebus non-interactively, then power off. + boot : boot the installed disk alone (no ISO, no -kernel), unlock LUKS, + log in and run verification commands. + +Everything is parameterised through environment variables so the script is not +tied to one host. See tests/vm/README.md for the variables. + +This script never touches a physical disk: DISK is always a qcow2 image. +""" +import os +import sys +import pexpect + +QEMU = os.environ.get("QEMU_BIN", "qemu-system-x86_64") +LIBDIR = os.environ.get("QEMU_LIBDIR", "") +DATADIR = os.environ.get("QEMU_DATADIR", "") +OVMF_CODE = os.environ["OVMF_CODE"] +OVMF_VARS = os.environ["OVMF_VARS"] +DISK = os.environ["DISK"] +ISO = os.environ.get("ISO", "") +KERNEL = os.environ.get("KERNEL", "") +INITRD = os.environ.get("INITRD", "") +SERIAL_LOG = os.environ.get("SERIAL_LOG", "/tmp/phoebus-vm-serial.log") +LUKS_PW = os.environ.get("LUKS_PASSPHRASE", "phoebus-luks-test") +USER_PW = os.environ.get("USER_PASSWORD", "phoebus-user-test") +USER = os.environ.get("USERNAME", "phoebus") +MEM = os.environ.get("VM_MEM", "8192") +SMP = os.environ.get("VM_SMP", "8") + +BLS_APPEND = ( + "root=live:CDLABEL=gentoo-amd64-livegui rd.live.dir=/ " + "rd.live.squashimg=image.squashfs cdroot console=ttyS0,115200" +) + + +def base_args(): + env = dict(os.environ) + if LIBDIR: + env["LD_LIBRARY_PATH"] = LIBDIR + args = ["-machine", "q35,accel=kvm"] + if DATADIR: + args += ["-L", DATADIR] + args += [ + "-cpu", "host", "-smp", SMP, "-m", MEM, + "-drive", f"if=pflash,format=raw,readonly=on,file={OVMF_CODE}", + "-drive", f"if=pflash,format=raw,file={OVMF_VARS}", + "-drive", f"file={DISK},if=virtio,format=qcow2", + "-netdev", "user,id=n0", "-device", "virtio-net-pci,netdev=n0,romfile=", + "-device", "virtio-rng-pci", "-vga", "std", "-display", "none", + "-serial", "stdio", "-monitor", "none", "-no-reboot", + ] + return env, args + + +def spawn(args, env): + child = pexpect.spawn(QEMU, args, env=env, timeout=600, + encoding="utf-8", codec_errors="replace", + maxread=65536) + child.delaybeforesend = 0.3 + return child + + +def do_install(): + env, args = base_args() + args += ["-drive", f"file={ISO},media=cdrom,readonly=on", + "-kernel", KERNEL, "-initrd", INITRD, "-append", BLS_APPEND] + log = open(SERIAL_LOG, "w") + child = spawn(args, env) + child.logfile = log + try: + child.expect(r"root@livecd[^\n]*# ", timeout=600) + url = os.environ.get("INSTALL_URL", "http://10.0.2.2:8000/install.sh") + child.sendline(f"curl -fsSL {url} -o /tmp/run.sh && bash /tmp/run.sh") + child.expect([r"===INSTALL-RC=([0-9]+)===", "===FETCH-FAIL===", + "Kernel panic", pexpect.EOF, pexpect.TIMEOUT], timeout=9000) + if "INSTALL-RC" in (child.after or ""): + print("INSTALL_RC", child.match.group(1), flush=True) + child.expect(["===POWEROFF===", pexpect.EOF, pexpect.TIMEOUT], timeout=600) + child.expect(pexpect.EOF, timeout=300) + finally: + child.close(force=True) + log.close() + + +def do_boot(): + env, args = base_args() + args += ["-boot", "order=c"] + checks = os.environ.get( + "BOOT_CHECKS", + "echo ===CHECKS-START===; " + "cat /proc/1/comm; systemctl is-system-running; " + "systemctl --failed --no-pager; ip -brief addr; " + "lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINTS; echo ===CHECKS-END===", + ) + log = open(SERIAL_LOG, "w") + child = spawn(args, env) + child.logfile = log + try: + child.expect([r"[Pp]assphrase", r"login:"], timeout=300) + if "assphrase" in (child.after or ""): + child.sendline(LUKS_PW) + for _ in range(5): + child.expect(r"phoebus login:", timeout=180) + child.sendline(USER) + idx = child.expect([r"[Pp]assword:", r"phoebus login:", + r"Login incorrect"], timeout=30) + if idx == 0: + child.sendline(USER_PW) + if child.expect([r"[$#] $", r"Login incorrect", + r"phoebus login:"], timeout=60) == 0: + break + child.sendline(checks) + child.expect("===CHECKS-END===", timeout=180) + print("checks complete", flush=True) + finally: + child.close(force=True) + log.close() + + +if __name__ == "__main__": + mode = sys.argv[1] if len(sys.argv) > 1 else "" + if mode == "install": + do_install() + elif mode == "boot": + do_boot() + else: + print(__doc__) + sys.exit(2) diff --git a/installer/tests/vm/test.conf.example b/installer/tests/vm/test.conf.example new file mode 100644 index 0000000..30ad764 --- /dev/null +++ b/installer/tests/vm/test.conf.example @@ -0,0 +1,37 @@ +# Test configuration for the disposable UEFI VM. +# +# TARGET_DISK is the virtio disk (/dev/vda). The ISO appears as /dev/sr0 and +# is protected by the installer's disk classification, so it is never offered. +# Secrets are NOT stored here; they are supplied via --*-password-file. + +HOSTNAME='phoebus' +USERNAME='phoebus' +USER_FULLNAME='Phoebus Test' +LOCALE='en_US.UTF-8' +TIMEZONE='UTC' +KEYMAP='us' + +TARGET_DISK='/dev/vda' +PARTITION_SCHEME='whole_disk' +EFI_SIZE_MIB='1024' +FILESYSTEM='btrfs' +ENCRYPTION='luks2' +COMPRESS='zstd:3' + +# safe = prebuilt distribution kernel (fast, reliable first boot) +KERNEL_PROFILE='safe' +KERNEL_UKI='no' +KERNEL_CONSOLE='console=tty0 console=ttyS0,115200' +KEEP_KERNELS='3' + +PACKAGE_POLICY='balanced' +FEATURES_BINPKG='yes' + +# none = core system only; dwl/full add the Wayland desktop +DESKTOP_PROFILE='none' +FLATPAK='no' + +# Pinned stage3 served from the host HTTP server so the SHA-256 is verified +# without a second download. Replace with a real Gentoo URL for other setups. +STAGE3_URL='http://10.0.2.2:8000/stage3.tar.xz' +STAGE3_SHA256='0000000000000000000000000000000000000000000000000000000000000000' diff --git a/installer/tui/menu.sh b/installer/tui/menu.sh new file mode 100644 index 0000000..3c9516c --- /dev/null +++ b/installer/tui/menu.sh @@ -0,0 +1,162 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Main menu and review/install flow. + +# _status_line - short right-hand column value for menu entries +_menu_items() { + printf '%s\n' \ + keyboard "Keyboard [$(config_get KEYMAP)]" \ + network "Network [$(network_online && echo online || echo offline)]" \ + source "Source [$(config_get STAGE3_URL)]" \ + hostname "Hostname [$(config_get HOSTNAME)]" \ + locale "Locale [$(config_get LOCALE)]" \ + timezone "Timezone [$(config_get TIMEZONE)]" \ + user "User [$(config_get USERNAME)]" \ + disk "Disk [$(config_get TARGET_DISK)]" \ + filesystem "Filesystem[$(config_get FILESYSTEM)/$(config_get ENCRYPTION)]" \ + boot "Boot [$(config_get BOOTLOADER)]" \ + kernel "Kernel [$(config_get KERNEL_PROFILE)]" \ + packages "Packages [$(config_get PACKAGE_POLICY)]" \ + desktop "Desktop [$(config_get DESKTOP_PROFILE)]" \ + ai "AI [$(opencode_available && echo ready || echo not-installed)]" \ + review "Review configuration" \ + install "Install" \ + exit "Exit" +} + +# menu_review - show the full plan and validation status +menu_review() { + local tmp rc + plan_generate + tmp="$(mktemp)" + { + plan_render + printf '\n\nValidation\n==========\n' + local problems + problems="$(validate_config)" + if [[ -z "$problems" ]]; then + printf 'Configuration looks complete.\n' + else + printf '%s\n' "$problems" | sed 's/^/- /' + fi + printf '\n\nPackage policy examples\n=======================\n' + pkgpolicy_report + } >"$tmp" + ui_textbox "Review configuration" "$tmp" + rc=$? + rm -f "$tmp" + if ui_yesno "Review configuration" "Save this configuration to a file?"; then + local dest="/root/phoebus-install.conf" + config_save_file "$dest" && ui_msgbox "Saved" "Configuration saved to $dest" + fi + return $rc +} + +# menu_install - the guarded, destructive path +menu_install() { + local problems preview + problems="$(validate_config)" + if [[ -n "$problems" ]]; then + ui_error "Configuration is incomplete: + +$problems" + return 1 + fi + + plan_generate + local tmp + tmp="$(mktemp)" + plan_render >"$tmp" + ui_textbox "Installation plan" "$tmp" + rm -f "$tmp" + + if config_bool DRY_RUN; then + ui_msgbox "Dry run" "Dry-run mode is enabled. + +No disk will be modified. Commands are only logged." + fi + + preview="$(plan_destructive_preview)" + if ! confirm_erase "$preview"; then + log_info "installation cancelled at ERASE confirmation" + ui_msgbox "Cancelled" "Installation cancelled. No changes were made." + return 1 + fi + if ! confirm_action "Start the installation now? This can take a long time."; then + log_info "installation cancelled at final confirmation" + ui_msgbox "Cancelled" "Installation cancelled. No changes were made." + return 1 + fi + + destructive_grant + (ui_infobox "Installing" "Installation in progress. Please wait...") 2>/dev/null || true + local rc=0 + install_run || rc=$? + destructive_revoke + + if ((rc == 0)); then + if config_bool DRY_RUN; then + ui_msgbox "Dry run complete" "The plan executed in dry-run mode. + +Log: $PHOEBUS_LOG_FILE" + else + ui_msgbox "Installation complete" "Installation finished successfully. + +Log: $PHOEBUS_LOG_FILE + +You can now reboot into $(config_get DISTRO_NAME)." + fi + return 0 + fi + + ui_error "Installation failed during stage: ${INSTALL_FAILED_STAGE:-unknown}" + if ui_yesno "Installation failed" "Show the last 60 log lines?"; then + tmp="$(mktemp)" + log_tail 60 >"$tmp" + ui_textbox "Installer log" "$tmp" + rm -f "$tmp" + fi + return 1 +} + +# menu_main - the top-level loop +menu_main() { + local choice + while true; do + local -a items=() + mapfile -t items < <(_menu_items) + if ! ui_menu "Main menu" "Configure the installation, then choose Install. + +Settings can be revisited at any time before installing." \ + 24 78 17 "${items[@]}"; then + if ui_yesno "Exit" "Exit the installer?"; then + return 0 + fi + continue + fi + choice="$UI_RESULT" + case "$choice" in + keyboard) screen_keyboard ;; + network) screen_network ;; + source) screen_source ;; + hostname) screen_hostname ;; + locale) screen_locale ;; + timezone) screen_timezone ;; + user) screen_user ;; + disk) screen_disk ;; + filesystem) screen_filesystem ;; + boot) screen_boot ;; + kernel) screen_kernel ;; + packages) screen_packages ;; + desktop) screen_desktop ;; + ai) screen_ai ;; + review) menu_review ;; + install) menu_install ;; + exit) + if ui_yesno "Exit" "Exit the installer?"; then + return 0 + fi ;; + esac + done +} diff --git a/installer/tui/screens.sh b/installer/tui/screens.sh new file mode 100644 index 0000000..4d67c99 --- /dev/null +++ b/installer/tui/screens.sh @@ -0,0 +1,463 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Configuration screens for the main menu. +# +# Each screen edits the structured configuration (CFG). Screens can be revisited +# at any time before installation; nothing here touches a disk. + +_ui_ok() { return 0; } + +# _pick_from_list TITLE TEXT CANDIDATES... - radiolist, sets UI_RESULT +_pick_from_list() { + local title="$1" text="$2" current="$3"; shift 3 + local -a items=() item + for item in "$@"; do + if [[ "$item" == "$current" ]]; then + items+=("$item" "" on) + else + items+=("$item" "" off) + fi + done + ui_radiolist "$title" "$text" 0 0 12 "${items[@]}" +} + +# --------------------------------------------------------------------------- +# 1. Keyboard +# --------------------------------------------------------------------------- +screen_keyboard() { + local current choice custom + current="$(config_get KEYMAP)" + local -a layouts=(us gb de fr es it pt-br dvorak colemak ru pl nl se no dk "fi" cz hu tr jp kr) + if _pick_from_list "Keyboard" "Select a console keymap:" "$current" "${layouts[@]}" other; then + choice="$UI_RESULT" + else + return 0 + fi + if [[ "$choice" == "other" ]]; then + ui_inputbox "Keyboard" "Enter a keymap name (e.g. us-acentos):" "$current" || return 0 + custom="$UI_RESULT" + [[ -n "$custom" ]] && config_set KEYMAP "$custom" + else + config_set KEYMAP "$choice" + fi +} + +# --------------------------------------------------------------------------- +# 2. Network +# --------------------------------------------------------------------------- +screen_network() { + local status action + network_live_start + status="$(network_status_text)" + while true; do + if ! ui_menu "Network" "$status + +Choose an action:" 18 70 5 \ + status "Show interface status" \ + wifi "Connect to a Wi-Fi network" \ + refresh "Refresh status" \ + "done" "Back"; then + return 0 + fi + action="$UI_RESULT" + case "$action" in + status|refresh) status="$(network_status_text)" ;; + wifi) + local scan + scan="$(network_wifi_scan)" + if [[ -z "$scan" ]]; then + ui_msgbox "Network" "No Wi-Fi networks found. You can configure networking later." + continue + fi + local tmp + tmp="$(mktemp)" + printf '%s\n' "$scan" >"$tmp" + local -a items=() + local ssid sig sec + while read -r ssid sig sec; do + [[ -z "$ssid" ]] && continue + items+=("$ssid" "${sig} ${sec}" off) + done <"$tmp" + rm -f "$tmp" + ((${#items[@]})) || continue + if ui_radiolist "Wi-Fi" "Select a network:" 0 0 12 "${items[@]}"; then + ssid="$UI_RESULT" + ui_passwordbox "Wi-Fi" "Passphrase for '$ssid' (blank for open):" || continue + network_connect_wifi "$ssid" "$UI_RESULT" || ui_error "Could not connect to $ssid" + fi + ;; + done) return 0 ;; + esac + done +} + +# --------------------------------------------------------------------------- +# 3. Source / installation media +# --------------------------------------------------------------------------- +screen_source() { + local url sha + while true; do + if ! ui_menu "Source" "Stage3 source + +Mirror: $(config_get STAGE3_MIRROR) +URL: $(config_get STAGE3_URL) +SHA-256: $(config_get STAGE3_SHA256)" 16 74 4 \ + auto "Use current stable systemd stage3" \ + pin "Pin an explicit stage3 URL" \ + sha "Set expected SHA-256" \ + "done" "Back"; then + return 0 + fi + case "$UI_RESULT" in + auto) config_set STAGE3_URL ""; config_set STAGE3_SHA256 "" ;; + pin) + ui_inputbox "Source" "Stage3 tarball URL:" "$(config_get STAGE3_URL)" || continue + config_set STAGE3_URL "$UI_RESULT" ;; + sha) + ui_inputbox "Source" "Expected SHA-256 (blank to clear):" "$(config_get STAGE3_SHA256)" || continue + config_set STAGE3_SHA256 "$UI_RESULT" ;; + done) return 0 ;; + esac + done +} + +# --------------------------------------------------------------------------- +# 4. Hostname +# --------------------------------------------------------------------------- +screen_hostname() { + local hostname + ui_inputbox "Hostname" "Enter the system hostname:" "$(config_get HOSTNAME)" || return 0 + hostname="$UI_RESULT" + if validate_hostname "$hostname" >/dev/null; then + config_set HOSTNAME "$hostname" + else + ui_error "$(validate_hostname "$hostname")" + fi +} + +# --------------------------------------------------------------------------- +# 5. Locale +# --------------------------------------------------------------------------- +screen_locale() { + local current + current="$(config_get LOCALE)" + local -a locales=(en_US.UTF-8 en_GB.UTF-8 de_DE.UTF-8 fr_FR.UTF-8 es_ES.UTF-8 it_IT.UTF-8 pt_BR.UTF-8 nl_NL.UTF-8 pl_PL.UTF-8 ru_RU.UTF-8) + if _pick_from_list "Locale" "Select the system locale:" "$current" "${locales[@]}" other; then + if [[ "$UI_RESULT" == "other" ]]; then + ui_inputbox "Locale" "Enter a locale (e.g. sv_SE.UTF-8):" "$current" || return 0 + [[ -n "$UI_RESULT" ]] && config_set LOCALE "$UI_RESULT" + else + config_set LOCALE "$UI_RESULT" + fi + fi +} + +# --------------------------------------------------------------------------- +# 6. Timezone +# --------------------------------------------------------------------------- +screen_timezone() { + local current + current="$(config_get TIMEZONE)" + local -a zones=(UTC Europe/London Europe/Berlin Europe/Paris Europe/Madrid Europe/Rome Europe/Amsterdam Europe/Warsaw America/New_York America/Chicago America/Denver America/Los_Angeles America/Sao_Paulo Asia/Tokyo Asia/Shanghai Asia/Kolkata Australia/Sydney) + if _pick_from_list "Timezone" "Select the timezone:" "$current" "${zones[@]}" other; then + if [[ "$UI_RESULT" == "other" ]]; then + ui_inputbox "Timezone" "Enter a timezone (e.g. Europe/Stockholm):" "$current" || return 0 + [[ -n "$UI_RESULT" ]] && config_set TIMEZONE "$UI_RESULT" + else + config_set TIMEZONE "$UI_RESULT" + fi + fi +} + +# --------------------------------------------------------------------------- +# 7. User account +# --------------------------------------------------------------------------- +screen_user() { + local username fullname + while true; do + if ! ui_menu "User account" "Username: $(config_get USERNAME) +Full name: $(config_get USER_FULLNAME) +Groups: $(config_get USER_GROUPS)" 15 74 4 \ + username "Set username" \ + fullname "Set full name" \ + password "Set password" \ + "done" "Back"; then + return 0 + fi + case "$UI_RESULT" in + username) + ui_inputbox "User account" "Username:" "$(config_get USERNAME)" || continue + username="$UI_RESULT" + if validate_username "$username" >/dev/null; then + config_set USERNAME "$username" + else + ui_error "$(validate_username "$username")" + fi + ;; + fullname) + ui_inputbox "User account" "Full name:" "$(config_get USER_FULLNAME)" || continue + config_set USER_FULLNAME "$UI_RESULT" ;; + password) + users_prompt_passwords || ui_error "Could not set password" + ;; + done) return 0 ;; + esac + done +} + +# --------------------------------------------------------------------------- +# 8. Disk +# --------------------------------------------------------------------------- +screen_disk() { + local current disk reason + current="$(config_get TARGET_DISK)" + disks_refresh + if ((${#DISK_LIST[@]} == 0)); then + ui_error "No disks were detected." + return 0 + fi + local -a items=() + for disk in "${DISK_LIST[@]}"; do + reason="$(disk_protected_reason "$disk")" + if [[ -n "$reason" ]]; then + continue + fi + if [[ "$disk" == "$current" ]]; then + items+=("$disk" "$(disk_display_line "$disk")" on) + else + items+=("$disk" "$(disk_display_line "$disk")" off) + fi + done + if ((${#items[@]} == 0)); then + ui_error "No safe target disks found. All detected disks are protected (live medium, mounted, or read-only)." + return 0 + fi + if ui_radiolist "Disk" "Select the installation target. + +All data on the selected disk will be destroyed later, after review." \ + 0 0 10 "${items[@]}"; then + config_set TARGET_DISK "$UI_RESULT" + local tmp + tmp="$(mktemp)" + disk_layout_text "$UI_RESULT" >"$tmp" 2>/dev/null + ui_textbox "Current layout: $UI_RESULT" "$tmp" + rm -f "$tmp" + fi +} + +# --------------------------------------------------------------------------- +# 9. Filesystem / encryption +# --------------------------------------------------------------------------- +screen_filesystem() { + local action + while true; do + if ! ui_menu "Filesystem" "Filesystem: $(config_get FILESYSTEM) +Encryption: $(config_get ENCRYPTION) +Compression: $(config_get COMPRESS) +EFI size: $(config_get EFI_SIZE_MIB) MiB" 17 74 6 \ + fs "Change filesystem" \ + encryption "Change encryption" \ + passphrase "Set encryption passphrase" \ + compress "Change Btrfs compression" \ + efi "Change EFI partition size" \ + "done" "Back"; then + return 0 + fi + case "$UI_RESULT" in + fs) + if _pick_from_list "Filesystem" "Select the root filesystem:" "$(config_get FILESYSTEM)" btrfs ext4; then + config_set FILESYSTEM "$UI_RESULT" + fi ;; + encryption) + if _pick_from_list "Encryption" "Select encryption for the root partition:" "$(config_get ENCRYPTION)" luks2 none; then + config_set ENCRYPTION "$UI_RESULT" + fi ;; + passphrase) + encryption_configure || ui_error "Passphrase not set" ;; + compress) + ui_inputbox "Filesystem" "Btrfs compression (zstd:3 recommended):" "$(config_get COMPRESS)" || continue + config_set COMPRESS "$UI_RESULT" ;; + efi) + ui_inputbox "Filesystem" "EFI partition size in MiB:" "$(config_get EFI_SIZE_MIB)" || continue + [[ "$UI_RESULT" =~ ^[0-9]+$ ]] && config_set EFI_SIZE_MIB "$UI_RESULT" ;; + done) return 0 ;; + esac + done +} + +# --------------------------------------------------------------------------- +# 10. Boot +# --------------------------------------------------------------------------- +screen_boot() { + local action + while true; do + if ! ui_menu "Boot" "Bootloader: $(config_get BOOTLOADER) +Unified UKI: $(config_get KERNEL_UKI) +Secure Boot: $(config_get SECUREBOOT) +Keep kernels: $(config_get KEEP_KERNELS) + +Secure Boot status: $(boot_secureboot_status)" 18 74 4 \ + uki "Toggle Unified Kernel Image" \ + keep "Set number of kernels to keep" \ + secure "Toggle Secure Boot preference (not enforced yet)" \ + "done" "Back"; then + return 0 + fi + case "$UI_RESULT" in + uki) + if config_bool KERNEL_UKI; then config_set KERNEL_UKI no; else config_set KERNEL_UKI yes; fi ;; + keep) + ui_inputbox "Boot" "Number of kernels to keep (>=2):" "$(config_get KEEP_KERNELS)" || continue + if [[ "$UI_RESULT" =~ ^[0-9]+$ ]] && ((UI_RESULT >= 2)); then + config_set KEEP_KERNELS "$UI_RESULT" + else + ui_error "Keep at least 2 kernels so a known-good kernel is always available." + fi ;; + secure) + if config_bool SECUREBOOT; then config_set SECUREBOOT no; else config_set SECUREBOOT yes; fi ;; + done) return 0 ;; + esac + done +} + +# --------------------------------------------------------------------------- +# 11. Kernel +# --------------------------------------------------------------------------- +screen_kernel() { + local action + while true; do + if ! ui_menu "Kernel" "Profile: $(config_get KERNEL_PROFILE) +Package: $(kernel_select_package) +UKI: $(config_get KERNEL_UKI) + +Recommended for this machine: $(hw_recommended_kernel_profile)" 17 74 4 \ + profile "Select kernel profile" \ + package "Select kernel package" \ + "done" "Back"; then + return 0 + fi + case "$UI_RESULT" in + profile) + if _pick_from_list "Kernel" "safe = prebuilt distribution kernel +optimized = distribution kernel, conservative local fragments (default) +aggressive = distribution sources with a locally tuned config" \ + "$(config_get KERNEL_PROFILE)" safe optimized aggressive; then + config_set KERNEL_PROFILE "$UI_RESULT" + fi ;; + package) + ui_inputbox "Kernel" "Kernel package:" "$(config_get KERNEL_PACKAGE)" || continue + config_set KERNEL_PACKAGE "$UI_RESULT" ;; + done) return 0 ;; + esac + done +} + +# --------------------------------------------------------------------------- +# 12. Package policy +# --------------------------------------------------------------------------- +screen_packages() { + local action + while true; do + if ! ui_menu "Packages" "Policy: $(config_get PACKAGE_POLICY) +Binary packages: $(config_get FEATURES_BINPKG) +Accept license: $(config_get ACCEPT_LICENSE) + +source_first - compile everything possible +balanced - compile cheap/frequent, use binaries for huge packages (default) +binary_first - prefer binaries whenever available" 19 76 5 \ + policy "Change policy" \ + binpkg "Toggle binary packages" \ + license "Change accepted licenses" \ + show "Show example decisions" \ + "done" "Back"; then + return 0 + fi + case "$UI_RESULT" in + policy) + if _pick_from_list "Packages" "Select the package policy:" "$(config_get PACKAGE_POLICY)" source_first balanced binary_first; then + config_set PACKAGE_POLICY "$UI_RESULT" + fi ;; + binpkg) + if config_bool FEATURES_BINPKG; then config_set FEATURES_BINPKG no; else config_set FEATURES_BINPKG yes; fi ;; + license) + ui_inputbox "Packages" "ACCEPT_LICENSE value:" "$(config_get ACCEPT_LICENSE)" || continue + config_set ACCEPT_LICENSE "$UI_RESULT" ;; + show) + local tmp + tmp="$(mktemp)" + pkgpolicy_report >"$tmp" + ui_textbox "Package policy examples" "$tmp" + rm -f "$tmp" ;; + done) return 0 ;; + esac + done +} + +# --------------------------------------------------------------------------- +# 13. Desktop +# --------------------------------------------------------------------------- +screen_desktop() { + local action + while true; do + if ! ui_menu "Desktop" "Profile: $(config_get DESKTOP_PROFILE) +Flatpak: $(config_get FLATPAK) +Audio: $(config_get AUDIO_STACK) + +none - server / no graphical session +minimal - Wayland libraries and XWayland only +dwl - dwl tiling desktop with Waybar, fuzzel, mako, ... +full - dwl plus Flatpak, BlueZ and keyring" 20 76 5 \ + profile "Select desktop profile" \ + flatpak "Toggle Flatpak" \ + "done" "Back"; then + return 0 + fi + case "$UI_RESULT" in + profile) + if _pick_from_list "Desktop" "Select the desktop profile:" "$(config_get DESKTOP_PROFILE)" none minimal dwl full; then + config_set DESKTOP_PROFILE "$UI_RESULT" + fi ;; + flatpak) + if config_bool FLATPAK; then config_set FLATPAK no; else config_set FLATPAK yes; fi ;; + done) return 0 ;; + esac + done +} + +# --------------------------------------------------------------------------- +# 14. AI configuration +# --------------------------------------------------------------------------- +screen_ai() { + local action + while true; do + if ! ui_menu "AI assistant" "$(ai_status_text)" 18 76 4 \ + configure "Configure provider and model" \ + bootstrap "Install / verify OpenCode" \ + test "Test OpenCode availability" \ + "done" "Back"; then + return 0 + fi + case "$UI_RESULT" in + configure) ai_configure ;; + bootstrap) + if opencode_bootstrap; then + ui_msgbox "AI assistant" "OpenCode installed and verified." + else + ui_error "OpenCode installation failed. See the log for details." + fi ;; + test) + if opencode_available; then + local bin ver + bin="$(opencode_detect)" + ver="$(opencode_print_version "$bin")" + ui_msgbox "AI assistant" "OpenCode found: +$bin +version: ${ver:-unknown}" + else + ui_msgbox "AI assistant" "OpenCode is not installed. Use 'Install / verify OpenCode'." + fi ;; + done) return 0 ;; + esac + done +} diff --git a/installer/tui/ui.sh b/installer/tui/ui.sh new file mode 100644 index 0000000..c6edfb3 --- /dev/null +++ b/installer/tui/ui.sh @@ -0,0 +1,127 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Thin TUI wrapper around dialog/whiptail. +# +# dialog is the preferred backend (present in the Gentoo LiveGUI reference). +# whiptail is accepted as a fallback so the installer also works in minimal +# environments. Only the common option subset is used. +# +# All functions store the result in UI_RESULT and return 0 on OK / 1 on cancel. + +declare -g UI_BACKEND="${UI_BACKEND:-auto}" +declare -g UI_RESULT="${UI_RESULT:-}" +declare -g UI_TITLE="${UI_TITLE:-}" + +ui_init() { + if [[ "$UI_BACKEND" == "auto" ]]; then + if command -v dialog >/dev/null 2>&1; then + UI_BACKEND="dialog" + elif command -v whiptail >/dev/null 2>&1; then + UI_BACKEND="whiptail" + else + UI_BACKEND="none" + fi + fi + UI_TITLE="${DISTRO_NAME:-Phoebus OS} Installer" + [[ "$UI_BACKEND" == "none" ]] && return 1 + return 0 +} + +ui_available() { [[ "$UI_BACKEND" != "none" ]]; } + +_ui() { + case "$UI_BACKEND" in + dialog) dialog "$@" ;; + whiptail) whiptail "$@" ;; + *) return 127 ;; + esac +} + +# _ui_capture ARGS... - run and put textual result in UI_RESULT +_ui_capture() { + local f rc + f="$(mktemp "${TMPDIR:-/tmp}/phoebus-ui.XXXXXX")" || return 1 + _ui --output-fd 3 "$@" 3>"$f" + rc=$? + UI_RESULT="$(cat "$f")" + rm -f "$f" + case "$rc" in + 0) return 0 ;; + *) return 1 ;; + esac +} + +ui_backtitle_args() { + printf '%s\n' --backtitle "$UI_TITLE" +} + +ui_msgbox() { + local title="$1" text="$2" + _ui --title "$title" --backtitle "$UI_TITLE" --msgbox "$text" 0 0 +} + +ui_yesno() { + local title="$1" text="$2" + _ui --title "$title" --backtitle "$UI_TITLE" --yesno "$text" 0 0 +} + +ui_inputbox() { + local title="$1" text="$2" init="${3-}" + _ui_capture --title "$title" --backtitle "$UI_TITLE" --inputbox "$text" 0 0 "$init" +} + +ui_passwordbox() { + local title="$1" text="$2" + if [[ "$UI_BACKEND" == "dialog" ]]; then + _ui_capture --title "$title" --backtitle "$UI_TITLE" --insecure --passwordbox "$text" 0 0 + else + _ui_capture --title "$title" --backtitle "$UI_TITLE" --passwordbox "$text" 0 0 + fi +} + +ui_menu() { + local title="$1" text="$2" height="$3" width="$4" listheight="$5" + shift 5 + _ui_capture --title "$title" --backtitle "$UI_TITLE" \ + --menu "$text" "$height" "$width" "$listheight" "$@" +} + +ui_radiolist() { + local title="$1" text="$2" height="$3" width="$4" listheight="$5" + shift 5 + _ui_capture --title "$title" --backtitle "$UI_TITLE" \ + --radiolist "$text" "$height" "$width" "$listheight" "$@" +} + +ui_checklist() { + local title="$1" text="$2" height="$3" width="$4" listheight="$5" + shift 5 + _ui_capture --title "$title" --backtitle "$UI_TITLE" \ + --checklist "$text" "$height" "$width" "$listheight" "$@" +} + +ui_textbox() { + local title="$1" file="$2" + _ui --title "$title" --backtitle "$UI_TITLE" --textbox "$file" 0 0 +} + +ui_infobox() { + local title="$1" text="$2" + _ui --title "$title" --backtitle "$UI_TITLE" --infobox "$text" 0 0 + return 0 +} + +# ui_pause - wait for the user to acknowledge a message +ui_pause() { + ui_msgbox "${1:-Information}" "${2:-Press OK to continue.}" +} + +# ui_error - show an error with the log location +ui_error() { + local message="$1" + ui_msgbox "Error" "$message + +See the log for details: +$PHOEBUS_LOG_FILE" +}