Improve no-follow filesystem behavior across platforms (#39666)

## What changed

- Use `statx` for no-follow metadata on Linux so `created_at_ms` includes the birth time when the filesystem provides it, with a fallback for unavailable or blocked `statx` calls.
- Mark files and directories for deletion explicitly on Windows after opening them without traversing reparse points.
- Cover create, write, metadata, remove, and link-rejection behavior for local and remote filesystems, including sandboxed execution on Linux and Windows.

## Testing

- Add Linux coverage for preserving birth time in no-follow metadata.
- Add cross-platform coverage for sandboxed no-follow operations and removal of files and empty directories.

GitOrigin-RevId: 1bc531669839bf5d033aa4a215220ed1cc5f63d5
This commit is contained in:
pakrym-oai authored and copyberry committed 2026-08-20 08:32:11 +00:00
1 parent fec2dccfcf
commit 2584e88cad
6 files changed
+369 -106

No files matched your search

+73 -7
View File
@@ -3,11 +3,17 @@ use rustix::fs::AtFlags;
use rustix::fs::Mode; use rustix::fs::Mode;
use rustix::fs::OFlags; use rustix::fs::OFlags;
use rustix::fs::Stat; use rustix::fs::Stat;
#[cfg(target_os = "linux")]
use rustix::fs::Statx;
#[cfg(target_os = "linux")]
use rustix::fs::StatxFlags;
use rustix::fs::fstat; use rustix::fs::fstat;
use rustix::fs::mkdirat; use rustix::fs::mkdirat;
use rustix::fs::open; use rustix::fs::open;
use rustix::fs::openat; use rustix::fs::openat;
use rustix::fs::statat; use rustix::fs::statat;
#[cfg(target_os = "linux")]
use rustix::fs::statx;
use rustix::fs::unlinkat; use rustix::fs::unlinkat;
use std::ffi::OsString; use std::ffi::OsString;
use std::io; use std::io;
@@ -141,16 +147,76 @@ pub(super) async fn write_file(path: PathBuf, contents: Vec<u8>) -> io::Result<(
fn metadata_sync(path: &Path) -> io::Result<FileMetadata> { fn metadata_sync(path: &Path) -> io::Result<FileMetadata> {
let components = components(path)?; let components = components(path)?;
let metadata = if components.is_empty() {
fstat(root()?).map_err(io::Error::from)? #[cfg(target_os = "linux")]
{
let (parent, leaf, flags) = if components.is_empty() {
(root()?, OsString::new(), AtFlags::EMPTY_PATH)
} else { } else {
let (parent, leaf) = parent(path)?; let (parent, leaf) = parent(path)?;
statat(&parent, leaf, AtFlags::SYMLINK_NOFOLLOW).map_err(io::Error::from)? (parent, leaf, AtFlags::SYMLINK_NOFOLLOW)
}; };
file_metadata(metadata) let metadata = statx(
&parent,
&leaf,
flags,
StatxFlags::BASIC_STATS | StatxFlags::BTIME,
);
match metadata {
Ok(metadata) => file_metadata_linux(metadata),
Err(error) if error == rustix::io::Errno::NOSYS || error == rustix::io::Errno::PERM => {
let metadata = if components.is_empty() {
fstat(&parent)
} else {
statat(&parent, &leaf, AtFlags::SYMLINK_NOFOLLOW)
}
.map_err(io::Error::from)?;
file_metadata(metadata, /*created_at_ms*/ 0)
}
Err(error) => Err(io::Error::from(error)),
}
}
#[cfg(not(target_os = "linux"))]
if components.is_empty() {
let root = root()?;
let metadata = fstat(&root).map_err(io::Error::from)?;
let created_at_ms = created_at_ms(&metadata);
file_metadata(metadata, created_at_ms)
} else {
let (parent, leaf) = parent(path)?;
let metadata =
statat(&parent, &leaf, AtFlags::SYMLINK_NOFOLLOW).map_err(io::Error::from)?;
let created_at_ms = created_at_ms(&metadata);
file_metadata(metadata, created_at_ms)
}
} }
fn file_metadata(metadata: Stat) -> io::Result<FileMetadata> { #[cfg(target_os = "linux")]
fn file_metadata_linux(metadata: Statx) -> io::Result<FileMetadata> {
let kind = u32::from(metadata.stx_mode) & libc::S_IFMT;
if kind == libc::S_IFLNK {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"path contains a symbolic link",
));
}
let created_at_ms = if metadata.stx_mask & StatxFlags::BTIME.bits() == 0 {
0
} else {
unix_time_ms(metadata.stx_btime.tv_sec, metadata.stx_btime.tv_nsec)
};
Ok(FileMetadata {
is_directory: kind == libc::S_IFDIR,
is_file: kind == libc::S_IFREG,
is_symlink: false,
size: metadata.stx_size,
created_at_ms,
modified_at_ms: unix_time_ms(metadata.stx_mtime.tv_sec, metadata.stx_mtime.tv_nsec),
})
}
fn file_metadata(metadata: Stat, created_at_ms: i64) -> io::Result<FileMetadata> {
let kind = metadata.st_mode & libc::S_IFMT; let kind = metadata.st_mode & libc::S_IFMT;
if kind == libc::S_IFLNK { if kind == libc::S_IFLNK {
return Err(io::Error::new( return Err(io::Error::new(
@@ -163,7 +229,7 @@ fn file_metadata(metadata: Stat) -> io::Result<FileMetadata> {
is_file: kind == libc::S_IFREG, is_file: kind == libc::S_IFREG,
is_symlink: false, is_symlink: false,
size: u64::try_from(metadata.st_size).unwrap_or(0), size: u64::try_from(metadata.st_size).unwrap_or(0),
created_at_ms: created_at_ms(&metadata), created_at_ms,
modified_at_ms: unix_time_ms(metadata.st_mtime, metadata.st_mtime_nsec), modified_at_ms: unix_time_ms(metadata.st_mtime, metadata.st_mtime_nsec),
}) })
} }
@@ -173,7 +239,7 @@ fn created_at_ms(metadata: &Stat) -> i64 {
unix_time_ms(metadata.st_birthtime, metadata.st_birthtime_nsec) unix_time_ms(metadata.st_birthtime, metadata.st_birthtime_nsec)
} }
#[cfg(not(target_vendor = "apple"))] #[cfg(not(any(target_vendor = "apple", target_os = "linux")))]
fn created_at_ms(_metadata: &Stat) -> i64 { fn created_at_ms(_metadata: &Stat) -> i64 {
0 0
} }
+20 -7
View File
@@ -5,6 +5,7 @@ use std::io;
use std::io::Write; use std::io::Write;
use std::mem::size_of; use std::mem::size_of;
use std::os::windows::ffi::OsStrExt; use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle; use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle; use std::os::windows::io::OwnedHandle;
use std::os::windows::io::RawHandle; use std::os::windows::io::RawHandle;
@@ -22,12 +23,15 @@ use windows_sys::Win32::Security::SECURITY_QUALITY_OF_SERVICE;
use windows_sys::Win32::Security::SecurityIdentification; use windows_sys::Win32::Security::SecurityIdentification;
use windows_sys::Win32::Storage::FileSystem::DELETE; use windows_sys::Win32::Storage::FileSystem::DELETE;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_NORMAL; use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_NORMAL;
use windows_sys::Win32::Storage::FileSystem::FILE_DISPOSITION_INFO;
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ; use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_READ_ATTRIBUTES; use windows_sys::Win32::Storage::FileSystem::FILE_READ_ATTRIBUTES;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_DELETE; use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_DELETE;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ; use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE; use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
use windows_sys::Win32::Storage::FileSystem::FILE_WRITE_DATA; use windows_sys::Win32::Storage::FileSystem::FILE_WRITE_DATA;
use windows_sys::Win32::Storage::FileSystem::FileDispositionInfo;
use windows_sys::Win32::Storage::FileSystem::SetFileInformationByHandle;
use windows_sys::Win32::System::IO::IO_STATUS_BLOCK; use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;
use windows_sys::Win32::System::IO::IO_STATUS_BLOCK_0; use windows_sys::Win32::System::IO::IO_STATUS_BLOCK_0;
use windows_sys::Win32::System::Kernel::OBJ_CASE_INSENSITIVE; use windows_sys::Win32::System::Kernel::OBJ_CASE_INSENSITIVE;
@@ -36,7 +40,6 @@ use windows_sys::Win32::System::Kernel::OBJ_DONT_REPARSE;
const FILE_DIRECTORY_FILE: u32 = 0x0000_0001; const FILE_DIRECTORY_FILE: u32 = 0x0000_0001;
const FILE_SYNCHRONOUS_IO_NONALERT: u32 = 0x0000_0020; const FILE_SYNCHRONOUS_IO_NONALERT: u32 = 0x0000_0020;
const FILE_NON_DIRECTORY_FILE: u32 = 0x0000_0040; const FILE_NON_DIRECTORY_FILE: u32 = 0x0000_0040;
const FILE_DELETE_ON_CLOSE: u32 = 0x0000_1000;
const FILE_OPEN: u32 = 1; const FILE_OPEN: u32 = 1;
const FILE_CREATE: u32 = 2; const FILE_CREATE: u32 = 2;
const FILE_OPEN_IF: u32 = 3; const FILE_OPEN_IF: u32 = 3;
@@ -300,12 +303,22 @@ fn remove_sync(path: &Path, recursive: bool, force: bool) -> io::Result<()> {
} else { } else {
FILE_NON_DIRECTORY_FILE FILE_NON_DIRECTORY_FILE
}; };
open_handle( let handle = open_handle(path, DELETE, FILE_OPEN, create_options)?;
path, let disposition = FILE_DISPOSITION_INFO {
DELETE, DeleteFile: BOOLEAN_TRUE,
FILE_OPEN, };
create_options | FILE_DELETE_ON_CLOSE, let result = unsafe {
)?; SetFileInformationByHandle(
handle.as_raw_handle() as HANDLE,
FileDispositionInfo,
(&raw const disposition).cast(),
size_of::<FILE_DISPOSITION_INFO>() as u32,
)
};
if result == 0 {
return Err(io::Error::last_os_error());
}
drop(handle);
Ok(()) Ok(())
} }
+107 -16
View File
@@ -16,6 +16,7 @@ use codex_exec_server::WalkEntry;
use codex_exec_server::WalkEntryKind; use codex_exec_server::WalkEntryKind;
use codex_exec_server::WalkOptions; use codex_exec_server::WalkOptions;
use codex_exec_server::WalkOutcome; use codex_exec_server::WalkOutcome;
use codex_exec_server::WriteFileOptions;
use codex_protocol::models::AdditionalPermissionProfile; use codex_protocol::models::AdditionalPermissionProfile;
use codex_protocol::models::FileSystemPermissions; use codex_protocol::models::FileSystemPermissions;
use codex_protocol::models::PermissionProfile; use codex_protocol::models::PermissionProfile;
@@ -31,6 +32,8 @@ use test_case::test_case;
use super::support::FileSystemImplementation; use super::support::FileSystemImplementation;
use super::support::absolute_path; use super::support::absolute_path;
use super::support::create_file_system_context; use super::support::create_file_system_context;
#[cfg(windows)]
use super::support::is_unsupported_restricted_token_host;
use super::support::read_only_sandbox; use super::support::read_only_sandbox;
use super::support::workspace_write_sandbox; use super::support::workspace_write_sandbox;
@@ -120,55 +123,92 @@ async fn file_system_get_metadata_reports_files_and_directories(
Ok(()) Ok(())
} }
#[test_case(FileSystemImplementation::Local ; "local")] #[test_case(FileSystemImplementation::Local, true, false ; "local_follow")]
#[test_case(FileSystemImplementation::Remote ; "remote")] #[test_case(FileSystemImplementation::Local, false, false ; "local_no_follow")]
#[test_case(FileSystemImplementation::Remote, true, false ; "remote_follow")]
#[test_case(FileSystemImplementation::Remote, false, false ; "remote_no_follow")]
#[cfg_attr(any(target_os = "linux", windows), test_case(FileSystemImplementation::Local, false, true ; "local_sandboxed_no_follow"))]
#[cfg_attr(any(target_os = "linux", windows), test_case(FileSystemImplementation::Remote, false, true ; "remote_sandboxed_no_follow"))]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn file_system_create_directory_creates_nested_directories( async fn file_system_create_directory_creates_nested_directories(
implementation: FileSystemImplementation, implementation: FileSystemImplementation,
follow_symlinks: bool,
sandboxed: bool,
) -> Result<()> { ) -> Result<()> {
let context = create_file_system_context(implementation).await?; let context = create_file_system_context(implementation).await?;
let file_system = context.file_system; let file_system = context.file_system;
let tmp = TempDir::new()?; let tmp = TempDir::new()?;
let nested_dir = tmp.path().join("source").join("nested"); let root = tmp.path().canonicalize()?;
let nested_dir = root.join("source").join("nested");
let sandbox = sandboxed.then(|| workspace_write_sandbox(root));
file_system let result = file_system
.create_directory( .create_directory(
&PathUri::from_host_native_path(&nested_dir)?, &PathUri::from_host_native_path(&nested_dir)?,
CreateDirectoryOptions { CreateDirectoryOptions {
recursive: true, recursive: true,
follow_symlinks: true, follow_symlinks,
}, },
/*sandbox*/ None, sandbox.as_ref(),
) )
.await .await;
.with_context(|| format!("mode={implementation}"))?; #[cfg(windows)]
if is_unsupported_restricted_token_host(&result) {
return Ok(());
}
result.with_context(|| format!("mode={implementation}, sandboxed={sandboxed}"))?;
assert!(nested_dir.is_dir()); assert!(nested_dir.is_dir());
Ok(()) Ok(())
} }
#[test_case(FileSystemImplementation::Local ; "local")] #[test_case(FileSystemImplementation::Local, true, false ; "local_follow")]
#[test_case(FileSystemImplementation::Remote ; "remote")] #[test_case(FileSystemImplementation::Local, false, false ; "local_no_follow")]
#[test_case(FileSystemImplementation::Remote, true, false ; "remote_follow")]
#[test_case(FileSystemImplementation::Remote, false, false ; "remote_no_follow")]
#[cfg_attr(any(target_os = "linux", windows), test_case(FileSystemImplementation::Local, false, true ; "local_sandboxed_no_follow"))]
#[cfg_attr(any(target_os = "linux", windows), test_case(FileSystemImplementation::Remote, false, true ; "remote_sandboxed_no_follow"))]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn file_system_write_file_writes_bytes( async fn file_system_write_file_writes_bytes(
implementation: FileSystemImplementation, implementation: FileSystemImplementation,
follow_symlinks: bool,
sandboxed: bool,
) -> Result<()> { ) -> Result<()> {
let context = create_file_system_context(implementation).await?; let context = create_file_system_context(implementation).await?;
let file_system = context.file_system; let file_system = context.file_system;
let tmp = TempDir::new()?; let tmp = TempDir::new()?;
let file_path = tmp.path().join("note.txt"); let root = tmp.path().canonicalize()?;
file_system let file_path = root.join("note.txt");
let sandbox = sandboxed.then(|| workspace_write_sandbox(root.clone()));
let result = file_system
.write_file( .write_file(
&PathUri::from_host_native_path(&file_path)?, &PathUri::from_host_native_path(&file_path)?,
b"hello from trait".to_vec(), b"hello from trait".to_vec(),
Default::default(), WriteFileOptions { follow_symlinks },
/*sandbox*/ None, sandbox.as_ref(),
)
.await;
#[cfg(windows)]
if is_unsupported_restricted_token_host(&result) {
return Ok(());
}
result.with_context(|| format!("mode={implementation}, sandboxed={sandboxed}"))?;
assert_eq!(std::fs::read(file_path)?, b"hello from trait");
let file_path = root.join("existing.txt");
std::fs::write(&file_path, b"before")?;
file_system
.write_file(
&PathUri::from_host_native_path(&file_path)?,
b"after".to_vec(),
WriteFileOptions { follow_symlinks },
sandbox.as_ref(),
) )
.await .await
.with_context(|| format!("mode={implementation}"))?; .with_context(|| format!("mode={implementation}, sandboxed={sandboxed}"))?;
assert_eq!(std::fs::read(file_path)?, b"hello from trait"); assert_eq!(std::fs::read(file_path)?, b"after");
Ok(()) Ok(())
} }
@@ -605,6 +645,57 @@ async fn file_system_remove_removes_directory(
Ok(()) Ok(())
} }
#[test_case(FileSystemImplementation::Local, false ; "local")]
#[test_case(FileSystemImplementation::Remote, false ; "remote")]
#[cfg_attr(any(target_os = "linux", windows), test_case(FileSystemImplementation::Local, true ; "local_sandboxed"))]
#[cfg_attr(any(target_os = "linux", windows), test_case(FileSystemImplementation::Remote, true ; "remote_sandboxed"))]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn file_system_remove_no_follow_removes_file_and_empty_directory(
implementation: FileSystemImplementation,
sandboxed: bool,
) -> Result<()> {
let context = create_file_system_context(implementation).await?;
let file_system = context.file_system;
let tmp = TempDir::new()?;
let root = tmp.path().canonicalize()?;
let sandbox = sandboxed.then(|| workspace_write_sandbox(root.clone()));
let options = RemoveOptions {
recursive: false,
force: false,
follow_symlinks: false,
};
let file_path = root.join("remove-me.txt");
std::fs::write(&file_path, b"remove")?;
let result = file_system
.remove(
&PathUri::from_host_native_path(&file_path)?,
options,
sandbox.as_ref(),
)
.await;
#[cfg(windows)]
if is_unsupported_restricted_token_host(&result) {
return Ok(());
}
result.with_context(|| format!("mode={implementation}, sandboxed={sandboxed}"))?;
assert!(!file_path.exists());
let directory_path = root.join("remove-me");
std::fs::create_dir(&directory_path)?;
file_system
.remove(
&PathUri::from_host_native_path(&directory_path)?,
options,
sandbox.as_ref(),
)
.await
.with_context(|| format!("mode={implementation}, sandboxed={sandboxed}"))?;
assert!(!directory_path.exists());
Ok(())
}
#[test_case(FileSystemImplementation::Local ; "local")] #[test_case(FileSystemImplementation::Local ; "local")]
#[test_case(FileSystemImplementation::Remote ; "remote")] #[test_case(FileSystemImplementation::Remote ; "remote")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -16,6 +16,8 @@ use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::FileSystemSpecialPath; use codex_protocol::permissions::FileSystemSpecialPath;
use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_absolute_path::AbsolutePathBuf;
#[cfg(windows)]
use codex_utils_path_uri::PathUri;
use crate::common::exec_server::ExecServerHarness; use crate::common::exec_server::ExecServerHarness;
use crate::common::exec_server::TestCodexHelperPaths; use crate::common::exec_server::TestCodexHelperPaths;
@@ -72,6 +74,14 @@ pub(crate) async fn create_file_system_context(
} }
} }
#[cfg(windows)]
pub(crate) fn is_unsupported_restricted_token_host<T>(result: &std::io::Result<T>) -> bool {
result.as_ref().err().is_some_and(|err| {
err.to_string()
.contains("windows sandbox failed: CreateRestrictedToken failed: 87")
})
}
pub(crate) fn absolute_path(path: std::path::PathBuf) -> AbsolutePathBuf { pub(crate) fn absolute_path(path: std::path::PathBuf) -> AbsolutePathBuf {
assert!( assert!(
path.is_absolute(), path.is_absolute(),
@@ -92,6 +102,7 @@ pub(crate) fn read_only_sandbox(readable_root: std::path::PathBuf) -> FileSystem
}]) }])
} }
#[cfg(not(windows))]
pub(crate) fn workspace_write_sandbox( pub(crate) fn workspace_write_sandbox(
writable_root: std::path::PathBuf, writable_root: std::path::PathBuf,
) -> FileSystemSandboxContext { ) -> FileSystemSandboxContext {
@@ -105,6 +116,35 @@ pub(crate) fn workspace_write_sandbox(
}]) }])
} }
#[cfg(windows)]
pub(crate) fn workspace_write_sandbox(
writable_root: std::path::PathBuf,
) -> FileSystemSandboxContext {
let writable_root = absolute_path(writable_root);
// Keep the runtime policy aligned with the legacy workspace-write projection used by the
// unelevated restricted-token preflight.
let policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
FileSystemAccessMode::Read,
),
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::project_roots(/*subpath*/ None),
},
FileSystemAccessMode::Write,
),
]);
let mut sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd(
PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted),
PathUri::from_abs_path(&writable_root),
);
sandbox.windows_sandbox_level = WindowsSandboxLevel::RestrictedToken;
sandbox
}
fn sandbox_context(mut entries: Vec<FileSystemSandboxEntry>) -> FileSystemSandboxContext { fn sandbox_context(mut entries: Vec<FileSystemSandboxEntry>) -> FileSystemSandboxContext {
if cfg!(windows) { if cfg!(windows) {
// Restricted-token sandboxing cannot enforce read restrictions, so leave the root // Restricted-token sandboxing cannot enforce read restrictions, so leave the root
+58 -9
View File
@@ -20,6 +20,8 @@ use std::path::PathBuf;
use std::process::Command; use std::process::Command;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
#[cfg(target_os = "linux")]
use std::time::UNIX_EPOCH;
use anyhow::Context; use anyhow::Context;
use anyhow::Result; use anyhow::Result;
@@ -213,11 +215,18 @@ async fn file_system_operations_can_reject_symlinks_in_any_path_component(
follow_symlinks: false, follow_symlinks: false,
}; };
let uri = |path: &Path| PathUri::from_host_native_path(path); let uri = |path: &Path| PathUri::from_host_native_path(path);
#[cfg(target_os = "linux")]
let strict_sandbox = workspace_write_sandbox(tmp_path);
#[cfg(target_os = "linux")]
let sandboxes = [None, Some(&strict_sandbox)];
#[cfg(not(target_os = "linux"))]
let sandboxes: [Option<&FileSystemSandboxContext>; 1] = [None];
for sandbox in sandboxes {
assert!( assert!(
context context
.file_system .file_system
.read_file(&uri(&file_link)?, no_follow_read, /*sandbox*/ None) .read_file(&uri(&file_link)?, no_follow_read, sandbox)
.await .await
.is_err() .is_err()
); );
@@ -227,7 +236,7 @@ async fn file_system_operations_can_reject_symlinks_in_any_path_component(
.read_file( .read_file(
&uri(&directory_link.join("existing.txt"))?, &uri(&directory_link.join("existing.txt"))?,
no_follow_read, no_follow_read,
/*sandbox*/ None, sandbox,
) )
.await .await
.is_err() .is_err()
@@ -239,7 +248,7 @@ async fn file_system_operations_can_reject_symlinks_in_any_path_component(
&uri(&file_link)?, &uri(&file_link)?,
b"changed".to_vec(), b"changed".to_vec(),
no_follow_write, no_follow_write,
/*sandbox*/ None, sandbox,
) )
.await .await
.is_err() .is_err()
@@ -252,7 +261,7 @@ async fn file_system_operations_can_reject_symlinks_in_any_path_component(
&uri(&directory_link.join("existing.txt"))?, &uri(&directory_link.join("existing.txt"))?,
b"changed".to_vec(), b"changed".to_vec(),
no_follow_write, no_follow_write,
/*sandbox*/ None, sandbox,
) )
.await .await
.is_err() .is_err()
@@ -261,13 +270,13 @@ async fn file_system_operations_can_reject_symlinks_in_any_path_component(
assert!( assert!(
context context
.file_system .file_system
.get_metadata(&uri(&file_link)?, no_follow_metadata, /*sandbox*/ None) .get_metadata(&uri(&file_link)?, no_follow_metadata, sandbox)
.await .await
.is_err() .is_err()
); );
let directory_metadata = context let directory_metadata = context
.file_system .file_system
.get_metadata(&uri(&real)?, no_follow_metadata, /*sandbox*/ None) .get_metadata(&uri(&real)?, no_follow_metadata, sandbox)
.await?; .await?;
assert!(directory_metadata.is_directory); assert!(directory_metadata.is_directory);
assert!( assert!(
@@ -276,7 +285,7 @@ async fn file_system_operations_can_reject_symlinks_in_any_path_component(
.create_directory( .create_directory(
&uri(&directory_link.join("created"))?, &uri(&directory_link.join("created"))?,
no_follow_create, no_follow_create,
/*sandbox*/ None, sandbox,
) )
.await .await
.is_err() .is_err()
@@ -288,7 +297,7 @@ async fn file_system_operations_can_reject_symlinks_in_any_path_component(
.remove( .remove(
&uri(&directory_link.join("removable.txt"))?, &uri(&directory_link.join("removable.txt"))?,
no_follow_remove, no_follow_remove,
/*sandbox*/ None, sandbox,
) )
.await .await
.is_err() .is_err()
@@ -297,11 +306,12 @@ async fn file_system_operations_can_reject_symlinks_in_any_path_component(
assert!( assert!(
context context
.file_system .file_system
.remove(&uri(&file_link)?, no_follow_remove, /*sandbox*/ None) .remove(&uri(&file_link)?, no_follow_remove, sandbox)
.await .await
.is_err() .is_err()
); );
assert!(file_link.symlink_metadata()?.file_type().is_symlink()); assert!(file_link.symlink_metadata()?.file_type().is_symlink());
}
Ok(()) Ok(())
} }
@@ -329,6 +339,45 @@ async fn file_system_no_follow_non_recursive_root_creation_fails(
Ok(()) Ok(())
} }
#[cfg(target_os = "linux")]
#[test_case(FileSystemImplementation::Local ; "local")]
#[test_case(FileSystemImplementation::Remote ; "remote")]
#[tokio::test]
async fn file_system_no_follow_metadata_preserves_linux_birthtime(
implementation: FileSystemImplementation,
) -> Result<()> {
let context = create_file_system_context(implementation).await?;
let tmp = TempDir::new()?;
let file = tmp.path().join("created.txt");
std::fs::write(&file, "created")?;
let expected = match std::fs::metadata(&file)?.created() {
Ok(created) => Some(i64::try_from(
created.duration_since(UNIX_EPOCH)?.as_millis(),
)?),
Err(error) if error.kind() == std::io::ErrorKind::Unsupported => None,
Err(error) => return Err(error.into()),
};
let metadata = context
.file_system
.get_metadata(
&PathUri::from_host_native_path(&file)?,
GetMetadataOptions {
follow_symlinks: false,
},
/*sandbox*/ None,
)
.await?;
if let Some(expected) = expected {
assert!(expected > 0);
assert_eq!(metadata.created_at_ms, expected);
} else {
assert_eq!(metadata.created_at_ms, 0);
}
Ok(())
}
#[test_case(FileSystemImplementation::Local ; "local")] #[test_case(FileSystemImplementation::Local ; "local")]
#[test_case(FileSystemImplementation::Remote ; "remote")] #[test_case(FileSystemImplementation::Remote ; "remote")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -29,6 +29,8 @@ use uuid::Uuid;
use crate::support::FileSystemImplementation; use crate::support::FileSystemImplementation;
use crate::support::create_file_system_context; use crate::support::create_file_system_context;
use crate::support::is_unsupported_restricted_token_host;
use crate::support::workspace_write_sandbox;
fn create_directory_junction(target: &Path, alias: &Path) -> Result<()> { fn create_directory_junction(target: &Path, alias: &Path) -> Result<()> {
let output = Command::new("cmd") let output = Command::new("cmd")
@@ -114,66 +116,6 @@ async fn file_system_operations_can_reject_junctions_in_any_path_component(
b"unchanged" b"unchanged"
); );
let overwritten = real.join("overwritten.txt");
std::fs::write(&overwritten, "before")?;
context
.file_system
.write_file(
&uri(&overwritten)?,
b"after".to_vec(),
no_follow_write,
/*sandbox*/ None,
)
.await?;
assert_eq!(std::fs::read_to_string(&overwritten)?, "after");
let created_file = real.join("created.txt");
context
.file_system
.write_file(
&uri(&created_file)?,
b"created".to_vec(),
no_follow_write,
/*sandbox*/ None,
)
.await?;
assert_eq!(std::fs::read_to_string(&created_file)?, "created");
let nested_directory = real.join("nested").join("directory");
context
.file_system
.create_directory(
&uri(&nested_directory)?,
no_follow_create,
/*sandbox*/ None,
)
.await?;
assert!(nested_directory.is_dir());
let removed_file = real.join("removed.txt");
std::fs::write(&removed_file, "remove")?;
context
.file_system
.remove(
&uri(&removed_file)?,
no_follow_remove,
/*sandbox*/ None,
)
.await?;
assert!(!removed_file.exists());
let removed_directory = real.join("removed-directory");
std::fs::create_dir(&removed_directory)?;
context
.file_system
.remove(
&uri(&removed_directory)?,
no_follow_remove,
/*sandbox*/ None,
)
.await?;
assert!(!removed_directory.exists());
let file_link_target = real.join("file-link-target.txt"); let file_link_target = real.join("file-link-target.txt");
std::fs::write(&file_link_target, "target")?; std::fs::write(&file_link_target, "target")?;
let file_link = tmp.path().join("file-link.txt"); let file_link = tmp.path().join("file-link.txt");
@@ -275,6 +217,75 @@ async fn file_system_operations_can_reject_junctions_in_any_path_component(
.is_symlink() .is_symlink()
); );
let sandbox = workspace_write_sandbox(tmp.path().to_path_buf());
let read_result = context
.file_system
.read_file(&uri(&existing)?, no_follow_read, Some(&sandbox))
.await;
if is_unsupported_restricted_token_host(&read_result) {
return Ok(());
}
assert_eq!(read_result?, b"unchanged");
assert!(
context
.file_system
.read_file(
&uri(&directory_junction.join("existing.txt"))?,
no_follow_read,
Some(&sandbox),
)
.await
.is_err()
);
assert!(
context
.file_system
.write_file(
&uri(&directory_junction.join("existing.txt"))?,
b"changed".to_vec(),
no_follow_write,
Some(&sandbox),
)
.await
.is_err()
);
assert_eq!(std::fs::read_to_string(&existing)?, "unchanged");
assert!(
context
.file_system
.get_metadata(
&uri(&directory_junction)?,
no_follow_metadata,
Some(&sandbox),
)
.await
.is_err()
);
assert!(
context
.file_system
.create_directory(
&uri(&directory_junction.join("sandbox-created"))?,
no_follow_create,
Some(&sandbox),
)
.await
.is_err()
);
assert!(!real.join("sandbox-created").exists());
assert!(
context
.file_system
.remove(
&uri(&directory_junction.join("removable.txt"))?,
no_follow_remove,
Some(&sandbox),
)
.await
.is_err()
);
assert!(removable.exists());
Ok(()) Ok(())
} }
@@ -382,10 +393,3 @@ fn read_only_sandbox_for_cwd(cwd: std::path::PathBuf) -> Result<FileSystemSandbo
PathUri::from_host_native_path(cwd)?, PathUri::from_host_native_path(cwd)?,
)?) )?)
} }
fn is_unsupported_restricted_token_host<T>(result: &std::io::Result<T>) -> bool {
result.as_ref().err().is_some_and(|err| {
err.to_string()
.contains("windows sandbox failed: CreateRestrictedToken failed: 87")
})
}