//! Nix as a built-in second package lane (bootstrap). //! //! The upstream Nix installer hardcodes `/nix`, calls `sudo`, and must run //! `nix-store --load-db` against the real root, so it cannot be repackaged as a //! normal binary ebuild. Instead we fetch the **pinned, SHA-256-verified** //! official release and reproduce its bootstrap with discrete commands in the //! target chroot. There is no `curl | sh` and no `sh -c`. //! //! Gated behind `packages.nix` because it is not VM-verified yet. use std::path::{Path, PathBuf}; use crate::command::CommandSpec; use crate::error::{ExecError, Result}; use crate::exec::Exec; pub const NIX_VERSION: &str = "2.24.9"; pub const NIX_URL: &str = "https://releases.nixos.org/nix/nix-2.24.9/nix-2.24.9-x86_64-linux.tar.xz"; pub const NIX_SHA256: &str = "3c0779e4878d1289cf3fbb158ec5ea9bdf61dfb9b4efac6b3b0b6bec5ba4cf13"; const NIX_TARBALL_DIR: &str = "nix-2.24.9-x86_64-linux"; const NIX_STORE_NAME: &str = "2nhrwv91g6ycpyxvhmvc0xs8p92wp4bk-nix-2.24.9"; const NIX_BUILD_USERS: u32 = 8; fn nix_store_bin() -> String { format!("/nix/store/{NIX_STORE_NAME}/bin/nix-store") } /// The generated `/etc/nix/nix.conf`. /// /// Build isolation is on and does not silently fall back: the Nix sandbox uses /// Linux user namespaces, which the Phoebus kernel enables. `min-free` and /// `max-free` bound the store so it cannot fill the root filesystem, and /// `auto-optimise-store` deduplicates. pub fn nix_conf() -> &'static str { "# Phoebus: Nix as a second package lane (developer tools only).\n\ build-users-group = nixbld\n\ sandbox = true\n\ sandbox-fallback = false\n\ auto-optimise-store = true\n\ min-free = 1073741824\n\ max-free = 10737418240\n\ experimental-features = nix-command flakes\n\ substituters = https://cache.nixos.org\n\ trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=\n" } fn target_path(root: &Path, rel: &str) -> PathBuf { root.join(rel) } /// Whether the pinned manifest entry looks usable (not a placeholder). pub fn manifest_is_pinned() -> bool { NIX_URL.ends_with(".tar.xz") && NIX_SHA256.len() == 64 && NIX_SHA256.chars().all(|c| c.is_ascii_hexdigit()) && NIX_SHA256.chars().any(|c| c != '0') } /// Fetch, verify and bootstrap the pinned Nix release into `root`. pub fn install(exec: &Exec, root: &Path) -> Result<()> { exec.require_tools(&["curl", "tar", "sha256sum"])?; if !manifest_is_pinned() { return Err(ExecError::operation( "nix", "bootstrap", "the embedded Nix manifest is not pinned", )); } if exec.dry_run { exec.logger.info(format!( "[dry-run] would bootstrap Nix {NIX_VERSION} into the target" )); return Ok(()); } let tarball = exec.state_dir.join("nix.tar.xz"); exec.logger.info(format!("Nix: fetching {NIX_URL}")); exec.run( CommandSpec::new("nix", "download Nix", "curl") .args(["-fL", "--retry", "3", "-o"]) .arg(tarball.to_string_lossy().to_string()) .arg(NIX_URL), )?; if !crate::opencode::checksum_ok(&tarball, NIX_SHA256)? { return Err(ExecError::operation( "nix", "verify Nix", "SHA-256 mismatch; discarding download", )); } exec.logger.info("Nix: checksum verified"); let result = bootstrap(exec, root, &tarball); let _ = std::fs::remove_file(&tarball); result } fn bootstrap(exec: &Exec, root: &Path, tarball: &Path) -> Result<()> { // Stage and extract inside the target so paths are target-relative. let tmp = target_path(root, "tmp"); std::fs::create_dir_all(&tmp).map_err(|e| ExecError::io(tmp.clone(), e))?; let staged = tmp.join("nix.tar.xz"); std::fs::copy(tarball, &staged).map_err(|e| ExecError::io(staged.clone(), e))?; exec.run( CommandSpec::new("nix", "extract Nix", "tar") .args(["-xJf"]) .arg(staged.to_string_lossy().to_string()) .args(["-C"]) .arg(tmp.to_string_lossy().to_string()), )?; let extracted = tmp.join(NIX_TARBALL_DIR); // The Nix store. let nix_dir = target_path(root, "nix"); std::fs::create_dir_all(&nix_dir).map_err(|e| ExecError::io(nix_dir.clone(), e))?; exec.run( CommandSpec::new("nix", "install Nix store", "cp") .args(["-a"]) .arg(extracted.join("store").to_string_lossy().to_string()) .arg(nix_dir.to_string_lossy().to_string()), )?; // Register the store paths from the shipped database. let reginfo = std::fs::read(extracted.join(".reginfo")) .map_err(|e| ExecError::io(extracted.join(".reginfo"), e))?; crate::portage::chroot_stdin(exec, root, &nix_store_bin(), &["--load-db"], ®info)?; // State directories. `nix-daemon.service` is gated on // ConditionPathIsReadWrite=/nix/var/nix/daemon-socket, so it must exist. for rel in [ "nix/var/nix/profiles", "nix/var/nix/profiles/per-user", "nix/var/nix/gcroots", "nix/var/nix/temproots", "nix/var/nix/daemon-socket", ] { let dir = target_path(root, rel); std::fs::create_dir_all(&dir).map_err(|e| ExecError::io(dir.clone(), e))?; } { use std::os::unix::fs::PermissionsExt; let sock = target_path(root, "nix/var/nix/daemon-socket"); let _ = std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o755)); } // Build users (`nixbld` group + N build users). let _ = crate::portage::chroot(exec, root, "groupadd", &["--system", "nixbld"]); for i in 1..=NIX_BUILD_USERS { let name = format!("nixbld{i}"); let _ = crate::portage::chroot( exec, root, "useradd", &[ "--system", "--gid", "nixbld", "--home-dir", "/var/empty", "--shell", "/sbin/nologin", "--comment", "Nix build user", name.as_str(), ], ); } // Configuration and profile wiring. Build isolation is enabled: the Nix // sandbox uses user namespaces and fails closed rather than silently // building unsandboxed, so a compromised build cannot reach the host. write_file(root, "etc/nix/nix.conf", nix_conf())?; let profile = "nix/var/nix/profiles"; std::fs::create_dir_all(target_path(root, profile)) .map_err(|e| ExecError::io(target_path(root, profile), e))?; let default_profile = target_path(root, "nix/var/nix/profiles/default"); let store_nix = format!("/nix/store/{NIX_STORE_NAME}"); relink(&default_profile, Path::new(&store_nix))?; relink( &target_path(root, "root/.nix-profile"), Path::new("/nix/var/nix/profiles/default"), )?; write_file( root, "etc/profile.d/nix.sh", "export PATH=/nix/var/nix/profiles/default/bin:$PATH\n", )?; // The daemon units ship inside the store; symlink them and create the // `.wants` links directly (systemctl enable can be a no-op in a chroot). let unit = format!("{store_nix}/lib/systemd/system"); for name in ["nix-daemon.service", "nix-daemon.socket"] { let link = target_path(root, &format!("etc/systemd/system/{name}")); relink(&link, Path::new(&format!("{unit}/{name}")))?; } for (wants, name) in [ ("multi-user.target.wants", "nix-daemon.service"), ("sockets.target.wants", "nix-daemon.socket"), ] { let link = target_path(root, &format!("etc/systemd/system/{wants}/{name}")); relink(&link, Path::new(&format!("{unit}/{name}")))?; } let _ = crate::portage::chroot(exec, root, "systemctl", &["enable", "nix-daemon.service"]); let _ = crate::portage::chroot(exec, root, "systemctl", &["enable", "nix-daemon.socket"]); exec.logger .info(format!("Nix {NIX_VERSION} bootstrapped into the target")); // Clean up the staging files. let _ = std::fs::remove_file(&staged); let _ = std::fs::remove_dir_all(&extracted); Ok(()) } /// Whether the Nix store is present in the target. pub fn installed(root: &Path) -> bool { target_path(root, &format!("nix/store/{NIX_STORE_NAME}")).is_dir() } /// Remove Nix's system integration: the daemon units and profile wiring. The /// store is only deleted when `purge` is set, because the store may back /// user environments that should be removed deliberately. pub fn remove(exec: &Exec, root: &Path, purge: bool) -> Result<()> { let _ = crate::portage::chroot(exec, root, "systemctl", &["disable", "nix-daemon.service"]); let _ = crate::portage::chroot(exec, root, "systemctl", &["disable", "nix-daemon.socket"]); for rel in [ "etc/systemd/system/nix-daemon.service", "etc/systemd/system/nix-daemon.socket", "etc/systemd/system/multi-user.target.wants/nix-daemon.service", "etc/systemd/system/sockets.target.wants/nix-daemon.socket", "root/.nix-profile", "etc/profile.d/nix.sh", ] { let path = target_path(root, rel); let _ = std::fs::remove_file(&path); } let _ = std::fs::remove_file(target_path(root, "nix/var/nix/profiles/default")); if purge { let nix_dir = target_path(root, "nix"); if let Err(e) = std::fs::remove_dir_all(&nix_dir) { if e.kind() != std::io::ErrorKind::NotFound { return Err(ExecError::io(nix_dir, e)); } } } exec.logger.info(format!( "removed Nix integration{}", if purge { " (store purged)" } else { "" } )); Ok(()) } /// Run the Nix garbage collector, bounded by the `min-free`/`max-free` settings /// in `/etc/nix/nix.conf`. pub fn gc(exec: &Exec, root: &Path) -> Result<()> { let binary = format!("{}/bin/nix-store", "/nix/var/nix/profiles/default"); crate::portage::chroot(exec, root, &binary, &["--gc"])?; exec.logger.info("Nix store garbage collection complete"); Ok(()) } /// Realise a bounded set of development packages so they are available offline. /// /// Each entry is a bare nixpkgs attribute name (`nodejs`, `python312`); URLs and /// flake references are refused, so the assistant cannot make Nix evaluate /// arbitrary remote inputs. pub fn prepare_dev_packages(exec: &Exec, root: &Path, packages: &[String]) -> Result> { let mut prepared = Vec::new(); let binary = "/nix/var/nix/profiles/default/bin/nix"; for package in packages { if !valid_nix_attribute(package) { return Err(ExecError::operation( "nix", "prepare package", format!("invalid nixpkgs attribute: {package}"), )); } crate::portage::chroot( exec, root, binary, &["shell", &format!("nixpkgs#{package}"), "-c", "true"], )?; prepared.push(package.clone()); } Ok(prepared) } /// A bounded nixpkgs attribute: no slashes, URLs, or flake references. pub fn valid_nix_attribute(value: &str) -> bool { phoebus_core::action::valid_nix_attribute(value) } fn write_file(root: &Path, rel: &str, contents: &str) -> Result<()> { let path = target_path(root, rel); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(|e| ExecError::io(parent.to_path_buf(), e))?; } std::fs::write(&path, contents).map_err(|e| ExecError::io(path, e)) } fn relink(link: &Path, target: &Path) -> Result<()> { 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); std::os::unix::fs::symlink(target, link).map_err(|e| ExecError::io(link.to_path_buf(), e)) } #[cfg(test)] mod tests { use super::*; use crate::command::RecordingRunner; use crate::log::Logger; use phoebus_core::Redactor; fn make_exec(runner: RecordingRunner, dry_run: bool) -> Exec { let path = tempfile::tempdir().unwrap().keep(); let logger = Logger::open(path.join("l.log"), Redactor::new(), false); Exec::new(Box::new(runner), logger, dry_run, path.join("root"), path) } #[test] fn manifest_is_pinned_to_a_real_release() { assert!(manifest_is_pinned()); assert!(NIX_URL.contains(NIX_VERSION)); assert_eq!(NIX_SHA256.len(), 64); } #[test] fn dry_run_bootstraps_nothing() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone(), true); install(&exec, Path::new(&exec.root)).unwrap(); assert!( runner.recorded().is_empty(), "dry-run must not run commands" ); } #[test] fn checksum_policy_reuses_the_shared_verifier() { let dir = tempfile::tempdir().unwrap(); let file = dir.path().join("nix.tar.xz"); std::fs::write(&file, b"fixture").unwrap(); let good = crate::opencode::sha256_hex(b"fixture"); assert!(crate::opencode::checksum_ok(&file, &good).unwrap()); assert!(!crate::opencode::checksum_ok(&file, &"0".repeat(64)).unwrap()); assert!(!crate::opencode::checksum_ok(&file, "deadbeef").unwrap()); } #[test] fn conf_enables_enforced_sandbox_and_store_bounds() { let conf = nix_conf(); assert!(conf.contains("sandbox = true")); assert!(conf.contains("sandbox-fallback = false")); assert!(conf.contains("min-free =")); assert!(conf.contains("max-free =")); assert!(!conf.contains("sandbox = false")); } #[test] fn nixpkg_attribute_is_bounded() { assert!(valid_nix_attribute("nodejs")); assert!(valid_nix_attribute("python312")); assert!(valid_nix_attribute("gcc13")); assert!(!valid_nix_attribute("")); assert!(!valid_nix_attribute("github:owner/repo")); assert!(!valid_nix_attribute("nixpkgs#x/y")); assert!(!valid_nix_attribute("a b")); } #[test] fn remove_unlinks_units_and_optionally_purges() { let runner = RecordingRunner::new(); let exec = make_exec(runner, false); let root = Path::new(&exec.root); std::fs::create_dir_all(root.join("etc/systemd/system")).unwrap(); std::fs::write(root.join("etc/systemd/system/nix-daemon.service"), "x").unwrap(); std::fs::create_dir_all(root.join("nix/store")).unwrap(); remove(&exec, root, false).unwrap(); assert!(!root.join("etc/systemd/system/nix-daemon.service").exists()); assert!(root.join("nix/store").exists()); remove(&exec, root, true).unwrap(); assert!(!root.join("nix").exists()); } }