blob: ccc568b67fd3e2df518323640c5179117da1c559 [file]
// Copyright 2026 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.
//! Symlink-safe case path validation, staging copies, and evidence export.
use super::*;
pub(super) fn owned_path(root: &Path, relative: &Path) -> TestResult<PathBuf> {
if relative.as_os_str().is_empty()
|| !relative.components().all(|part| matches!(part, Component::Normal(_)))
{
return Err(format!("expected a case-relative path: {}", relative.display()));
}
let path = root.join(relative);
reject_symlink_components(&path)?;
Ok(path)
}
pub(super) fn validate_case_name(name: &str) -> TestResult {
let mut components = Path::new(name).components();
if !matches!(
(components.next(), components.next()),
(Some(Component::Normal(part)), None) if part == name
) {
return Err(format!("expected a case name consisting of one filename: {name:?}"));
}
Ok(())
}
pub(super) fn export_evidence(source: &Path, destination: &Path) -> TestResult {
let source = fs::canonicalize(source)
.map_err(|error| format!("resolve {}: {error}", source.display()))?;
let destination = resolve_destination(destination)?;
if destination.starts_with(&source) || source.starts_with(&destination) {
return Err("evidence export must be disjoint from the retained run".into());
}
// Existing export roots are supported: copied entries below replace files
// with fresh inodes so outside hard-link aliases stay unchanged. Tighten
// only this resolved directory; file chmod could affect outside aliases,
// and existing diagnostics-parent permissions belong to the caller.
let mut builder = fs::DirBuilder::new();
builder.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(0o700);
}
builder
.create(&destination)
.map_err(|error| format!("create {}: {error}", destination.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&destination, fs::Permissions::from_mode(0o700))
.map_err(|error| format!("restrict {}: {error}", destination.display()))?;
}
for entry in
fs::read_dir(&source).map_err(|error| format!("list {}: {error}", source.display()))?
{
let entry = entry.map_err(|error| format!("read evidence entry: {error}"))?;
// Toolchains can be several GiB; retain the owned installation in the
// original run while exporting its identity and command logs.
if entry.file_name() != "installation" {
copy_regular_tree(&entry.path(), &destination.join(entry.file_name()))?;
}
}
Ok(())
}
// Resolve existing ancestors before appending missing directories so aliases
// followed by `..` are caught before creating any destination directory.
fn resolve_destination(path: &Path) -> TestResult<PathBuf> {
let absolute = std::path::absolute(path)
.map_err(|error| format!("resolve {}: {error}", path.display()))?;
let mut resolved = PathBuf::new();
for component in absolute.components() {
match component {
Component::CurDir => continue,
Component::ParentDir => {
resolved.pop();
}
other => resolved.push(other),
}
match fs::canonicalize(&resolved) {
Ok(path) => resolved = path,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => {
return Err(format!("resolve {}: {error}", resolved.display()));
}
}
}
Ok(resolved)
}
pub(super) fn copy_regular_tree(source: &Path, destination: &Path) -> TestResult {
let metadata = fs::symlink_metadata(source)
.map_err(|error| format!("inspect {}: {error}", source.display()))?;
if !metadata.is_file() && !metadata.is_dir() {
return Err(format!("expected regular fixture file or directory: {}", source.display()));
}
reject_symlink_components(destination)?;
let resolved_source = fs::canonicalize(source)
.map_err(|error| format!("resolve {}: {error}", source.display()))?;
let destination = resolve_destination(destination)?;
if destination.starts_with(&resolved_source) || resolved_source.starts_with(&destination) {
return Err("fixture copy source and destination must be disjoint".into());
}
copy_regular_tree_contents(source, &destination)
}
fn copy_regular_tree_contents(source: &Path, destination: &Path) -> TestResult {
reject_symlink_components(destination)?;
let metadata = fs::symlink_metadata(source)
.map_err(|error| format!("inspect {}: {error}", source.display()))?;
if metadata.is_file() {
fs::create_dir_all(destination.parent().unwrap())
.map_err(|error| format!("create copy parent: {error}"))?;
// Replace existing regular entries with a fresh inode so outside hard
// links are never mutated while preserving source file permissions.
let temporary = tempfile::NamedTempFile::new_in(destination.parent().unwrap())
.map_err(|error| format!("stage {}: {error}", destination.display()))?;
fs::copy(source, temporary.path()).map_err(|error| {
format!("copy {} to {}: {error}", source.display(), destination.display())
})?;
temporary
.persist(destination)
.map_err(|error| format!("replace {}: {error}", destination.display()))?;
} else if metadata.is_dir() {
fs::create_dir_all(destination)
.map_err(|error| format!("create {}: {error}", destination.display()))?;
let mut entries = fs::read_dir(source)
.map_err(|error| format!("list {}: {error}", source.display()))?
.collect::<Result<Vec<_>, _>>()
.map_err(|error| format!("read entry in {}: {error}", source.display()))?;
entries.sort_by_key(|entry| entry.file_name());
for entry in entries {
copy_regular_tree_contents(&entry.path(), &destination.join(entry.file_name()))?;
}
} else {
return Err(format!("expected regular fixture file or directory: {}", source.display()));
}
Ok(())
}