use std::collections::{BTreeSet, HashMap};
use std::fs::{self, File};
use std::io::Read;
use std::os::unix::fs::MetadataExt as _;
use std::path::{Component, Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
pub const MANIFEST_FILE: &str = "bundle-manifest.json";
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum VerificationStatus {
Verified,
LegacyUnverified,
Invalid,
}
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
pub struct ManifestArtifact {
pub role: String,
pub path: String,
pub size_bytes: u64,
pub sha256: String,
}
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
pub struct ManifestGuest {
pub os: String,
pub architecture: String,
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, JsonSchema)]
pub struct ManifestConfig {
pub cpu_count: i64,
pub memory_mb: i64,
pub guest_agent_port: u32,
pub guest_connect_timeout_ms: i64,
pub kernel_command_line: String,
pub resources: ImmutableResources,
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, JsonSchema)]
pub struct ImmutableResources {
pub kernel: String,
pub initrd: Option<String>,
pub disk: String,
}
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
pub struct BuildProvenance {
pub source_revision: Option<String>,
pub source_dirty: bool,
pub build_script_sha256: String,
pub docker_platform: String,
pub base_image: String,
pub base_image_digest: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rr_software_counters_revision: Option<String>,
}
#[derive(Clone, Debug, Serialize, JsonSchema)]
pub struct VerificationReport {
pub schema_version: u32,
pub status: VerificationStatus,
pub bundle_path: String,
pub image_digest: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub guest: Option<ManifestGuest>,
#[serde(skip_serializing_if = "Option::is_none")]
pub config: Option<ManifestConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub build: Option<BuildProvenance>,
pub artifacts: Vec<ManifestArtifact>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
#[derive(Debug, Deserialize)]
struct BundleManifest {
schema_version: u32,
guest: ManifestGuest,
config: ManifestConfig,
build: BuildProvenance,
artifacts: Vec<ManifestArtifact>,
}
#[derive(Debug, Deserialize)]
struct BundleConfig {
#[serde(rename = "cpuCount")]
cpu_count: i64,
#[serde(rename = "memoryMB")]
memory_mb: i64,
#[serde(rename = "guestAgentPort")]
guest_agent_port: u32,
#[serde(rename = "guestConnectTimeoutMS")]
guest_connect_timeout_ms: i64,
#[serde(rename = "imageDigest")]
image_digest: Option<String>,
#[serde(rename = "kernelCommandLine")]
kernel_command_line: String,
resources: BundleResources,
}
#[derive(Debug, Deserialize)]
struct BundleResources {
kernel: String,
initrd: Option<String>,
disk: Option<String>,
}
impl BundleConfig {
fn immutable(&self) -> Result<ManifestConfig, String> {
Ok(ManifestConfig {
cpu_count: self.cpu_count,
memory_mb: self.memory_mb,
guest_agent_port: self.guest_agent_port,
guest_connect_timeout_ms: self.guest_connect_timeout_ms,
kernel_command_line: self.kernel_command_line.clone(),
resources: ImmutableResources {
kernel: self.resources.kernel.clone(),
initrd: self.resources.initrd.clone(),
disk: self
.resources
.disk
.clone()
.ok_or_else(|| "config resources.disk is required".to_string())?,
},
})
}
}
pub fn verify_reference(raw: &str) -> Result<VerificationReport, String> {
let (bundle_path, expected_digest) = resolve_reference(raw)?;
Ok(verify_bundle(&bundle_path, expected_digest.as_deref()))
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct ImmutableFileStamp {
path: String,
device: u64,
inode: u64,
size: u64,
modified_seconds: i64,
modified_nanoseconds: i64,
changed_seconds: i64,
changed_nanoseconds: i64,
regular: bool,
symlink: bool,
}
#[derive(Clone)]
struct CachedVerification {
expected_digest: Option<String>,
stamps: Vec<ImmutableFileStamp>,
report: VerificationReport,
}
static VERIFICATION_CACHE: OnceLock<Mutex<HashMap<PathBuf, CachedVerification>>> = OnceLock::new();
pub fn verify_reference_cached(raw: &str) -> Result<VerificationReport, String> {
let (bundle_path, expected_digest) = resolve_reference(raw)?;
let cached = verification_cache()
.lock()
.map_err(|_| "Image verification cache is poisoned".to_string())?
.get(&bundle_path)
.cloned();
if let Some(cached) = cached
&& cached.expected_digest == expected_digest
&& immutable_file_stamps(&bundle_path, &cached.report.artifacts)
.ok()
.as_ref()
== Some(&cached.stamps)
{
return Ok(cached.report);
}
let report = verify_bundle(&bundle_path, expected_digest.as_deref());
let mut cache = verification_cache()
.lock()
.map_err(|_| "Image verification cache is poisoned".to_string())?;
if report.status == VerificationStatus::Verified {
let stamps = immutable_file_stamps(&bundle_path, &report.artifacts)?;
cache.insert(
bundle_path,
CachedVerification {
expected_digest,
stamps,
report: report.clone(),
},
);
} else {
cache.remove(&bundle_path);
}
Ok(report)
}
fn verification_cache() -> &'static Mutex<HashMap<PathBuf, CachedVerification>> {
VERIFICATION_CACHE.get_or_init(|| Mutex::new(HashMap::new()))
}
fn immutable_file_stamps(
bundle_path: &Path,
artifacts: &[ManifestArtifact],
) -> Result<Vec<ImmutableFileStamp>, String> {
std::iter::once("config.json")
.chain(std::iter::once(MANIFEST_FILE))
.chain(artifacts.iter().map(|artifact| artifact.path.as_str()))
.map(|relative| {
let metadata = fs::symlink_metadata(bundle_path.join(relative)).map_err(|error| {
format!("Cannot inspect immutable image file {relative}: {error}")
})?;
Ok(ImmutableFileStamp {
path: relative.to_string(),
device: metadata.dev(),
inode: metadata.ino(),
size: metadata.size(),
modified_seconds: metadata.mtime(),
modified_nanoseconds: metadata.mtime_nsec(),
changed_seconds: metadata.ctime(),
changed_nanoseconds: metadata.ctime_nsec(),
regular: metadata.file_type().is_file(),
symlink: metadata.file_type().is_symlink(),
})
})
.collect()
}
pub(crate) struct ImportedImage {
pub source_bundle: String,
pub target_bundle: String,
pub image_digest: String,
pub files: u64,
pub bytes: u64,
pub already_present: bool,
}
pub(crate) fn import_verified_bundle(
source: &Path,
image_store: &Path,
) -> Result<ImportedImage, String> {
let source = fs::canonicalize(source).map_err(|error| {
format!(
"Image bundle does not exist at {}: {error}",
source.display()
)
})?;
let report = verify_bundle(&source, None);
if report.status != VerificationStatus::Verified {
return Err(report
.error
.unwrap_or_else(|| "Image bundle is not verified".to_string()));
}
let image_digest = report
.image_digest
.clone()
.ok_or_else(|| "Verified image has no digest".to_string())?;
let digest = image_digest
.strip_prefix("sha256:")
.ok_or_else(|| "Verified image digest is not canonical".to_string())?;
let store = image_store.join("sha256");
let target = store.join(digest);
let files = u64::try_from(report.artifacts.len() + 2)
.map_err(|_| "Image file count is outside u64".to_string())?;
let bytes = immutable_bundle_bytes(&source, &report.artifacts)?;
if target.exists() {
let existing = verify_bundle(&target, Some(&image_digest));
if existing.status != VerificationStatus::Verified {
return Err(format!(
"Digest-addressed image target is already present but invalid: {}",
target.display()
));
}
return Ok(ImportedImage {
source_bundle: source.to_string_lossy().into_owned(),
target_bundle: target.to_string_lossy().into_owned(),
image_digest,
files,
bytes,
already_present: true,
});
}
fs::create_dir_all(&store)
.map_err(|error| format!("Cannot create image store {}: {error}", store.display()))?;
let staging = store.join(format!(".import-{}", uuid::Uuid::now_v7()));
let copied = (|| {
fs::create_dir(&staging)
.map_err(|error| format!("Cannot create image import staging directory: {error}"))?;
for relative in std::iter::once("config.json")
.chain(std::iter::once(MANIFEST_FILE))
.chain(
report
.artifacts
.iter()
.map(|artifact| artifact.path.as_str()),
)
{
copy_immutable_file(&source, &staging, relative)?;
}
let staged = verify_bundle(&staging, None);
if staged.status != VerificationStatus::Verified
|| staged.image_digest.as_deref() != Some(image_digest.as_str())
{
return Err(staged.error.unwrap_or_else(|| {
"Imported image staging bundle does not match the verified source".to_string()
}));
}
fs::rename(&staging, &target)
.map_err(|error| format!("Cannot publish imported image atomically: {error}"))?;
Ok(())
})();
if copied.is_err() {
let _ = fs::remove_dir_all(&staging);
}
copied?;
Ok(ImportedImage {
source_bundle: source.to_string_lossy().into_owned(),
target_bundle: target.to_string_lossy().into_owned(),
image_digest,
files,
bytes,
already_present: false,
})
}
fn immutable_bundle_bytes(source: &Path, artifacts: &[ManifestArtifact]) -> Result<u64, String> {
std::iter::once("config.json")
.chain(std::iter::once(MANIFEST_FILE))
.chain(artifacts.iter().map(|artifact| artifact.path.as_str()))
.try_fold(0_u64, |total, relative| {
let metadata = fs::symlink_metadata(source.join(relative)).map_err(|error| {
format!("Cannot inspect immutable image file {relative}: {error}")
})?;
if !metadata.file_type().is_file() || metadata.file_type().is_symlink() {
return Err(format!(
"Immutable image file is not a regular file: {relative}"
));
}
total
.checked_add(metadata.len())
.ok_or_else(|| "Immutable image byte count overflowed".to_string())
})
}
fn copy_immutable_file(source: &Path, target: &Path, relative: &str) -> Result<(), String> {
let source_file = source.join(relative);
let metadata = fs::symlink_metadata(&source_file)
.map_err(|error| format!("Cannot inspect immutable image file {relative}: {error}"))?;
if !metadata.file_type().is_file() || metadata.file_type().is_symlink() {
return Err(format!(
"Immutable image file is not a regular file: {relative}"
));
}
let target_file = target.join(relative);
if let Some(parent) = target_file.parent() {
fs::create_dir_all(parent)
.map_err(|error| format!("Cannot create image artifact directory: {error}"))?;
}
fs::copy(&source_file, &target_file)
.map_err(|error| format!("Cannot copy immutable image file {relative}: {error}"))?;
Ok(())
}
fn resolve_reference(raw: &str) -> Result<(PathBuf, Option<String>), String> {
let (path, expected_digest) = if raw == "local" {
(
resolve_local_bundle().ok_or_else(|| {
"Local image is unavailable; install vm-bundle beside apoc or set APOC_EXECUTOR_VM_BUNDLE"
.to_string()
})?,
None,
)
} else if let Some(digest) = raw.strip_prefix("sha256:") {
validate_digest_hex(digest)
.map_err(|error| format!("Invalid sha256 image reference: {error}"))?;
(
image_store()?.join("sha256").join(digest),
Some(format!("sha256:{digest}")),
)
} else {
(PathBuf::from(raw), None)
};
let canonical = fs::canonicalize(&path)
.map_err(|error| format!("Image bundle does not exist at {}: {error}", path.display()))?;
if !canonical.is_dir() {
return Err(format!(
"Image bundle is not a directory: {}",
canonical.display()
));
}
Ok((canonical, expected_digest))
}
fn resolve_local_bundle() -> Option<PathBuf> {
let configured = std::env::var_os("APOC_EXECUTOR_VM_BUNDLE").map(PathBuf::from);
let sibling = std::env::current_exe()
.ok()
.and_then(|path| path.parent().map(|parent| parent.join("vm-bundle")));
let repository = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
configured
.into_iter()
.chain(sibling)
.chain([
repository.join("extensions/macos-native/.build/vm-bundle"),
repository.join("extensions/macos-native/vm-bundle"),
])
.find(|path| path.is_dir())
}
pub(crate) fn image_store() -> Result<PathBuf, String> {
if let Some(path) = std::env::var_os("APOC_IMAGE_STORE") {
return Ok(PathBuf::from(path));
}
if let Some(path) = std::env::var_os("APOC_HOME") {
return Ok(PathBuf::from(path).join("images"));
}
let home = std::env::var_os("HOME")
.ok_or_else(|| "HOME, APOC_HOME, and APOC_IMAGE_STORE are unset".to_string())?;
Ok(PathBuf::from(home).join(".local/share/apoc/images"))
}
#[cfg(test)]
mod import_tests {
use super::*;
#[test]
fn imports_only_verified_immutable_bundle_files() {
let store = tempfile::tempdir().unwrap();
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/image-v1");
let imported = import_verified_bundle(&source, store.path()).unwrap();
assert!(!imported.already_present);
assert_eq!(imported.files, 5);
assert!(
Path::new(&imported.target_bundle)
.join(MANIFEST_FILE)
.is_file()
);
assert_eq!(
verify_reference(&imported.target_bundle).unwrap().status,
VerificationStatus::Verified
);
}
#[test]
fn cached_verification_invalidates_when_an_artifact_changes() {
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/image-v1");
let bundle = tempfile::tempdir().unwrap();
let initial = verify_reference(&source.to_string_lossy()).unwrap();
for relative in std::iter::once("config.json")
.chain(std::iter::once(MANIFEST_FILE))
.chain(
initial
.artifacts
.iter()
.map(|artifact| artifact.path.as_str()),
)
{
let destination = bundle.path().join(relative);
if let Some(parent) = destination.parent() {
fs::create_dir_all(parent).unwrap();
}
fs::copy(source.join(relative), destination).unwrap();
}
let reference = bundle.path().to_string_lossy();
let first = verify_reference_cached(&reference).unwrap();
assert_eq!(first.status, VerificationStatus::Verified);
let artifact = &first.artifacts[0];
let path = bundle.path().join(&artifact.path);
let mut bytes = fs::read(&path).unwrap();
bytes.push(0);
fs::write(path, bytes).unwrap();
let second = verify_reference_cached(&reference).unwrap();
assert_eq!(second.status, VerificationStatus::Invalid);
}
}
fn verify_bundle(bundle_path: &Path, expected_digest: Option<&str>) -> VerificationReport {
let display_path = bundle_path.to_string_lossy().into_owned();
match verify_bundle_inner(bundle_path, expected_digest) {
Ok(VerifiedBundle::Verified(verified)) => VerificationReport {
schema_version: 1,
status: VerificationStatus::Verified,
bundle_path: display_path,
image_digest: Some(verified.image_digest),
guest: Some(verified.guest),
config: Some(verified.config),
build: Some(verified.build),
artifacts: verified.artifacts,
error: None,
},
Ok(VerifiedBundle::Legacy) => VerificationReport {
schema_version: 1,
status: VerificationStatus::LegacyUnverified,
bundle_path: display_path,
image_digest: None,
guest: None,
config: None,
build: None,
artifacts: Vec::new(),
error: Some("bundle-manifest.json is missing".to_string()),
},
Err(error) => VerificationReport {
schema_version: 1,
status: VerificationStatus::Invalid,
bundle_path: display_path,
image_digest: None,
guest: None,
config: None,
build: None,
artifacts: Vec::new(),
error: Some(error),
},
}
}
enum VerifiedBundle {
Verified(Box<VerifiedImage>),
Legacy,
}
struct VerifiedImage {
image_digest: String,
guest: ManifestGuest,
config: ManifestConfig,
build: BuildProvenance,
artifacts: Vec<ManifestArtifact>,
}
fn verify_bundle_inner(
bundle_path: &Path,
expected_digest: Option<&str>,
) -> Result<VerifiedBundle, String> {
let config_bytes = fs::read(bundle_path.join("config.json"))
.map_err(|error| format!("Cannot read config.json: {error}"))?;
let config: BundleConfig = serde_json::from_slice(&config_bytes)
.map_err(|error| format!("Cannot decode config.json: {error}"))?;
let manifest_path = bundle_path.join(MANIFEST_FILE);
let manifest_bytes = match fs::read(&manifest_path) {
Ok(bytes) => bytes,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
if expected_digest.is_some() {
return Err("Digest-addressed bundles require bundle-manifest.json".to_string());
}
return Ok(VerifiedBundle::Legacy);
}
Err(error) => return Err(format!("Cannot read {MANIFEST_FILE}: {error}")),
};
let manifest_digest = format!("sha256:{:x}", Sha256::digest(&manifest_bytes));
if config.image_digest.as_deref() != Some(manifest_digest.as_str()) {
return Err(format!(
"config imageDigest does not match {MANIFEST_FILE}: expected {manifest_digest}"
));
}
if let Some(expected) = expected_digest {
if expected != manifest_digest {
return Err(format!(
"Image reference does not match {MANIFEST_FILE}: expected {expected}, found {manifest_digest}"
));
}
if bundle_path.file_name().and_then(|value| value.to_str())
!= expected.strip_prefix("sha256:")
{
return Err("Image-store directory does not match the requested digest".to_string());
}
}
let manifest: BundleManifest = serde_json::from_slice(&manifest_bytes)
.map_err(|error| format!("Cannot decode {MANIFEST_FILE}: {error}"))?;
if manifest.schema_version != 1 {
return Err(format!(
"Unsupported bundle manifest schema version: {}",
manifest.schema_version
));
}
if manifest.guest.os != "linux" || manifest.guest.architecture != "arm64" {
return Err(format!(
"Unsupported guest platform: {}/{}",
manifest.guest.os, manifest.guest.architecture
));
}
if manifest.config != config.immutable()? {
return Err("Manifest configuration does not match config.json".to_string());
}
validate_build_provenance(&manifest.build)?;
validate_artifacts(bundle_path, &manifest.config.resources, &manifest.artifacts)?;
Ok(VerifiedBundle::Verified(Box::new(VerifiedImage {
image_digest: manifest_digest,
guest: manifest.guest,
config: manifest.config,
build: manifest.build,
artifacts: manifest.artifacts,
})))
}
fn validate_build_provenance(build: &BuildProvenance) -> Result<(), String> {
validate_prefixed_digest(&build.build_script_sha256, "build.build_script_sha256")?;
if let Some(digest) = &build.base_image_digest {
validate_prefixed_digest(digest, "build.base_image_digest")?;
}
if build.source_revision.as_deref() == Some("") {
return Err("build.source_revision must not be empty when present".to_string());
}
if let Some(revision) = &build.rr_software_counters_revision
&& (revision.len() != 40
|| !revision
.bytes()
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()))
{
return Err(
"build.rr_software_counters_revision must be a 40-character lowercase Git commit"
.to_string(),
);
}
if build.docker_platform.is_empty() || build.base_image.is_empty() {
return Err("Build platform and base image must not be empty".to_string());
}
Ok(())
}
fn validate_artifacts(
bundle_path: &Path,
resources: &ImmutableResources,
artifacts: &[ManifestArtifact],
) -> Result<(), String> {
let mut roles = BTreeSet::new();
let mut paths = BTreeSet::new();
for artifact in artifacts {
if !matches!(artifact.role.as_str(), "kernel" | "initrd" | "rootfs") {
return Err(format!("Unsupported artifact role: {}", artifact.role));
}
if !roles.insert(artifact.role.as_str()) {
return Err(format!("Duplicate artifact role: {}", artifact.role));
}
if !paths.insert(artifact.path.as_str()) {
return Err(format!("Duplicate artifact path: {}", artifact.path));
}
validate_prefixed_digest(&artifact.sha256, "artifact sha256")?;
let path = confined_regular_file(bundle_path, &artifact.path)?;
let metadata = fs::metadata(&path)
.map_err(|error| format!("Cannot inspect artifact {}: {error}", artifact.path))?;
if metadata.len() != artifact.size_bytes {
return Err(format!(
"Artifact size mismatch for {}: expected {}, found {}",
artifact.path,
artifact.size_bytes,
metadata.len()
));
}
let actual = hash_file(&path)
.map_err(|error| format!("Cannot hash artifact {}: {error}", artifact.path))?;
if actual != artifact.sha256 {
return Err(format!(
"Artifact digest mismatch for {}: expected {}, found {}",
artifact.path, artifact.sha256, actual
));
}
}
let expected = [
("kernel", Some(resources.kernel.as_str())),
("rootfs", Some(resources.disk.as_str())),
("initrd", resources.initrd.as_deref()),
];
for (role, path) in expected {
match path {
Some(path) => {
let artifact = artifacts
.iter()
.find(|artifact| artifact.role == role)
.ok_or_else(|| format!("Missing required artifact role: {role}"))?;
if artifact.path != path {
return Err(format!(
"Artifact path for {role} does not match config: expected {path}, found {}",
artifact.path
));
}
}
None if roles.contains(role) => {
return Err(format!("Unexpected artifact role: {role}"));
}
None => {}
}
}
Ok(())
}
fn confined_regular_file(bundle_path: &Path, relative: &str) -> Result<PathBuf, String> {
let canonical_bundle = fs::canonicalize(bundle_path)
.map_err(|error| format!("Cannot resolve bundle path: {error}"))?;
let path = Path::new(relative);
if relative.is_empty()
|| relative
.split('/')
.any(|component| component.is_empty() || component == "." || component == "..")
|| path
.components()
.any(|component| !matches!(component, Component::Normal(_)))
{
return Err(format!(
"Artifact path must be normalized and relative: {relative}"
));
}
let mut current = canonical_bundle.clone();
for component in path.components() {
let Component::Normal(value) = component else {
unreachable!();
};
current.push(value);
let metadata = fs::symlink_metadata(¤t)
.map_err(|error| format!("Cannot inspect artifact path {relative}: {error}"))?;
if metadata.file_type().is_symlink() {
return Err(format!(
"Artifact path must not contain symlinks: {relative}"
));
}
}
let canonical = fs::canonicalize(¤t)
.map_err(|error| format!("Cannot resolve artifact path {relative}: {error}"))?;
if !canonical.starts_with(&canonical_bundle) {
return Err(format!("Artifact path escapes the bundle: {relative}"));
}
let metadata = fs::metadata(&canonical)
.map_err(|error| format!("Cannot inspect artifact {relative}: {error}"))?;
if !metadata.is_file() {
return Err(format!("Artifact is not a regular file: {relative}"));
}
Ok(canonical)
}
fn hash_file(path: &Path) -> Result<String, String> {
let mut file = File::open(path).map_err(|error| error.to_string())?;
let mut hasher = Sha256::new();
let mut buffer = [0_u8; 1024 * 1024];
loop {
let count = file.read(&mut buffer).map_err(|error| error.to_string())?;
if count == 0 {
break;
}
hasher.update(&buffer[..count]);
}
Ok(format!("sha256:{:x}", hasher.finalize()))
}
fn validate_prefixed_digest(value: &str, field: &str) -> Result<(), String> {
let digest = value
.strip_prefix("sha256:")
.ok_or_else(|| format!("{field} must use sha256:<digest>"))?;
validate_digest_hex(digest).map_err(|error| format!("Invalid {field}: {error}"))
}
fn validate_digest_hex(value: &str) -> Result<(), String> {
if value.len() != 64
|| !value
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
{
return Err("Digest must contain 64 lowercase hexadecimal characters".to_string());
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn digest_validation_is_canonical() {
assert!(validate_digest_hex(&"a".repeat(64)).is_ok());
assert!(validate_digest_hex(&"A".repeat(64)).is_err());
assert!(validate_digest_hex("abc").is_err());
}
#[test]
fn artifact_paths_are_normalized() {
let directory = tempfile::tempdir().unwrap();
fs::write(directory.path().join("kernel"), b"bytes").unwrap();
assert!(confined_regular_file(directory.path(), "kernel").is_ok());
assert!(confined_regular_file(directory.path(), "../kernel").is_err());
assert!(confined_regular_file(directory.path(), "./kernel").is_err());
assert!(confined_regular_file(directory.path(), "path//kernel").is_err());
}
#[test]
fn rr_software_counter_provenance_requires_a_canonical_commit() {
let build = |revision| BuildProvenance {
source_revision: None,
source_dirty: false,
build_script_sha256: format!("sha256:{}", "a".repeat(64)),
docker_platform: "linux/arm64".to_string(),
base_image: "debian:trixie-slim".to_string(),
base_image_digest: None,
rr_software_counters_revision: revision,
};
assert!(validate_build_provenance(&build(Some("a".repeat(40)))).is_ok());
assert!(validate_build_provenance(&build(Some("A".repeat(40)))).is_err());
assert!(validate_build_provenance(&build(Some("a".repeat(39)))).is_err());
}
}