Skip to content

Commit a417a15

Browse files
Rolv-Apnesethcgwalters
authored andcommitted
ostree-ext: preserve directory metadata from OCI layers
When building a derived image from OCI layers, the ostree `UnionFiles` checkout preserves directory metadata (mode, uid, gid) from the first layer that created the directory. This means later layers that only modify metadata (e.g. `RUN chmod 0555 /usr`) are silently lost. OCI semantics and composefs-rs require last-layer-wins, but this should be handled by [3]. For root specifically, copy the mode, uid and gid from /usr (matching the approach by composefs-rs [1]) since OCI images don't reliably include root directory metadata, and container runtimes disagree on how to apply it when present. Unlike composefs-rs, mtime and xattrs are not copied. ostree dirmeta has no mtime field, and the SELinux relabelling pass assigns the root its own label. This should fix systemd-tmpfiles failures on read-only root systems with systemd v261+. See: [2] Assisted-by: llm Signed-off-by: Rolv Apneseth <rolv.apneseth@gmail.com> [1]: https://docs.rs/composefs/0.9.4/composefs/generic_tree/struct.FileSystem.html#method.copy_root_metadata_from_usr [2]: coreos/fedora-coreos-tracker#2238 [3]: #2236
1 parent 22cd72a commit a417a15

5 files changed

Lines changed: 164 additions & 9 deletions

File tree

‎crates/ostree-ext/src/container/store.rs‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,8 @@ use oci_spec::image::{
158158
};
159159
use ocidir::oci_spec::distribution::Reference;
160160
use ostree::prelude::{Cast, FileEnumeratorExt, FileExt, ToVariant};
161-
use ostree::{gio, glib};
161+
use ostree::{DirMetaParsed, gio, glib};
162+
use rustix::fs::{Gid, Mode, OFlags, Uid};
162163
use std::collections::{BTreeMap, BTreeSet, HashMap};
163164
use std::fmt::Write as _;
164165
use std::iter::FromIterator;
@@ -642,6 +643,62 @@ fn cleanup_root(root: &Dir) -> Result<()> {
642643
Ok(())
643644
}
644645

