blob: 882f602f327eacd61d8d506501301e23e4babf5c [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.
//! Path validation and the atomic file writes used for command logs.
use super::*;
pub(super) fn path_utf8<'a>(path: &'a Path, label: &str) -> TestResult<&'a str> {
path.to_str()
.ok_or_else(|| format!("{label} path is not valid UTF-8: {}", path.display()))
}
/// Reject any symlink component along `path` (including dangling final links).
pub fn reject_symlink_components(path: &Path) -> TestResult {
for ancestor in path.ancestors().collect::<Vec<_>>().into_iter().rev() {
match fs::symlink_metadata(ancestor) {
Ok(metadata) if metadata.file_type().is_symlink() => {
return Err(format!(
"symlink is not an owned fixture destination: {}",
ancestor.display()
));
}
Ok(_) => {}
Err(error)
if matches!(
error.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
) => {}
Err(error) => {
return Err(format!("inspect {}: {error}", ancestor.display()));
}
}
}
Ok(())
}
pub(crate) fn validate_single_component(name: &str, label: &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 single normal {label}: {name:?}"));
}
Ok(())
}
/// Symlink-safe atomic JSON write replacing any existing hard-linked inode.
pub fn write_json(path: &Path, value: &Value) -> TestResult {
reject_symlink_components(path)?;
let bytes = serde_json::to_vec_pretty(value)
.map_err(|error| format!("serialize {}: {error}", path.display()))?;
write_regular_file(path, &bytes)
}
/// Symlink-safe atomic regular-file write preserving existing Unix permissions
/// and replacing any hard-linked destination inode.
pub fn write_regular_file(path: &Path, bytes: &[u8]) -> TestResult {
use std::io::Write;
reject_symlink_components(path)?;
let parent = path
.parent()
.ok_or_else(|| format!("destination has no parent directory: {path:?}"))?;
let permissions = match fs::metadata(path) {
Ok(metadata) => metadata.is_file().then(|| metadata.permissions()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
Err(error) => return Err(format!("inspect {}: {error}", path.display())),
};
let mut temporary = tempfile::NamedTempFile::new_in(parent)
.map_err(|error| format!("stage {}: {error}", path.display()))?;
temporary
.write_all(bytes)
.map_err(|error| format!("write {}: {error}", path.display()))?;
if let Some(permissions) = permissions {
temporary
.as_file()
.set_permissions(permissions)
.map_err(|error| format!("set permissions {}: {error}", path.display()))?;
}
temporary
.persist(path)
.map_err(|error| format!("replace {}: {error}", path.display()))?;
Ok(())
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use serde_json::json;
use super::*;
struct CanonicalTempDir {
_dir: tempfile::TempDir,
root: PathBuf,
}
impl CanonicalTempDir {
fn new() -> Self {
let dir = tempfile::tempdir().unwrap();
// Canonicalize `dir.path()` so symlinked `TMPDIR` roots (such as
// macOS `/var -> /private/var`) never trip
// `reject_symlink_components`.
let root = fs::canonicalize(dir.path()).unwrap();
Self { _dir: dir, root }
}
fn path(&self) -> &Path {
&self.root
}
}
#[cfg(unix)]
fn assert_sym_err(res: TestResult, expected_path: &Path) {
let err = res.unwrap_err();
let expected =
format!("symlink is not an owned fixture destination: {}", expected_path.display());
assert_eq!(err, expected);
}
#[test]
fn path_utf8_accepts_valid_and_rejects_non_utf8() {
let ok = path_utf8(Path::new("sub/file.log"), "log").unwrap();
assert_eq!(ok, "sub/file.log");
#[cfg(unix)]
{
use std::{ffi::OsStr, os::unix::ffi::OsStrExt};
let invalid = Path::new(OsStr::from_bytes(b"bad/\xff/leaf"));
let err = path_utf8(invalid, "fixture").unwrap_err();
assert!(err.contains("fixture path is not valid UTF-8:"), "{err}");
assert!(err.contains("bad/"), "{err}");
}
}
#[test]
fn validate_single_component_enforces_exact_normal_part() {
validate_single_component("case_01", "slot").unwrap();
validate_single_component(".dot", "slot").unwrap();
for bad in ["", ".", "..", "a/b", "/abs", "./a", "../a", "a/"] {
let err = validate_single_component(bad, "slot").unwrap_err();
assert!(err.contains("expected a single normal slot:"), "{bad}: {err}");
}
}
#[test]
fn reject_symlink_components_covers_ancestors_missing_and_non_dir() {
let dir = CanonicalTempDir::new();
let real_dir = dir.path().join("real");
let real_file = real_dir.join("leaf.txt");
fs::create_dir_all(&real_dir).unwrap();
fs::write(&real_file, b"ok").unwrap();
reject_symlink_components(&real_file).unwrap();
reject_symlink_components(&real_dir.join("missing/nested/leaf.txt")).unwrap();
reject_symlink_components(&real_file.join("child")).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
let sub_link = real_dir.join("sub_link");
symlink(&real_dir, &sub_link).unwrap();
let dir_link = dir.path().join("dir_link");
symlink(&real_dir, &dir_link).unwrap();
assert_sym_err(
reject_symlink_components(&dir_link.join("sub_link/leaf.txt")),
&dir_link,
);
let file_link = dir.path().join("file_link");
symlink(&real_file, &file_link).unwrap();
assert_sym_err(reject_symlink_components(&file_link), &file_link);
let dangling = dir.path().join("dangling");
symlink(dir.path().join("absent"), &dangling).unwrap();
assert_sym_err(reject_symlink_components(&dangling), &dangling);
}
}
#[test]
fn write_regular_file_rejects_parentless_and_symlinks() {
for bad in [Path::new(""), Path::new("/")] {
let err = write_regular_file(bad, b"x").unwrap_err();
assert!(err.contains("destination has no parent directory:"), "{err}");
}
let dir = CanonicalTempDir::new();
let err = write_regular_file(&dir.path().join("absent/out.txt"), b"x").unwrap_err();
assert!(err.contains("stage "), "{err}");
let subdir = dir.path().join("subdir");
fs::create_dir(&subdir).unwrap();
let err = write_regular_file(&subdir, b"x").unwrap_err();
assert!(err.contains("replace "), "{err}");
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
let secret = dir.path().join("secret.txt");
fs::write(&secret, b"keep").unwrap();
let file_link = dir.path().join("link.txt");
symlink(&secret, &file_link).unwrap();
assert_sym_err(write_regular_file(&file_link, b"clobber"), &file_link);
assert_eq!(fs::read(&secret).unwrap(), b"keep");
let outside = dir.path().join("outside");
fs::create_dir(&outside).unwrap();
let dir_link = dir.path().join("dir_link");
symlink(&outside, &dir_link).unwrap();
assert_sym_err(write_regular_file(&dir_link.join("out.txt"), b"clobber"), &dir_link);
assert!(!outside.join("out.txt").exists());
}
}
#[test]
#[cfg(unix)]
fn write_regular_file_preserves_permissions_and_breaks_hard_links() {
use std::os::unix::fs::{MetadataExt, PermissionsExt};
let dir = CanonicalTempDir::new();
let dest = dir.path().join("dest.txt");
let alias = dir.path().join("alias.txt");
fs::write(&dest, b"old").unwrap();
fs::hard_link(&dest, &alias).unwrap();
let old_ino = fs::metadata(&dest).unwrap().ino();
for mode in [0o750, 0o640] {
fs::set_permissions(&dest, fs::Permissions::from_mode(mode)).unwrap();
write_regular_file(&dest, b"new").unwrap();
let got = fs::metadata(&dest).unwrap().permissions().mode() & 0o777;
assert_eq!(got, mode);
}
assert_eq!(fs::read(&dest).unwrap(), b"new");
assert_eq!(fs::read(&alias).unwrap(), b"old");
assert_ne!(fs::metadata(&dest).unwrap().ino(), old_ino);
assert_eq!(fs::metadata(&alias).unwrap().ino(), old_ino);
}
#[test]
fn write_json_writes_pretty_safely_and_breaks_hard_links() {
let dir = CanonicalTempDir::new();
let path = dir.path().join("data.json");
write_json(&path, &json!({"step": 1})).unwrap();
let alias = dir.path().join("alias.json");
fs::hard_link(&path, &alias).unwrap();
let next = json!({"status": "ok", "count": 2});
write_json(&path, &next).unwrap();
let text = fs::read_to_string(&path).unwrap();
assert!(text.contains('\n'), "{text}");
assert!(text.contains(" \"status\": \"ok\""), "{text}");
assert_eq!(serde_json::from_str::<Value>(&text).unwrap(), next);
let alias_val: Value = serde_json::from_slice(&fs::read(&alias).unwrap()).unwrap();
assert_eq!(alias_val, json!({"step": 1}));
#[cfg(unix)]
{
use std::os::unix::fs::{MetadataExt, symlink};
let (p_ino, a_ino) =
(fs::metadata(&path).unwrap().ino(), fs::metadata(&alias).unwrap().ino());
assert_ne!(p_ino, a_ino);
let link = dir.path().join("link.json");
symlink(&path, &link).unwrap();
assert_sym_err(write_json(&link, &json!({"bad": true})), &link);
let cur_val: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
assert_eq!(cur_val, next);
}
}
}