Skip to main content

bootc_lib/
status.rs

1use std::borrow::Cow;
2use std::collections::VecDeque;
3use std::io::IsTerminal;
4use std::io::Read;
5use std::io::Write;
6
7use anyhow::{Context, Result};
8use canon_json::CanonJsonSerialize;
9use fn_error_context::context;
10use ostree::glib;
11use ostree_container::OstreeImageReference;
12use ostree_ext::container as ostree_container;
13use ostree_ext::keyfileext::KeyFileExt;
14use ostree_ext::oci_spec;
15use ostree_ext::oci_spec::image::Digest;
16use ostree_ext::oci_spec::image::ImageConfiguration;
17use ostree_ext::sysroot::SysrootLock;
18use unicode_width::UnicodeWidthStr;
19
20use ostree_ext::ostree;
21
22use crate::cli::OutputFormat;
23use crate::spec::BootEntryComposefs;
24use crate::spec::ImageStatus;
25use crate::spec::{BootEntry, BootOrder, Host, HostSpec, HostStatus, HostType};
26use crate::spec::{ImageReference, ImageSignature};
27use crate::store::BootedStorage;
28use crate::store::BootedStorageKind;
29use crate::store::CachedImageStatus;
30
31impl From<ostree_container::SignatureSource> for ImageSignature {
32    fn from(sig: ostree_container::SignatureSource) -> Self {
33        use ostree_container::SignatureSource;
34        match sig {
35            SignatureSource::OstreeRemote(r) => Self::OstreeRemote(r),
36            SignatureSource::ContainerPolicy => Self::ContainerPolicy,
37            SignatureSource::ContainerPolicyAllowInsecure => Self::Insecure,
38        }
39    }
40}
41
42impl From<ImageSignature> for ostree_container::SignatureSource {
43    fn from(sig: ImageSignature) -> Self {
44        use ostree_container::SignatureSource;
45        match sig {
46            ImageSignature::OstreeRemote(r) => SignatureSource::OstreeRemote(r),
47            ImageSignature::ContainerPolicy => Self::ContainerPolicy,
48            ImageSignature::Insecure => Self::ContainerPolicyAllowInsecure,
49        }
50    }
51}
52
53/// Fixme lower serializability into ostree-ext
54fn transport_to_string(transport: ostree_container::Transport) -> String {
55    match transport {
56        // Canonicalize to registry for our own use
57        ostree_container::Transport::Registry => "registry".to_string(),
58        o => {
59            let mut s = o.to_string();
60            s.truncate(s.rfind(':').unwrap());
61            s
62        }
63    }
64}
65
66impl From<OstreeImageReference> for ImageReference {
67    fn from(imgref: OstreeImageReference) -> Self {
68        let signature = match imgref.sigverify {
69            ostree_container::SignatureSource::ContainerPolicyAllowInsecure => None,
70            v => Some(v.into()),
71        };
72        Self {
73            signature,
74            transport: transport_to_string(imgref.imgref.transport),
75            image: imgref.imgref.name,
76        }
77    }
78}
79
80impl From<ImageReference> for OstreeImageReference {
81    fn from(img: ImageReference) -> Self {
82        let sigverify = match img.signature {
83            Some(v) => v.into(),
84            None => ostree_container::SignatureSource::ContainerPolicyAllowInsecure,
85        };
86        Self {
87            sigverify,
88            imgref: ostree_container::ImageReference {
89                // SAFETY: We validated the schema in kube-rs
90                transport: img.transport.as_str().try_into().unwrap(),
91                name: img.image,
92            },
93        }
94    }
95}
96
97/// Check if SELinux policies are compatible between booted and target deployments.
98/// Returns false if SELinux is enabled and the policies differ or have mismatched presence.
99fn check_selinux_policy_compatible(
100    sysroot: &SysrootLock,
101    booted_deployment: &ostree::Deployment,
102    target_deployment: &ostree::Deployment,
103) -> Result<bool> {
104    // Only check if SELinux is enabled
105    if !crate::lsm::selinux_enabled()? {
106        return Ok(true);
107    }
108
109    let booted_fd = crate::utils::deployment_fd(sysroot, booted_deployment)
110        .context("Failed to get file descriptor for booted deployment")?;
111    let booted_policy = crate::lsm::new_sepolicy_at(&booted_fd)
112        .context("Failed to load SELinux policy from booted deployment")?;
113    let target_fd = crate::utils::deployment_fd(sysroot, target_deployment)
114        .context("Failed to get file descriptor for target deployment")?;
115    let target_policy = crate::lsm::new_sepolicy_at(&target_fd)
116        .context("Failed to load SELinux policy from target deployment")?;
117
118    let booted_csum = booted_policy.and_then(|p| p.csum());
119    let target_csum = target_policy.and_then(|p| p.csum());
120
121    match (booted_csum, target_csum) {
122        (None, None) => Ok(true), // Both absent, compatible
123        (Some(_), None) | (None, Some(_)) => {
124            // Incompatible: one has policy, other doesn't
125            Ok(false)
126        }
127        (Some(booted_csum), Some(target_csum)) => {
128            // Both have policies, checksums must match
129            Ok(booted_csum == target_csum)
130        }
131    }
132}
133
134/// Check if a deployment has soft reboot capability
135// TODO: Lower SELinux policy check into ostree's deployment_can_soft_reboot API
136fn has_soft_reboot_capability(sysroot: &SysrootLock, deployment: &ostree::Deployment) -> bool {
137    if !ostree_ext::systemd_has_soft_reboot() {
138        return false;
139    }
140
141    // When the ostree version is < 2025.7 and the deployment is
142    // missing the ostree= karg (happens during a factory reset),
143    // there is a bug that causes deployment_can_soft_reboot to crash.
144    // So in this case default to disabling soft reboot.
145    let has_ostree_karg = deployment
146        .bootconfig()
147        .and_then(|bootcfg| bootcfg.get("options"))
148        .map(|options| options.contains("ostree="))
149        .unwrap_or(false);
150
151    if !ostree::check_version(2025, 7) && !has_ostree_karg {
152        return false;
153    }
154
155    if !sysroot.deployment_can_soft_reboot(deployment) {
156        return false;
157    }
158
159    // Check SELinux policy compatibility with booted deployment
160    // Block soft reboot if SELinux policies differ, as policy is not reloaded across soft reboots
161    if let Some(booted_deployment) = sysroot.booted_deployment() {
162        // deployment_fd should not fail for valid deployments
163        if !check_selinux_policy_compatible(sysroot, &booted_deployment, deployment)
164            .expect("deployment_fd should not fail for valid deployments")
165        {
166            return false;
167        }
168    }
169
170    true
171}
172
173/// Parse an ostree origin file (a keyfile) and extract the targeted
174/// container image reference.
175fn get_image_origin(origin: &glib::KeyFile) -> Result<Option<OstreeImageReference>> {
176    origin
177        .optional_string("origin", ostree_container::deploy::ORIGIN_CONTAINER)
178        .context("Failed to load container image from origin")?
179        .map(|v| ostree_container::OstreeImageReference::try_from(v.as_str()))
180        .transpose()
181}
182
183pub(crate) struct Deployments {
184    pub(crate) staged: Option<ostree::Deployment>,
185    pub(crate) rollback: Option<ostree::Deployment>,
186    #[allow(dead_code)]
187    pub(crate) other: VecDeque<ostree::Deployment>,
188}
189
190pub(crate) fn labels_of_config(
191    config: &oci_spec::image::ImageConfiguration,
192) -> Option<&std::collections::HashMap<String, String>> {
193    config.config().as_ref().and_then(|c| c.labels().as_ref())
194}
195
196/// Convert between a subset of ostree-ext metadata and the exposed spec API.
197fn create_imagestatus(
198    image: ImageReference,
199    manifest_digest: &Digest,
200    config: &ImageConfiguration,
201) -> ImageStatus {
202    let labels = labels_of_config(config);
203    let timestamp = labels
204        .and_then(|l| {
205            l.get(oci_spec::image::ANNOTATION_CREATED)
206                .map(|s| s.as_str())
207        })
208        .or_else(|| config.created().as_deref())
209        .and_then(bootc_utils::try_deserialize_timestamp);
210
211    let version = ostree_container::version_for_config(config).map(ToOwned::to_owned);
212    let architecture = config.architecture().to_string();
213    ImageStatus {
214        image,
215        version,
216        timestamp,
217        image_digest: manifest_digest.to_string(),
218        architecture,
219    }
220}
221
222fn imagestatus(
223    sysroot: &SysrootLock,
224    deployment: &ostree::Deployment,
225    image: ostree_container::OstreeImageReference,
226) -> Result<CachedImageStatus> {
227    let repo = &sysroot.repo();
228    let imgstate = ostree_container::store::query_image_commit(repo, &deployment.csum())?;
229    let image = ImageReference::from(image);
230    let cached = imgstate
231        .cached_update
232        .map(|cached| create_imagestatus(image.clone(), &cached.manifest_digest, &cached.config));
233    let imagestatus = create_imagestatus(image, &imgstate.manifest_digest, &imgstate.configuration);
234
235    Ok(CachedImageStatus {
236        image: Some(imagestatus),
237        cached_update: cached,
238    })
239}
240
241/// Given an OSTree deployment, parse out metadata into our spec.
242#[context("Reading deployment metadata")]
243pub(crate) fn boot_entry_from_deployment(
244    sysroot: &SysrootLock,
245    deployment: &ostree::Deployment,
246) -> Result<BootEntry> {
247    let (
248        CachedImageStatus {
249            image,
250            cached_update,
251        },
252        incompatible,
253    ) = if let Some(origin) = deployment.origin().as_ref() {
254        let incompatible = crate::utils::origin_has_rpmostree_stuff(origin);
255        let cached_imagestatus = if incompatible {
256            // If there are local changes, we can't represent it as a bootc compatible image.
257            CachedImageStatus::default()
258        } else if let Some(image) = get_image_origin(origin)? {
259            imagestatus(sysroot, deployment, image)?
260        } else {
261            // The deployment isn't using a container image
262            CachedImageStatus::default()
263        };
264        (cached_imagestatus, incompatible)
265    } else {
266        // The deployment has no origin at all (this generally shouldn't happen)
267        (CachedImageStatus::default(), false)
268    };
269
270    let soft_reboot_capable = has_soft_reboot_capability(sysroot, deployment);
271    let download_only = deployment.is_staged() && deployment.is_finalization_locked();
272    let store = Some(crate::spec::Store::OstreeContainer);
273    let r = BootEntry {
274        image,
275        cached_update,
276        incompatible,
277        soft_reboot_capable,
278        download_only,
279        store,
280        pinned: deployment.is_pinned(),
281        ostree: Some(crate::spec::BootEntryOstree {
282            checksum: deployment.csum().into(),
283            // SAFETY: The deployserial is really unsigned
284            deploy_serial: deployment.deployserial().try_into().unwrap(),
285            stateroot: deployment.stateroot().into(),
286        }),
287        composefs: None,
288    };
289    Ok(r)
290}
291
292impl BootEntry {
293    /// Given a boot entry, find its underlying ostree container image
294    pub(crate) fn query_image(
295        &self,
296        repo: &ostree::Repo,
297    ) -> Result<Option<Box<ostree_container::store::LayeredImageState>>> {
298        if self.image.is_none() {
299            return Ok(None);
300        }
301        if let Some(checksum) = self.ostree.as_ref().map(|c| c.checksum.as_str()) {
302            ostree_container::store::query_image_commit(repo, checksum).map(Some)
303        } else {
304            Ok(None)
305        }
306    }
307
308    pub(crate) fn require_composefs(&self) -> Result<&BootEntryComposefs> {
309        self.composefs.as_ref().ok_or(anyhow::anyhow!(
310            "BootEntry is not a composefs native boot entry"
311        ))
312    }
313
314    /// Get the boot digest for this deployment
315    /// This is the
316    /// - SHA256SUM of kernel + initrd for Type1 booted deployments
317    /// - SHA256SUM of UKI for Type2 booted deployments
318    pub(crate) fn composefs_boot_digest(&self) -> Result<&String> {
319        self.require_composefs()?
320            .boot_digest
321            .as_ref()
322            .ok_or_else(|| anyhow::anyhow!("Could not find boot digest for deployment"))
323    }
324}
325
326/// A variant of [`get_status`] that requires a booted deployment.
327pub(crate) fn get_status_require_booted(
328    sysroot: &SysrootLock,
329) -> Result<(crate::store::BootedOstree<'_>, Deployments, Host)> {
330    let booted_deployment = sysroot.require_booted_deployment()?;
331    let booted_ostree = crate::store::BootedOstree {
332        sysroot,
333        deployment: booted_deployment,
334    };
335    let (deployments, host) = get_status(&booted_ostree)?;
336    Ok((booted_ostree, deployments, host))
337}
338
339/// Gather the ostree deployment objects, but also extract metadata from them into
340/// a more native Rust structure.
341#[context("Computing status")]
342pub(crate) fn get_status(
343    booted_ostree: &crate::store::BootedOstree<'_>,
344) -> Result<(Deployments, Host)> {
345    let sysroot = booted_ostree.sysroot;
346    let booted_deployment = Some(&booted_ostree.deployment);
347    let stateroot = booted_deployment.as_ref().map(|d| d.osname());
348    let (mut related_deployments, other_deployments) = sysroot
349        .deployments()
350        .into_iter()
351        .partition::<VecDeque<_>, _>(|d| Some(d.osname()) == stateroot);
352    let staged = related_deployments
353        .iter()
354        .position(|d| d.is_staged())
355        .map(|i| related_deployments.remove(i).unwrap());
356    tracing::debug!("Staged: {staged:?}");
357    // Filter out the booted, the caller already found that
358    if let Some(booted) = booted_deployment.as_ref() {
359        related_deployments.retain(|f| !f.equal(booted));
360    }
361    let rollback = related_deployments.pop_front();
362    let rollback_queued = match (booted_deployment.as_ref(), rollback.as_ref()) {
363        (Some(booted), Some(rollback)) => rollback.index() < booted.index(),
364        _ => false,
365    };
366    let boot_order = if rollback_queued {
367        BootOrder::Rollback
368    } else {
369        BootOrder::Default
370    };
371    tracing::debug!("Rollback queued={rollback_queued:?}");
372    let other = {
373        related_deployments.extend(other_deployments);
374        related_deployments
375    };
376    let deployments = Deployments {
377        staged,
378        rollback,
379        other,
380    };
381
382    let staged = deployments
383        .staged
384        .as_ref()
385        .map(|d| boot_entry_from_deployment(sysroot, d))
386        .transpose()
387        .context("Staged deployment")?;
388    let booted = booted_deployment
389        .as_ref()
390        .map(|d| boot_entry_from_deployment(sysroot, d))
391        .transpose()
392        .context("Booted deployment")?;
393    let rollback = deployments
394        .rollback
395        .as_ref()
396        .map(|d| boot_entry_from_deployment(sysroot, d))
397        .transpose()
398        .context("Rollback deployment")?;
399    let other_deployments = deployments
400        .other
401        .iter()
402        .map(|d| boot_entry_from_deployment(sysroot, d))
403        .collect::<Result<Vec<_>>>()
404        .context("Other deployments")?;
405    let spec = staged
406        .as_ref()
407        .or(booted.as_ref())
408        .and_then(|entry| entry.image.as_ref())
409        .map(|img| HostSpec {
410            image: Some(img.image.clone()),
411            boot_order,
412        })
413        .unwrap_or_default();
414
415    let ty = if booted
416        .as_ref()
417        .map(|b| b.image.is_some())
418        .unwrap_or_default()
419    {
420        // We're only of type BootcHost if we booted via container image
421        Some(HostType::BootcHost)
422    } else {
423        None
424    };
425
426    let usr_overlay = booted_deployment
427        .as_ref()
428        .map(|d| d.unlocked())
429        .and_then(crate::spec::deployment_unlocked_state_to_usr_overlay);
430
431    let mut host = Host::new(spec);
432    host.status = HostStatus {
433        staged,
434        booted,
435        rollback,
436        other_deployments,
437        rollback_queued,
438        ty,
439        usr_overlay,
440        // Set by callers that have storage context (e.g. get_host).
441        read_only: false,
442    };
443    Ok((deployments, host))
444}
445
446pub(crate) async fn get_host() -> Result<Host> {
447    let env = crate::store::Environment::detect()?;
448    if env.needs_mount_namespace() {
449        crate::cli::prepare_for_write()?;
450    }
451
452    let Some(storage) = BootedStorage::new(env, crate::store::EspAccess::ReadOnly).await? else {
453        // If we're not booted, then return a default.
454        return Ok(Host::default());
455    };
456
457    let mut host = match storage.kind() {
458        Ok(kind) => match kind {
459            BootedStorageKind::Ostree(booted_ostree) => {
460                let (_deployments, host) = get_status(&booted_ostree)?;
461                host
462            }
463            BootedStorageKind::Composefs(booted_cfs) => {
464                crate::bootc_composefs::status::get_composefs_status(&storage, &booted_cfs).await?
465            }
466        },
467        Err(_) => {
468            // If determining storage kind fails (e.g., no booted deployment),
469            // return a default host indicating the system is not deployed via bootc
470            Host::default()
471        }
472    };
473
474    // Surface whether the physical root is on a read-only medium (e.g. a live
475    // ISO), so consumers know mutating operations are unavailable.
476    host.status.read_only = storage.is_ro;
477
478    Ok(host)
479}
480
481/// Implementation of the `bootc status` CLI command.
482#[context("Status")]
483pub(crate) async fn status(opts: super::cli::StatusOpts) -> Result<()> {
484    match opts.format_version.unwrap_or_default() {
485        // For historical reasons, both 0 and 1 mean "v1".
486        0 | 1 => {}
487        o => anyhow::bail!("Unsupported format version: {o}"),
488    };
489    let mut host = get_host().await?;
490
491    // We could support querying the staged or rollback deployments
492    // here too, but it's not a common use case at the moment.
493    if opts.booted {
494        host.filter_to_slot(Slot::Booted);
495    }
496
497    // If we're in JSON mode, then convert the ostree data into Rust-native
498    // structures that can be serialized.
499    // Filter to just the serializable status structures.
500    let out = std::io::stdout();
501    let mut out = out.lock();
502    let legacy_opt = if opts.json {
503        OutputFormat::Json
504    } else if std::io::stdout().is_terminal() {
505        OutputFormat::HumanReadable
506    } else {
507        OutputFormat::Yaml
508    };
509    let format = opts.format.unwrap_or(legacy_opt);
510    match format {
511        OutputFormat::Json => host
512            .to_canon_json_writer(&mut out)
513            .map_err(anyhow::Error::new),
514        OutputFormat::Yaml => serde_yaml::to_writer(&mut out, &host).map_err(anyhow::Error::new),
515        OutputFormat::HumanReadable => human_readable_output(&mut out, &host, opts.verbose),
516    }
517    .context("Writing to stdout")?;
518
519    Ok(())
520}
521
522#[derive(Debug, Clone, Copy)]
523pub enum Slot {
524    Staged,
525    Booted,
526    Rollback,
527}
528
529impl std::fmt::Display for Slot {
530    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
531        let s = match self {
532            Slot::Staged => "staged",
533            Slot::Booted => "booted",
534            Slot::Rollback => "rollback",
535        };
536        f.write_str(s)
537    }
538}
539
540/// Output a row title, prefixed by spaces
541fn write_row_name(mut out: impl Write, s: &str, prefix_len: usize) -> Result<()> {
542    let n = prefix_len.saturating_sub(s.chars().count());
543    let mut spaces = std::io::repeat(b' ').take(n as u64);
544    std::io::copy(&mut spaces, &mut out)?;
545    write!(out, "{s}: ")?;
546    Ok(())
547}
548
549/// Format a timestamp for human display, without nanoseconds.
550///
551/// Nanoseconds are irrelevant noise for container build timestamps;
552/// this produces the same format as RFC3339 but truncated to seconds.
553fn format_timestamp(t: &chrono::DateTime<chrono::Utc>) -> impl std::fmt::Display {
554    t.format("%Y-%m-%dT%H:%M:%SZ")
555}
556
557/// Helper function to render verbose ostree information
558fn render_verbose_ostree_info(
559    mut out: impl Write,
560    ostree: &crate::spec::BootEntryOstree,
561    slot: Option<Slot>,
562    prefix_len: usize,
563) -> Result<()> {
564    write_row_name(&mut out, "StateRoot", prefix_len)?;
565    writeln!(out, "{}", ostree.stateroot)?;
566
567    // Show deployment serial (similar to Index in rpm-ostree)
568    write_row_name(&mut out, "Deploy serial", prefix_len)?;
569    writeln!(out, "{}", ostree.deploy_serial)?;
570
571    // Show if this is staged
572    let is_staged = matches!(slot, Some(Slot::Staged));
573    write_row_name(&mut out, "Staged", prefix_len)?;
574    writeln!(out, "{}", if is_staged { "yes" } else { "no" })?;
575
576    Ok(())
577}
578
579/// Helper function to render if soft-reboot capable
580fn write_soft_reboot(
581    mut out: impl Write,
582    entry: &crate::spec::BootEntry,
583    prefix_len: usize,
584) -> Result<()> {
585    // Show soft-reboot capability
586    write_row_name(&mut out, "Soft-reboot", prefix_len)?;
587    writeln!(
588        out,
589        "{}",
590        if entry.soft_reboot_capable {
591            "yes"
592        } else {
593            "no"
594        }
595    )?;
596
597    Ok(())
598}
599
600/// Helper function to render download-only lock status
601fn write_download_only(
602    mut out: impl Write,
603    slot: Option<Slot>,
604    entry: &crate::spec::BootEntry,
605    prefix_len: usize,
606) -> Result<()> {
607    // Only staged deployments can have download-only status
608    if matches!(slot, Some(Slot::Staged)) {
609        write_row_name(&mut out, "Download-only", prefix_len)?;
610        writeln!(out, "{}", if entry.download_only { "yes" } else { "no" })?;
611    }
612    Ok(())
613}
614
615fn write_fsverity_enforcement(
616    mut out: impl Write,
617    entry: &crate::spec::BootEntry,
618    prefix_len: usize,
619) -> Result<()> {
620    if let Some(cfs) = &entry.composefs {
621        write_row_name(&mut out, "FsVerity", prefix_len)?;
622        writeln!(
623            out,
624            "{}",
625            if cfs.missing_verity_allowed {
626                "Not Enforced"
627            } else {
628                "Enforced"
629            }
630        )?;
631    };
632
633    Ok(())
634}
635
636/// Render cached update information, showing what update is available.
637///
638/// This is populated by a previous `bootc upgrade --check` that found
639/// a newer image in the registry. We only display it when the cached
640/// digest differs from the currently deployed image.
641fn render_cached_update(
642    mut out: impl Write,
643    cached: &crate::spec::ImageStatus,
644    current: &crate::spec::ImageStatus,
645    prefix_len: usize,
646) -> Result<()> {
647    if cached.image_digest == current.image_digest {
648        return Ok(());
649    }
650
651    if let Some(version) = cached.version.as_deref() {
652        write_row_name(&mut out, "UpdateVersion", prefix_len)?;
653        let timestamp_str = cached
654            .timestamp
655            .as_ref()
656            .map(|t| format!(" ({})", format_timestamp(t)))
657            .unwrap_or_default();
658        writeln!(out, "{version}{timestamp_str}")?;
659    } else {
660        write_row_name(&mut out, "Update", prefix_len)?;
661        writeln!(out, "Available")?;
662    }
663    write_row_name(&mut out, "UpdateDigest", prefix_len)?;
664    writeln!(out, "{}", cached.image_digest)?;
665
666    Ok(())
667}
668
669/// Write the data for a container image based status.
670fn human_render_slot(
671    mut out: impl Write,
672    slot: Option<Slot>,
673    entry: &crate::spec::BootEntry,
674    image: &crate::spec::ImageStatus,
675    host_status: &crate::spec::HostStatus,
676    verbose: bool,
677) -> Result<()> {
678    let transport = &image.image.transport;
679    let imagename = &image.image.image;
680    // Registry is the default, so don't show that
681    let imageref = if transport == "registry" {
682        Cow::Borrowed(imagename)
683    } else {
684        // But for non-registry we include the transport
685        Cow::Owned(format!("{transport}:{imagename}"))
686    };
687    let prefix = match slot {
688        Some(Slot::Staged) => "  Staged image".into(),
689        Some(Slot::Booted) => format!("{} Booted image", crate::glyph::Glyph::BlackCircle),
690        Some(Slot::Rollback) => "  Rollback image".into(),
691        _ => "   Other image".into(),
692    };
693    let prefix_len = prefix.chars().count();
694    writeln!(out, "{prefix}: {imageref}")?;
695
696    let arch = image.architecture.as_str();
697    write_row_name(&mut out, "Digest", prefix_len)?;
698    let digest = &image.image_digest;
699    writeln!(out, "{digest} ({arch})")?;
700
701    // Write the EROFS verity if present
702    if let Some(composefs) = &entry.composefs {
703        write_row_name(&mut out, "Verity", prefix_len)?;
704        writeln!(out, "{}", composefs.verity)?;
705    }
706
707    let timestamp = image.timestamp.as_ref().map(format_timestamp);
708    // If we have a version, combine with timestamp
709    if let Some(version) = image.version.as_deref() {
710        write_row_name(&mut out, "Version", prefix_len)?;
711        if let Some(timestamp) = timestamp {
712            writeln!(out, "{version} ({timestamp})")?;
713        } else {
714            writeln!(out, "{version}")?;
715        }
716    } else if let Some(timestamp) = timestamp {
717        // Otherwise just output timestamp
718        write_row_name(&mut out, "Timestamp", prefix_len)?;
719        writeln!(out, "{timestamp}")?;
720    }
721
722    if entry.pinned {
723        write_row_name(&mut out, "Pinned", prefix_len)?;
724        writeln!(out, "yes")?;
725    }
726
727    // Show cached update information when available (from a previous `bootc upgrade --check`)
728    if let Some(cached) = &entry.cached_update {
729        render_cached_update(&mut out, cached, image, prefix_len)?;
730    }
731
732    // Show /usr overlay status
733    write_usr_overlay(&mut out, slot, host_status, prefix_len)?;
734
735    if verbose {
736        // Show additional information in verbose mode similar to rpm-ostree
737        if let Some(ostree) = &entry.ostree {
738            render_verbose_ostree_info(&mut out, ostree, slot, prefix_len)?;
739
740            // Show the commit (equivalent to Base Commit in rpm-ostree)
741            write_row_name(&mut out, "Commit", prefix_len)?;
742            writeln!(out, "{}", ostree.checksum)?;
743        }
744
745        // Show signature information if available
746        if let Some(signature) = &image.image.signature {
747            write_row_name(&mut out, "Signature", prefix_len)?;
748            match signature {
749                crate::spec::ImageSignature::OstreeRemote(remote) => {
750                    writeln!(out, "ostree-remote:{remote}")?;
751                }
752                crate::spec::ImageSignature::ContainerPolicy => {
753                    writeln!(out, "container-policy")?;
754                }
755                crate::spec::ImageSignature::Insecure => {
756                    writeln!(out, "insecure")?;
757                }
758            }
759        }
760
761        // Show soft-reboot capability
762        write_soft_reboot(&mut out, entry, prefix_len)?;
763
764        write_fsverity_enforcement(&mut out, entry, prefix_len)?;
765
766        // Show download-only lock status
767        write_download_only(&mut out, slot, entry, prefix_len)?;
768    }
769
770    tracing::debug!("pinned={}", entry.pinned);
771
772    Ok(())
773}
774
775/// Helper function to render usr overlay status
776fn write_usr_overlay(
777    mut out: impl Write,
778    slot: Option<Slot>,
779    host_status: &crate::spec::HostStatus,
780    prefix_len: usize,
781) -> Result<()> {
782    // Only booted deployments can have /usr overlay status
783    if matches!(slot, Some(Slot::Booted)) {
784        // Only print row if overlay is present
785        if let Some(ref overlay) = host_status.usr_overlay {
786            write_row_name(&mut out, "/usr overlay", prefix_len)?;
787            writeln!(out, "{}", overlay)?;
788        }
789    }
790    Ok(())
791}
792
793/// Output a rendering of a non-container boot entry.
794fn human_render_slot_ostree(
795    mut out: impl Write,
796    slot: Option<Slot>,
797    entry: &crate::spec::BootEntry,
798    ostree_commit: &str,
799    host_status: &crate::spec::HostStatus,
800    verbose: bool,
801) -> Result<()> {
802    // TODO consider rendering more ostree stuff here like rpm-ostree status does
803    let prefix = match slot {
804        Some(Slot::Staged) => "  Staged ostree".into(),
805        Some(Slot::Booted) => format!("{} Booted ostree", crate::glyph::Glyph::BlackCircle),
806        Some(Slot::Rollback) => "  Rollback ostree".into(),
807        _ => " Other ostree".into(),
808    };
809    let prefix_len = prefix.len();
810    writeln!(out, "{prefix}")?;
811    write_row_name(&mut out, "Commit", prefix_len)?;
812    writeln!(out, "{ostree_commit}")?;
813
814    if entry.pinned {
815        write_row_name(&mut out, "Pinned", prefix_len)?;
816        writeln!(out, "yes")?;
817    }
818
819    // Show /usr overlay status
820    write_usr_overlay(&mut out, slot, host_status, prefix_len)?;
821
822    if verbose {
823        // Show additional information in verbose mode similar to rpm-ostree
824        if let Some(ostree) = &entry.ostree {
825            render_verbose_ostree_info(&mut out, ostree, slot, prefix_len)?;
826        }
827
828        // Show soft-reboot capability
829        write_soft_reboot(&mut out, entry, prefix_len)?;
830
831        // Show download-only lock status
832        write_download_only(&mut out, slot, entry, prefix_len)?;
833    }
834
835    tracing::debug!("pinned={}", entry.pinned);
836    Ok(())
837}
838
839/// Output a rendering of a non-container composefs boot entry.
840fn human_render_slot_composefs(
841    mut out: impl Write,
842    slot: Slot,
843    entry: &crate::spec::BootEntry,
844    erofs_verity: &str,
845) -> Result<()> {
846    // TODO consider rendering more ostree stuff here like rpm-ostree status does
847    let prefix = match slot {
848        Slot::Staged => "  Staged composefs".into(),
849        Slot::Booted => format!("{} Booted composefs", crate::glyph::Glyph::BlackCircle),
850        Slot::Rollback => "  Rollback composefs".into(),
851    };
852    let prefix_len = prefix.len();
853    writeln!(out, "{prefix}")?;
854    write_row_name(&mut out, "Commit", prefix_len)?;
855    writeln!(out, "{erofs_verity}")?;
856    tracing::debug!("pinned={}", entry.pinned);
857    Ok(())
858}
859
860fn human_readable_output_booted(mut out: impl Write, host: &Host, verbose: bool) -> Result<()> {
861    let mut first = true;
862    for (slot_name, status) in [
863        (Slot::Staged, &host.status.staged),
864        (Slot::Booted, &host.status.booted),
865        (Slot::Rollback, &host.status.rollback),
866    ] {
867        if let Some(host_status) = status {
868            if first {
869                first = false;
870            } else {
871                writeln!(out)?;
872            }
873
874            if let Some(image) = &host_status.image {
875                human_render_slot(
876                    &mut out,
877                    Some(slot_name),
878                    host_status,
879                    image,
880                    &host.status,
881                    verbose,
882                )?;
883            } else if let Some(ostree) = host_status.ostree.as_ref() {
884                human_render_slot_ostree(
885                    &mut out,
886                    Some(slot_name),
887                    host_status,
888                    &ostree.checksum,
889                    &host.status,
890                    verbose,
891                )?;
892            } else if let Some(composefs) = &host_status.composefs {
893                human_render_slot_composefs(&mut out, slot_name, host_status, &composefs.verity)?;
894            } else {
895                writeln!(out, "Current {slot_name} state is unknown")?;
896            }
897        }
898    }
899
900    if !host.status.other_deployments.is_empty() {
901        for entry in &host.status.other_deployments {
902            writeln!(out)?;
903
904            if let Some(image) = &entry.image {
905                human_render_slot(&mut out, None, entry, image, &host.status, verbose)?;
906            } else if let Some(ostree) = entry.ostree.as_ref() {
907                human_render_slot_ostree(
908                    &mut out,
909                    None,
910                    entry,
911                    &ostree.checksum,
912                    &host.status,
913                    verbose,
914                )?;
915            }
916        }
917    }
918
919    Ok(())
920}
921
922/// Implementation of rendering our host structure in a "human readable" way.
923fn human_readable_output(mut out: impl Write, host: &Host, verbose: bool) -> Result<()> {
924    if host.status.booted.is_some() {
925        human_readable_output_booted(out, host, verbose)?;
926    } else {
927        writeln!(out, "System is not deployed via bootc.")?;
928    }
929    Ok(())
930}
931
932/// Output container inspection in human-readable format
933fn container_inspect_print_human(
934    inspect: &crate::spec::ContainerInspect,
935    mut out: impl Write,
936) -> Result<()> {
937    // Collect rows to determine the max label width
938    let mut rows: Vec<(&str, String)> = Vec::new();
939
940    if let Some(kernel) = &inspect.kernel {
941        rows.push(("Kernel", kernel.version.clone()));
942        let kernel_type = if kernel.unified { "UKI" } else { "vmlinuz" };
943        rows.push(("Type", kernel_type.to_string()));
944    } else {
945        rows.push(("Kernel", "<none>".to_string()));
946    }
947
948    let kargs = if inspect.kargs.is_empty() {
949        "<none>".to_string()
950    } else {
951        inspect.kargs.join(" ")
952    };
953    rows.push(("Kargs", kargs));
954
955    // Find the max label width for right-alignment
956    let max_label_len = rows
957        .iter()
958        .map(|(label, _)| label.width())
959        .max()
960        .unwrap_or(0);
961
962    for (label, value) in rows {
963        write_row_name(&mut out, label, max_label_len)?;
964        writeln!(out, "{value}")?;
965    }
966
967    Ok(())
968}
969
970/// Inspect a container image and output information about it.
971pub(crate) fn container_inspect(
972    rootfs: &camino::Utf8Path,
973    json: bool,
974    format: Option<OutputFormat>,
975) -> Result<()> {
976    let root = cap_std_ext::cap_std::fs::Dir::open_ambient_dir(
977        rootfs,
978        cap_std_ext::cap_std::ambient_authority(),
979    )?;
980    let kargs = crate::bootc_kargs::get_kargs_in_root(&root, std::env::consts::ARCH)?;
981    let kargs: Vec<String> = kargs.iter_str().map(|s| s.to_owned()).collect();
982    let kernel = crate::kernel::find_kernel(&root)?.map(Into::into);
983    let inspect = crate::spec::ContainerInspect { kargs, kernel };
984
985    // Determine output format: explicit --format wins, then --json, then default to human-readable
986    let format = format.unwrap_or(if json {
987        OutputFormat::Json
988    } else {
989        OutputFormat::HumanReadable
990    });
991
992    let mut out = std::io::stdout().lock();
993    match format {
994        OutputFormat::Json => {
995            serde_json::to_writer_pretty(&mut out, &inspect)?;
996        }
997        OutputFormat::Yaml => {
998            serde_yaml::to_writer(&mut out, &inspect)?;
999        }
1000        OutputFormat::HumanReadable => {
1001            container_inspect_print_human(&inspect, &mut out)?;
1002        }
1003    }
1004    Ok(())
1005}
1006
1007#[cfg(test)]
1008mod tests {
1009    use super::*;
1010
1011    #[test]
1012    fn test_format_timestamp() {
1013        use chrono::TimeZone;
1014        let cases = [
1015            // Standard case
1016            (
1017                chrono::Utc.with_ymd_and_hms(2024, 8, 7, 12, 0, 0).unwrap(),
1018                "2024-08-07T12:00:00Z",
1019            ),
1020            // Midnight
1021            (
1022                chrono::Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap(),
1023                "2023-01-01T00:00:00Z",
1024            ),
1025            // End of day
1026            (
1027                chrono::Utc
1028                    .with_ymd_and_hms(2025, 12, 31, 23, 59, 59)
1029                    .unwrap(),
1030                "2025-12-31T23:59:59Z",
1031            ),
1032            // Subsecond precision should be dropped
1033            (
1034                chrono::Utc
1035                    .with_ymd_and_hms(2024, 6, 15, 10, 30, 45)
1036                    .unwrap()
1037                    + chrono::Duration::nanoseconds(123_456_789),
1038                "2024-06-15T10:30:45Z",
1039            ),
1040        ];
1041        for (input, expected) in cases {
1042            let result = format_timestamp(&input).to_string();
1043            assert_eq!(result, expected, "Failed for input {input:?}");
1044        }
1045    }
1046
1047    fn human_status_from_spec_fixture(spec_fixture: &str) -> Result<String> {
1048        let host: Host = serde_yaml::from_str(spec_fixture).unwrap();
1049        let mut w = Vec::new();
1050        human_readable_output(&mut w, &host, false).unwrap();
1051        let w = String::from_utf8(w).unwrap();
1052        Ok(w)
1053    }
1054
1055    /// Helper function to generate human-readable status output with verbose mode enabled
1056    /// from a YAML fixture string. Used for testing verbose output formatting.
1057    fn human_status_from_spec_fixture_verbose(spec_fixture: &str) -> Result<String> {
1058        let host: Host = serde_yaml::from_str(spec_fixture).unwrap();
1059        let mut w = Vec::new();
1060        human_readable_output(&mut w, &host, true).unwrap();
1061        let w = String::from_utf8(w).unwrap();
1062        Ok(w)
1063    }
1064
1065    #[test]
1066    fn test_human_readable_base_spec() {
1067        // Tests Staged and Booted, null Rollback
1068        let w = human_status_from_spec_fixture(include_str!("fixtures/spec-staged-booted.yaml"))
1069            .expect("No spec found");
1070        let expected = indoc::indoc! { r"
1071            Staged image: quay.io/example/someimage:latest
1072                  Digest: sha256:16dc2b6256b4ff0d2ec18d2dbfb06d117904010c8cf9732cdb022818cf7a7566 (arm64)
1073                 Version: nightly (2023-10-14T19:22:15Z)
1074
1075          ● Booted image: quay.io/example/someimage:latest
1076                  Digest: sha256:736b359467c9437c1ac915acaae952aad854e07eb4a16a94999a48af08c83c34 (arm64)
1077                 Version: nightly (2023-09-30T19:22:16Z)
1078        "};
1079        similar_asserts::assert_eq!(w, expected);
1080    }
1081
1082    #[test]
1083    fn test_human_readable_rfe_spec() {
1084        // Basic rhel for edge bootc install with nothing
1085        let w = human_status_from_spec_fixture(include_str!(
1086            "fixtures/spec-rfe-ostree-deployment.yaml"
1087        ))
1088        .expect("No spec found");
1089        let expected = indoc::indoc! { r"
1090            Staged ostree
1091                   Commit: 1c24260fdd1be20f72a4a97a75c582834ee3431fbb0fa8e4f482bb219d633a45
1092
1093          ● Booted ostree
1094                     Commit: f9fa3a553ceaaaf30cf85bfe7eed46a822f7b8fd7e14c1e3389cbc3f6d27f791
1095        "};
1096        similar_asserts::assert_eq!(w, expected);
1097    }
1098
1099    #[test]
1100    fn test_human_readable_staged_spec() {
1101        // staged image, no boot/rollback
1102        let w = human_status_from_spec_fixture(include_str!("fixtures/spec-ostree-to-bootc.yaml"))
1103            .expect("No spec found");
1104        let expected = indoc::indoc! { r"
1105            Staged image: quay.io/centos-bootc/centos-bootc:stream9
1106                  Digest: sha256:47e5ed613a970b6574bfa954ab25bb6e85656552899aa518b5961d9645102b38 (s390x)
1107                 Version: stream9.20240807.0
1108
1109          ● Booted ostree
1110                     Commit: f9fa3a553ceaaaf30cf85bfe7eed46a822f7b8fd7e14c1e3389cbc3f6d27f791
1111        "};
1112        similar_asserts::assert_eq!(w, expected);
1113    }
1114
1115    #[test]
1116    fn test_human_readable_booted_spec() {
1117        // booted image, no staged/rollback
1118        let w = human_status_from_spec_fixture(include_str!("fixtures/spec-only-booted.yaml"))
1119            .expect("No spec found");
1120        let expected = indoc::indoc! { r"
1121          ● Booted image: quay.io/centos-bootc/centos-bootc:stream9
1122                  Digest: sha256:47e5ed613a970b6574bfa954ab25bb6e85656552899aa518b5961d9645102b38 (arm64)
1123                 Version: stream9.20240807.0
1124        "};
1125        similar_asserts::assert_eq!(w, expected);
1126    }
1127
1128    #[test]
1129    fn test_human_readable_staged_rollback_spec() {
1130        // staged/rollback image, no booted
1131        let w = human_status_from_spec_fixture(include_str!("fixtures/spec-staged-rollback.yaml"))
1132            .expect("No spec found");
1133        let expected = "System is not deployed via bootc.\n";
1134        similar_asserts::assert_eq!(w, expected);
1135    }
1136
1137    #[test]
1138    fn test_via_oci() {
1139        let w = human_status_from_spec_fixture(include_str!("fixtures/spec-via-local-oci.yaml"))
1140            .unwrap();
1141        let expected = indoc::indoc! { r"
1142          ● Booted image: oci:/var/mnt/osupdate
1143                  Digest: sha256:47e5ed613a970b6574bfa954ab25bb6e85656552899aa518b5961d9645102b38 (amd64)
1144                 Version: stream9.20240807.0
1145        "};
1146        similar_asserts::assert_eq!(w, expected);
1147    }
1148
1149    #[test]
1150    fn test_convert_signatures() {
1151        use std::str::FromStr;
1152        let ir_unverified = &OstreeImageReference::from_str(
1153            "ostree-unverified-registry:quay.io/someexample/foo:latest",
1154        )
1155        .unwrap();
1156        let ir_ostree = &OstreeImageReference::from_str(
1157            "ostree-remote-registry:fedora:quay.io/fedora/fedora-coreos:stable",
1158        )
1159        .unwrap();
1160
1161        let ir = ImageReference::from(ir_unverified.clone());
1162        assert_eq!(ir.image, "quay.io/someexample/foo:latest");
1163        assert_eq!(ir.signature, None);
1164
1165        let ir = ImageReference::from(ir_ostree.clone());
1166        assert_eq!(ir.image, "quay.io/fedora/fedora-coreos:stable");
1167        assert_eq!(
1168            ir.signature,
1169            Some(ImageSignature::OstreeRemote("fedora".into()))
1170        );
1171    }
1172
1173    #[test]
1174    fn test_human_readable_booted_pinned_spec() {
1175        // booted image, no staged/rollback
1176        let w = human_status_from_spec_fixture(include_str!("fixtures/spec-booted-pinned.yaml"))
1177            .expect("No spec found");
1178        let expected = indoc::indoc! { r"
1179          ● Booted image: quay.io/centos-bootc/centos-bootc:stream9
1180                  Digest: sha256:47e5ed613a970b6574bfa954ab25bb6e85656552899aa518b5961d9645102b38 (arm64)
1181                 Version: stream9.20240807.0
1182                  Pinned: yes
1183
1184             Other image: quay.io/centos-bootc/centos-bootc:stream9
1185                  Digest: sha256:47e5ed613a970b6574bfa954ab25bb6e85656552899aa518b5961d9645102b37 (arm64)
1186                 Version: stream9.20240807.0
1187                  Pinned: yes
1188        "};
1189        similar_asserts::assert_eq!(w, expected);
1190    }
1191
1192    #[test]
1193    fn test_human_readable_verbose_spec() {
1194        // Test verbose output includes additional fields
1195        let w =
1196            human_status_from_spec_fixture_verbose(include_str!("fixtures/spec-only-booted.yaml"))
1197                .expect("No spec found");
1198
1199        // Verbose output should include StateRoot, Deploy serial, Staged, and Commit
1200        assert!(w.contains("StateRoot:"));
1201        assert!(w.contains("Deploy serial:"));
1202        assert!(w.contains("Staged:"));
1203        assert!(w.contains("Commit:"));
1204        assert!(w.contains("Soft-reboot:"));
1205    }
1206
1207    #[test]
1208    fn test_human_readable_staged_download_only() {
1209        // Test that download-only staged deployment shows the status in non-verbose mode
1210        // Download-only status is only shown in verbose mode per design
1211        let w =
1212            human_status_from_spec_fixture(include_str!("fixtures/spec-staged-download-only.yaml"))
1213                .expect("No spec found");
1214        let expected = indoc::indoc! { r"
1215            Staged image: quay.io/example/someimage:latest
1216                  Digest: sha256:16dc2b6256b4ff0d2ec18d2dbfb06d117904010c8cf9732cdb022818cf7a7566 (arm64)
1217                 Version: nightly (2023-10-14T19:22:15Z)
1218
1219          ● Booted image: quay.io/example/someimage:latest
1220                  Digest: sha256:736b359467c9437c1ac915acaae952aad854e07eb4a16a94999a48af08c83c34 (arm64)
1221                 Version: nightly (2023-09-30T19:22:16Z)
1222        "};
1223        similar_asserts::assert_eq!(w, expected);
1224    }
1225
1226    #[test]
1227    fn test_human_readable_staged_download_only_verbose() {
1228        // Test that download-only status is shown in verbose mode for staged deployments
1229        let w = human_status_from_spec_fixture_verbose(include_str!(
1230            "fixtures/spec-staged-download-only.yaml"
1231        ))
1232        .expect("No spec found");
1233
1234        // Verbose output should include download-only status
1235        assert!(w.contains("Download-only: yes"));
1236    }
1237
1238    #[test]
1239    fn test_human_readable_staged_not_download_only_verbose() {
1240        // Test that staged deployment not in download-only mode shows "Download-only: no" in verbose mode
1241        let w = human_status_from_spec_fixture_verbose(include_str!(
1242            "fixtures/spec-staged-booted.yaml"
1243        ))
1244        .expect("No spec found");
1245
1246        // Verbose output should include download-only status as "no" for normal staged deployments
1247        assert!(w.contains("Download-only: no"));
1248    }
1249
1250    #[test]
1251    fn test_container_inspect_human_readable() {
1252        let inspect = crate::spec::ContainerInspect {
1253            kargs: vec!["console=ttyS0".into(), "quiet".into()],
1254            kernel: Some(crate::kernel::Kernel {
1255                version: "6.12.0-100.fc41.x86_64".into(),
1256                unified: false,
1257            }),
1258        };
1259        let mut w = Vec::new();
1260        container_inspect_print_human(&inspect, &mut w).unwrap();
1261        let output = String::from_utf8(w).unwrap();
1262        let expected = indoc::indoc! { r"
1263            Kernel: 6.12.0-100.fc41.x86_64
1264              Type: vmlinuz
1265             Kargs: console=ttyS0 quiet
1266        "};
1267        similar_asserts::assert_eq!(output, expected);
1268    }
1269
1270    #[test]
1271    fn test_container_inspect_human_readable_uki() {
1272        let inspect = crate::spec::ContainerInspect {
1273            kargs: vec![],
1274            kernel: Some(crate::kernel::Kernel {
1275                version: "6.12.0-100.fc41.x86_64".into(),
1276                unified: true,
1277            }),
1278        };
1279        let mut w = Vec::new();
1280        container_inspect_print_human(&inspect, &mut w).unwrap();
1281        let output = String::from_utf8(w).unwrap();
1282        let expected = indoc::indoc! { r"
1283            Kernel: 6.12.0-100.fc41.x86_64
1284              Type: UKI
1285             Kargs: <none>
1286        "};
1287        similar_asserts::assert_eq!(output, expected);
1288    }
1289
1290    #[test]
1291    fn test_container_inspect_human_readable_no_kernel() {
1292        let inspect = crate::spec::ContainerInspect {
1293            kargs: vec!["console=ttyS0".into()],
1294            kernel: None,
1295        };
1296        let mut w = Vec::new();
1297        container_inspect_print_human(&inspect, &mut w).unwrap();
1298        let output = String::from_utf8(w).unwrap();
1299        let expected = indoc::indoc! { r"
1300            Kernel: <none>
1301             Kargs: console=ttyS0
1302        "};
1303        similar_asserts::assert_eq!(output, expected);
1304    }
1305
1306    #[test]
1307    fn test_human_readable_booted_usroverlay() {
1308        let w =
1309            human_status_from_spec_fixture(include_str!("fixtures/spec-booted-usroverlay.yaml"))
1310                .unwrap();
1311        let expected = indoc::indoc! { r"
1312          ● Booted image: quay.io/example/someimage:latest
1313                  Digest: sha256:736b359467c9437c1ac915acaae952aad854e07eb4a16a94999a48af08c83c34 (arm64)
1314                 Version: nightly (2023-09-30T19:22:16Z)
1315            /usr overlay: transient, read/write
1316        "};
1317        similar_asserts::assert_eq!(w, expected);
1318    }
1319
1320    #[test]
1321    fn test_human_readable_booted_with_cached_update() {
1322        // When a cached update is present (from a previous `bootc upgrade --check`),
1323        // the human-readable output should show the available update info.
1324        let w =
1325            human_status_from_spec_fixture(include_str!("fixtures/spec-booted-with-update.yaml"))
1326                .expect("No spec found");
1327        let expected = indoc::indoc! { r"
1328          ● Booted image: quay.io/centos-bootc/centos-bootc:stream9
1329                  Digest: sha256:47e5ed613a970b6574bfa954ab25bb6e85656552899aa518b5961d9645102b38 (arm64)
1330                 Version: stream9.20240807.0 (2024-08-07T12:00:00Z)
1331           UpdateVersion: stream9.20240901.0 (2024-09-01T12:00:00Z)
1332            UpdateDigest: sha256:a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0
1333        "};
1334        similar_asserts::assert_eq!(w, expected);
1335    }
1336
1337    #[test]
1338    fn test_human_readable_cached_update_same_digest_hidden() {
1339        // When the cached update has the same digest as the current image,
1340        // no update line should be shown.
1341        let w = human_status_from_spec_fixture(include_str!(
1342            "fixtures/spec-booted-update-same-digest.yaml"
1343        ))
1344        .expect("No spec found");
1345        assert!(
1346            !w.contains("UpdateVersion:"),
1347            "Should not show update version when digest matches current"
1348        );
1349        assert!(
1350            !w.contains("UpdateDigest:"),
1351            "Should not show update digest when digest matches current"
1352        );
1353    }
1354
1355    #[test]
1356    fn test_human_readable_cached_update_no_version() {
1357        // When the cached update has no version label, show "Available" as fallback.
1358        let w = human_status_from_spec_fixture(include_str!(
1359            "fixtures/spec-booted-with-update-no-version.yaml"
1360        ))
1361        .expect("No spec found");
1362        let expected = indoc::indoc! { r"
1363          ● Booted image: quay.io/centos-bootc/centos-bootc:stream9
1364                  Digest: sha256:47e5ed613a970b6574bfa954ab25bb6e85656552899aa518b5961d9645102b38 (arm64)
1365                 Version: stream9.20240807.0
1366                  Update: Available
1367            UpdateDigest: sha256:b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1
1368        "};
1369        similar_asserts::assert_eq!(w, expected);
1370    }
1371}