Skip to content
Open
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
1 change: 1 addition & 0 deletions Cargo.lock

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

3 changes: 3 additions & 0 deletions crates/victory-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ serde.workspace = true
toml.workspace = true
tracing-subscriber.workspace = true

[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = ["Win32_Storage_FileSystem"] }

[dev-dependencies]
tempfile.workspace = true

Expand Down
92 changes: 88 additions & 4 deletions crates/victory-core/src/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
//! [`ensure_outside_repo`] on the destination first. The static half of the
//! rule is `cargo xtask policy`, which checks what git tracks.

use std::io;
use std::path::{Component, Path, PathBuf};

/// Marker file at the root of the source tree.
Expand Down Expand Up @@ -39,9 +40,25 @@ pub enum PolicyError {
/// 2. none of its ancestors contains the [`ROOT_MARKER`] file (catches
/// other clones/copies of the repository).
pub fn ensure_outside_repo(path: &Path) -> Result<(), PolicyError> {
let resolved = resolve(path)?;
let result = ensure_outside_repo_with(path, |path| std::fs::canonicalize(path));
#[cfg(windows)]
if let Err(PolicyError::Io { source, .. }) = &result
&& source.kind() == io::ErrorKind::PermissionDenied
{
// An AppContainer can open a directory without access to its DOS volume name.
// Compare both paths in the same namespace and still check the resolved ancestors.
return ensure_outside_repo_with(path, canonicalize_native);
}
result
}

if let Ok(root) = std::fs::canonicalize(compiled_workspace_root())
fn ensure_outside_repo_with(
path: &Path,
canonicalize: impl Fn(&Path) -> io::Result<PathBuf>,
) -> Result<(), PolicyError> {
let resolved = resolve(path, &canonicalize)?;

if let Ok(root) = canonicalize(&compiled_workspace_root())
&& root.join(ROOT_MARKER).is_file()
&& resolved.starts_with(&root)
{
Expand All @@ -64,7 +81,10 @@ pub fn ensure_outside_repo(path: &Path) -> Result<(), PolicyError> {

/// Canonicalizes the longest existing prefix of `path` and re-appends the
/// rest, so that paths which do not exist yet can still be compared.
fn resolve(path: &Path) -> Result<PathBuf, PolicyError> {
fn resolve(
path: &Path,
canonicalize: impl Fn(&Path) -> io::Result<PathBuf>,
) -> Result<PathBuf, PolicyError> {
let absolute = if path.is_absolute() {
path.to_path_buf()
} else {
Expand All @@ -79,14 +99,20 @@ fn resolve(path: &Path) -> Result<PathBuf, PolicyError> {
let mut existing = absolute.as_path();
let mut rest = Vec::new();
loop {
match std::fs::canonicalize(existing) {
match canonicalize(existing) {
Ok(canon) => {
let mut out = canon;
for component in rest.iter().rev() {
out.push(component);
}
return Ok(normalize(&out));
}
Err(source) if cfg!(windows) && source.kind() == io::ErrorKind::PermissionDenied => {
return Err(PolicyError::Io {
path: path.to_path_buf(),
source,
});
}
Err(source) => match (existing.parent(), existing.file_name()) {
(Some(parent), Some(name)) => {
rest.push(name.to_os_string());
Expand All @@ -103,6 +129,44 @@ fn resolve(path: &Path) -> Result<PathBuf, PolicyError> {
}
}

#[cfg(windows)]
fn canonicalize_native(path: &Path) -> io::Result<PathBuf> {
use std::fs::OpenOptions;
use std::os::windows::{ffi::OsStringExt, fs::OpenOptionsExt, io::AsRawHandle};
use windows_sys::Win32::Storage::FileSystem::{
FILE_FLAG_BACKUP_SEMANTICS, GetFinalPathNameByHandleW, VOLUME_NAME_NT,
};

let file = OpenOptions::new()
.access_mode(0)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(path)?;
let mut name = vec![0u16; 512];
loop {
// SAFETY: the live file owns the handle, and the buffer is writable for its given length.
let len = unsafe {
GetFinalPathNameByHandleW(
file.as_raw_handle(),
name.as_mut_ptr(),
name.len() as u32,
VOLUME_NAME_NT,
)
} as usize;
if len == 0 {
return Err(io::Error::last_os_error());
}
if len >= name.len() {
name.resize(len, 0);
continue;
}

// Make the normalized NT path usable by ordinary Win32 file APIs.
let mut absolute = std::ffi::OsString::from(r"\\?\GLOBALROOT");
absolute.push(std::ffi::OsString::from_wide(&name[..len]));
return Ok(PathBuf::from(absolute));
}
}

/// Removes `.` and resolves `..` lexically (only used on the non-existing tail).
fn normalize(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
Expand Down Expand Up @@ -156,4 +220,24 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
ensure_outside_repo(&tmp.path().join("does").join("not").join("exist")).unwrap();
}

#[cfg(windows)]
#[test]
fn native_paths_still_check_repository_markers() {
let temp = tempfile::tempdir().unwrap();
let target = temp.path().join("missing").join("cache");
ensure_outside_repo_with(&target, canonicalize_native).unwrap();
std::fs::write(temp.path().join(ROOT_MARKER), "").unwrap();
assert!(matches!(
ensure_outside_repo_with(&target, canonicalize_native),
Err(PolicyError::InsideRepo { .. })
));
assert!(matches!(
ensure_outside_repo_with(
&compiled_workspace_root().join("missing").join("cache"),
canonicalize_native,
),
Err(PolicyError::InsideRepo { .. })
));
}
}