Skip to content

Commit 41049cc

Browse files
committed
generator: Order tmpfiles before random seed and TPM setup
There's a very complex dependency chain between `systemd-tmpfiles-setup.service`, `systemd-random-seed.service` and `systemd-tpm2-setup.service` among others. Basically we need `/var/lib` to be created, which will be done by the tmpfiles setup, but random-seed will normally do it too, but it can't because Fedora SELinux denies it. A surprising discovery is that this happens to be papered over for the OSTree backend by `ostree-remount.service`. Add a test case that no services fail. However this check needs to currently skip due to https://bugzilla.redhat.com/show_bug.cgi?id=2507393. Assisted-by: AI Signed-off-by: Colin Walters <walters@verbum.org>
1 parent de18ba7 commit 41049cc

2 files changed

Lines changed: 159 additions & 44 deletions

File tree

‎crates/lib/src/generator.rs‎

Lines changed: 116 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -90,48 +90,58 @@ pub(crate) fn unit_enablement_impl(sysroot: &Dir, unit_dir: &Dir) -> Result<()>
9090

9191
/// Main entrypoint for the generator
9292
pub(crate) fn generator(root: &Dir, unit_dir: &Dir) -> Result<()> {
93-
// === Relabel unit: runs for ALL composefs boots (native or ostree) ===
93+
// Detect composefs and ostree once, reuse across all blocks below.
94+
//
95+
// composefs always uses overlayfs, so check the filesystem magic first as
96+
// a cheap gate. Then inspect the mount source to distinguish regular
97+
// composefs ("composefs:<digest>") from transient ("transient:composefs=<digest>").
98+
let is_overlayfs = rustix::fs::fstatfs(root.as_fd())?.f_type == libc::OVERLAYFS_SUPER_MAGIC;
99+
let root_source = if is_overlayfs {
100+
match bootc_mount::inspect_filesystem(camino::Utf8Path::new("/")) {
101+
Ok(fs) => Some(fs.source),
102+
Err(e) => {
103+
tracing::debug!("Could not inspect root filesystem: {e:#}");
104+
None
105+
}
106+
}
107+
} else {
108+
None
109+
};
110+
let root_is_transient = root_source
111+
.as_deref()
112+
.is_some_and(|s| s.starts_with("transient:composefs="));
113+
let is_composefs = root_is_transient
114+
|| root_source
115+
.as_deref()
116+
.is_some_and(|s| s.starts_with("composefs:"));
117+
let is_ostree = root.try_exists(OSTREE_BOOTED)?;
118+
119+
// === Relabel unit: runs for transient composefs boots (native or ostree) ===
94120
// Must be before the ostree-booted guard because native composefs boots do
95121
// not write /run/ostree-booted, but still need the relabel unit when any
96122
// transient overlay is active.
97123
//
98-
// Gate on the root being overlayfs (composefs always mounts an overlay, so
99-
// this excludes non-composefs systems without needing the ostree-booted marker).
100-
//
101124
// Two triggering conditions, detected independently:
102125
//
103126
// 1. Transient root: the initramfs sets the overlay source to
104-
// "transient:composefs=<digest>" in /proc/self/mountinfo. Detect via
105-
// inspect_filesystem() rather than fstatvfs() because the `ro` kernel
106-
// cmdline flag can make an otherwise-writable overlay appear read-only
107-
// at generator time.
127+
// "transient:composefs=<digest>" in /proc/self/mountinfo. Detected
128+
// via root_is_transient above.
108129
//
109130
// 2. Transient /etc: this is mounted by bootc-root-setup.service
110131
// which runs *after* the generator, so fstatvfs would see the read-only
111132
// composefs at generator time. Read setup-root-conf.toml directly from
112133
// the booted image instead.
113-
{
114-
let st = rustix::fs::fstatfs(root.as_fd())?;
115-
if st.f_type == libc::OVERLAYFS_SUPER_MAGIC {
116-
let root_is_transient =
117-
match bootc_mount::inspect_filesystem(camino::Utf8Path::new("/")) {
118-
Ok(fs) => fs.source.starts_with("transient:composefs="),
119-
Err(e) => {
120-
tracing::debug!("Could not inspect root filesystem: {e:#}");
121-
false
122-
}
123-
};
124-
let submounts_are_transient = bootc_initramfs_setup::config_has_transient_submounts(
125-
std::path::Path::new(bootc_initramfs_setup::SETUP_ROOT_CONF_PATH),
134+
if is_composefs {
135+
let submounts_are_transient = bootc_initramfs_setup::config_has_transient_submounts(
136+
std::path::Path::new(bootc_initramfs_setup::SETUP_ROOT_CONF_PATH),
137+
);
138+
if root_is_transient || submounts_are_transient {
139+
tracing::debug!(
140+
root_is_transient,
141+
submounts_are_transient,
142+
"Transient overlay detected; generating relabel unit"
126143
);
127-
if root_is_transient || submounts_are_transient {
128-
tracing::debug!(
129-
root_is_transient,
130-
submounts_are_transient,
131-
"Transient overlay detected; generating relabel unit"
132-
);
133-
generate_transient_overlay_relabel(unit_dir)?;
134-
}
144+
generate_transient_overlay_relabel(unit_dir)?;
135145
}
136146
}
137147

@@ -140,21 +150,28 @@ pub(crate) fn generator(root: &Dir, unit_dir: &Dir) -> Result<()> {
140150
// not write /run/ostree-booted, but still need the shadow sync to clean up
141151
// stale shadow/gshadow entries (the rechunk scenario). Gate on either a
142152
// composefs mount source (native composefs boot) or the ostree-booted marker.
143-
{
144-
let is_composefs = match bootc_mount::inspect_filesystem(camino::Utf8Path::new("/")) {
145-
Ok(fs) => {
146-
fs.source.starts_with("composefs:") || fs.source.starts_with("transient:composefs=")
147-
}
148-
Err(e) => {
149-
tracing::debug!("Could not inspect root filesystem: {e:#}");
150-
false
151-
}
152-
};
153-
let is_ostree = root.try_exists(OSTREE_BOOTED)?;
154-
if is_composefs || is_ostree {
155-
let updated = shadow_sync_generator_impl(root, unit_dir)?;
156-
tracing::trace!("Enabled shadow sync: {updated}");
157-
}
153+
if is_composefs || is_ostree {
154+
let updated = shadow_sync_generator_impl(root, unit_dir)?;
155+
tracing::trace!("Enabled shadow sync: {updated}");
156+
}
157+
158+
// === tmpfiles ordering fix: native composefs boots only ===
159+
// On ostree boots, ostree-remount.service provides
160+
// Before=systemd-tmpfiles-setup.service
161+
// Before=systemd-random-seed.service
162+
// which (together with the generated var.mount unit) ensures tmpfiles
163+
// creates /var/lib/systemd before any service tries to use it.
164+
//
165+
// On native composefs boots neither ostree-remount nor a var.mount unit
166+
// exist, so systemd-tmpfiles-setup and systemd-random-seed race. If
167+
// the container image ships a sparse /var (common after the var-tmpfiles
168+
// lint), /var/lib/systemd may not exist yet when random-seed starts,
169+
// causing an SELinux denial or ENOENT.
170+
//
171+
// Fix: generate a drop-in that orders tmpfiles-setup before the services
172+
// that need its output.
173+
if is_composefs && !is_ostree {
174+
generate_tmpfiles_ordering(unit_dir)?;
158175
}
159176

160177
// === Ostree-specific generator logic ===
@@ -236,6 +253,33 @@ ExecStart=bootc internals fixup-etc-fstab\n\
236253
Ok(())
237254
}
238255

256+
/// On native composefs boots (no ostree-remount), ensure
257+
/// systemd-tmpfiles-setup runs before services that need /var/lib/systemd.
258+
///
259+
/// Without this, systemd-tmpfiles-setup and systemd-random-seed race: both
260+
/// are wanted by sysinit.target with no ordering between them. If the
261+
/// container image has a sparse /var (e.g. after `rm -rf /var/lib` for the
262+
/// var-tmpfiles lint), /var/lib/systemd won't exist when random-seed starts.
263+
/// A .mount unit (e.g. var-lib-nfs-rpc_pipefs.mount) may even create
264+
/// /var/lib with an unlabeled_t SELinux context before policy loads, causing
265+
/// an AVC denial when random-seed tries to mkdir /var/lib/systemd.
266+
///
267+
/// On ostree boots, ostree-remount.service already provides this ordering.
268+
fn generate_tmpfiles_ordering(unit_dir: &Dir) -> Result<()> {
269+
let dropin_dir = "systemd-tmpfiles-setup.service.d";
270+
unit_dir.create_dir_all(dropin_dir)?;
271+
unit_dir.atomic_write(
272+
&format!("{dropin_dir}/bootc-ordering.conf"),
273+
"# Generated by bootc generator for native composefs boots.\n\
274+
# Ensure /var/lib/systemd and other tmpfiles-managed directories\n\
275+
# exist before services that depend on them.\n\
276+
[Unit]\n\
277+
Before=systemd-random-seed.service systemd-tpm2-setup.service\n",
278+
)?;
279+
tracing::debug!("Generated tmpfiles-setup ordering drop-in for composefs boot");
280+
Ok(())
281+
}
282+
239283
/// Generate a oneshot service that relabels the transient overlay inode
240284
/// after SELinux policy loads, fixing the tmpfs_t label SELinux assigns to
241285
/// overlay upper-dir inodes at policy-load time.
@@ -466,6 +510,34 @@ UUID=341c4712-54e8-4839-8020-d94073b1dc8b /boot xfs defaul
466510
Ok(())
467511
}
468512

513+
#[test]
514+
fn test_tmpfiles_ordering_dropin() -> Result<()> {
515+
let tempdir = fixture()?;
516+
let unit_dir = &tempdir.open_dir("run/systemd/system")?;
517+
518+
generate_tmpfiles_ordering(unit_dir)?;
519+
520+
let dropin_dir = unit_dir.open_dir("systemd-tmpfiles-setup.service.d")?;
521+
let content = dropin_dir.read_to_string("bootc-ordering.conf")?;
522+
assert!(
523+
content.contains("\n[Unit]\n"),
524+
"drop-in [Unit] header must be left-aligned: {content}"
525+
);
526+
assert!(
527+
content.contains("\nBefore=systemd-random-seed.service"),
528+
"drop-in must order tmpfiles before random-seed: {content}"
529+
);
530+
assert!(
531+
content.contains("systemd-tpm2-setup.service"),
532+
"drop-in must order tmpfiles before tpm2-setup: {content}"
533+
);
534+
535+
// Calling again must succeed (idempotent)
536+
generate_tmpfiles_ordering(unit_dir)?;
537+
538+
Ok(())
539+
}
540+
469541
#[test]
470542
fn test_shadow_sync_no_shadow() -> Result<()> {
471543
// No /etc/shadow => should not enable (boot detection is caller's job)
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Verify no systemd or bootc units are in a failed state.
2+
#
3+
# This catches first-boot ordering issues such as the race between
4+
# systemd-tmpfiles-setup and systemd-random-seed/systemd-tpm2-setup
5+
# when /var/lib/systemd does not yet exist (the bootc generator
6+
# emits a drop-in to prevent this).
7+
use std assert
8+
use tap.nu
9+
10+
tap begin "verify no failed systemd/bootc units"
11+
12+
let selinux_enabled = ("/sys/fs/selinux/enforce" | path exists)
13+
14+
let failed_candidates = (systemctl list-units --failed --no-legend --plain
15+
| lines
16+
| filter { |l| $l != "" }
17+
| filter { |l|
18+
let unit = ($l | split row " " | first)
19+
(($unit | str starts-with "systemd-") or ($unit | str starts-with "bootc-"))
20+
})
21+
22+
let failed = if $selinux_enabled {
23+
# https://bugzilla.redhat.com/show_bug.cgi?id=2507393
24+
$failed_candidates | filter { |l|
25+
let unit = ($l | split row " " | first)
26+
if $unit == "systemd-tpm2-setup.service" {
27+
print "# SELinux workaround: ignoring systemd-tpm2-setup.service failure (SELinux denies writing the NvPCR credential to dosfs_t)"
28+
false
29+
} else {
30+
true
31+
}
32+
}
33+
} else {
34+
$failed_candidates
35+
}
36+
37+
if ($failed | length) > 0 {
38+
print $"Failed units:\n($failed | str join "\n")"
39+
assert equal ($failed | length) 0 "Expected zero failed systemd-*/bootc-* units"
40+
}
41+
42+
print "No failed systemd-*/bootc-* units"
43+
tap ok

0 commit comments

Comments
 (0)