From 81ce70dbacead40d60f67020b064d369fc588881 Mon Sep 17 00:00:00 2001 From: ckyrouac Date: Thu, 29 Oct 2026 17:00:47 +0000 Subject: [PATCH 01/10] image: Mount deployment image content Expose paths from booted or staged deployment images through caller-owned read-only mounts. Keep image content and persistent /var ownership separate, and add explicit unmount and integration coverage. Assisted-by: AI Signed-off-by: ckyrouac --- crates/initramfs/src/lib.rs | 22 + crates/lib/src/cli.rs | 6 + crates/lib/src/image_mount.rs | 667 ++++++++++++++++++++++++ crates/lib/src/lib.rs | 1 + docs/src/bootc-experimental-image.7.md | 42 +- tmt/plans/integration.fmf | 7 + tmt/tests/booted/test-64-image-mount.nu | 116 +++++ tmt/tests/tests.fmf | 5 + 8 files changed, 865 insertions(+), 1 deletion(-) create mode 100644 crates/lib/src/image_mount.rs create mode 100644 tmt/tests/booted/test-64-image-mount.nu diff --git a/crates/initramfs/src/lib.rs b/crates/initramfs/src/lib.rs index 7c9af14d78..a7bc063844 100644 --- a/crates/initramfs/src/lib.rs +++ b/crates/initramfs/src/lib.rs @@ -38,6 +38,9 @@ use linux_kernel_cmdline::utf8::Cmdline; // mount_setattr syscall support const MOUNT_ATTR_RDONLY: u64 = 0x00000001; +const MOUNT_ATTR_NOSUID: u64 = 0x00000002; +const MOUNT_ATTR_NODEV: u64 = 0x00000004; +const MOUNT_ATTR_NOSYMFOLLOW: u64 = 0x00200000; #[repr(C)] struct MountAttr { @@ -91,6 +94,25 @@ pub fn set_mount_tree_readonly(fd: impl AsFd) -> Result<()> { mount_setattr(fd, libc::AT_EMPTY_PATH | libc::AT_RECURSIVE, &attr) } +/// Set a mount tree read-only, nosuid, nodev, and prevent symlink traversal within it. +/// +/// A bind-mounted image tree is not a chroot: absolute and escaping symlinks +/// can otherwise resolve against the caller's root. `nosymfollow` keeps the +/// exposed tree confined to the image while leaving the underlying image +/// untouched. `nosuid` also prevents set-user-ID and set-group-ID bits in the +/// image from affecting processes that access the mounted tree. This deliberately +/// does not set `noexec`, so image executables remain runnable. +#[context("Setting mount tree readonly and nosymfollow")] +pub fn set_mount_tree_readonly_nosymfollow(fd: impl AsFd) -> Result<()> { + let attr = MountAttr { + attr_set: MOUNT_ATTR_RDONLY | MOUNT_ATTR_NOSUID | MOUNT_ATTR_NODEV | MOUNT_ATTR_NOSYMFOLLOW, + attr_clr: 0, + propagation: 0, + userns_fd: 0, + }; + mount_setattr(fd, libc::AT_EMPTY_PATH | libc::AT_RECURSIVE, &attr) +} + /// Types of mounts supported by the configuration #[derive(Clone, Copy, Debug, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] diff --git a/crates/lib/src/cli.rs b/crates/lib/src/cli.rs index 8a46071c60..b41b810fb7 100644 --- a/crates/lib/src/cli.rs +++ b/crates/lib/src/cli.rs @@ -785,6 +785,10 @@ pub(crate) enum ImageOpts { /// The image to pull image: String, }, + /// Mount content from the booted or staged deployment image read-only. + Mount(crate::image_mount::MountOpts), + /// Unmount the named non-root mount (non-recursive; bootc provenance is not checked). + Unmount(crate::image_mount::UnmountOpts), /// Wrapper for selected `podman image` subcommands in bootc storage. #[clap(subcommand)] Cmd(ImageCmdOpts), @@ -2521,6 +2525,8 @@ async fn run_from_opt(opt: Opt) -> Result { .pull_from_host_storage(&image) .await } + ImageOpts::Mount(opts) => crate::image_mount::mount(opts).await, + ImageOpts::Unmount(opts) => crate::image_mount::unmount(opts), ImageOpts::Cmd(opt) => { let storage = get_storage().await?; let imgstore = storage.get_ensure_imgstore()?; diff --git a/crates/lib/src/image_mount.rs b/crates/lib/src/image_mount.rs new file mode 100644 index 0000000000..86a8723055 --- /dev/null +++ b/crates/lib/src/image_mount.rs @@ -0,0 +1,667 @@ +//! Read-only access to the image content of a booted or staged deployment. +//! +//! This deliberately does not assemble deployment state: in particular, it +//! never bind-mounts `/var` or the deployment's mutable `/etc` over the image. + +use std::os::fd::{AsFd, AsRawFd, OwnedFd}; +use std::os::unix::fs::MetadataExt; + +use anyhow::{Context, Result, bail, ensure}; +use camino::{Utf8Path, Utf8PathBuf}; +use cap_std_ext::cap_std::{ambient_authority, fs::Dir}; +use clap::{Args, ValueEnum}; +use composefs_ctl::composefs::fsverity::{FsVerityHashValue, Sha512HashValue}; +use ostree::gio; +use ostree_ext::{ostree, ostree_prepareroot, sysroot::SysrootLock}; +use rustix::fs::{AtFlags, CWD, Mode, OFlags, StatxFlags, openat, statx}; +use rustix::mount::{ + MoveMountFlags, OpenTreeFlags, UnmountFlags, move_mount, open_tree, unmount as unmount_path, +}; + +#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)] +#[clap(rename_all = "lowercase")] +pub(crate) enum Deployment { + Booted, + Staged, +} + +#[derive(Debug, Args, PartialEq, Eq)] +pub(crate) struct MountOpts { + /// Select exactly the booted deployment or the pending staged deployment. + #[arg(long, value_enum)] + pub(crate) deployment: Deployment, + + /// Absolute directory path inside the selected image to expose (`/` selects its root). + /// No path component may be a symlink. + #[arg(long, value_parser = crate::cli::parse_absolute_path)] + pub(crate) source: Utf8PathBuf, + + /// Existing empty absolute directory to mount the selected image content on. + #[arg(long, value_parser = crate::cli::parse_absolute_path)] + pub(crate) target: Utf8PathBuf, +} + +#[derive(Debug, Args, PartialEq, Eq)] +pub(crate) struct UnmountOpts { + /// Named mountpoint to unmount (non-recursive; bootc provenance is not checked). + #[arg(value_parser = crate::cli::parse_absolute_path)] + pub(crate) target: Utf8PathBuf, +} + +struct MountedImageRoot { + tree: OwnedFd, + // Keep the repository/sysroot locked while cloning and attaching its tree. + _storage: StorageGuard, + // A non-composefs OSTree checkout has deployment-local /etc. Replace it + // with pristine image content from /usr/etc before exposing the tree. + checkout: bool, +} + +enum StorageGuard { + Composefs { + _repo: crate::store::ComposefsRepository, + }, + Ostree { + _sysroot: SysrootLock, + }, +} + +pub(crate) async fn mount(opts: MountOpts) -> Result<()> { + source_relative_path(&opts.source)?; + let composefs_booted = crate::bootc_composefs::status::composefs_booted()?; + // Select only from the active backend. These lookups are deliberately + // narrower than `status::get_host()`: they do not initialize storage, + // migrate repository metadata, configure the ESP, or change namespaces. + let image = if let Some(booted) = composefs_booted { + let (id, allow_missing_fsverity) = match opts.deployment { + Deployment::Booted => (booted.digest.to_string(), booted.allow_missing_fsverity), + Deployment::Staged => ( + staged_composefs_deployment_id(&booted.digest)?, + booted.allow_missing_fsverity, + ), + }; + mount_composefs_image(&opts, id, allow_missing_fsverity)? + } else { + mount_ostree_image(&opts).await? + }; + let MountedImageRoot { + tree, + _storage, + checkout, + } = image; + + if checkout { + mount_pristine_etc(&tree)?; + } + bootc_initramfs_setup::set_mount_tree_readonly(&tree) + .context("Making selected deployment image read-only")?; + + let image_root = Dir::reopen_dir(&tree).context("Opening selected image root")?; + let source = open_source(&image_root, &opts.source)?; + // Open once and retain this descriptor through validation and attachment. + // This avoids checking one pathname and mounting on a replacement object. + let (target, target_parent) = open_mount_target(&opts.target)?; + ensure_not_root_target(&target, &opts.target)?; + let source_metadata = source.metadata().context("Inspecting image source")?; + let target_metadata = target + .metadata() + .with_context(|| format!("Inspecting mount target {}", opts.target))?; + ensure!( + source_metadata.is_dir() && target_metadata.is_dir(), + "image source {} and target {} must both be directories", + opts.source, + opts.target + ); + + let source_path = format!("/proc/self/fd/{}", source.as_raw_fd()); + let source_tree = open_tree( + CWD, + source_path.as_str(), + OpenTreeFlags::OPEN_TREE_CLONE | OpenTreeFlags::OPEN_TREE_CLOEXEC, + ) + .with_context(|| format!("Cloning image source {}", opts.source))?; + bootc_initramfs_setup::set_mount_tree_readonly_nosymfollow(&source_tree) + .context("Making selected image content read-only and preventing symlink traversal")?; + + // Check immediately before attachment so a changed target cannot silently + // hide newly-added contents or stack another mount. + ensure_directory_empty(&target, &opts.target)?; + if let Some(parent) = target_parent.as_ref() { + ensure_not_mountpoint(&target, parent, &opts.target)?; + } + + move_mount( + &source_tree, + "", + &target, + "", + MoveMountFlags::MOVE_MOUNT_F_EMPTY_PATH | MoveMountFlags::MOVE_MOUNT_T_EMPTY_PATH, + ) + .with_context(|| format!("Attaching image source {} at {}", opts.source, opts.target))?; + + Ok(()) +} + +/// Read the composefs staged selector without constructing `BootedStorage`. +/// The staged ID is valid only when it names a distinct deployment with local +/// composefs state and a parseable origin file. +fn staged_composefs_deployment_id(booted_id: &str) -> Result { + use crate::composefs_consts::{ + COMPOSEFS_STAGED_DEPLOYMENT_FNAME, COMPOSEFS_TRANSIENT_STATE_DIR, + }; + + let staged_path = + format!("{COMPOSEFS_TRANSIENT_STATE_DIR}/{COMPOSEFS_STAGED_DEPLOYMENT_FNAME}"); + let staged_json = std::fs::read_to_string(&staged_path) + .with_context(|| format!("Reading staged composefs deployment selector {staged_path}"))?; + let id = staged_composefs_id_from_json(&staged_json, booted_id)?; + + let sysroot = Dir::open_ambient_dir("/sysroot", ambient_authority()) + .context("Opening booted system sysroot")?; + let origin = crate::bootc_composefs::state::read_origin(&sysroot, &id)?.ok_or_else(|| { + anyhow::anyhow!("No composefs state or origin for staged deployment {id}") + })?; + let boot_type = origin + .get::( + crate::composefs_consts::ORIGIN_KEY_BOOT, + crate::composefs_consts::ORIGIN_KEY_BOOT_TYPE, + ) + .ok_or_else(|| { + anyhow::anyhow!("Staged composefs deployment {id} has no boot type in its origin") + })?; + crate::bootc_composefs::boot::BootType::try_from(boot_type.as_str()) + .context("Parsing staged composefs deployment boot type")?; + Ok(id) +} + +fn staged_composefs_id_from_json(contents: &str, booted_id: &str) -> Result { + let staged: crate::bootc_composefs::status::StagedDeployment = + serde_json::from_str(contents).context("Parsing staged composefs deployment selector")?; + let id = Sha512HashValue::from_hex(&staged.depl_id) + .context("Parsing staged composefs deployment ID")? + .to_hex(); + ensure!(id != booted_id, "No staged composefs deployment found"); + Ok(id) +} + +fn mount_composefs_image( + opts: &MountOpts, + id: String, + allow_missing_fsverity: bool, +) -> Result { + let sysroot = Dir::open_ambient_dir("/sysroot", ambient_authority()) + .context("Opening booted system sysroot")?; + let mut repo = crate::bootc_composefs::repo::open_composefs_repo(&sysroot) + .context("Opening existing composefs repository")?; + if allow_missing_fsverity { + repo.set_insecure(); + } + let tree = repo + .mount(&id) + .with_context(|| format!("Mounting {:?} composefs deployment {id}", opts.deployment))?; + Ok(MountedImageRoot { + tree, + _storage: StorageGuard::Composefs { _repo: repo }, + checkout: false, + }) +} + +async fn mount_ostree_image(opts: &MountOpts) -> Result { + // Open /sysroot through a retained directory fd and do the same narrow + // load/lock sequence used by install-mount. In particular, do not call + // prepare_for_write() or initialize boot storage for this read-only query. + let sysroot_dir = Dir::open_ambient_dir("/sysroot", ambient_authority()) + .context("Opening booted system sysroot")?; + let path = format!("/proc/self/fd/{}", sysroot_dir.as_raw_fd()); + let sysroot_file = gio::File::for_path(path); + let sysroot = ostree::Sysroot::new(Some(&sysroot_file)); + sysroot + .load(gio::Cancellable::NONE) + .context("Loading booted OSTree sysroot")?; + let sysroot = SysrootLock::new_from_sysroot(&sysroot) + .await + .context("Locking booted OSTree sysroot")?; + + let deployment = match opts.deployment { + Deployment::Booted => sysroot + .require_booted_deployment() + .context("No booted OSTree deployment found")? + .clone(), + Deployment::Staged => { + let booted = sysroot + .require_booted_deployment() + .context("No booted OSTree deployment found")?; + sysroot + .deployments() + .into_iter() + .find(|deployment| deployment.is_staged() && deployment.osname() == booted.osname()) + .ok_or_else(|| anyhow::anyhow!("No staged OSTree deployment found"))? + } + }; + let sysroot_dir = crate::utils::sysroot_dir(&sysroot)?; + let deployment_path = sysroot.deployment_dirpath(&deployment); + let deployment_dir = sysroot_dir + .open_dir(deployment_path.as_str()) + .with_context(|| format!("Opening selected OSTree deployment {deployment_path}"))?; + let repo = sysroot_dir + .open_dir("ostree/repo") + .context("Opening booted OSTree repository")?; + let config = ostree_prepareroot::load_config_from_root(&deployment_dir) + .context("Loading selected deployment's prepare-root.conf")?; + let (tree, checkout) = match ostree_prepareroot::mount_composefs( + &deployment_dir, + &repo, + deployment.csum().as_str(), + config.as_ref(), + ) + .context("Mounting selected OSTree deployment image")? + { + Some(tree) => (tree, false), + None => ( + open_tree( + &sysroot_dir, + deployment_path.as_str(), + OpenTreeFlags::OPEN_TREE_CLONE | OpenTreeFlags::OPEN_TREE_CLOEXEC, + ) + .context("Cloning selected OSTree deployment checkout")?, + true, + ), + }; + Ok(MountedImageRoot { + tree, + _storage: StorageGuard::Ostree { _sysroot: sysroot }, + checkout, + }) +} + +fn mount_pristine_etc(tree: &impl AsFd) -> Result<()> { + let root = Dir::reopen_dir(tree).context("Opening selected OSTree checkout")?; + let usr_etc = root + .open_dir("usr/etc") + .context("Opening pristine image /usr/etc")?; + let etc_tree = open_tree( + &usr_etc, + ".", + OpenTreeFlags::OPEN_TREE_CLONE | OpenTreeFlags::OPEN_TREE_CLOEXEC, + ) + .context("Cloning pristine image /usr/etc")?; + move_mount( + &etc_tree, + "", + &root, + "etc", + MoveMountFlags::MOVE_MOUNT_F_EMPTY_PATH, + ) + .context("Replacing deployment-local /etc with pristine image /usr/etc") +} + +fn open_source(root: &Dir, source: &Utf8Path) -> Result { + let relative = source_relative_path(source)?; + let components = relative + .components() + .filter_map(|component| match component { + camino::Utf8Component::Normal(component) => Some(component), + _ => None, + }) + .collect::>(); + + let mut parent: Option = None; + if components.is_empty() { + let fd = openat( + root, + ".", + OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC, + Mode::empty(), + ) + .context("Opening image root")?; + return Ok(std::fs::File::from(fd)); + } + + for (index, component) in components.iter().enumerate() { + let fd = match &parent { + Some(parent) => openat( + parent, + *component, + OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC, + Mode::empty(), + ), + None => openat( + root, + *component, + OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC, + Mode::empty(), + ), + } + .with_context(|| format!("Opening image source component {component} in {source}"))?; + let file = std::fs::File::from(fd); + let metadata = file + .metadata() + .with_context(|| format!("Inspecting image source component {component}"))?; + ensure!( + !metadata.file_type().is_symlink(), + "image source path components must not be symlinks: {source}" + ); + if index + 1 < components.len() { + ensure!( + metadata.is_dir(), + "image source path component {component} is not a directory" + ); + parent = Some(file.into()); + } else { + return Ok(file); + } + } + unreachable!("non-empty component list returns from the loop") +} + +fn source_relative_path(source: &Utf8Path) -> Result { + ensure!( + source.is_absolute(), + "image source must be absolute: {source}" + ); + for component in source.components() { + if matches!(component, camino::Utf8Component::ParentDir) { + bail!("image source must not contain `..`: {source}"); + } + } + source + .strip_prefix("/") + .map(|path| path.to_owned()) + .with_context(|| format!("Invalid absolute image source {source}")) +} + +pub(crate) fn unmount(opts: UnmountOpts) -> Result<()> { + // Pin the object named by the explicit target and ask the kernel to unmount + // through its procfs fd link. The kernel rejects the operation unless this + // descriptor resolves to a mount root; no recursive flag is used. + let target = open_existing_path(&opts.target)?; + ensure_not_root_target(&target, &opts.target)?; + let fd_path = format!("/proc/self/fd/{}", target.as_raw_fd()); + unmount_path(fd_path.as_str(), UnmountFlags::empty()) + .with_context(|| format!("Unmounting {}", opts.target))?; + Ok(()) +} + +fn open_existing_path(path: &Utf8Path) -> Result { + open_path_no_symlinks(path, false).map(|(target, _)| target) +} + +fn open_mount_target(path: &Utf8Path) -> Result<(std::fs::File, Option)> { + open_path_no_symlinks(path, true) +} + +/// Resolve an absolute path one component at a time, retaining the parent +/// descriptor so checks and mount attachment refer to the same directory. +fn open_path_no_symlinks( + path: &Utf8Path, + final_directory: bool, +) -> Result<(std::fs::File, Option)> { + ensure!(path.is_absolute(), "target path must be absolute: {path}"); + ensure!( + path.components().all(|component| !matches!( + component, + camino::Utf8Component::ParentDir | camino::Utf8Component::Prefix(_) + )), + "target path must not contain `..`: {path}" + ); + let components = path + .components() + .filter_map(|component| match component { + camino::Utf8Component::RootDir => None, + camino::Utf8Component::Normal(component) => Some(component.to_owned()), + camino::Utf8Component::CurDir => None, + camino::Utf8Component::ParentDir | camino::Utf8Component::Prefix(_) => unreachable!(), + }) + .collect::>(); + + let root = openat( + CWD, + "/", + OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC, + Mode::empty(), + ) + .context("Opening filesystem root")?; + let mut parent = std::fs::File::from(root); + if components.is_empty() { + ensure!(!final_directory, "mount target must not be filesystem root"); + return Ok((parent, None)); + } + + for (index, component) in components.iter().enumerate() { + let final_component = index + 1 == components.len(); + let mut flags = OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC; + if !final_component || final_directory { + flags |= OFlags::DIRECTORY; + } + let fd = openat(&parent, component.as_str(), flags, Mode::empty()) + .with_context(|| format!("Opening target path component {component} in {path}"))?; + let current = std::fs::File::from(fd); + let metadata = current + .metadata() + .with_context(|| format!("Inspecting target path component {component} in {path}"))?; + ensure!( + !metadata.file_type().is_symlink(), + "target path components must not be symlinks: {path}" + ); + if final_component { + return Ok((current, Some(parent))); + } + parent = current; + } + unreachable!("non-empty component list returns from the loop") +} + +fn ensure_directory_empty(target: &impl AsFd, path: &Utf8Path) -> Result<()> { + let mut entries = Dir::reopen_dir(target) + .with_context(|| format!("Opening mount target directory {path}"))? + .entries()?; + ensure!( + entries.next().is_none(), + "mount target {path} must be empty" + ); + Ok(()) +} + +/// Compare Linux mount IDs for a directory and its parent. A different ID +/// means the target is already a mountpoint, including an overmount. +fn ensure_not_mountpoint(target: &impl AsFd, parent: &impl AsFd, path: &Utf8Path) -> Result<()> { + let target_mount_id = mount_id(target)?; + let parent_mount_id = mount_id(parent)?; + ensure!( + target_mount_id == parent_mount_id, + "mount target {path} is already a mountpoint" + ); + Ok(()) +} + +fn mount_id(fd: &impl AsFd) -> Result { + let stat = statx(fd.as_fd(), "", AtFlags::EMPTY_PATH, StatxFlags::MNT_ID) + .context("Reading mount ID with statx")?; + ensure!( + stat.stx_mask & StatxFlags::MNT_ID.bits() == StatxFlags::MNT_ID.bits(), + "kernel did not provide mount IDs via statx (STATX_MNT_ID is required)" + ); + Ok(stat.stx_mnt_id) +} + +fn ensure_not_root_target(target: &std::fs::File, path: &Utf8Path) -> Result<()> { + let root = openat(CWD, "/", OFlags::PATH | OFlags::CLOEXEC, Mode::empty()) + .context("Opening filesystem root")?; + let root = std::fs::File::from(root); + let target_metadata = target + .metadata() + .with_context(|| format!("Inspecting target {path}"))?; + let root_metadata = root.metadata().context("Inspecting filesystem root")?; + ensure!( + target_metadata.dev() != root_metadata.dev() + || target_metadata.ino() != root_metadata.ino(), + "Refusing to mount or unmount the root filesystem" + ); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::{ + Deployment, MountOpts, UnmountOpts, ensure_directory_empty, ensure_not_mountpoint, + ensure_not_root_target, open_existing_path, open_mount_target, open_source, + source_relative_path, + }; + use crate::cli::{ImageOpts, InstallOpts, Opt}; + use camino::{Utf8Path, Utf8PathBuf}; + use cap_std_ext::cap_std::ambient_authority; + use clap::Parser; + use std::os::unix::fs::symlink; + + #[test] + fn parses_image_mount_and_unmount_without_changing_install_mount() { + let parsed = Opt::try_parse_from([ + "bootc", + "image", + "mount", + "--deployment", + "staged", + "--source", + "/usr", + "--target", + "/mnt/image", + ]) + .unwrap(); + assert!(matches!( + parsed, + Opt::Image(ImageOpts::Mount(MountOpts { + deployment: Deployment::Staged, + .. + })) + )); + assert!(matches!( + Opt::try_parse_from(["bootc", "image", "unmount", "/mnt/image"]).unwrap(), + Opt::Image(ImageOpts::Unmount(UnmountOpts { .. })) + )); + assert!(matches!( + Opt::try_parse_from([ + "bootc", + "install", + "mount", + "--sysroot", + "/sysroot", + "--latest", + "/mnt/installed" + ]) + .unwrap(), + Opt::Install(InstallOpts::Mount(_)) + )); + } + + #[test] + fn source_paths_must_stay_beneath_image_root() { + for path in ["relative", "/usr/../etc", "/../../etc"] { + assert!(source_relative_path(Utf8Path::new(path)).is_err(), "{path}"); + } + assert_eq!( + source_relative_path(Utf8Path::new("/usr/bin")) + .unwrap() + .as_str(), + "usr/bin" + ); + assert_eq!( + source_relative_path(Utf8Path::new("/")).unwrap().as_str(), + "" + ); + } + + #[test] + fn refuses_root_as_mount_or_unmount_target() { + let root = open_existing_path(Utf8Path::new("/")).unwrap(); + assert!(ensure_not_root_target(&root, Utf8Path::new("/")).is_err()); + + let temp = tempfile::tempdir().unwrap(); + let target = Utf8PathBuf::from_path_buf(temp.path().to_owned()).unwrap(); + let target_fd = open_existing_path(&target).unwrap(); + assert!(ensure_not_root_target(&target_fd, &target).is_ok()); + + let root_alias = temp.path().join("root-alias"); + symlink("/", &root_alias).unwrap(); + let root_alias = Utf8PathBuf::from_path_buf(root_alias).unwrap(); + assert!(open_existing_path(&root_alias).is_err()); + } + + #[test] + fn source_lookup_rejects_symlink_components_and_preserves_file_directory_matches() { + let temp = tempfile::tempdir().unwrap(); + std::fs::create_dir(temp.path().join("real-dir")).unwrap(); + std::fs::write(temp.path().join("real-file"), b"image").unwrap(); + symlink("/", temp.path().join("absolute-link")).unwrap(); + symlink("real-file", temp.path().join("file-link")).unwrap(); + let root = + cap_std_ext::cap_std::fs::Dir::open_ambient_dir(temp.path(), ambient_authority()) + .unwrap(); + + assert!(open_source(&root, Utf8Path::new("/absolute-link/etc")).is_err()); + assert!(open_source(&root, Utf8Path::new("/file-link")).is_err()); + assert!( + open_source(&root, Utf8Path::new("/real-file")) + .unwrap() + .metadata() + .unwrap() + .is_file() + ); + assert!( + open_source(&root, Utf8Path::new("/real-dir")) + .unwrap() + .metadata() + .unwrap() + .is_dir() + ); + assert!( + open_source(&root, Utf8Path::new("/")) + .unwrap() + .metadata() + .unwrap() + .is_dir() + ); + } + + #[test] + fn mount_target_must_be_empty_and_have_no_symlink_components() { + let temp = tempfile::tempdir().unwrap(); + let target_path = Utf8PathBuf::from_path_buf(temp.path().join("empty")).unwrap(); + std::fs::create_dir(&target_path).unwrap(); + let (target, parent) = open_mount_target(&target_path).unwrap(); + ensure_directory_empty(&target, &target_path).unwrap(); + ensure_not_mountpoint(&target, parent.as_ref().unwrap(), &target_path).unwrap(); + + std::fs::write(target_path.join("existing"), b"content").unwrap(); + assert!(ensure_directory_empty(&target, &target_path).is_err()); + + let linked_target = temp.path().join("linked-target"); + symlink(&target_path, &linked_target).unwrap(); + let linked_target = Utf8PathBuf::from_path_buf(linked_target).unwrap(); + assert!(open_mount_target(&linked_target).is_err()); + + let linked_parent = temp.path().join("linked-parent"); + symlink(temp.path(), &linked_parent).unwrap(); + let nested_target = Utf8PathBuf::from_path_buf(linked_parent.join("empty")).unwrap(); + assert!(open_mount_target(&nested_target).is_err()); + } + + #[test] + fn staged_composefs_selector_requires_a_valid_distinct_digest() { + let booted = "aa".repeat(64); + let staged = "bb".repeat(64); + let valid_json = format!(r#"{{"depl_id":"{staged}","finalization_locked":false}}"#); + assert_eq!( + super::staged_composefs_id_from_json(&valid_json, &booted).unwrap(), + staged + ); + assert!(super::staged_composefs_id_from_json(&valid_json, &staged).is_err()); + assert!(super::staged_composefs_id_from_json("{}", &booted).is_err()); + assert!( + super::staged_composefs_id_from_json( + r#"{"depl_id":"not-a-digest","finalization_locked":false}"#, + &booted + ) + .is_err() + ); + } +} diff --git a/crates/lib/src/lib.rs b/crates/lib/src/lib.rs index 07e6441868..4747bc6c96 100644 --- a/crates/lib/src/lib.rs +++ b/crates/lib/src/lib.rs @@ -81,6 +81,7 @@ pub(crate) mod fsck; pub(crate) mod generator; mod glyph; mod image; +mod image_mount; mod install; pub(crate) mod journal; mod k8sapitypes; diff --git a/docs/src/bootc-experimental-image.7.md b/docs/src/bootc-experimental-image.7.md index e86a7c8e39..0b88017db2 100644 --- a/docs/src/bootc-experimental-image.7.md +++ b/docs/src/bootc-experimental-image.7.md @@ -15,6 +15,47 @@ then be managed independently; used as a base image, pushed to a registry, etc. Run `bootc image copy-to-storage --help` for more options. +## Mounting deployment image content + +`bootc image mount` exposes a path from the locally available booted or staged +deployment image at an existing empty directory. The source must be a directory; +`--source /` selects the image root. It refuses target paths with symlink +components and targets that are already mountpoints. It does not pull an image +or merge deployment state: `/var` is never mounted from host state, and OSTree +checkout fallbacks use the image's pristine `/usr/etc` rather than deployment-local +`/etc`. The target is checked immediately before attachment; callers must prevent +concurrent changes to the target directory while the command runs. + +```sh +bootc image mount --deployment booted --source /usr --target /mnt/booted-usr +bootc image unmount /mnt/booted-usr +``` + +Use `--deployment staged` to select the pending deployment from the active +backend: OSTree selects its staged deployment, while composefs reads the +existing `/run/composefs/staged-deployment` selector. Staged selection does not +discover transitions across backends. If the active backend has no staged +deployment, the command fails instead of guessing an image. This lookup does +not initialize storage, migrate repository metadata, configure the ESP, or +change mount namespaces. + +The mounted content is read-only, `nosuid`, and `nodev`. It intentionally +remains executable: the mount does not use `noexec`, so direct executable +paths in the mounted image can be run. The image root itself (`--source /`) is +a valid directory source. Read-only, `nosuid`, `nodev`, and `nosymfollow` do not +disable execution. However, `nosymfollow` prevents following symlinks in the +mounted tree, so a symlink path to an executable will not resolve, even when +its target is also inside the image. The requested source path itself must +also contain no symlink components; this prevents source lookup from escaping +the image before the mount is created. Unmount is non-recursive and operates on +the opened target; it fails if the target is not a mount root or if child mounts +prevent a safe unmount. `bootc image unmount TARGET` is a general-purpose +`umount TARGET`: it unmounts the named non-root mount, whether or not bootc +created it. It does not track or verify bootc provenance, so take care to name +only the mount you intend to remove. Mount attachment follows the propagation +behavior of the target mount namespace; use a private mount namespace if +propagation is undesired. + Example workflow: ``` @@ -25,4 +66,3 @@ FROM localhost/bootc $ podman build -t localhost/bootc-custom . $ bootc switch --transport containers-storage localhost/bootc-custom ``` - diff --git a/tmt/plans/integration.fmf b/tmt/plans/integration.fmf index b7d1e932f4..8030883cd0 100644 --- a/tmt/plans/integration.fmf +++ b/tmt/plans/integration.fmf @@ -459,4 +459,11 @@ execute: enabled: false because: the derived images are built in the VM, which has no keys to sign their UKIs for Secure Boot extra-skip_if_ostree: true + +/plan-68-image-mount: + summary: Verify booted and staged deployment image mounts + discover: + how: fmf + test: + - /tmt/tests/tests/test-64-image-mount # END GENERATED PLANS diff --git a/tmt/tests/booted/test-64-image-mount.nu b/tmt/tests/booted/test-64-image-mount.nu new file mode 100644 index 0000000000..ed54bd4d68 --- /dev/null +++ b/tmt/tests/booted/test-64-image-mount.nu @@ -0,0 +1,116 @@ +# number: 64 +# tmt: +# summary: Verify booted and staged deployment image mounts +# duration: 10m + +use std assert + +def assert_mount_options [target] { + let options = ( + findmnt --mountpoint $target --json + | from json + | get filesystems.0.options + | split row "," + ) + # findmnt's options field reports these VFS mount options, including nosymfollow. + for option in [ro nosuid nodev nosymfollow] { + assert ( + $options | any { |value| $value == $option } + ) $"($target) should have the ($option) mount option" + } + assert (not ($options | any { |value| $value == "noexec" })) $"($target) should not have noexec" +} + +def cleanup_targets [targets] { + $targets | each { |target| + let result = (do -i { bootc image unmount $target } | complete) + if $result.exit_code != 0 { + $"($target): unmount failed: ($result.stderr); mount target left in place" + } + } | where { |failure| $failure != null } +} + +def mount_image [deployment source target] { + let result = (do -i { + bootc image mount --deployment $deployment --source $source --target $target + } | complete) + if $result.exit_code != 0 { + error make { + msg: $"Failed to mount ($deployment) image source ($source) at ($target): ($result.stderr)" + } + } +} + +def verify_image_mounts [base] { + let root_target = ($base | path join "root") + let usr_target = ($base | path join "usr") + let staged_target = ($base | path join "staged") + mut mounted = [] + let result = try { + mkdir $root_target $usr_target $staged_target + + mount_image booted / $root_target + $mounted = ($mounted | append $root_target) + mount_image booted /usr $usr_target + $mounted = ($mounted | append $usr_target) + + let root_os_release = ($root_target | path join "usr/lib/os-release") + let usr_os_release = ($usr_target | path join "lib/os-release") + assert ($root_os_release | path exists) "booted root mount should contain usr/lib/os-release" + assert ($usr_os_release | path exists) "/usr mount should contain lib/os-release" + assert equal (open $root_os_release | into string) (open $usr_os_release | into string) + + assert_mount_options $root_target + assert_mount_options $usr_target + + let write_path = ($usr_target | path join ".bootc-image-mount-write-test") + let write_result = (do -i { touch $write_path } | complete) + assert ($write_result.exit_code != 0) "writes to mounted image content should fail" + assert (not ($write_path | path exists)) "failed write should not create a file" + + # The mount is intentionally not noexec; verify an image executable runs. + let true_path = ($usr_target | path join "bin/true") + let executable_result = (do -i { ^$true_path } | complete) + assert equal $executable_result.exit_code 0 "mounted /usr/bin/true should be executable" + + let status = (bootc status --json | from json) + if (($status.status.staged? | default null) != null) { + mount_image staged /usr $staged_target + $mounted = ($mounted | append $staged_target) + let staged_os_release = ($staged_target | path join "lib/os-release") + assert ($staged_os_release | path exists) "staged /usr mount should contain lib/os-release" + assert_mount_options $staged_target + } else { + print "SKIP: staged image-mount coverage unavailable (active backend reports no staged deployment)" + } + true + } catch { |error| $error } + + { + result: $result + mounted: $mounted + } +} + +let base = (^mktemp -d /run/bootc-image-mount.XXXXXX | str trim) +let test_outcome = (verify_image_mounts $base) +let mount_cleanup_errors = (cleanup_targets $test_outcome.mounted) +let cleanup_errors = if (($mount_cleanup_errors | length) > 0) { + $mount_cleanup_errors | append $"($base): directory retained because a mount could not be unmounted" +} else { + let remove_result = (do -i { rm --recursive $base } | complete) + if $remove_result.exit_code == 0 { + [] + } else { + [$"($base): failed to remove test directory: ($remove_result.stderr)"] + } +} + +if (($cleanup_errors | length) > 0) { + error make { + msg: $"Failed to clean up image mounts: ($cleanup_errors); test result: ($test_outcome.result)" + } +} +if $test_outcome.result != true { + error make { msg: $"Image mount assertions failed: ($test_outcome.result)" } +} diff --git a/tmt/tests/tests.fmf b/tmt/tests/tests.fmf index 21aab2ea64..3e6dd6214f 100644 --- a/tmt/tests/tests.fmf +++ b/tmt/tests/tests.fmf @@ -301,3 +301,8 @@ check: enabled: false because: the derived images are built in the VM, which has no keys to sign their UKIs for Secure Boot test: nu booted/test-composefs-xbootldr.nu + +/test-68-image-mount: + summary: Verify booted and staged deployment image mounts + duration: 10m + test: nu booted/test-64-image-mount.nu From a8fe9ae1ff1812ccef09f45303daa797addf2081 Mon Sep 17 00:00:00 2001 From: ckyrouac Date: Mon, 2 Nov 2026 16:15:10 -0600 Subject: [PATCH 02/10] image: Fix deployment mount cleanup Invoke external rm when capturing cleanup status, and close the mountpoint descriptor before unmounting it to avoid EBUSY. Assisted-by: AI Signed-off-by: ckyrouac --- crates/lib/src/image_mount.rs | 35 +++++++++++++++---------- tmt/tests/booted/test-64-image-mount.nu | 2 +- 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/crates/lib/src/image_mount.rs b/crates/lib/src/image_mount.rs index 86a8723055..63f3d420f4 100644 --- a/crates/lib/src/image_mount.rs +++ b/crates/lib/src/image_mount.rs @@ -371,21 +371,28 @@ fn source_relative_path(source: &Utf8Path) -> Result { } pub(crate) fn unmount(opts: UnmountOpts) -> Result<()> { - // Pin the object named by the explicit target and ask the kernel to unmount - // through its procfs fd link. The kernel rejects the operation unless this - // descriptor resolves to a mount root; no recursive flag is used. - let target = open_existing_path(&opts.target)?; + // Resolve through directory descriptors so parent path components cannot + // be swapped for symlinks. Keep the parent, but close the target before + // unmounting: an open descriptor to the mount root makes it busy. + let (target, parent) = open_path_no_symlinks(&opts.target, false)?; ensure_not_root_target(&target, &opts.target)?; - let fd_path = format!("/proc/self/fd/{}", target.as_raw_fd()); - unmount_path(fd_path.as_str(), UnmountFlags::empty()) + let parent = parent.ok_or_else(|| anyhow::anyhow!("Cannot unmount filesystem root"))?; + ensure!( + mount_id(&target)? != mount_id(&parent)?, + "{} is not a mountpoint", + opts.target + ); + let name = opts + .target + .file_name() + .ok_or_else(|| anyhow::anyhow!("Invalid unmount target {}", opts.target))?; + let fd_path = format!("/proc/self/fd/{}/{}", parent.as_raw_fd(), name); + drop(target); + unmount_path(fd_path.as_str(), UnmountFlags::NOFOLLOW) .with_context(|| format!("Unmounting {}", opts.target))?; Ok(()) } -fn open_existing_path(path: &Utf8Path) -> Result { - open_path_no_symlinks(path, false).map(|(target, _)| target) -} - fn open_mount_target(path: &Utf8Path) -> Result<(std::fs::File, Option)> { open_path_no_symlinks(path, true) } @@ -504,7 +511,7 @@ fn ensure_not_root_target(target: &std::fs::File, path: &Utf8Path) -> Result<()> mod tests { use super::{ Deployment, MountOpts, UnmountOpts, ensure_directory_empty, ensure_not_mountpoint, - ensure_not_root_target, open_existing_path, open_mount_target, open_source, + ensure_not_root_target, open_mount_target, open_path_no_symlinks, open_source, source_relative_path, }; use crate::cli::{ImageOpts, InstallOpts, Opt}; @@ -572,18 +579,18 @@ mod tests { #[test] fn refuses_root_as_mount_or_unmount_target() { - let root = open_existing_path(Utf8Path::new("/")).unwrap(); + let (root, _) = open_path_no_symlinks(Utf8Path::new("/"), false).unwrap(); assert!(ensure_not_root_target(&root, Utf8Path::new("/")).is_err()); let temp = tempfile::tempdir().unwrap(); let target = Utf8PathBuf::from_path_buf(temp.path().to_owned()).unwrap(); - let target_fd = open_existing_path(&target).unwrap(); + let (target_fd, _) = open_path_no_symlinks(&target, false).unwrap(); assert!(ensure_not_root_target(&target_fd, &target).is_ok()); let root_alias = temp.path().join("root-alias"); symlink("/", &root_alias).unwrap(); let root_alias = Utf8PathBuf::from_path_buf(root_alias).unwrap(); - assert!(open_existing_path(&root_alias).is_err()); + assert!(open_path_no_symlinks(&root_alias, false).is_err()); } #[test] diff --git a/tmt/tests/booted/test-64-image-mount.nu b/tmt/tests/booted/test-64-image-mount.nu index ed54bd4d68..a50b8e1bb7 100644 --- a/tmt/tests/booted/test-64-image-mount.nu +++ b/tmt/tests/booted/test-64-image-mount.nu @@ -98,7 +98,7 @@ let mount_cleanup_errors = (cleanup_targets $test_outcome.mounted) let cleanup_errors = if (($mount_cleanup_errors | length) > 0) { $mount_cleanup_errors | append $"($base): directory retained because a mount could not be unmounted" } else { - let remove_result = (do -i { rm --recursive $base } | complete) + let remove_result = (do -i { ^rm --recursive $base } | complete) if $remove_result.exit_code == 0 { [] } else { From e10b44a4f6e4c522918d94dbb68094c5de84b892 Mon Sep 17 00:00:00 2001 From: ckyrouac Date: Tue, 3 Nov 2026 13:31:26 -0600 Subject: [PATCH 03/10] image: Fix booted deployment image mounts Acquire the OSTree lock through a writable detached sysroot clone while keeping read-only data paths attached. Stage detached source mounts in a private worker namespace before cloning so they can be attached in the caller namespace. Fix Nushell cleanup command capture and assert image mounts leave /sysroot options unchanged. Assisted-by: AI Signed-off-by: ckyrouac --- crates/initramfs/src/lib.rs | 11 + crates/lib/src/image_mount.rs | 256 ++++++++++++++++++++++-- tmt/tests/booted/test-64-image-mount.nu | 13 +- 3 files changed, 257 insertions(+), 23 deletions(-) diff --git a/crates/initramfs/src/lib.rs b/crates/initramfs/src/lib.rs index a7bc063844..708a25387d 100644 --- a/crates/initramfs/src/lib.rs +++ b/crates/initramfs/src/lib.rs @@ -94,6 +94,17 @@ pub fn set_mount_tree_readonly(fd: impl AsFd) -> Result<()> { mount_setattr(fd, libc::AT_EMPTY_PATH | libc::AT_RECURSIVE, &attr) } +/// Clear the read-only attribute on a detached mount without changing its children. +pub fn clear_mount_readonly(fd: impl AsFd) -> Result<()> { + let attr = MountAttr { + attr_set: 0, + attr_clr: MOUNT_ATTR_RDONLY, + propagation: 0, + userns_fd: 0, + }; + mount_setattr(fd, libc::AT_EMPTY_PATH, &attr) +} + /// Set a mount tree read-only, nosuid, nodev, and prevent symlink traversal within it. /// /// A bind-mounted image tree is not a chroot: absolute and escaping symlinks diff --git a/crates/lib/src/image_mount.rs b/crates/lib/src/image_mount.rs index 63f3d420f4..387a788c1a 100644 --- a/crates/lib/src/image_mount.rs +++ b/crates/lib/src/image_mount.rs @@ -3,8 +3,12 @@ //! This deliberately does not assemble deployment state: in particular, it //! never bind-mounts `/var` or the deployment's mutable `/etc` over the image. -use std::os::fd::{AsFd, AsRawFd, OwnedFd}; use std::os::unix::fs::MetadataExt; +use std::{ + os::fd::{AsFd, AsRawFd, OwnedFd}, + path::PathBuf, + thread, +}; use anyhow::{Context, Result, bail, ensure}; use camino::{Utf8Path, Utf8PathBuf}; @@ -17,6 +21,10 @@ use rustix::fs::{AtFlags, CWD, Mode, OFlags, StatxFlags, openat, statx}; use rustix::mount::{ MoveMountFlags, OpenTreeFlags, UnmountFlags, move_mount, open_tree, unmount as unmount_path, }; +use rustix::{ + mount::{MountPropagationFlags, mount_change}, + thread::{UnshareFlags, unshare_unsafe}, +}; #[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)] #[clap(rename_all = "lowercase")] @@ -62,7 +70,9 @@ enum StorageGuard { _repo: crate::store::ComposefsRepository, }, Ostree { + // Drop the lock before closing the detached mount it was opened through. _sysroot: SysrootLock, + _mount: OwnedFd, }, } @@ -113,13 +123,13 @@ pub(crate) async fn mount(opts: MountOpts) -> Result<()> { opts.target ); - let source_path = format!("/proc/self/fd/{}", source.as_raw_fd()); - let source_tree = open_tree( - CWD, - source_path.as_str(), - OpenTreeFlags::OPEN_TREE_CLONE | OpenTreeFlags::OPEN_TREE_CLOEXEC, - ) - .with_context(|| format!("Cloning image source {}", opts.source))?; + // `tree` is a detached mount. Kernel 6.12 rejects open_tree() paths which + // resolve through a directory fd inside an unattached mount. Attach it in + // an isolated worker namespace before cloning the already-validated source + // fd; never change mount visibility in the caller's namespace. + drop(image_root); + let source_tree = clone_source_in_staging_namespace(tree, source) + .with_context(|| format!("Cloning image source {}", opts.source))?; bootc_initramfs_setup::set_mount_tree_readonly_nosymfollow(&source_tree) .context("Making selected image content read-only and preventing symlink traversal")?; @@ -142,6 +152,102 @@ pub(crate) async fn mount(opts: MountOpts) -> Result<()> { Ok(()) } +/// Temporarily attach a detached image mount in a private worker namespace so +/// that the kernel can clone a validated directory fd from inside it. +#[allow(unsafe_code)] +fn clone_source_in_staging_namespace(tree: OwnedFd, source: std::fs::File) -> Result { + thread::Builder::new() + .name("bootc-image-mount-stage".to_owned()) + .spawn(move || -> Result { + // A dedicated OS thread is required because mount namespace + // unsharing applies to the calling thread, not the whole process. + // SAFETY: This is a dedicated worker thread and only CLONE_NEWNS + // is requested (not CLONE_FILES), so the operation cannot alter + // the calling thread's namespace or invalidate shared fd tables. + unsafe { unshare_unsafe(UnshareFlags::NEWNS) } + .context("Unsharing image mount staging thread namespace")?; + mount_change( + c"/", + MountPropagationFlags::PRIVATE | MountPropagationFlags::REC, + ) + .context("Making image mount staging namespace private")?; + + let directory = + tempfile::tempdir().context("Creating image mount staging directory")?; + let mut attachment = TemporaryMountAttachment { + path: directory.path().to_owned(), + _directory: directory, + mounted: false, + }; + move_mount( + &tree, + "", + CWD, + attachment.path.as_path(), + MoveMountFlags::MOVE_MOUNT_F_EMPTY_PATH, + ) + .context("Attaching image mount in staging namespace")?; + attachment.mounted = true; + + // Use AT_EMPTY_PATH only after the fd has a path in this namespace. + // Do not recurse: image-mount source selection has always cloned + // only the selected mount, not its mounted children. + let cloned = open_tree( + &source, + "", + OpenTreeFlags::OPEN_TREE_CLONE + | OpenTreeFlags::OPEN_TREE_CLOEXEC + | OpenTreeFlags::AT_EMPTY_PATH, + ) + .context("Cloning validated image source fd"); + + // Drop all handles into the attached mount before its synchronous, + // non-recursive unmount. The detached clone (if successful) remains + // alive independently and is returned to the caller. + drop(source); + drop(tree); + let unmounted = attachment.unmount(); + match (cloned, unmounted) { + (Ok(cloned), Ok(())) => Ok(cloned), + (Err(error), Ok(())) => Err(error), + (Ok(_), Err(error)) => Err(error), + (Err(error), Err(unmount_error)) => Err(error.context(format!( + "Also failed to unmount staging attachment: {unmount_error:#}" + ))), + } + }) + .context("Starting image mount staging thread")? + .join() + .map_err(|_| anyhow::anyhow!("Image mount staging thread panicked"))? +} + +/// Normal-unmount guard for the temporary staging attachment. Drop retries +/// synchronously during error unwinding; it intentionally never lazy-detaches. +struct TemporaryMountAttachment { + path: PathBuf, + _directory: tempfile::TempDir, + mounted: bool, +} + +impl TemporaryMountAttachment { + fn unmount(&mut self) -> Result<()> { + if self.mounted { + unmount_path(&self.path, UnmountFlags::empty()) + .context("Unmounting image mount staging attachment")?; + self.mounted = false; + } + Ok(()) + } +} + +impl Drop for TemporaryMountAttachment { + fn drop(&mut self) { + if let Err(error) = self.unmount() { + tracing::error!("Failed to unmount image staging attachment: {error:#}"); + } + } +} + /// Read the composefs staged selector without constructing `BootedStorage`. /// The staged ID is valid only when it names a distinct deployment with local /// composefs state and a parseable origin file. @@ -207,12 +313,27 @@ fn mount_composefs_image( } async fn mount_ostree_image(opts: &MountOpts) -> Result { - // Open /sysroot through a retained directory fd and do the same narrow - // load/lock sequence used by install-mount. In particular, do not call - // prepare_for_write() or initialize boot storage for this read-only query. + // OSTree's sysroot lock creates/opens a lock file, but /sysroot is normally + // mounted read-only. Clone the mount so that only this private mount view + // can be made writable; never call prepare_for_write(), which changes the + // mount namespace and would hide the image mount from the caller. let sysroot_dir = Dir::open_ambient_dir("/sysroot", ambient_authority()) .context("Opening booted system sysroot")?; - let path = format!("/proc/self/fd/{}", sysroot_dir.as_raw_fd()); + let sysroot_mount = open_tree( + &sysroot_dir, + ".", + OpenTreeFlags::OPEN_TREE_CLONE + | OpenTreeFlags::AT_RECURSIVE + | OpenTreeFlags::OPEN_TREE_CLOEXEC, + ) + .context("Cloning booted system sysroot mount")?; + bootc_initramfs_setup::clear_mount_readonly(&sysroot_mount) + .context("Making cloned booted system sysroot writable for OSTree locking")?; + + // OSTree opens the supplied path during load and uses its resulting + // directory fd for the genuine inter-process lock. Keep sysroot_mount + // alive for that fd and lock's full lifetime. + let path = format!("/proc/self/fd/{}", sysroot_mount.as_raw_fd()); let sysroot_file = gio::File::for_path(path); let sysroot = ostree::Sysroot::new(Some(&sysroot_file)); sysroot @@ -221,24 +342,39 @@ async fn mount_ostree_image(opts: &MountOpts) -> Result { let sysroot = SysrootLock::new_from_sysroot(&sysroot) .await .context("Locking booted OSTree sysroot")?; - - let deployment = match opts.deployment { - Deployment::Booted => sysroot + sysroot + .load(gio::Cancellable::NONE) + .context("Reloading locked booted OSTree sysroot")?; + + // libostree identifies the booted deployment only when its Sysroot points + // at the current root (/), not the physical backing sysroot (/sysroot). + // Read that identity while holding the lock above, then resolve it against + // the deployments from the locked backing sysroot below. + let booted_sysroot = ostree::Sysroot::new_default(); + booted_sysroot + .load(gio::Cancellable::NONE) + .context("Loading current OSTree root")?; + let selected_deployment = match opts.deployment { + Deployment::Booted => booted_sysroot .require_booted_deployment() .context("No booted OSTree deployment found")? .clone(), Deployment::Staged => { - let booted = sysroot + let booted = booted_sysroot .require_booted_deployment() .context("No booted OSTree deployment found")?; - sysroot + booted_sysroot .deployments() .into_iter() .find(|deployment| deployment.is_staged() && deployment.osname() == booted.osname()) .ok_or_else(|| anyhow::anyhow!("No staged OSTree deployment found"))? } }; - let sysroot_dir = crate::utils::sysroot_dir(&sysroot)?; + let deployments = sysroot.deployments(); + let deployment = resolve_locked_deployment(&selected_deployment, &deployments)?; + // Keep composefs lower/data paths rooted on the attached /sysroot mount. + // On older supported kernels (including 6.12), overlayfs cannot clone a + // lowerpath reached through the detached mount used for OSTree locking. let deployment_path = sysroot.deployment_dirpath(&deployment); let deployment_dir = sysroot_dir .open_dir(deployment_path.as_str()) @@ -269,11 +405,63 @@ async fn mount_ostree_image(opts: &MountOpts) -> Result { }; Ok(MountedImageRoot { tree, - _storage: StorageGuard::Ostree { _sysroot: sysroot }, + _storage: StorageGuard::Ostree { + _sysroot: sysroot, + _mount: sysroot_mount, + }, checkout, }) } +/// Resolve the deployment selected from the current-root view to its matching +/// object in the locked backing sysroot. Deployment indexes and staged flags +/// can differ between these views, so use only the stable OSTree identity. +fn resolve_locked_deployment( + selected: &ostree::Deployment, + locked_deployments: &[ostree::Deployment], +) -> Result { + let identity = deployment_identity(selected); + let identities = locked_deployments + .iter() + .map(deployment_identity) + .collect::>(); + let index = matching_deployment_index(&identity, &identities)?; + Ok(locked_deployments[index].clone()) +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct DeploymentIdentity { + osname: String, + checksum: String, + deploy_serial: i32, +} + +fn deployment_identity(deployment: &ostree::Deployment) -> DeploymentIdentity { + DeploymentIdentity { + osname: deployment.osname().to_string(), + checksum: deployment.csum().to_string(), + deploy_serial: deployment.deployserial(), + } +} + +fn matching_deployment_index( + selected: &DeploymentIdentity, + candidates: &[DeploymentIdentity], +) -> Result { + let mut matches = candidates + .iter() + .enumerate() + .filter(|(_, candidate)| *candidate == selected); + let (index, _) = matches.next().ok_or_else(|| { + anyhow::anyhow!("Selected OSTree deployment is absent from locked sysroot") + })?; + ensure!( + matches.next().is_none(), + "Selected OSTree deployment is ambiguous in locked sysroot" + ); + Ok(index) +} + fn mount_pristine_etc(tree: &impl AsFd) -> Result<()> { let root = Dir::reopen_dir(tree).context("Opening selected OSTree checkout")?; let usr_etc = root @@ -510,9 +698,9 @@ fn ensure_not_root_target(target: &std::fs::File, path: &Utf8Path) -> Result<()> #[cfg(test)] mod tests { use super::{ - Deployment, MountOpts, UnmountOpts, ensure_directory_empty, ensure_not_mountpoint, - ensure_not_root_target, open_mount_target, open_path_no_symlinks, open_source, - source_relative_path, + Deployment, DeploymentIdentity, MountOpts, UnmountOpts, ensure_directory_empty, + ensure_not_mountpoint, ensure_not_root_target, open_mount_target, open_path_no_symlinks, + open_source, source_relative_path, }; use crate::cli::{ImageOpts, InstallOpts, Opt}; use camino::{Utf8Path, Utf8PathBuf}; @@ -671,4 +859,28 @@ mod tests { .is_err() ); } + + #[test] + fn locked_deployment_resolution_requires_one_exact_identity_match() { + let identity = |osname: &str, checksum: &str, deploy_serial: i32| DeploymentIdentity { + osname: osname.to_owned(), + checksum: checksum.to_owned(), + deploy_serial, + }; + let selected = identity("default", &"aa".repeat(32), 3); + let candidates = [ + identity("other", &"aa".repeat(32), 3), + identity("default", &"bb".repeat(32), 3), + identity("default", &"aa".repeat(32), 4), + selected.clone(), + ]; + + assert_eq!( + super::matching_deployment_index(&selected, &candidates).unwrap(), + 3 + ); + assert!(super::matching_deployment_index(&selected, &[]).is_err()); + let ambiguous = [selected.clone(), selected.clone()]; + assert!(super::matching_deployment_index(&selected, &ambiguous).is_err()); + } } diff --git a/tmt/tests/booted/test-64-image-mount.nu b/tmt/tests/booted/test-64-image-mount.nu index a50b8e1bb7..24b55aa3ef 100644 --- a/tmt/tests/booted/test-64-image-mount.nu +++ b/tmt/tests/booted/test-64-image-mount.nu @@ -42,6 +42,11 @@ def mount_image [deployment source target] { } def verify_image_mounts [base] { + let sysroot_options = ( + findmnt --mountpoint /sysroot --json + | from json + | get filesystems.0.options + ) let root_target = ($base | path join "root") let usr_target = ($base | path join "usr") let staged_target = ($base | path join "staged") @@ -64,7 +69,7 @@ def verify_image_mounts [base] { assert_mount_options $usr_target let write_path = ($usr_target | path join ".bootc-image-mount-write-test") - let write_result = (do -i { touch $write_path } | complete) + let write_result = (do -i { ^touch $write_path } | complete) assert ($write_result.exit_code != 0) "writes to mounted image content should fail" assert (not ($write_path | path exists)) "failed write should not create a file" @@ -83,6 +88,12 @@ def verify_image_mounts [base] { } else { print "SKIP: staged image-mount coverage unavailable (active backend reports no staged deployment)" } + let sysroot_options_after = ( + findmnt --mountpoint /sysroot --json + | from json + | get filesystems.0.options + ) + assert equal $sysroot_options_after $sysroot_options "image mounts should not change /sysroot mount options" true } catch { |error| $error } From 3fbc9c06bae88c08f48e6180f4d43a02180d93ca Mon Sep 17 00:00:00 2001 From: ckyrouac Date: Tue, 10 Nov 2026 11:26:26 -0600 Subject: [PATCH 04/10] image: Avoid child mounts in OSTree checkout sources Map checkout fallback /etc requests to pristine /usr/etc, and reject whole-root exports that cannot safely preserve that replacement in a non-recursive mount. Keep other source subtrees available without a detached child-mount operation. Document the backend-specific behavior and add divergent-marker regression coverage. Assisted-by: AI Signed-off-by: ckyrouac --- crates/lib/src/image_mount.rs | 98 ++++++++++++++++++------- docs/src/bootc-experimental-image.7.md | 19 +++-- tmt/tests/booted/test-64-image-mount.nu | 48 ++++++++---- 3 files changed, 117 insertions(+), 48 deletions(-) diff --git a/crates/lib/src/image_mount.rs b/crates/lib/src/image_mount.rs index 387a788c1a..b6d6e4da8e 100644 --- a/crates/lib/src/image_mount.rs +++ b/crates/lib/src/image_mount.rs @@ -39,7 +39,8 @@ pub(crate) struct MountOpts { #[arg(long, value_enum)] pub(crate) deployment: Deployment, - /// Absolute directory path inside the selected image to expose (`/` selects its root). + /// Absolute directory path inside the selected image to expose (`/` selects its root when + /// supported). OSTree checkout fallback rejects `/` and maps `/etc` to pristine `/usr/etc`. /// No path component may be a symlink. #[arg(long, value_parser = crate::cli::parse_absolute_path)] pub(crate) source: Utf8PathBuf, @@ -60,8 +61,8 @@ struct MountedImageRoot { tree: OwnedFd, // Keep the repository/sysroot locked while cloning and attaching its tree. _storage: StorageGuard, - // A non-composefs OSTree checkout has deployment-local /etc. Replace it - // with pristine image content from /usr/etc before exposing the tree. + // A non-composefs OSTree checkout has deployment-local /etc. Source + // selection maps /etc to pristine image content in /usr/etc instead. checkout: bool, } @@ -100,14 +101,12 @@ pub(crate) async fn mount(opts: MountOpts) -> Result<()> { checkout, } = image; - if checkout { - mount_pristine_etc(&tree)?; - } + let source_path = select_source_path(checkout, &opts.source)?; bootc_initramfs_setup::set_mount_tree_readonly(&tree) .context("Making selected deployment image read-only")?; let image_root = Dir::reopen_dir(&tree).context("Opening selected image root")?; - let source = open_source(&image_root, &opts.source)?; + let source = open_source(&image_root, &source_path)?; // Open once and retain this descriptor through validation and attachment. // This avoids checking one pathname and mounting on a replacement object. let (target, target_parent) = open_mount_target(&opts.target)?; @@ -462,25 +461,25 @@ fn matching_deployment_index( Ok(index) } -fn mount_pristine_etc(tree: &impl AsFd) -> Result<()> { - let root = Dir::reopen_dir(tree).context("Opening selected OSTree checkout")?; - let usr_etc = root - .open_dir("usr/etc") - .context("Opening pristine image /usr/etc")?; - let etc_tree = open_tree( - &usr_etc, - ".", - OpenTreeFlags::OPEN_TREE_CLONE | OpenTreeFlags::OPEN_TREE_CLOEXEC, - ) - .context("Cloning pristine image /usr/etc")?; - move_mount( - &etc_tree, - "", - &root, - "etc", - MoveMountFlags::MOVE_MOUNT_F_EMPTY_PATH, - ) - .context("Replacing deployment-local /etc with pristine image /usr/etc") +fn select_source_path(checkout: bool, source: &Utf8Path) -> Result { + if !checkout { + return Ok(source.to_owned()); + } + ensure!( + source != Utf8Path::new("/"), + "OSTree checkout fallback does not support --source /: refusing to expose deployment-local /etc" + ); + if source == Utf8Path::new("/etc") || source.starts_with("/etc/") { + let suffix = source + .strip_prefix("/etc") + .expect("/etc source prefix was checked"); + let mut selected = Utf8PathBuf::from("/usr/etc"); + if !suffix.as_str().is_empty() { + selected.push(suffix); + } + return Ok(selected); + } + Ok(source.to_owned()) } fn open_source(root: &Dir, source: &Utf8Path) -> Result { @@ -700,11 +699,11 @@ mod tests { use super::{ Deployment, DeploymentIdentity, MountOpts, UnmountOpts, ensure_directory_empty, ensure_not_mountpoint, ensure_not_root_target, open_mount_target, open_path_no_symlinks, - open_source, source_relative_path, + open_source, select_source_path, source_relative_path, }; use crate::cli::{ImageOpts, InstallOpts, Opt}; use camino::{Utf8Path, Utf8PathBuf}; - use cap_std_ext::cap_std::ambient_authority; + use cap_std_ext::cap_std::{ambient_authority, fs::Dir}; use clap::Parser; use std::os::unix::fs::symlink; @@ -817,6 +816,49 @@ mod tests { ); } + #[test] + fn checkout_sources_map_etc_to_pristine_image_content() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + std::fs::create_dir_all(root.join("etc/subdir")).unwrap(); + std::fs::create_dir_all(root.join("usr/etc/subdir")).unwrap(); + std::fs::create_dir_all(root.join("etc-other")).unwrap(); + std::fs::create_dir_all(root.join("usr/lib")).unwrap(); + std::fs::write(root.join("etc/marker"), b"deployment-local").unwrap(); + std::fs::write(root.join("usr/etc/marker"), b"image-pristine").unwrap(); + std::fs::write(root.join("etc/subdir/marker"), b"deployment-local-child").unwrap(); + std::fs::write(root.join("usr/etc/subdir/marker"), b"image-pristine-child").unwrap(); + std::fs::write(root.join("etc-other/marker"), b"etc-other").unwrap(); + + let image = Dir::open_ambient_dir(root, ambient_authority()).unwrap(); + assert_eq!(image.read("etc/marker").unwrap(), b"deployment-local"); + // Resolve through open_source as the mount path does, then read the + // marker relative to that selected source directory. + let read_source_marker = |source: &str| { + let selected = select_source_path(true, Utf8Path::new(source)).unwrap(); + let dir = Dir::reopen_dir(&image).unwrap(); + let source = open_source(&dir, &selected).unwrap(); + let source = Dir::reopen_dir(&source).unwrap(); + source.read("marker").unwrap() + }; + assert_eq!(read_source_marker("/etc"), b"image-pristine"); + assert_eq!(read_source_marker("/etc/subdir"), b"image-pristine-child"); + assert_eq!(read_source_marker("/etc-other"), b"etc-other"); + assert_eq!( + select_source_path(true, Utf8Path::new("/usr")).unwrap(), + Utf8Path::new("/usr") + ); + assert_eq!( + select_source_path(false, Utf8Path::new("/etc")).unwrap(), + Utf8Path::new("/etc") + ); + assert_eq!( + select_source_path(false, Utf8Path::new("/")).unwrap(), + Utf8Path::new("/") + ); + assert!(select_source_path(true, Utf8Path::new("/")).is_err()); + } + #[test] fn mount_target_must_be_empty_and_have_no_symlink_components() { let temp = tempfile::tempdir().unwrap(); diff --git a/docs/src/bootc-experimental-image.7.md b/docs/src/bootc-experimental-image.7.md index 0b88017db2..33a95b59b8 100644 --- a/docs/src/bootc-experimental-image.7.md +++ b/docs/src/bootc-experimental-image.7.md @@ -19,11 +19,16 @@ Run `bootc image copy-to-storage --help` for more options. `bootc image mount` exposes a path from the locally available booted or staged deployment image at an existing empty directory. The source must be a directory; -`--source /` selects the image root. It refuses target paths with symlink -components and targets that are already mountpoints. It does not pull an image -or merge deployment state: `/var` is never mounted from host state, and OSTree -checkout fallbacks use the image's pristine `/usr/etc` rather than deployment-local -`/etc`. The target is checked immediately before attachment; callers must prevent +`--source /` selects the image root when supported. It refuses target paths with +symlink components and targets that are already mountpoints. It does not pull an +image or merge deployment state: `/var` is never mounted from host state. For an +OSTree checkout fallback, root is unsupported and fails closed because a +non-recursive root mount would expose deployment-local `/etc`. Instead, `/etc` +and descendants select the image's pristine `/usr/etc` and descendants. Other +subpaths, including `/usr`, remain available on older kernels; this avoids the +detached child-mount operation that older kernels do not support. Composefs and +OSTree composefs trees retain normal source-path semantics, including root. +The target is checked immediately before attachment; callers must prevent concurrent changes to the target directory while the command runs. ```sh @@ -41,8 +46,8 @@ change mount namespaces. The mounted content is read-only, `nosuid`, and `nodev`. It intentionally remains executable: the mount does not use `noexec`, so direct executable -paths in the mounted image can be run. The image root itself (`--source /`) is -a valid directory source. Read-only, `nosuid`, `nodev`, and `nosymfollow` do not +paths in the mounted image can be run. Where supported, the image root itself +(`--source /`) is a valid directory source. Read-only, `nosuid`, `nodev`, and `nosymfollow` do not disable execution. However, `nosymfollow` prevents following symlinks in the mounted tree, so a symlink path to an executable will not resolve, even when its target is also inside the image. The requested source path itself must diff --git a/tmt/tests/booted/test-64-image-mount.nu b/tmt/tests/booted/test-64-image-mount.nu index 24b55aa3ef..c44b719606 100644 --- a/tmt/tests/booted/test-64-image-mount.nu +++ b/tmt/tests/booted/test-64-image-mount.nu @@ -41,7 +41,7 @@ def mount_image [deployment source target] { } } -def verify_image_mounts [base] { +def verify_image_mounts [base deployment_etc_marker] { let sysroot_options = ( findmnt --mountpoint /sysroot --json | from json @@ -54,19 +54,33 @@ def verify_image_mounts [base] { let result = try { mkdir $root_target $usr_target $staged_target - mount_image booted / $root_target - $mounted = ($mounted | append $root_target) + let marker_result = (do -i { ^touch $deployment_etc_marker } | complete) + assert equal $marker_result.exit_code 0 $"failed to create deployment-local /etc marker: ($marker_result.stderr)" + let root_result = (do -i { + bootc image mount --deployment booted --source / --target $root_target + } | complete) + if $root_result.exit_code == 0 { + $mounted = ($mounted | append $root_target) + let root_os_release = ($root_target | path join "usr/lib/os-release") + let mounted_deployment_marker = ($root_target | path join "etc" ($deployment_etc_marker | path basename)) + assert ($root_os_release | path exists) "booted root mount should contain usr/lib/os-release" + assert (not ($mounted_deployment_marker | path exists)) "image root must not expose deployment-local /etc" + assert_mount_options $root_target + } else { + assert ($root_result.stderr | str contains "OSTree checkout fallback does not support --source /") $"unexpected root mount failure: ($root_result.stderr)" + print "SKIP: image-root mount is unsupported for OSTree checkout fallback" + } mount_image booted /usr $usr_target $mounted = ($mounted | append $usr_target) - let root_os_release = ($root_target | path join "usr/lib/os-release") let usr_os_release = ($usr_target | path join "lib/os-release") - assert ($root_os_release | path exists) "booted root mount should contain usr/lib/os-release" assert ($usr_os_release | path exists) "/usr mount should contain lib/os-release" - assert equal (open $root_os_release | into string) (open $usr_os_release | into string) - assert_mount_options $root_target assert_mount_options $usr_target + if ($mounted | any { |target| $target == $root_target }) { + let root_os_release = ($root_target | path join "usr/lib/os-release") + assert equal (open $root_os_release | into string) (open $usr_os_release | into string) + } let write_path = ($usr_target | path join ".bootc-image-mount-write-test") let write_result = (do -i { ^touch $write_path } | complete) @@ -104,17 +118,25 @@ def verify_image_mounts [base] { } let base = (^mktemp -d /run/bootc-image-mount.XXXXXX | str trim) -let test_outcome = (verify_image_mounts $base) +let deployment_etc_marker = $"/etc/.bootc-image-mount-deployment-local-(($base | path basename))" +let test_outcome = (verify_image_mounts $base $deployment_etc_marker) let mount_cleanup_errors = (cleanup_targets $test_outcome.mounted) -let cleanup_errors = if (($mount_cleanup_errors | length) > 0) { - $mount_cleanup_errors | append $"($base): directory retained because a mount could not be unmounted" -} else { +mut cleanup_errors = $mount_cleanup_errors +if ($deployment_etc_marker | path exists) { + let marker_cleanup = (do -i { ^rm -- $deployment_etc_marker } | complete) + if $marker_cleanup.exit_code != 0 { + $cleanup_errors = ($cleanup_errors | append $"($deployment_etc_marker): failed to remove deployment-local /etc marker: ($marker_cleanup.stderr)") + } +} +if (($cleanup_errors | length) == 0) { let remove_result = (do -i { ^rm --recursive $base } | complete) if $remove_result.exit_code == 0 { - [] + $cleanup_errors = [] } else { - [$"($base): failed to remove test directory: ($remove_result.stderr)"] + $cleanup_errors = [$"($base): failed to remove test directory: ($remove_result.stderr)"] } +} else { + $cleanup_errors = ($cleanup_errors | append $"($base): directory retained because a mount could not be unmounted") } if (($cleanup_errors | length) > 0) { From 1421e35b7a8e4bbc2c236d14f44b720986c008c6 Mon Sep 17 00:00:00 2001 From: ckyrouac Date: Tue, 10 Nov 2026 12:01:14 -0600 Subject: [PATCH 05/10] tests: Exercise staged deployment image mounts Build and stage a distinct containers-storage image with a unique marker, then verify bootc image mount selects its /usr content rather than the booted image. Keep booted checks on Secure Boot composefs UKIs, where the shared fixture helper cannot produce a signed staged image. Assisted-by: AI Signed-off-by: ckyrouac --- tmt/tests/booted/test-64-image-mount.nu | 85 ++++++++++++++++++++++--- tmt/tests/tests.fmf | 2 +- 2 files changed, 78 insertions(+), 9 deletions(-) diff --git a/tmt/tests/booted/test-64-image-mount.nu b/tmt/tests/booted/test-64-image-mount.nu index c44b719606..0f96974c0e 100644 --- a/tmt/tests/booted/test-64-image-mount.nu +++ b/tmt/tests/booted/test-64-image-mount.nu @@ -1,9 +1,10 @@ # number: 64 # tmt: # summary: Verify booted and staged deployment image mounts -# duration: 10m +# duration: 30m use std assert +use tap.nu def assert_mount_options [target] { let options = ( @@ -41,7 +42,32 @@ def mount_image [deployment source target] { } } -def verify_image_mounts [base deployment_etc_marker] { +def secure_boot_enabled [] { + let secure_boot_var = "/sys/firmware/efi/efivars/SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c" + let read_result = (do -i { ^od -An -t u1 $secure_boot_var } | complete) + if $read_result.exit_code != 0 { + error make { + msg: $"Failed to read Secure Boot EFI variable ($secure_boot_var): ($read_result.stderr)" + } + } + let bytes = try { + $read_result.stdout | split words | each { into int } + } catch { + error make { msg: $"Failed to parse Secure Boot EFI variable ($secure_boot_var)" } + } + if ($bytes | length) != 5 { + error make { + msg: $"Unexpected Secure Boot EFI variable size at ($secure_boot_var): expected 5 bytes, got (($bytes | length))" + } + } + let enabled = ($bytes | last) + if not ($enabled in [0 1]) { + error make { msg: $"Invalid Secure Boot EFI variable value at ($secure_boot_var): ($enabled)" } + } + $enabled == 1 +} + +def verify_image_mounts [base deployment_etc_marker staged_marker staged_fixture] { let sysroot_options = ( findmnt --mountpoint /sysroot --json | from json @@ -75,6 +101,8 @@ def verify_image_mounts [base deployment_etc_marker] { let usr_os_release = ($usr_target | path join "lib/os-release") assert ($usr_os_release | path exists) "/usr mount should contain lib/os-release" + let booted_staged_marker = ($usr_target | path join "share" ($staged_marker | path basename)) + assert (not ($booted_staged_marker | path exists)) "booted /usr must not contain the staged image marker" assert_mount_options $usr_target if ($mounted | any { |target| $target == $root_target }) { @@ -92,15 +120,15 @@ def verify_image_mounts [base deployment_etc_marker] { let executable_result = (do -i { ^$true_path } | complete) assert equal $executable_result.exit_code 0 "mounted /usr/bin/true should be executable" - let status = (bootc status --json | from json) - if (($status.status.staged? | default null) != null) { + if $staged_fixture { mount_image staged /usr $staged_target $mounted = ($mounted | append $staged_target) let staged_os_release = ($staged_target | path join "lib/os-release") assert ($staged_os_release | path exists) "staged /usr mount should contain lib/os-release" + let staged_marker_path = ($staged_target | path join "share" ($staged_marker | path basename)) + assert ($staged_marker_path | path exists) "staged /usr mount should contain the staged image marker" + assert equal (open $staged_marker_path | into string) "staged image mount marker\n" "staged image marker content should match exactly" assert_mount_options $staged_target - } else { - print "SKIP: staged image-mount coverage unavailable (active backend reports no staged deployment)" } let sysroot_options_after = ( findmnt --mountpoint /sysroot --json @@ -119,7 +147,48 @@ def verify_image_mounts [base deployment_etc_marker] { let base = (^mktemp -d /run/bootc-image-mount.XXXXXX | str trim) let deployment_etc_marker = $"/etc/.bootc-image-mount-deployment-local-(($base | path basename))" -let test_outcome = (verify_image_mounts $base $deployment_etc_marker) +let staged_marker = $"/usr/share/bootc-image-mount-(($base | path basename))" +let staged_tag = $"localhost/bootc-image-mount:(($base | path basename))" +let staged_marker_content = "staged image mount marker" + +let test_outcome = try { + let booted_status = (bootc status --json | from json) + let booted_digest = $booted_status.status.booted.image.imageDigest + let booted_composefs = ($booted_status.status.booted.composefs? | default null) + let is_composefs_uki = if $booted_composefs == null { + false + } else { + (($booted_composefs.bootType? | default "" | str downcase) == "uki") + } + let skip_staged_fixture = if $is_composefs_uki { + secure_boot_enabled + } else { + false + } + assert (not ($staged_marker | path exists)) "staged image marker must be absent from booted /usr before building the fixture" + let staged_fixture = if $skip_staged_fixture { + print "SKIP: Secure Boot composefs UKI; tap's staged fixture is unsealed and cannot be signed; booted checks still run" + false + } else { + bootc image copy-to-storage + let containerfile = (tap make_uki_containerfile $"FROM localhost/bootc as base\nRUN printf '%s\\n' '($staged_marker_content)' > ($staged_marker)") + let build_result = (do -i { $containerfile | podman build --network=none -t $staged_tag $base -f - } | complete) + assert equal $build_result.exit_code 0 $"failed to build staged image fixture: ($build_result.stderr)" + + let switch_result = (do -i { bootc switch --transport containers-storage $staged_tag } | complete) + assert equal $switch_result.exit_code 0 $"failed to stage local image fixture: ($switch_result.stderr)" + + let staged_status = (bootc status --json | from json).status.staged + assert ($staged_status != null) "bootc switch should create a staged deployment" + assert equal $staged_status.image.image.transport containers-storage "staged image should use containers-storage transport" + assert equal $staged_status.image.image.image $staged_tag "staged image should use the derived local image tag" + assert (($staged_status.image.imageDigest? | default "") != "") "staged image digest should be reported" + assert (($booted_digest | default "") != "") "booted image digest should be reported" + assert ($staged_status.image.imageDigest != $booted_digest) "staged image digest should differ from the booted image digest" + true + } + verify_image_mounts $base $deployment_etc_marker $staged_marker $staged_fixture +} catch { |error| { result: $error, mounted: [] } } let mount_cleanup_errors = (cleanup_targets $test_outcome.mounted) mut cleanup_errors = $mount_cleanup_errors if ($deployment_etc_marker | path exists) { @@ -136,7 +205,7 @@ if (($cleanup_errors | length) == 0) { $cleanup_errors = [$"($base): failed to remove test directory: ($remove_result.stderr)"] } } else { - $cleanup_errors = ($cleanup_errors | append $"($base): directory retained because a mount could not be unmounted") + $cleanup_errors = ($cleanup_errors | append $"($base): directory retained because cleanup failed") } if (($cleanup_errors | length) > 0) { diff --git a/tmt/tests/tests.fmf b/tmt/tests/tests.fmf index 3e6dd6214f..c047a54a6e 100644 --- a/tmt/tests/tests.fmf +++ b/tmt/tests/tests.fmf @@ -304,5 +304,5 @@ check: /test-68-image-mount: summary: Verify booted and staged deployment image mounts - duration: 10m + duration: 30m test: nu booted/test-64-image-mount.nu From 6569c4d34d2b00d823ce4db83a2b66619f6b3186 Mon Sep 17 00:00:00 2001 From: ckyrouac Date: Thu, 12 Nov 2026 12:47:35 -0600 Subject: [PATCH 06/10] image: Resolve staged deployments from current sysroot Libostree exposes runtime staged deployments through the current-root sysroot, not the detached backing sysroot used for locking. Use the selected deployment's relative path and checksum directly while keeping the real backing-sysroot lock and attached read-only data paths. Assisted-by: AI Signed-off-by: ckyrouac --- crates/lib/src/image_mount.rs | 96 +++++------------------------------ 1 file changed, 12 insertions(+), 84 deletions(-) diff --git a/crates/lib/src/image_mount.rs b/crates/lib/src/image_mount.rs index b6d6e4da8e..7846143e59 100644 --- a/crates/lib/src/image_mount.rs +++ b/crates/lib/src/image_mount.rs @@ -345,10 +345,13 @@ async fn mount_ostree_image(opts: &MountOpts) -> Result { .load(gio::Cancellable::NONE) .context("Reloading locked booted OSTree sysroot")?; - // libostree identifies the booted deployment only when its Sysroot points - // at the current root (/), not the physical backing sysroot (/sysroot). - // Read that identity while holding the lock above, then resolve it against - // the deployments from the locked backing sysroot below. + // libostree identifies the booted deployment, and exposes runtime staged + // deployments, only when its Sysroot points at the current root (/), not + // the physical backing sysroot (/sysroot). Select from that view while + // holding the lock above. A staged deployment can be absent from the + // locked backing sysroot's deployment list, but its deployment path still + // names content beneath /sysroot; keep reads on the attached /sysroot + // mount for compatibility with overlayfs/kernel lower paths. let booted_sysroot = ostree::Sysroot::new_default(); booted_sysroot .load(gio::Cancellable::NONE) @@ -369,12 +372,10 @@ async fn mount_ostree_image(opts: &MountOpts) -> Result { .ok_or_else(|| anyhow::anyhow!("No staged OSTree deployment found"))? } }; - let deployments = sysroot.deployments(); - let deployment = resolve_locked_deployment(&selected_deployment, &deployments)?; // Keep composefs lower/data paths rooted on the attached /sysroot mount. // On older supported kernels (including 6.12), overlayfs cannot clone a // lowerpath reached through the detached mount used for OSTree locking. - let deployment_path = sysroot.deployment_dirpath(&deployment); + let deployment_path = sysroot.deployment_dirpath(&selected_deployment); let deployment_dir = sysroot_dir .open_dir(deployment_path.as_str()) .with_context(|| format!("Opening selected OSTree deployment {deployment_path}"))?; @@ -386,7 +387,7 @@ async fn mount_ostree_image(opts: &MountOpts) -> Result { let (tree, checkout) = match ostree_prepareroot::mount_composefs( &deployment_dir, &repo, - deployment.csum().as_str(), + selected_deployment.csum().as_str(), config.as_ref(), ) .context("Mounting selected OSTree deployment image")? @@ -412,55 +413,6 @@ async fn mount_ostree_image(opts: &MountOpts) -> Result { }) } -/// Resolve the deployment selected from the current-root view to its matching -/// object in the locked backing sysroot. Deployment indexes and staged flags -/// can differ between these views, so use only the stable OSTree identity. -fn resolve_locked_deployment( - selected: &ostree::Deployment, - locked_deployments: &[ostree::Deployment], -) -> Result { - let identity = deployment_identity(selected); - let identities = locked_deployments - .iter() - .map(deployment_identity) - .collect::>(); - let index = matching_deployment_index(&identity, &identities)?; - Ok(locked_deployments[index].clone()) -} - -#[derive(Debug, Clone, PartialEq, Eq)] -struct DeploymentIdentity { - osname: String, - checksum: String, - deploy_serial: i32, -} - -fn deployment_identity(deployment: &ostree::Deployment) -> DeploymentIdentity { - DeploymentIdentity { - osname: deployment.osname().to_string(), - checksum: deployment.csum().to_string(), - deploy_serial: deployment.deployserial(), - } -} - -fn matching_deployment_index( - selected: &DeploymentIdentity, - candidates: &[DeploymentIdentity], -) -> Result { - let mut matches = candidates - .iter() - .enumerate() - .filter(|(_, candidate)| *candidate == selected); - let (index, _) = matches.next().ok_or_else(|| { - anyhow::anyhow!("Selected OSTree deployment is absent from locked sysroot") - })?; - ensure!( - matches.next().is_none(), - "Selected OSTree deployment is ambiguous in locked sysroot" - ); - Ok(index) -} - fn select_source_path(checkout: bool, source: &Utf8Path) -> Result { if !checkout { return Ok(source.to_owned()); @@ -697,9 +649,9 @@ fn ensure_not_root_target(target: &std::fs::File, path: &Utf8Path) -> Result<()> #[cfg(test)] mod tests { use super::{ - Deployment, DeploymentIdentity, MountOpts, UnmountOpts, ensure_directory_empty, - ensure_not_mountpoint, ensure_not_root_target, open_mount_target, open_path_no_symlinks, - open_source, select_source_path, source_relative_path, + Deployment, MountOpts, UnmountOpts, ensure_directory_empty, ensure_not_mountpoint, + ensure_not_root_target, open_mount_target, open_path_no_symlinks, open_source, + select_source_path, source_relative_path, }; use crate::cli::{ImageOpts, InstallOpts, Opt}; use camino::{Utf8Path, Utf8PathBuf}; @@ -901,28 +853,4 @@ mod tests { .is_err() ); } - - #[test] - fn locked_deployment_resolution_requires_one_exact_identity_match() { - let identity = |osname: &str, checksum: &str, deploy_serial: i32| DeploymentIdentity { - osname: osname.to_owned(), - checksum: checksum.to_owned(), - deploy_serial, - }; - let selected = identity("default", &"aa".repeat(32), 3); - let candidates = [ - identity("other", &"aa".repeat(32), 3), - identity("default", &"bb".repeat(32), 3), - identity("default", &"aa".repeat(32), 4), - selected.clone(), - ]; - - assert_eq!( - super::matching_deployment_index(&selected, &candidates).unwrap(), - 3 - ); - assert!(super::matching_deployment_index(&selected, &[]).is_err()); - let ambiguous = [selected.clone(), selected.clone()]; - assert!(super::matching_deployment_index(&selected, &ambiguous).is_err()); - } } From 5afa81f1c6a5202067b0b03d5cad822ad77cc512 Mon Sep 17 00:00:00 2001 From: ckyrouac Date: Thu, 12 Nov 2026 14:56:14 -0600 Subject: [PATCH 07/10] image: Propagate composefs repository setup errors ComposefsRepository::set_insecure returns a Result. Propagate it so docgen builds don't reject an unused must-use result and callers see setup failures. Assisted-by: AI Signed-off-by: ckyrouac --- crates/lib/src/image_mount.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/lib/src/image_mount.rs b/crates/lib/src/image_mount.rs index 7846143e59..6d220f2b6d 100644 --- a/crates/lib/src/image_mount.rs +++ b/crates/lib/src/image_mount.rs @@ -299,7 +299,7 @@ fn mount_composefs_image( let mut repo = crate::bootc_composefs::repo::open_composefs_repo(&sysroot) .context("Opening existing composefs repository")?; if allow_missing_fsverity { - repo.set_insecure(); + repo.set_insecure()?; } let tree = repo .mount(&id) From df701000b5338b4af7ed932f666714142b7f56fb Mon Sep 17 00:00:00 2001 From: ckyrouac Date: Thu, 12 Nov 2026 14:56:15 -0600 Subject: [PATCH 08/10] tmt: Regenerate image mount metadata Register test and plan 64 from the current booted test metadata and remove stale entries for test 68. Assisted-by: AI Signed-off-by: ckyrouac --- tmt/plans/integration.fmf | 14 +++++++------- tmt/tests/tests.fmf | 10 +++++----- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/tmt/plans/integration.fmf b/tmt/plans/integration.fmf index 8030883cd0..6399143cac 100644 --- a/tmt/plans/integration.fmf +++ b/tmt/plans/integration.fmf @@ -441,6 +441,13 @@ execute: - /tmt/tests/tests/test-63-install-shared-propagation extra-fixme_skip_if_composefs: true +/plan-64-image-mount: + summary: Verify booted and staged deployment image mounts + discover: + how: fmf + test: + - /tmt/tests/tests/test-64-image-mount + /plan-66-encrypted-swap-ordering: summary: Verify a random-key encrypted swap boots without an ordering cycle discover: @@ -459,11 +466,4 @@ execute: enabled: false because: the derived images are built in the VM, which has no keys to sign their UKIs for Secure Boot extra-skip_if_ostree: true - -/plan-68-image-mount: - summary: Verify booted and staged deployment image mounts - discover: - how: fmf - test: - - /tmt/tests/tests/test-64-image-mount # END GENERATED PLANS diff --git a/tmt/tests/tests.fmf b/tmt/tests/tests.fmf index c047a54a6e..ecda3eb7f2 100644 --- a/tmt/tests/tests.fmf +++ b/tmt/tests/tests.fmf @@ -286,6 +286,11 @@ check: duration: 30m test: nu booted/test-install-shared-propagation.nu +/test-64-image-mount: + summary: Verify booted and staged deployment image mounts + duration: 30m + test: nu booted/test-64-image-mount.nu + /test-66-encrypted-swap-ordering: summary: Verify a random-key encrypted swap boots without an ordering cycle duration: 30m @@ -301,8 +306,3 @@ check: enabled: false because: the derived images are built in the VM, which has no keys to sign their UKIs for Secure Boot test: nu booted/test-composefs-xbootldr.nu - -/test-68-image-mount: - summary: Verify booted and staged deployment image mounts - duration: 30m - test: nu booted/test-64-image-mount.nu From 7f6142b2f1b60ee01a695ee7c16b5701e514c758 Mon Sep 17 00:00:00 2001 From: ckyrouac Date: Mon, 16 Nov 2026 11:46:12 -0600 Subject: [PATCH 09/10] tests: Keep staged image mount marker newline-free The staged marker is read without a trailing line feed in the image-mount test. Generate the sentinel without one and compare against that exact content, so the assertion remains strict without depending on line-ending normalization. Assisted-by: AI Signed-off-by: ckyrouac --- tmt/tests/booted/test-64-image-mount.nu | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tmt/tests/booted/test-64-image-mount.nu b/tmt/tests/booted/test-64-image-mount.nu index 0f96974c0e..588bc8978b 100644 --- a/tmt/tests/booted/test-64-image-mount.nu +++ b/tmt/tests/booted/test-64-image-mount.nu @@ -67,7 +67,7 @@ def secure_boot_enabled [] { $enabled == 1 } -def verify_image_mounts [base deployment_etc_marker staged_marker staged_fixture] { +def verify_image_mounts [base deployment_etc_marker staged_marker staged_marker_content staged_fixture] { let sysroot_options = ( findmnt --mountpoint /sysroot --json | from json @@ -127,7 +127,7 @@ def verify_image_mounts [base deployment_etc_marker staged_marker staged_fixture assert ($staged_os_release | path exists) "staged /usr mount should contain lib/os-release" let staged_marker_path = ($staged_target | path join "share" ($staged_marker | path basename)) assert ($staged_marker_path | path exists) "staged /usr mount should contain the staged image marker" - assert equal (open $staged_marker_path | into string) "staged image mount marker\n" "staged image marker content should match exactly" + assert equal (open $staged_marker_path | into string) $staged_marker_content "staged image marker content should match exactly" assert_mount_options $staged_target } let sysroot_options_after = ( @@ -171,7 +171,7 @@ let test_outcome = try { false } else { bootc image copy-to-storage - let containerfile = (tap make_uki_containerfile $"FROM localhost/bootc as base\nRUN printf '%s\\n' '($staged_marker_content)' > ($staged_marker)") + let containerfile = (tap make_uki_containerfile $"FROM localhost/bootc as base\nRUN printf '%s' '($staged_marker_content)' > ($staged_marker)") let build_result = (do -i { $containerfile | podman build --network=none -t $staged_tag $base -f - } | complete) assert equal $build_result.exit_code 0 $"failed to build staged image fixture: ($build_result.stderr)" @@ -187,7 +187,7 @@ let test_outcome = try { assert ($staged_status.image.imageDigest != $booted_digest) "staged image digest should differ from the booted image digest" true } - verify_image_mounts $base $deployment_etc_marker $staged_marker $staged_fixture + verify_image_mounts $base $deployment_etc_marker $staged_marker $staged_marker_content $staged_fixture } catch { |error| { result: $error, mounted: [] } } let mount_cleanup_errors = (cleanup_targets $test_outcome.mounted) mut cleanup_errors = $mount_cleanup_errors From 267c6d1b76ae33fbce80ab7c3bbb8e83789c51eb Mon Sep 17 00:00:00 2001 From: ckyrouac Date: Mon, 16 Nov 2026 12:30:26 -0600 Subject: [PATCH 10/10] tests: Skip staged fixture when Secure Boot is unknown Some UEFI test VMs do not expose the SecureBoot EFI variable. Treat only the missing-variable diagnostic as unknown, skip the unsealed staged fixture in that case, and continue the booted-image mount checks. Assisted-by: AI Signed-off-by: ckyrouac --- tmt/tests/booted/test-64-image-mount.nu | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/tmt/tests/booted/test-64-image-mount.nu b/tmt/tests/booted/test-64-image-mount.nu index 588bc8978b..b07ccefd50 100644 --- a/tmt/tests/booted/test-64-image-mount.nu +++ b/tmt/tests/booted/test-64-image-mount.nu @@ -42,10 +42,13 @@ def mount_image [deployment source target] { } } -def secure_boot_enabled [] { +def get_secure_boot_state [] { let secure_boot_var = "/sys/firmware/efi/efivars/SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c" - let read_result = (do -i { ^od -An -t u1 $secure_boot_var } | complete) + let read_result = (do -i { ^env LC_ALL=C od -An -t u1 $secure_boot_var } | complete) if $read_result.exit_code != 0 { + if ($read_result.stderr | str contains $"od: ($secure_boot_var): No such file or directory") { + return "unknown" + } error make { msg: $"Failed to read Secure Boot EFI variable ($secure_boot_var): ($read_result.stderr)" } @@ -64,7 +67,7 @@ def secure_boot_enabled [] { if not ($enabled in [0 1]) { error make { msg: $"Invalid Secure Boot EFI variable value at ($secure_boot_var): ($enabled)" } } - $enabled == 1 + if $enabled == 1 { "enabled" } else { "disabled" } } def verify_image_mounts [base deployment_etc_marker staged_marker staged_marker_content staged_fixture] { @@ -160,14 +163,18 @@ let test_outcome = try { } else { (($booted_composefs.bootType? | default "" | str downcase) == "uki") } - let skip_staged_fixture = if $is_composefs_uki { - secure_boot_enabled + let secure_boot_state = if $is_composefs_uki { + get_secure_boot_state } else { - false + null } assert (not ($staged_marker | path exists)) "staged image marker must be absent from booted /usr before building the fixture" - let staged_fixture = if $skip_staged_fixture { - print "SKIP: Secure Boot composefs UKI; tap's staged fixture is unsealed and cannot be signed; booted checks still run" + let staged_fixture = if $is_composefs_uki and $secure_boot_state != "disabled" { + if $secure_boot_state == "enabled" { + print "SKIP: Secure Boot is enabled for the composefs UKI; tap's staged fixture is unsealed and cannot be signed; booted checks still run" + } else { + print "SKIP: Secure Boot state is unknown because the EFI variable is missing; skipping the unsealed composefs UKI staged fixture; booted checks still run" + } false } else { bootc image copy-to-storage