use std::path::{Path, PathBuf};
pub const FORCE_ENV: &str = "TRUSTY_TEST_HARNESS";
pub const ALLOW_PRODUCTION_ENV: &str = "TRUSTY_ALLOW_PRODUCTION_STATE";
pub fn running_under_test_harness() -> bool {
let exe = std::env::current_exe();
let allow_production = std::env::var(ALLOW_PRODUCTION_ENV).ok();
if let Err(e) = &exe
&& !is_truthy(allow_production.as_deref())
{
static WARNED: std::sync::Once = std::sync::Once::new();
WARNED.call_once(|| {
tracing::warn!(
"cannot read this process's executable path ({e}); treating it as a test \
process and refusing production-state writes (#11138). Set \
{ALLOW_PRODUCTION_ENV}=1 to override."
);
});
}
detect(
allow_production.as_deref(),
std::env::var(FORCE_ENV).ok().as_deref(),
cfg!(test),
exe.ok().as_deref(),
)
}
fn detect(
allow_production: Option<&str>,
force: Option<&str>,
compiled_as_test: bool,
current_exe: Option<&Path>,
) -> bool {
if is_truthy(allow_production) {
return false;
}
if is_truthy(force) || compiled_as_test {
return true;
}
current_exe.is_none_or(is_cargo_test_binary)
}
fn is_truthy(value: Option<&str>) -> bool {
value.is_some_and(|v| {
matches!(
v.trim().to_ascii_lowercase().as_str(),
"1" | "true" | "yes" | "on"
)
})
}
fn is_cargo_test_binary(exe: &Path) -> bool {
fn dir_name(p: Option<&Path>) -> Option<&str> {
p.and_then(Path::file_name).and_then(|n| n.to_str())
}
let Some(file_name) = exe.file_name().and_then(|s| s.to_str()) else {
return false;
};
let file_name = file_name.strip_suffix(" (deleted)").unwrap_or(file_name);
let Some(stem) = Path::new(file_name).file_stem().and_then(|s| s.to_str()) else {
return false;
};
let Some(hash) = stem.rsplit_once('-').and_then(|(name, hash)| {
(!name.is_empty() && hash.len() >= 8 && hash.chars().all(|c| c.is_ascii_hexdigit()))
.then_some(hash)
}) else {
return false;
};
let parent = exe.parent();
if dir_name(parent) == Some("deps") {
return true;
}
let hash_dir = parent.and_then(Path::parent);
let build_dir = hash_dir.and_then(Path::parent).and_then(Path::parent);
if dir_name(parent) == Some("out")
&& dir_name(hash_dir) == Some(hash)
&& dir_name(build_dir) == Some("build")
{
return true;
}
hash.len() == 16
}
pub const REPO_ROOT_ENV: &str = "TRUSTY_TEST_REPO_ROOT";
pub fn test_repo_root() -> std::io::Result<PathBuf> {
let explicit = std::env::var_os(REPO_ROOT_ENV).map(PathBuf::from);
let manifest_dir = std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from);
let cwd = std::env::current_dir().ok();
resolve_repo_root(explicit.as_deref(), manifest_dir.as_deref(), cwd.as_deref())
}
pub fn resolve_repo_root(
explicit: Option<&Path>,
manifest_dir: Option<&Path>,
cwd: Option<&Path>,
) -> std::io::Result<PathBuf> {
use std::io::{Error, ErrorKind};
if let Some(dir) = explicit {
let root = (!dir.as_os_str().is_empty())
.then(|| dir.canonicalize().ok())
.flatten()
.filter(|d| is_workspace_root(d));
return root.ok_or_else(|| {
Error::new(
ErrorKind::InvalidInput,
format!(
"{REPO_ROOT_ENV}={} does not hold a Cargo.toml with a [workspace] table",
dir.display()
),
)
});
}
for start in [manifest_dir, cwd].into_iter().flatten() {
let Ok(start) = start.canonicalize() else {
continue;
};
if let Some(root) = start.ancestors().find(|d| is_workspace_root(d)) {
return Ok(root.to_path_buf());
}
}
Err(Error::new(
ErrorKind::NotFound,
format!(
"no Cargo workspace root at or above CARGO_MANIFEST_DIR ({}) or the current \
directory ({}); set {REPO_ROOT_ENV} to the checkout root",
display_or_unset(manifest_dir),
display_or_unset(cwd)
),
))
}
fn is_workspace_root(dir: &Path) -> bool {
std::fs::read_to_string(dir.join("Cargo.toml"))
.is_ok_and(|toml| toml.lines().any(|line| line.trim() == "[workspace]"))
}
fn display_or_unset(path: Option<&Path>) -> String {
path.map_or_else(|| "unset".to_string(), |p| p.display().to_string())
}
#[cfg(test)]
#[path = "test_harness_repo_root_tests.rs"]
mod repo_root_tests;
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn test_exe() -> PathBuf {
PathBuf::from("/repo/target/debug/deps/integration_tests-f54141ba75b48011")
}
#[test]
fn running_under_test_harness_is_true_in_this_test_binary() {
let _guard = crate::data_dir::ENV_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
assert!(
running_under_test_harness(),
"a cargo test process must be detected as a test harness"
);
}
#[test]
fn detect_allow_production_outranks_everything() {
assert!(
!detect(Some("1"), Some("1"), true, Some(&test_exe())),
"TRUSTY_ALLOW_PRODUCTION_STATE must win over force, cfg(test) and the path check"
);
}
#[test]
fn detect_force_env_wins_over_path_check() {
let installed = PathBuf::from("/Users/me/.cargo/bin/trusty-search");
assert!(detect(None, Some("true"), false, Some(&installed)));
}
#[test]
fn detect_falls_back_to_exe_path() {
assert!(detect(None, None, false, Some(&test_exe())));
}
#[test]
fn detect_is_false_for_a_real_invocation() {
for exe in [
"/Users/me/.cargo/bin/trusty-search",
"/opt/homebrew/bin/trusty-search",
"/repo/target/debug/trusty-search",
"/repo/target/release/trusty-search",
] {
assert!(
!detect(None, None, false, Some(Path::new(exe))),
"{exe} must not be mistaken for a test binary"
);
}
}
#[test]
fn detect_fails_closed_when_exe_is_unresolvable() {
assert!(detect(None, None, false, None));
assert!(!detect(Some("1"), None, false, None));
}
#[test]
fn is_cargo_test_binary_accepts_the_rust_1100_build_out_layout() {
for exe in [
"/repo/target/debug/build/trusty-mpm/98af4e218cd2e034/out/trusty_mpm-98af4e218cd2e034",
"/repo/target/debug/build/trusty-mpm/62c73b50a0eeb776/out/tm-62c73b50a0eeb776",
"/repo/target/debug/build/trusty-mpm/3322f910a0c480bf/out/integration-3322f910a0c480bf",
"/repo/target/release/build/trusty-search/0802fde7a9957161/out/registry_isolation-0802fde7a9957161",
] {
assert!(
detect(None, None, false, Some(Path::new(exe))),
"{exe} is a cargo test binary"
);
}
}
#[test]
fn is_cargo_test_binary_ignores_a_deleted_exe_suffix() {
for exe in [
"/repo/target/debug/deps/integration_tests-f54141ba75b48011 (deleted)",
"/repo/target/debug/build/trusty-mpm/62c73b50a0eeb776/out/tm-62c73b50a0eeb776 (deleted)",
] {
assert!(
detect(None, None, false, Some(Path::new(exe))),
"{exe} is a replaced cargo test binary"
);
}
}
#[test]
fn detect_fails_closed_for_an_unknown_layout_with_a_cargo_hash() {
for exe in [
"/repo/target/debug/artifacts/trusty_mpm-98af4e218cd2e034",
"/build-dir/x86_64/debug/trusty-mpm/out/tm-62c73b50a0eeb776",
] {
assert!(
detect(None, None, false, Some(Path::new(exe))),
"{exe} carries cargo's metadata hash and must fail closed"
);
}
}
#[test]
fn detect_is_false_for_production_shapes_beside_the_1100_layout() {
for exe in [
"/repo/target/debug/tm",
"/repo/target/debug/trusty-search",
"/Users/me/.cargo/bin/tm",
"/repo/target/debug/build/trusty-mpm/98af4e218cd2e034/out/build-script-build",
"/repo/target/debug/build/trusty-mpm/98af4e218cd2e034/out/tm",
"/usr/local/bin/tool-deadbeef",
"/opt/x/bin/agent-0123456789abc",
] {
assert!(
!detect(None, None, false, Some(Path::new(exe))),
"{exe} must not be mistaken for a test binary"
);
}
}
#[test]
fn is_cargo_test_binary_accepts_every_target_kind() {
for exe in [
"/repo/target/debug/deps/trusty_search-88c47ed536c1e550",
"/repo/target/debug/deps/integration_tests-f54141ba75b48011",
"/repo/target/release/deps/registry_isolation-0802fde7a9957161",
] {
assert!(
is_cargo_test_binary(Path::new(exe)),
"{exe} is a cargo test binary"
);
}
}
#[test]
fn is_cargo_test_binary_requires_the_metadata_hash() {
assert!(!is_cargo_test_binary(Path::new("/repo/deps/trusty-search")));
assert!(!is_cargo_test_binary(Path::new(
"/repo/target/debug/deps/trusty-search-notahash"
)));
assert!(!is_cargo_test_binary(Path::new(
"/repo/target/debug/deps/thing-abc"
)));
}
#[test]
fn is_truthy_accepts_the_documented_spellings_only() {
for yes in ["1", "true", "TRUE", "Yes", " on "] {
assert!(is_truthy(Some(yes)), "{yes:?} must be truthy");
}
for no in ["0", "false", "", "no", "off", "maybe"] {
assert!(!is_truthy(Some(no)), "{no:?} must not be truthy");
}
assert!(!is_truthy(None));
}
}