Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion crates/lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ version = "1.16.10"
# In general we try to keep this pinned to what's in the latest RHEL9.
rust-version = "1.85.0"

include = ["/src", "LICENSE-APACHE", "LICENSE-MIT"]
include = ["/src", "/build.rs", "LICENSE-APACHE", "LICENSE-MIT"]

[dependencies]
# Internal crates
Expand Down Expand Up @@ -92,5 +92,8 @@ rhsm = []
# Implementation detail of man page generation.
docgen = ["clap_mangen"]

[build-dependencies]
cargo_metadata = "0.19"

[lints]
workspace = true
18 changes: 18 additions & 0 deletions crates/lib/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
fn main() {
let metadata = cargo_metadata::MetadataCommand::new()
.current_dir(env!("CARGO_MANIFEST_DIR"))
.no_deps()
.exec()
.expect("running cargo metadata");
let workspace_manifest = metadata.workspace_root.join("Cargo.toml");
println!("cargo::rerun-if-changed={workspace_manifest}");

let bins = metadata.workspace_metadata["binary-dependencies"]["bins"]
.as_array()
.expect("workspace.metadata.binary-dependencies.bins must be an array");
let bins: Vec<&str> = bins
.iter()
.map(|bin| bin.as_str().expect("binary dependency must be a string"))
.collect();
println!("cargo::rustc-env=BOOTC_BINARY_DEPS={}", bins.join(","));
}
91 changes: 91 additions & 0 deletions crates/lib/src/lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -895,6 +895,55 @@ fn prune_known_run_paths(paths: &mut BTreeSet<Utf8PathBuf>) {
}
}

/// List sourced from [workspace.metadata.binary-dependencies] in the workspace
/// Cargo.toml via build.rs.
const BINARY_DEPS: &str = env!("BOOTC_BINARY_DEPS");

/// Return the resolved set of required runtime binaries.
///
/// Entries that match the default podman/skopeo names are replaced with the
/// values from `bootc_utils::{podman,skopeo}_bin()` so that
/// `BOOTC_EXP_EXTERNAL_CONTAINER_TOOL` overrides are honoured.
fn resolve_runtime_bins<'a>(podman: &'a str, skopeo: &'a str) -> Vec<&'a str> {
let mut bins: Vec<&str> = BINARY_DEPS
.split(',')
.map(|b| match b {
"podman" => podman,
"skopeo" => skopeo,
other => other,
})
.collect();
bins.sort_unstable();
bins.dedup();
bins
}

fn resolved_runtime_bins() -> Vec<&'static str> {
resolve_runtime_bins(bootc_utils::podman_bin(), bootc_utils::skopeo_bin())
}

#[distributed_slice(LINTS)]
static LINT_RUNTIME_DEPS: Lint = Lint::new_warning(
"runtime-deps",
"Check that required runtime dependencies are present in the image.",
check_runtime_deps,
);
fn check_runtime_deps(root: &Dir, _config: &LintExecutionConfig) -> LintResult {
let mut missing = Vec::new();
for bin in resolved_runtime_bins() {
if !crate::utils::have_executable_in_root(root, bin)? {
missing.push(bin);
}
}
if missing.is_empty() {
return lint_ok();
}
lint_err(format!(
"Missing required runtime dependencies: {}",
missing.join(", ")
))
}

#[cfg(test)]
mod tests {
use std::sync::LazyLock;
Expand Down Expand Up @@ -933,9 +982,19 @@ mod tests {
root.create_dir_all(Utf8Path::new(PREPAREROOT_PATH).parent().unwrap())?;
root.atomic_write(PREPAREROOT_PATH, PREPAREROOT)?;

for bin in resolved_runtime_bins() {
add_runtime_bin(&root, bin)?;
}

Ok(root)
}

fn add_runtime_bin(root: &Dir, bin: &str) -> Result<()> {
root.create_dir_all("usr/bin")?;
root.write(format!("usr/bin/{bin}"), "")?;
Ok(())
}

#[test]
fn test_var_run() -> Result<()> {
let root = &fixture()?;
Expand Down Expand Up @@ -1460,4 +1519,36 @@ mod tests {

Ok(())
}

#[test]
fn test_runtime_deps() -> Result<()> {
let root = &fixture()?;
let config = &LintExecutionConfig::default();

let bins = resolved_runtime_bins();
let err = check_runtime_deps(root, config)?.unwrap_err();
assert_eq!(
err.to_string(),
format!("Missing required runtime dependencies: {}", bins.join(", "))
);

for bin in &bins {
add_runtime_bin(root, bin)?;
}
check_runtime_deps(root, config)??;

let podman = bootc_utils::podman_bin();
root.remove_file(format!("usr/bin/{podman}"))?;
let err = check_runtime_deps(root, config)?.unwrap_err();
assert_eq!(
err.to_string(),
format!("Missing required runtime dependencies: {podman}")
);

assert_eq!(
resolve_runtime_bins("dtool", "dtool"),
["chcon", "dtool", "ostree", "setpriv", "systemctl", "zstd"]
);
Ok(())
}
}
42 changes: 38 additions & 4 deletions crates/lib/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,32 @@ pub(crate) fn find_mount_option<'a>(
}

pub fn have_executable(name: &str) -> Result<bool> {
for elt in executable_candidates(name) {
if elt.try_exists()? {
return Ok(true);
}
}
Ok(false)
}

fn executable_candidates(name: &str) -> Vec<PathBuf> {
let Some(path) = std::env::var_os("PATH") else {
return Ok(false);
return Vec::new();
};
for mut elt in std::env::split_paths(&path) {
elt.push(name);
if elt.try_exists()? {
std::env::split_paths(&path)
.map(|mut path| {
path.push(name);
path
})
.collect()
}

/// Like [`have_executable`], but checks inside a filesystem root (e.g. a
/// container image) rather than the host's `$PATH`.
pub fn have_executable_in_root(root: &Dir, name: &str) -> Result<bool> {
for candidate in executable_candidates(name) {
let candidate = candidate.strip_prefix("/").unwrap_or(&candidate);
if root.try_exists(candidate)? {
return Ok(true);
}
}
Expand Down Expand Up @@ -336,4 +356,18 @@ mod tests {
assert!(have_executable("true").unwrap());
assert!(!have_executable("someexethatdoesnotexist").unwrap());
}

#[test]
fn test_have_executable_in_root() -> anyhow::Result<()> {
use cap_std_ext::cap_std;

let root = cap_std_ext::cap_tempfile::tempdir(cap_std::ambient_authority())?;
assert!(!have_executable_in_root(&root, "podman")?);

root.create_dir_all("usr/bin")?;
root.write("usr/bin/podman", "")?;
assert!(have_executable_in_root(&root, "podman")?);
assert!(!have_executable_in_root(&root, "missing")?);
Ok(())
}
}