646+
/// Apply directory mode and ownership from an ostree DirMeta to a filesystem
647+
/// directory.
648+
///
649+
/// We intentionally skip xattrs here since the SELinux relabelling pass in
650+
/// `write_dfd_to_mtree` overwrites `security.selinux` on every directory,
651+
/// and no other directory xattrs are meaningful in practice.
652+
fn apply_dirmeta(
653+
dir: impl rustix::fd::AsFd,
654+
metadata: &ostree::DirMetaParsed,
655+
should_fchown: bool,
656+
) -> Result<()> {
657+
if should_fchown {
658+
rustix::fs::fchown(
659+
&dir,
660+
Some(Uid::from_raw(metadata.uid)),
661+
Some(Gid::from_raw(metadata.gid)),
662+
)
663+
.context("fchown")?;
664+
}
665+
let mode = Mode::from_raw_mode(metadata.mode);
666+
rustix::fs::fchmod(&dir, mode).context("fchmod")?;
667+
Ok(())
668+
}
669+
670+
/// Copy the `/usr` directory mode and ownership to the root, like composefs-rs's
671+
/// `copy_root_metadata_from_usr`. OCI images don't reliably include root dir
672+
/// metadata, so layer root metadata (including an explicit `.` entry) is
673+
/// intentionally overridden. Must run before the merged tree is committed, so
674+
/// the root still gets its own SELinux label (root_t).
675+
///
676+
/// More generally, the union checkout only applies the metadata of
677+
/// directories it creates, so a derived layer which only changes a
678+
/// directory's mode or ownership (e.g. `RUN chmod 0555 /usr`) is silently
679+
/// lost. This only covers the root, which is what deployed systems need.
680+
/// Handling that in general is deferred to the composefs-based commit
681+
/// synthesis (<https://github.com/bootc-dev/bootc/pull/2236>).
682+
///
683+
/// See:
684+
/// - <https://github.com/coreos/fedora-coreos-tracker/issues/2238>
685+
/// - <https://github.com/coreos/fedora-coreos-tracker/issues/2238#issuecomment-6082074286>
686+
fn normalize_root_dirmeta(root: &Dir, should_fchown: bool) -> Result<()> {
687+
let usr = root.symlink_metadata("usr").context("looking up /usr")?;
688+
anyhow::ensure!(usr.is_dir(), "image has no /usr directory");
689+
// `root` may be an `O_PATH` fd, on which fchmod/fchown fail with EBADF.
690+
let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC;
691+
let rootfd = rustix::fs::openat(root, ".", flags, Mode::empty()).context("opening root")?;
692+
693+
let metadata = DirMetaParsed {
694+
uid: usr.uid(),
695+
gid: usr.gid(),
696+
mode: usr.mode(),
697+
xattrs: vec![],
698+
};
699+
apply_dirmeta(rootfd, &metadata, should_fchown).context("applying /usr metadata to root")
700+
}
701+
645702
impl ImageImporter {
646703
/// The metadata key used in ostree commit metadata to serialize
647704
const CACHED_KEY_MANIFEST_DIGEST: &'static str = "ostree-ext.cached.manifest-digest";
@@ -1431,6 +1488,12 @@ impl ImageImporter {
14311488

14321489
cleanup_root(&root_dir)?;
14331490

1491+
// Apply the layer uid/gid only for bare checkouts, where the
1492+
// checked-out files carry real ownership.
1493+
let should_fchown = checkout_mode == ostree::RepoCheckoutMode::None;
1494+
normalize_root_dirmeta(&root_dir, should_fchown)
1495+
.context("normalizing root dir metadata")?;
1496+
14341497
let mt = ostree::MutableTree::new();
14351498
repo.write_dfd_to_mtree(
14361499
(*td).as_raw_fd(),

‎crates/ostree-ext/src/fixture.rs‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1013,6 +1013,33 @@ impl NonOstreeFixture {
10131013

10141014
let bw = self.src_oci.create_gzip_layer(None)?;
10151015
let mut bw = tar::Builder::new(bw);
1016+
// Emit explicit entries for every directory, like a real layer tar
1017+
// does. The tar import re-stamps the ancestors of any directory it
1018+
// has to synthesize to the default 0755, so the 0555 on /usr below
1019+
// would be lost when the files under it are imported.
1020+
let mut dirs = std::collections::BTreeSet::new();
1021+
for def in FileDef::iter_from(CONTENTS_V0) {
1022+
let def = def.unwrap();
1023+
let mut p: &Utf8Path = &def.path;
1024+
while let Some(parent) = p.parent() {
1025+
if !parent.as_str().is_empty() {
1026+
dirs.insert(parent.to_owned());
1027+
}
1028+
p = parent;
1029+
}
1030+
}
1031+
for d in &dirs {
1032+
let mode = if d.as_str() == "usr" { 0o555 } else { 0o755 };
1033+
FileDef {
1034+
uid: 0,
1035+
gid: 0,
1036+
mode,
1037+
path: Cow::Owned(d.clone()),
1038+
xattrs: Default::default(),
1039+
ty: FileDefType::Directory,
1040+
}
1041+
.append_tar(&mut bw)?;
1042+
}
10161043
for def in FileDef::iter_from(CONTENTS_V0) {
10171044
let def = def.unwrap();
10181045
def.append_tar(&mut bw)?;

‎crates/ostree-ext/tests/it/main.rs‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,40 @@ fn assert_err_contains<T>(r: Result<T>, s: impl AsRef<str>) {
6060
}
6161
}
6262

63+
/// Verify that a commit's root directory mode/uid/gid matches `/usr`.
64+
///
65+
/// Returns the mode if successful.
66+
fn assert_root_dirmeta_matches_usr(repo: &ostree::Repo, commit: &str) -> u32 {
67+
let root = repo.read_commit(commit, gio::Cancellable::NONE).unwrap().0;
68+
let root = root.downcast::<ostree::RepoFile>().unwrap();
69+
root.ensure_resolved().unwrap();
70+
71+
let usr = root.resolve_relative_path("usr");
72+
let usr = usr.downcast::<ostree::RepoFile>().unwrap();
73+
usr.ensure_resolved().unwrap();
74+
75+
let query = |f: &ostree::RepoFile| {
76+
let info = f
77+
.query_info(
78+
"unix::mode,unix::uid,unix::gid",
79+
gio::FileQueryInfoFlags::NOFOLLOW_SYMLINKS,
80+
gio::Cancellable::NONE,
81+
)
82+
.unwrap();
83+
(
84+
info.attribute_uint32("unix::mode"),
85+
info.attribute_uint32("unix::uid"),
86+
info.attribute_uint32("unix::gid"),
87+
)
88+
};
89+
90+
let root_meta = query(&root);
91+
let usr_meta = query(&usr);
92+
assert_eq!(root_meta, usr_meta, "root dirmeta should match /usr");
93+
94+
root_meta.0 & 0o7777
95+
}
96+
6397
static TEST_REGISTRY: LazyLock<String> =
6498
LazyLock::new(|| match std::env::var_os("TEST_REGISTRY") {
6599
Some(t) => t.to_str().unwrap().to_owned(),
@@ -709,6 +743,7 @@ async fn test_export_as_container_nonderived() -> Result<()> {
709743
let reimported = fixture.must_import(&dest).await?;
710744
let reimport_ls = fixture::ostree_ls(fixture.destrepo(), &reimported.merge_commit).unwrap();
711745
similar_asserts::assert_eq!(initimport_ls, reimport_ls);
746+
assert_root_dirmeta_matches_usr(fixture.destrepo(), &reimported.merge_commit);
712747
Ok(())
713748
}
714749

@@ -1653,6 +1688,13 @@ async fn test_non_ostree() -> Result<()> {
16531688
similar_asserts::assert_eq!(&src_manifest, &dest_manifest);
16541689
}
16551690
assert_eq!(imp.manifest_digest, src_digest);
1691+
1692+
let root_mode = assert_root_dirmeta_matches_usr(fixture.destrepo(), &imp.merge_commit);
1693+
assert_eq!(
1694+
root_mode, 0o555,
1695+
"root mode ({root_mode:#o}) matches /usr but is not 0o555"
1696+
);
1697+
16561698
Ok(())
16571699
}
16581700

‎tmt/tests/booted/readonly/040-test-baseconfigs.nu‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,6 @@ for config in $configs {
2121
let fstype = $mnt.filesystems.0.fstype
2222
assert equal $fstype "overlay" "/etc should be mounted as overlay when etc-transient is active"
2323

24-
print "# Checking / has 755 permissions (overlay upper dir must not block traversal)"
25-
let perms = (stat -c "%a" / | str trim)
26-
assert equal $perms "755" "/ should have 755 permissions"
27-
2824
print "# Checking /etc is writable (transient overlay)"
2925
let result = (do { ^touch /etc/bootc-baseconfig-test } | complete)
3026
assert equal $result.exit_code 0 "/etc should be writable with etc-transient"
@@ -36,10 +32,6 @@ for config in $configs {
3632
let fstype = $mnt.filesystems.0.fstype
3733
assert equal $fstype "overlay" "/ should be mounted as overlay when root-transient is active"
3834

39-
print "# Checking / has 755 permissions"
40-
let perms = (stat -c "%a" / | str trim)
41-
assert equal $perms "755" "/ should have 755 permissions"
42-
4335
print "# Checking / is writable (transient overlay)"
4436
let result = (do { ^touch /bootc-baseconfig-root-test } | complete)
4537
assert equal $result.exit_code 0 "/ should be writable with root-transient"
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Verify that the root dir's uid, gid, and permissions match /usr.
2+
#
3+
# See: https://github.com/coreos/fedora-coreos-tracker/issues/2238
4+
use std assert
5+
use tap.nu
6+
7+
tap begin "verify root dir metadata matches /usr"
8+
9+
let root_meta = (stat -c "mode: %a, gid: %g, uid: %u" / | str trim)
10+
let usr_meta = (stat -c "mode: %a, gid: %g, uid: %u" /usr | str trim)
11+
12+
print $"# root: ($root_meta)"
13+
print $"# /usr: ($usr_meta)"
14+
15+
# When this system was upgraded from a published base image (test-upgrade flow),
16+
# the import ran with the older bootc from that image, which predates
17+
# normalize_root_dirmeta. The root keeps the 0755 of the importer's checkout
18+
# temp dir, while /usr keeps the 0555 from the image layers. The two only
19+
# match on systems imported by a bootc that has the fix, so check /usr alone
20+
# here.
21+
# TODO: once published base images ship the metadata fix, compare
22+
# /var/bootc-pre-upgrade-version against the fixed version instead (like 031 does).
23+
if not ("/var/bootc-pre-upgrade-version" | path exists) {
24+
assert equal $root_meta $usr_meta $"root dir metadata \(($root_meta)\) should match /usr \(($usr_meta)\)"
25+
assert equal $root_meta "mode: 555, gid: 0, uid: 0" $"root dir metadata \(($root_meta)\) should match expected \(mode: 555, gid: 0, uid: 0\)"
26+
} else {
27+
print "# skipping root == /usr check: imported by pre-fix bootc during upgrade"
28+
assert equal $usr_meta "mode: 555, gid: 0, uid: 0" $"/usr metadata \(($usr_meta)\) should match expected \(mode: 555, gid: 0, uid: 0\)"
29+
}
30+
31+
tap ok

0 commit comments

Comments
 (0)