Skip to main content

bootc_lib/store/
mod.rs

1//! The [`Storage`] type holds references to three different types of
2//! storage that together implement the unified storage model.
3//!
4//! # Planned three-store architecture
5//!
6//! The planned architecture for unified storage involves three content stores that
7//! share physical disk blocks on a reflink-capable filesystem (XFS, btrfs):
8//!
9//! 1. **bootc-owned containers-storage** at `/sysroot/ostree/bootc/storage`
10//!    (overlay driver) — the image is accessible to podman and shares layers
11//!    with Logically Bound Images.
12//! 2. **composefs object store** at `/sysroot/composefs/objects/`
13//!    (SHA-512 content-addressed) — used by composefs-boot to mount the
14//!    rootfs as EROFS.  Populated from containers-storage via `FICLONE`
15//!    (`composefs_oci::pull` with `ZeroCopy`).
16//! 3. **ostree bare repo** at `/sysroot/ostree/repo/objects/`
17//!    (SHA-256 content-addressed) — provides deployment, rollback, fsck, and
18//!    delta updates.  Populated from the composefs object store via `FICLONE`
19//!    (`import_from_composefs_repo`).
20//!
21//! Each `FICLONE` ioctl lets the kernel mark source and destination extents as
22//! copy-on-write siblings with no userspace data movement. On ext4 (no
23//! reflinks), each step falls back to a byte copy.
24//!
25//! ## Implementation Plan
26//!
27//! The containers-storage → composefs step (arrow 1) is already implemented
28//! for the composefs boot backend in `crates/lib/src/bootc_composefs/repo.rs`
29//! via `pull_composefs_unified`.
30//!
31//! Wiring all three steps together for the ostree backend is the major planned work.
32//! The composefs → ostree step (arrow 2) was proven by the `composefs-to-ostree`
33//! spike branch. The planned implementation for the ostree backend will:
34//!
35//! 1. Perform a lazy cached probe (`reflinks_supported`) at install time.
36//! 2. Pull into containers-storage first (Stage 1).
37//! 3. Use `composefs_oci::pull` with `LocalFetchOpt::ZeroCopy` to populate composefs (Stage 2).
38//! 4. Finally, synthesize the ostree commit by walking the composefs tree,
39//!    reading metadata, computing SELinux labels, computing the ostree checksum,
40//!    and `FICLONE`ing into the ostree bare repo (Stage 3).
41//!
42//! ## Long-term: Global composefs store
43//!
44//! The ultimate planned state (the "composefs-as-storage" plan) is to have podman's
45//! composefs backend natively write objects to `/sysroot/composefs` directly, bypassing
46//! even `containers-storage`. This would mean flatpak, podman, and bootc all share exactly
47//! one global pool of content-addressed, deduplicated files.
48//!
49//! ## Why composefs in the middle
50//!
51//! The old unified storage path (containers-storage → skopeo tar → ostree)
52//! serialized layers twice. composefs-ctl's `ZeroCopy` pull mode instead walks
53//! the overlay `diff/` directories and FICLONEs each file into the composefs
54//! object store keyed by SHA-512 fsverity digest — no tar involved.
55//! See [container-libs#144](https://github.com/containers/container-libs/issues/144).
56//!
57//! ## Why reflink and not hardlink between composefs and ostree
58//!
59//! composefs is content-addressed by SHA-512 of raw bytes: two paths with
60//! identical content share one composefs inode. ostree bare mode stores
61//! uid/gid/mode/xattrs including `security.selinux` on each inode. Two files
62//! with the same bytes but different SELinux labels produce different ostree
63//! checksums but share one composefs object. One inode can hold only one
64//! `security.selinux` value, so hardlinking would silently corrupt labels.
65//! Reflink gives each ostree object its own inode while sharing disk extents.
66//!
67//! ## Reflink probe
68//!
69//! The reflink probe is performed lazily and cached. It creates
70//! two anonymous temporary files (via `O_TMPFILE`, no
71//! cleanup needed), writes one byte to the source, and attempts
72//! `ioctl(FICLONE)`. Returns `true` on success, `false` on `EOPNOTSUPP` or
73//! `EXDEV`. The probe directory is `composefs/objects` if it already exists,
74//! otherwise the physical root itself.
75//!
76//! # OSTree
77//!
78//! The default backend for the bootable container store; this
79//! lives in `/ostree` in the physical root.
80//!
81//! # containers-storage:
82//!
83//! Later, bootc gained support for Logically Bound Images.
84//! On ostree systems this is a `containers-storage:` instance that
85//! lives in `/ostree/bootc/storage`.  On composefs systems the
86//! physical location is `/composefs/bootc/storage` with a compat
87//! symlink at `ostree/bootc -> ../composefs/bootc`.
88//!
89//! # composefs
90//!
91//! This lives in `/composefs` in the physical root.
92
93use std::cell::OnceCell;
94use std::ops::Deref;
95use std::sync::Arc;
96
97use anyhow::{Context, Result};
98use bootc_mount::tempmount::TempMount;
99use camino::Utf8PathBuf;
100use cap_std_ext::cap_std;
101use cap_std_ext::cap_std::fs::{
102    Dir, DirBuilder, DirBuilderExt as _, Permissions, PermissionsExt as _,
103};
104use cap_std_ext::dirext::CapStdExtDirExt;
105use fn_error_context::context;
106
107use ostree_ext::container_utils::ostree_booted;
108use ostree_ext::prelude::FileExt;
109use ostree_ext::sysroot::SysrootLock;
110use ostree_ext::{gio, ostree};
111use rustix::fs::Mode;
112
113use composefs::fsverity::Sha512HashValue;
114use composefs::repository::RepositoryConfig;
115use composefs_ctl::composefs;
116
117use crate::bootc_composefs::backwards_compat::bcompat_boot::prepend_custom_prefix;
118use crate::bootc_composefs::boot::{EFI_LINUX, mount_esp};
119use crate::bootc_composefs::status::{ComposefsCmdline, composefs_booted, get_bootloader};
120use crate::lsm;
121use crate::podstorage::CStorage;
122use crate::spec::{BootloaderKind, ImageStatus};
123use crate::utils::{deployment_fd, open_dir_remount_rw};
124
125/// See <https://github.com/containers/composefs-rs/issues/159>
126pub type ComposefsRepository = composefs::repository::Repository<Sha512HashValue>;
127
128/// Path to the physical root
129pub const SYSROOT: &str = "sysroot";
130
131/// The toplevel composefs directory path
132pub const COMPOSEFS: &str = "composefs";
133
134/// The mode for the composefs directory; this is intentionally restrictive
135/// to avoid leaking information.
136pub(crate) const COMPOSEFS_MODE: Mode = Mode::from_raw_mode(0o700);
137
138/// Ensure the composefs directory exists in the given physical root
139/// with the correct permissions (mode 0700).
140pub(crate) fn ensure_composefs_dir(physical_root: &Dir) -> Result<()> {
141    let mut db = DirBuilder::new();
142    db.mode(COMPOSEFS_MODE.as_raw_mode());
143    physical_root
144        .ensure_dir_with(COMPOSEFS, &db)
145        .context("Creating composefs directory")?;
146    // Always update permissions, in case the directory pre-existed
147    // with incorrect mode (e.g. from an older version of bootc).
148    physical_root
149        .set_permissions(
150            COMPOSEFS,
151            Permissions::from_mode(COMPOSEFS_MODE.as_raw_mode()),
152        )
153        .context("Setting composefs directory permissions")?;
154    Ok(())
155}
156
157/// The path to the bootc root directory, relative to the physical
158/// system root.  On ostree systems this is a real directory; on composefs
159/// systems it is a symlink to `../composefs/bootc` (see
160/// [`ensure_composefs_bootc_link`]).
161pub(crate) const BOOTC_ROOT: &str = "ostree/bootc";
162
163/// The "real" bootc root for composefs-native systems, relative to the
164/// physical system root.
165pub(crate) const COMPOSEFS_BOOTC_ROOT: &str = "composefs/bootc";
166
167/// On a composefs install the containers-storage lives under
168/// `composefs/bootc/storage`.  To keep the rest of the code (and the
169/// `/usr/lib/bootc/storage` symlink which points through `ostree/bootc`)
170/// working, we create:
171///
172///   `ostree/bootc -> ../composefs/bootc`
173///
174/// This function is idempotent.
175pub(crate) fn ensure_composefs_bootc_link(physical_root: &Dir) -> Result<()> {
176    // Ensure the real directory exists
177    physical_root
178        .create_dir_all(COMPOSEFS_BOOTC_ROOT)
179        .with_context(|| format!("Creating {COMPOSEFS_BOOTC_ROOT}"))?;
180
181    // Create the `ostree/` parent if needed (it won't exist on a pure
182    // composefs install that never touched ostree).
183    physical_root
184        .create_dir_all("ostree")
185        .context("Creating ostree directory")?;
186
187    // If ostree/bootc already exists as a real directory (e.g. from an
188    // older install or from the ostree path), leave it alone — this
189    // function is only for fresh composefs installs.
190    match physical_root.symlink_metadata(BOOTC_ROOT) {
191        Ok(meta) if meta.is_symlink() => {
192            // Already a symlink — nothing to do
193            return Ok(());
194        }
195        Ok(_meta) => {
196            // It's a real directory.  This shouldn't happen during a fresh
197            // composefs install, but if it does just leave it.
198            tracing::warn!(
199                "{BOOTC_ROOT} already exists as a directory, not replacing with symlink"
200            );
201            return Ok(());
202        }
203        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
204            // Good — doesn't exist yet, we'll create the symlink
205        }
206        Err(e) => return Err(e).context(format!("Querying {BOOTC_ROOT}")),
207    }
208
209    physical_root
210        .symlink_contents(format!("../{COMPOSEFS_BOOTC_ROOT}"), BOOTC_ROOT)
211        .with_context(|| format!("Creating {BOOTC_ROOT} -> ../{COMPOSEFS_BOOTC_ROOT} symlink"))?;
212
213    tracing::info!("Created {BOOTC_ROOT} -> ../{COMPOSEFS_BOOTC_ROOT}");
214    Ok(())
215}
216
217/// Storage accessor for a booted system.
218///
219/// This wraps [`Storage`] and can determine whether the system is booted
220/// via ostree or composefs, providing a unified interface for both.
221pub(crate) struct BootedStorage {
222    pub(crate) storage: Storage,
223}
224
225impl Deref for BootedStorage {
226    type Target = Storage;
227
228    fn deref(&self) -> &Self::Target {
229        &self.storage
230    }
231}
232
233/// Represents an ostree-based boot environment
234pub struct BootedOstree<'a> {
235    pub(crate) sysroot: &'a SysrootLock,
236    pub(crate) deployment: ostree::Deployment,
237}
238
239impl<'a> BootedOstree<'a> {
240    /// Get the ostree repository
241    pub(crate) fn repo(&self) -> ostree::Repo {
242        self.sysroot.repo()
243    }
244
245    /// Get the stateroot name
246    pub(crate) fn stateroot(&self) -> ostree::glib::GString {
247        self.deployment.osname()
248    }
249}
250
251/// Represents a composefs-based boot environment
252#[allow(dead_code)]
253pub struct BootedComposefs {
254    pub repo: Arc<ComposefsRepository>,
255    pub cmdline: &'static ComposefsCmdline,
256}
257
258/// Discriminated union representing the boot storage backend.
259///
260/// The runtime environment in which bootc is executing.
261pub(crate) enum Environment {
262    /// System booted via ostree
263    OstreeBooted,
264    /// System booted via composefs
265    ComposefsBooted(ComposefsCmdline),
266    /// Running in a container
267    Container,
268    /// Other (not booted via bootc)
269    Other,
270}
271
272impl Environment {
273    /// Detect the current runtime environment.
274    pub(crate) fn detect() -> Result<Self> {
275        if ostree_ext::container_utils::running_in_container() {
276            return Ok(Self::Container);
277        }
278
279        if let Some(cmdline) = composefs_booted()? {
280            return Ok(Self::ComposefsBooted(cmdline.clone()));
281        }
282
283        if ostree_booted()? {
284            return Ok(Self::OstreeBooted);
285        }
286
287        Ok(Self::Other)
288    }
289
290    /// Returns true if this environment requires entering a mount namespace
291    /// before loading storage (to avoid leaving /sysroot writable).
292    pub(crate) fn needs_mount_namespace(&self) -> bool {
293        matches!(self, Self::OstreeBooted | Self::ComposefsBooted(_))
294    }
295}
296
297/// A system can boot via either ostree or composefs; this enum
298/// allows code to handle both cases while maintaining type safety.
299pub(crate) enum BootedStorageKind<'a> {
300    Ostree(BootedOstree<'a>),
301    Composefs(BootedComposefs),
302}
303
304/// Open the physical root (/sysroot) and /run directories for a booted system.
305fn get_physical_root_and_run() -> Result<(Dir, Dir)> {
306    let physical_root = {
307        let d = Dir::open_ambient_dir("/sysroot", cap_std::ambient_authority())
308            .context("Opening /sysroot")?;
309        open_dir_remount_rw(&d, ".".into())?
310    };
311    let run =
312        Dir::open_ambient_dir("/run", cap_std::ambient_authority()).context("Opening /run")?;
313    Ok((physical_root, run))
314}
315
316impl BootedStorage {
317    /// Create a new booted storage accessor for the given environment.
318    ///
319    /// The caller must have already called `prepare_for_write()` if
320    /// `env.needs_mount_namespace()` is true.
321    pub(crate) async fn new(env: Environment) -> Result<Option<Self>> {
322        let r = match &env {
323            Environment::ComposefsBooted(cmdline) => {
324                let (physical_root, run) = get_physical_root_and_run()?;
325                let mut composefs = ComposefsRepository::open_path(&physical_root, COMPOSEFS)?;
326                if cmdline.allow_missing_fsverity {
327                    composefs.set_insecure();
328                }
329                let composefs = Arc::new(composefs);
330
331                // Locate ESP by walking up to the root disk(s)
332                let root_dev = bootc_blockdev::list_dev_by_dir(&physical_root)?;
333                let esp_dev = root_dev.find_first_colocated_esp()?;
334                let esp_mount = mount_esp(&esp_dev.path())?;
335
336                let boot_dir = match get_bootloader()?.kind()? {
337                    BootloaderKind::GRUBClassic => {
338                        physical_root.open_dir("boot").context("Opening boot")?
339                    }
340                    // NOTE: Handle XBOOTLDR partitions here if and when we use it
341                    BootloaderKind::BLSCompatible => {
342                        esp_mount.fd.try_clone().context("Cloning fd")?
343                    }
344                };
345
346                let storage = Storage {
347                    physical_root,
348                    physical_root_path: Utf8PathBuf::from("/sysroot"),
349                    run,
350                    boot_dir: Some(boot_dir),
351                    esp: Some(esp_mount),
352                    ostree: Default::default(),
353                    composefs: OnceCell::from(composefs.clone()),
354                    imgstore: Default::default(),
355                };
356
357                // prepend_custom_prefix is idempotent: it checks has_prefix on each
358                // entry and skips any that already have it, so it's safe to call on
359                // every boot. This handles upgrades from older bootc versions that
360                // lacked the prefix — we can't use meta.json presence as a trigger
361                // because open_upgrade() in the initramfs writes meta.json before
362                // userspace ever runs.
363                let cmdline = composefs_booted()?
364                    .ok_or_else(|| anyhow::anyhow!("Could not get booted composefs cmdline"))?;
365                prepend_custom_prefix(&storage, &cmdline).await?;
366
367                Some(Self { storage })
368            }
369            Environment::OstreeBooted => {
370                // The caller must have entered a private mount namespace before
371                // calling this function. This is because ostree's sysroot.load() will
372                // remount /sysroot as writable, and we call set_mount_namespace_in_use()
373                // to indicate we're in a mount namespace. Without actually being in a
374                // mount namespace, this would leave the global /sysroot writable.
375                let (physical_root, run) = get_physical_root_and_run()?;
376
377                let sysroot = ostree::Sysroot::new_default();
378                sysroot.set_mount_namespace_in_use();
379                let sysroot = ostree_ext::sysroot::SysrootLock::new_from_sysroot(&sysroot).await?;
380                sysroot.load(gio::Cancellable::NONE)?;
381
382                let storage = Storage {
383                    physical_root,
384                    physical_root_path: Utf8PathBuf::from("/sysroot"),
385                    run,
386                    boot_dir: None,
387                    esp: None,
388                    ostree: OnceCell::from(sysroot),
389                    composefs: Default::default(),
390                    imgstore: Default::default(),
391                };
392
393                Some(Self { storage })
394            }
395            // For container or non-bootc environments, there's no storage
396            Environment::Container | Environment::Other => None,
397        };
398        Ok(r)
399    }
400
401    /// Determine the boot storage backend kind.
402    ///
403    /// Returns information about whether the system booted via ostree or composefs,
404    /// along with the relevant sysroot/deployment or repository/cmdline data.
405    pub(crate) fn kind(&self) -> Result<BootedStorageKind<'_>> {
406        if let Some(cmdline) = composefs_booted()? {
407            // SAFETY: This must have been set above in new()
408            let repo = self.composefs.get().unwrap();
409            Ok(BootedStorageKind::Composefs(BootedComposefs {
410                repo: Arc::clone(repo),
411                cmdline,
412            }))
413        } else {
414            // SAFETY: This must have been set above in new()
415            let sysroot = self.ostree.get().unwrap();
416            let deployment = sysroot.require_booted_deployment()?;
417            Ok(BootedStorageKind::Ostree(BootedOstree {
418                sysroot,
419                deployment,
420            }))
421        }
422    }
423}
424
425/// A reference to a physical filesystem root, plus
426/// accessors for the different types of container storage.
427pub(crate) struct Storage {
428    /// Directory holding the physical root
429    pub physical_root: Dir,
430
431    /// Absolute path to the physical root directory.
432    /// This is `/sysroot` on a running system, or the target mount point during install.
433    pub physical_root_path: Utf8PathBuf,
434
435    /// The 'boot' directory, useful and `Some` only for composefs systems
436    /// For grub booted systems, this points to `/sysroot/boot`
437    /// For systemd booted systems, this points to the ESP
438    pub boot_dir: Option<Dir>,
439
440    /// The ESP mounted at a tmp location
441    pub esp: Option<TempMount>,
442
443    /// Our runtime state
444    run: Dir,
445
446    /// The OSTree storage
447    ostree: OnceCell<SysrootLock>,
448    /// The composefs storage
449    composefs: OnceCell<Arc<ComposefsRepository>>,
450    /// The containers-image storage used for LBIs
451    imgstore: OnceCell<CStorage>,
452}
453
454/// Cached image status data used for optimization.
455///
456/// This stores the current image status and any cached update information
457/// to avoid redundant fetches during status operations.
458#[derive(Default)]
459pub(crate) struct CachedImageStatus {
460    pub image: Option<ImageStatus>,
461    pub cached_update: Option<ImageStatus>,
462}
463
464impl Storage {
465    /// Create a new storage accessor from an existing ostree sysroot.
466    ///
467    /// This is used for non-booted scenarios (e.g., `bootc install`) where
468    /// we're operating on a target filesystem rather than the running system.
469    pub fn new_ostree(sysroot: SysrootLock, run: &Dir) -> Result<Self> {
470        let run = run.try_clone()?;
471
472        // ostree has historically always relied on
473        // having ostree -> sysroot/ostree as a symlink in the image to
474        // make it so that code doesn't need to distinguish between booted
475        // vs offline target. The ostree code all just looks at the ostree/
476        // directory, and will follow the link in the booted case.
477        //
478        // For composefs we aren't going to do a similar thing, so here
479        // we need to explicitly distinguish the two and the storage
480        // here hence holds a reference to the physical root.
481        let ostree_sysroot_dir = crate::utils::sysroot_dir(&sysroot)?;
482        let (physical_root, physical_root_path) = if sysroot.is_booted() {
483            (
484                ostree_sysroot_dir.open_dir(SYSROOT)?,
485                Utf8PathBuf::from("/sysroot"),
486            )
487        } else {
488            // For non-booted case (install), get the path from the sysroot
489            let path = sysroot.path();
490            let path_str = path.parse_name().to_string();
491            let path = Utf8PathBuf::from(path_str);
492            (ostree_sysroot_dir, path)
493        };
494
495        let ostree_cell = OnceCell::new();
496        let _ = ostree_cell.set(sysroot);
497
498        Ok(Self {
499            physical_root,
500            physical_root_path,
501            run,
502            boot_dir: None,
503            esp: None,
504            ostree: ostree_cell,
505            composefs: Default::default(),
506            imgstore: Default::default(),
507        })
508    }
509
510    /// Returns `boot_dir` if it exists
511    pub(crate) fn require_boot_dir(&self) -> Result<&Dir> {
512        self.boot_dir
513            .as_ref()
514            .ok_or_else(|| anyhow::anyhow!("Boot dir not found"))
515    }
516
517    /// Returns the mounted `esp` if it exists
518    pub(crate) fn require_esp(&self) -> Result<&TempMount> {
519        self.esp
520            .as_ref()
521            .ok_or_else(|| anyhow::anyhow!("ESP not found"))
522    }
523
524    /// Returns the Directory where the Type1 boot binaries are stored
525    /// `/sysroot/boot` for Grub, and ESP/EFI/Linux for systemd-boot
526    pub(crate) fn bls_boot_binaries_dir(&self) -> Result<Dir> {
527        let boot_dir = self.require_boot_dir()?;
528
529        // boot dir in case of systemd-boot points to the ESP, but we store
530        // the actual binaries inside ESP/EFI/Linux
531        let boot_dir = match get_bootloader()?.kind()? {
532            BootloaderKind::GRUBClassic => boot_dir.try_clone()?,
533            BootloaderKind::BLSCompatible => {
534                let boot_dir = boot_dir
535                    .open_dir(EFI_LINUX)
536                    .with_context(|| format!("Opening {EFI_LINUX}"))?;
537
538                boot_dir
539            }
540        };
541
542        Ok(boot_dir)
543    }
544
545    /// Access the underlying ostree repository
546    pub(crate) fn get_ostree(&self) -> Result<&SysrootLock> {
547        self.ostree
548            .get()
549            .ok_or_else(|| anyhow::anyhow!("OSTree storage not initialized"))
550    }
551
552    /// Get a cloned reference to the ostree sysroot.
553    ///
554    /// This is used when code needs an owned `ostree::Sysroot` rather than
555    /// a reference to the `SysrootLock`.
556    pub(crate) fn get_ostree_cloned(&self) -> Result<ostree::Sysroot> {
557        let r = self.get_ostree()?;
558        Ok((*r).clone())
559    }
560
561    /// Access the image storage; will automatically initialize it if necessary.
562    ///
563    /// Works on both ostree and composefs-only systems.  On ostree the
564    /// SELinux policy is loaded from the booted deployment; on composefs
565    /// (where ostree isn't initialized) we fall back to the host root policy.
566    pub(crate) fn get_ensure_imgstore(&self) -> Result<&CStorage> {
567        if let Some(imgstore) = self.imgstore.get() {
568            return Ok(imgstore);
569        }
570
571        let (sysroot_dir, sepolicy) = if let Ok(ostree) = self.get_ostree() {
572            let sysroot_dir = crate::utils::sysroot_dir(ostree)?;
573            let sepolicy = if ostree.booted_deployment().is_none() {
574                tracing::trace!("falling back to container root's selinux policy");
575                let container_root = Dir::open_ambient_dir("/", cap_std::ambient_authority())?;
576                lsm::new_sepolicy_at(&container_root)?
577            } else {
578                tracing::trace!("loading sepolicy from booted ostree deployment");
579                let dep = ostree.booted_deployment().unwrap();
580                let dep_fs = deployment_fd(ostree, &dep)?;
581                lsm::new_sepolicy_at(&dep_fs)?
582            };
583            (sysroot_dir, sepolicy)
584        } else {
585            // Composefs-only: ostree is not initialized. Use the physical
586            // root directly and load SELinux policy from the host root.
587            let sysroot_dir = self.physical_root.try_clone()?;
588            let root = Dir::open_ambient_dir("/", cap_std::ambient_authority())?;
589            let sepolicy = lsm::new_sepolicy_at(&root)?;
590            (sysroot_dir, sepolicy)
591        };
592
593        tracing::trace!("sepolicy in get_ensure_imgstore: {sepolicy:?}");
594
595        let imgstore = CStorage::create(&sysroot_dir, &self.run, sepolicy.as_ref())?;
596        Ok(self.imgstore.get_or_init(|| imgstore))
597    }
598
599    /// Ensure the image storage is properly SELinux-labeled. This should be
600    /// called after all image pulls are complete.
601    pub(crate) fn ensure_imgstore_labeled(&self) -> Result<()> {
602        if let Some(imgstore) = self.imgstore.get() {
603            imgstore.ensure_labeled()?;
604        }
605        Ok(())
606    }
607
608    /// Access the composefs repository; will automatically initialize it if necessary.
609    ///
610    /// This lazily opens the composefs repository, creating the directory if needed
611    /// and bootstrapping verity settings from the ostree configuration.
612    pub(crate) fn get_ensure_composefs(&self) -> Result<Arc<ComposefsRepository>> {
613        if let Some(composefs) = self.composefs.get() {
614            return Ok(Arc::clone(composefs));
615        }
616
617        ensure_composefs_dir(&self.physical_root)?;
618
619        // Bootstrap verity off of the ostree state. In practice this means disabled by
620        // default right now.
621        let ostree = self.get_ostree()?;
622        let ostree_repo = &ostree.repo();
623        let ostree_verity = ostree_ext::fsverity::is_verity_enabled(ostree_repo)?;
624        let config = RepositoryConfig::new(composefs::fsverity::Algorithm::SHA512);
625        let config = if ostree_verity.enabled {
626            config
627        } else {
628            config.set_insecure()
629        };
630        let (composefs, _created) =
631            ComposefsRepository::init_path(self.physical_root.open_dir(COMPOSEFS)?, ".", config)?;
632        let composefs = Arc::new(composefs);
633        let r = Arc::clone(self.composefs.get_or_init(|| composefs));
634        Ok(r)
635    }
636
637    /// Update the mtime on the storage root directory.
638    ///
639    /// This touches `ostree/bootc` (or its symlink target on composefs
640    /// systems) so that `bootc-status-updated.path` fires.
641    #[context("Updating storage root mtime")]
642    pub(crate) fn update_mtime(&self) -> Result<()> {
643        // On composefs-only systems ostree is not initialized, so fall
644        // back to the physical root directly.
645        let sysroot_dir = if let Ok(ostree) = self.get_ostree() {
646            crate::utils::sysroot_dir(ostree).context("Reopen sysroot directory")?
647        } else {
648            self.physical_root.try_clone()?
649        };
650
651        sysroot_dir
652            .update_timestamps(std::path::Path::new(BOOTC_ROOT))
653            .context("update_timestamps")
654    }
655}
656
657#[cfg(test)]
658mod tests {
659    use super::*;
660
661    /// The raw mode returned by metadata includes file type bits (S_IFDIR,
662    /// etc.) in addition to permission bits. This constant masks to only
663    /// the permission bits (owner/group/other rwx).
664    const PERMS: Mode = Mode::from_raw_mode(0o777);
665
666    #[test]
667    fn test_ensure_composefs_dir_mode() -> Result<()> {
668        use cap_std_ext::cap_primitives::fs::PermissionsExt as _;
669
670        let td = cap_std_ext::cap_tempfile::TempDir::new(cap_std::ambient_authority())?;
671
672        let assert_mode = || -> Result<()> {
673            let perms = td.metadata(COMPOSEFS)?.permissions();
674            let mode = Mode::from_raw_mode(perms.mode());
675            assert_eq!(mode & PERMS, COMPOSEFS_MODE);
676            Ok(())
677        };
678
679        ensure_composefs_dir(&td)?;
680        assert_mode()?;
681
682        // Calling again should be a no-op (ensure is idempotent)
683        ensure_composefs_dir(&td)?;
684        assert_mode()?;
685
686        Ok(())
687    }
688
689    #[test]
690    fn test_ensure_composefs_dir_fixes_existing() -> Result<()> {
691        use cap_std_ext::cap_primitives::fs::PermissionsExt as _;
692
693        let td = cap_std_ext::cap_tempfile::TempDir::new(cap_std::ambient_authority())?;
694
695        // Create with overly permissive mode (simulating old bootc behavior)
696        let mut db = DirBuilder::new();
697        db.mode(0o755);
698        td.create_dir_with(COMPOSEFS, &db)?;
699
700        // Verify it starts with wrong permissions
701        let perms = td.metadata(COMPOSEFS)?.permissions();
702        let mode = Mode::from_raw_mode(perms.mode());
703        assert_eq!(mode & PERMS, Mode::from_raw_mode(0o755));
704
705        // ensure_composefs_dir should fix the permissions
706        ensure_composefs_dir(&td)?;
707
708        let perms = td.metadata(COMPOSEFS)?.permissions();
709        let mode = Mode::from_raw_mode(perms.mode());
710        assert_eq!(mode & PERMS, COMPOSEFS_MODE);
711
712        Ok(())
713    }
714}