Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(gen-ui): bind Windows fragment reads to native directories

vastsa54824dd9f48d
diff --git a/crates/host-core/src/visualizations/files/windows.rs b/crates/host-core/src/visualizations/files/windows.rs
index 1c6964727..d40f54844 100644
--- a/crates/host-core/src/visualizations/files/windows.rs
+++ b/crates/host-core/src/visualizations/files/windows.rs
@@ -1,4 +1,5 @@
use super::{read_open_file, FragmentReadError};
+use std::ffi::OsStr;
use std::fs::{self, File, OpenOptions};
use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
use std::os::windows::io::AsRawHandle;
@@ -6,89 +7,98 @@ use std::path::{Component, Path, PathBuf, Prefix};
use windows_sys::Win32::Storage::FileSystem::{
GetFileType, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS,
FILE_FLAG_OPEN_REPARSE_POINT, FILE_LIST_DIRECTORY, FILE_READ_ATTRIBUTES, FILE_SHARE_READ,
- FILE_TYPE_DISK,
+ FILE_TYPE_DISK, SYNCHRONIZE,
};
+#[path = "windows_native.rs"]
+mod native;
+
pub(super) fn read_fragment(
data_dir: &Path,
session_id: &str,
file_name: &str,
) -> Result<Vec<u8>, FragmentReadError> {
- read_fragment_impl(data_dir, session_id, file_name, || {})
+ read_fragment_impl(data_dir, session_id, file_name, |_| {})
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum DirectoryPin {
+ Data,
+ Base,
+ Session,
}
-// Private seam for share/rename tests; it cannot be supplied through the RPC.
+// Private deterministic race seam; no hook can be supplied through the RPC.
fn read_fragment_impl(
data_dir: &Path,
session_id: &str,
file_name: &str,
- after_directory_pin: impl FnOnce(),
+ mut after_directory_pin: impl FnMut(DirectoryPin),
) -> Result<Vec<u8>, FragmentReadError> {
- // std canonicalize uses the native final handle path and retains the
- // extended drive/UNC prefix. Only this trusted root may resolve aliases.
+ // Resolve aliases only for the trusted data root. From the drive/share
+ // root onwards, every component is opened relative to its parent HANDLE.
let canonical = fs::canonicalize(data_dir).map_err(|_| FragmentReadError::NotFound)?;
- let mut pins = Vec::new();
- // Pin from the volume/share root downwards, BEFORE resolving each next
- // component. Keeping just data/base/session handles would leave their
- // earlier ancestors free to be renamed or converted to junctions.
- for ancestor in directory_chain(&canonical)? {
- pins.push(open_directory(&ancestor)?);
+ let (volume, components) = directory_components(&canonical)?;
+ let mut pins = vec![open_volume(&volume)?];
+ for component in components {
+ pin_directory(&mut pins, component)?;
}
- let base = canonical.join("visualizations");
- pins.push(open_directory(&base)?);
- let session = base.join(session_id);
- pins.push(open_directory(&session)?);
- after_directory_pin();
+ after_directory_pin(DirectoryPin::Data);
+ pin_directory(&mut pins, OsStr::new("visualizations"))?;
+ after_directory_pin(DirectoryPin::Base);
+ pin_directory(&mut pins, OsStr::new(session_id))?;
+ after_directory_pin(DirectoryPin::Session);
- // All ancestors now deny write/delete sharing. Absolute resolution cannot
- // be redirected while they are held. The leaf denies those shares too,
- // including when a writable/deletable attacker handle already exists.
- let leaf = OpenOptions::new()
- .read(true)
- .share_mode(FILE_SHARE_READ)
- .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
- .open(session.join(file_name))
- .map_err(|_| FragmentReadError::NotFound)?;
- let metadata = leaf.metadata().map_err(|_| FragmentReadError::NotFound)?;
- if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
- || !metadata.is_file()
- || !is_disk(&leaf)
- {
- return Err(FragmentReadError::NotFound);
- }
+ // Share masks alone are not capabilities: FILE_WRITE_ATTRIBUTES can set
+ // reparse data even while read pins are held. Never reopen an absolute
+ // child path; RootDirectory binds the leaf to the actual session object.
+ let session = pins.last().ok_or(FragmentReadError::NotFound)?;
+ let leaf = native::open_child(session, OsStr::new(file_name), false)?;
+ validate_entry(&leaf, false)?;
let result = read_open_file(leaf);
- // Explicitly keep every directory capability alive THROUGH the read.
drop(pins);
result
}
-fn open_directory(path: &Path) -> Result<File, FragmentReadError> {
+fn pin_directory(pins: &mut Vec<File>, name: &OsStr) -> Result<(), FragmentReadError> {
+ let parent = pins.last().ok_or(FragmentReadError::NotFound)?;
+ let child = native::open_child(parent, name, true)?;
+ validate_entry(&child, true)?;
+ pins.push(child);
+ Ok(())
+}
+
+// The sole absolute open is the trusted canonical drive/share root, not any
+// mutable directory entry below it. Owned entries are all native-relative.
+fn open_volume(path: &Path) -> Result<File, FragmentReadError> {
let file = OpenOptions::new()
- .read(true)
- // Attribute-only opens do not participate in Windows share-access
- // accounting. LIST_DIRECTORY (the directory READ_DATA bit) makes
- // this a real read pin that excludes existing/future writers/deleters.
- .access_mode(FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES)
+ .access_mode(FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | SYNCHRONIZE)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)
.map_err(|_| FragmentReadError::NotFound)?;
+ validate_entry(&file, true)?;
+ Ok(file)
+}
+
+fn validate_entry(file: &File, directory: bool) -> Result<(), FragmentReadError> {
let metadata = file.metadata().map_err(|_| FragmentReadError::NotFound)?;
- if !metadata.is_dir()
+ // SAFETY: File owns a live Windows handle for the duration of this call.
+ let disk = unsafe { GetFileType(file.as_raw_handle()) == FILE_TYPE_DISK };
+ if !disk
|| metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
- || !is_disk(&file)
+ || if directory {
+ !metadata.is_dir()
+ } else {
+ !metadata.is_file()
+ }
{
return Err(FragmentReadError::NotFound);
}
- Ok(file)
+ Ok(())
}
-fn is_disk(file: &File) -> bool {
- // SAFETY: File owns a live Windows handle for the duration of this call.
- unsafe { GetFileType(file.as_raw_handle()) == FILE_TYPE_DISK }
-}
-
-fn directory_chain(canonical: &Path) -> Result<Vec<PathBuf>, FragmentReadError> {
+fn directory_components(canonical: &Path) -> Result<(PathBuf, Vec<&OsStr>), FragmentReadError> {
let mut components = canonical.components();
let prefix = match components.next() {
Some(Component::Prefix(prefix))
@@ -104,17 +114,16 @@ fn directory_chain(canonical: &Path) -> Result<Vec<PathBuf>, FragmentReadError>
if components.next() != Some(Component::RootDir) {
return Err(FragmentReadError::NotFound);
}
- let mut current = PathBuf::from(prefix.as_os_str());
- current.push(Component::RootDir.as_os_str());
- let mut chain = vec![current.clone()];
+ let mut volume = PathBuf::from(prefix.as_os_str());
+ volume.push(Component::RootDir.as_os_str());
+ let mut names = Vec::new();
for component in components {
- if !matches!(component, Component::Normal(_)) {
+ let Component::Normal(name) = component else {
return Err(FragmentReadError::NotFound);
- }
- current.push(component.as_os_str());
- chain.push(current.clone());
+ };
+ names.push(name);
}
- Ok(chain)
+ Ok((volume, names))
}
#[cfg(test)]
diff --git a/crates/host-core/src/visualizations/files/windows_native.rs b/crates/host-core/src/visualizations/files/windows_native.rs
new file mode 100644
index 000000000..b8bc9f7ad
--- /dev/null
+++ b/crates/host-core/src/visualizations/files/windows_native.rs
@@ -0,0 +1,206 @@
+//! The documented NtCreateFile RootDirectory contract is Windows' native
+//! directory-relative open. No DOS child path or reopened ancestor is used.
+
+use super::FragmentReadError;
+use std::ffi::{c_void, OsStr};
+use std::fs::File;
+use std::mem::size_of;
+use std::os::windows::ffi::OsStrExt;
+use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
+use windows_sys::Win32::Foundation::{
+ HANDLE, INVALID_HANDLE_VALUE, NTSTATUS, OBJ_CASE_INSENSITIVE, OBJ_DONT_REPARSE, UNICODE_STRING,
+};
+use windows_sys::Win32::Storage::FileSystem::{
+ FILE_LIST_DIRECTORY, FILE_READ_ATTRIBUTES, FILE_READ_DATA, FILE_SHARE_READ, SYNCHRONIZE,
+};
+
+const FILE_OPEN: u32 = 1;
+const FILE_DIRECTORY_FILE: u32 = 0x0000_0001;
+const FILE_NON_DIRECTORY_FILE: u32 = 0x0000_0040;
+const FILE_SYNCHRONOUS_IO_NONALERT: u32 = 0x0000_0020;
+const FILE_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
+
+// winternl OBJECT_ATTRIBUTES / IO_STATUS_BLOCK layouts. The existing Cargo
+// features expose UNICODE_STRING but not Wdk::Foundation or System::IO. The
+// optional security fields really are PVOID in this contract and stay null;
+// user-mode opens still enforce the caller's normal access token and ACLs.
+#[repr(C)]
+struct ObjectAttributes {
+ length: u32,
+ root_directory: HANDLE,
+ object_name: *const UNICODE_STRING,
+ attributes: u32,
+ security_descriptor: *const c_void,
+ security_quality_of_service: *const c_void,
+}
+
+#[repr(C)]
+union IoStatus {
+ status: NTSTATUS,
+ pointer: *mut c_void,
+}
+
+#[repr(C)]
+struct IoStatusBlock {
+ result: IoStatus,
+ information: usize,
+}
+
+#[link(name = "ntdll")]
+unsafe extern "system" {
+ #[link_name = "NtCreateFile"]
+ fn nt_create_file(
+ file_handle: *mut HANDLE,
+ desired_access: u32,
+ object_attributes: *const ObjectAttributes,
+ io_status_block: *mut IoStatusBlock,
+ allocation_size: *const i64,
+ file_attributes: u32,
+ share_access: u32,
+ create_disposition: u32,
+ create_options: u32,
+ ea_buffer: *const c_void,
+ ea_length: u32,
+ ) -> NTSTATUS;
+}
+
+pub(super) fn open_child(
+ parent: &File,
+ name: &OsStr,
+ directory: bool,
+) -> Result<File, FragmentReadError> {
+ let mut wide = component_name(name)?;
+ let length = u16::try_from(wide.len() * 2).map_err(|_| FragmentReadError::NotFound)?;
+ let maximum_length = length.checked_add(2).ok_or(FragmentReadError::NotFound)?;
+ wide.push(0);
+ let unicode = UNICODE_STRING {
+ Length: length,
+ MaximumLength: maximum_length,
+ Buffer: wide.as_mut_ptr(),
+ };
+ let attributes = ObjectAttributes {
+ length: size_of::<ObjectAttributes>() as u32,
+ root_directory: parent.as_raw_handle(),
+ object_name: &unicode,
+ attributes: OBJ_CASE_INSENSITIVE | OBJ_DONT_REPARSE,
+ security_descriptor: std::ptr::null(),
+ security_quality_of_service: std::ptr::null(),
+ };
+ let mut io_status = IoStatusBlock {
+ result: IoStatus {
+ pointer: std::ptr::null_mut(),
+ },
+ information: 0,
+ };
+ let mut handle: HANDLE = std::ptr::null_mut();
+ let desired_access = FILE_READ_ATTRIBUTES
+ | SYNCHRONIZE
+ | if directory {
+ FILE_LIST_DIRECTORY
+ } else {
+ FILE_READ_DATA
+ };
+ let options = FILE_OPEN_REPARSE_POINT
+ | FILE_SYNCHRONOUS_IO_NONALERT
+ | if directory {
+ FILE_DIRECTORY_FILE
+ } else {
+ FILE_NON_DIRECTORY_FILE
+ };
+ // SAFETY: parent is a live directory File, the single-component UTF-16
+ // name and all repr(C) arguments live through the synchronous create.
+ // FILE_OPEN never creates/truncates; SYNCHRONIZE is paired with synchronous
+ // I/O. OBJ_DONT_REPARSE rejects reparsing and OPEN_REPARSE_POINT forbids
+ // following the final entry; the caller also checks opened-handle metadata.
+ let status = unsafe {
+ nt_create_file(
+ &mut handle,
+ desired_access,
+ &attributes,
+ &mut io_status,
+ std::ptr::null(),
+ 0,
+ FILE_SHARE_READ,
+ FILE_OPEN,
+ options,
+ std::ptr::null(),
+ 0,
+ )
+ };
+ // Immediately own any returned handle, even on a failure status, so all
+ // later early returns close it. NtCreateFile initializes no handle on
+ // failed opens; the output was initialized to null before the call.
+ let owned = if handle.is_null() || handle == INVALID_HANDLE_VALUE {
+ None
+ } else {
+ // SAFETY: NtCreateFile returned a new, exclusively owned HANDLE.
+ Some(unsafe { OwnedHandle::from_raw_handle(handle) })
+ };
+ // NT_SUCCESS is status >= 0. Native failures are NTSTATUS, not GetLastError.
+ if status < 0 {
+ return Err(FragmentReadError::NotFound);
+ }
+ owned.map(File::from).ok_or(FragmentReadError::NotFound)
+}
+
+fn component_name(name: &OsStr) -> Result<Vec<u16>, FragmentReadError> {
+ let wide: Vec<u16> = name.encode_wide().collect();
+ if wide.is_empty()
+ || name == "."
+ || name == ".."
+ || wide.iter().any(|unit| matches!(*unit, 0 | 47 | 58 | 92))
+ || wide.len() > (u16::MAX as usize - 2) / 2
+ {
+ return Err(FragmentReadError::NotFound);
+ }
+ Ok(wide)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::mem::{align_of, offset_of};
+
+ #[test]
+ fn native_binding_layout_matches_winternl() {
+ let pointer = size_of::<HANDLE>();
+ assert_eq!(size_of::<UNICODE_STRING>(), pointer * 2);
+ assert_eq!(size_of::<ObjectAttributes>(), pointer * 6);
+ assert_eq!(align_of::<ObjectAttributes>(), pointer);
+ assert_eq!(offset_of!(ObjectAttributes, root_directory), pointer);
+ assert_eq!(offset_of!(ObjectAttributes, object_name), pointer * 2);
+ assert_eq!(offset_of!(ObjectAttributes, attributes), pointer * 3);
+ assert_eq!(
+ offset_of!(ObjectAttributes, security_descriptor),
+ pointer * 4
+ );
+ assert_eq!(
+ offset_of!(ObjectAttributes, security_quality_of_service),
+ pointer * 5
+ );
+ assert_eq!(size_of::<IoStatusBlock>(), pointer * 2);
+ assert_eq!(align_of::<IoStatusBlock>(), pointer);
+ assert_eq!(offset_of!(IoStatusBlock, information), pointer);
+ }
+
+ #[test]
+ fn relative_native_names_cannot_reach_another_directory_or_stream() {
+ for name in [
+ "",
+ ".",
+ "..",
+ "a/b",
+ "a\\b",
+ "C:child",
+ "chart.html:stream",
+ "a\0b",
+ ] {
+ assert_eq!(
+ component_name(OsStr::new(name)),
+ Err(FragmentReadError::NotFound)
+ );
+ }
+ assert!(component_name(OsStr::new("a folder")).is_ok());
+ assert!(component_name(OsStr::new("chart.html")).is_ok());
+ }
+}
diff --git a/crates/host-core/src/visualizations/files/windows_tests.rs b/crates/host-core/src/visualizations/files/windows_tests.rs
index e3e7a8380..56961061a 100644
--- a/crates/host-core/src/visualizations/files/windows_tests.rs
+++ b/crates/host-core/src/visualizations/files/windows_tests.rs
@@ -1,16 +1,16 @@
use super::super::tests::{fixture, FILE_NAME, ORIGINAL, SESSION, VICTIM};
use super::super::{read_fragment, FragmentReadError};
-use super::{directory_chain, read_fragment_impl};
-use std::ffi::c_void;
+use super::{directory_components, read_fragment_impl, DirectoryPin};
+use std::ffi::{c_void, OsStr};
use std::fs::{self, File, OpenOptions};
use std::io;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::fs::{symlink_file, MetadataExt, OpenOptionsExt};
use std::os::windows::io::AsRawHandle;
use std::os::windows::process::CommandExt;
-use std::path::{Component, Path, PathBuf, Prefix};
+use std::path::{Component, Path, Prefix};
use std::process::Command;
-use windows_sys::Win32::Foundation::{ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION, GENERIC_WRITE};
+use windows_sys::Win32::Foundation::{ERROR_SHARING_VIOLATION, GENERIC_WRITE};
use windows_sys::Win32::Storage::FileSystem::{
DELETE, FILE_APPEND_DATA, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS,
FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
@@ -142,32 +142,28 @@ fn junction_command_paths_convert_verbatim_drive_and_unc_spelling() {
#[test]
fn extended_drive_and_unc_paths_keep_their_root_components() {
+ let (drive, names) =
+ directory_components(Path::new(r"\\?\C:\Users\example\data")).expect("drive components");
+ assert_eq!(drive, Path::new(r"\\?\C:\"));
assert_eq!(
- directory_chain(Path::new(r"\\?\C:\Users\example\data")).expect("drive chain"),
+ names,
[
- PathBuf::from(r"\\?\C:\"),
- PathBuf::from(r"\\?\C:\Users"),
- PathBuf::from(r"\\?\C:\Users\example"),
- PathBuf::from(r"\\?\C:\Users\example\data"),
- ]
- );
- assert_eq!(
- directory_chain(Path::new(r"\\?\UNC\server\share\data")).expect("UNC chain"),
- [
- PathBuf::from(r"\\?\UNC\server\share\"),
- PathBuf::from(r"\\?\UNC\server\share\data"),
+ OsStr::new("Users"),
+ OsStr::new("example"),
+ OsStr::new("data")
]
);
+ let (share, names) =
+ directory_components(Path::new(r"\\?\UNC\server\share\data")).expect("UNC components");
+ assert_eq!(share, Path::new(r"\\?\UNC\server\share\"));
+ assert_eq!(names, [OsStr::new("data")]);
for path in [
r"C:\data",
r"C:data",
r"\\.\pipe\data",
r"\\?\C:\data\..\other",
] {
- assert_eq!(
- directory_chain(Path::new(path)),
- Err(FragmentReadError::NotFound)
- );
+ assert!(directory_components(Path::new(path)).is_err());
}
}
@@ -264,7 +260,10 @@ fn pins_data_ancestors_base_and_session_until_read_completes() {
drop(open_directory_access(path, access).expect("unpinned mutable directory"));
}
}
- let result = read_fragment_impl(&fixture.data, SESSION, FILE_NAME, || {
+ let result = read_fragment_impl(&fixture.data, SESSION, FILE_NAME, |stage| {
+ if stage != DirectoryPin::Session {
+ return;
+ }
for path in paths {
let replacement = path.with_file_name("rename-attempt");
assert!(
@@ -314,51 +313,97 @@ fn refuses_preexisting_write_or_delete_directory_handles() {
}
#[test]
-fn pins_block_native_junction_mutation_and_release_after_read() {
+fn relative_leaf_open_survives_attribute_only_session_junction_mutation() {
let fixture = fixture();
fs::remove_file(fixture.session.join(FILE_NAME)).expect("empty original session");
let victim = fixture.data.join("visualizations").join("session-B");
fs::create_dir(&victim).expect("victim session");
fs::write(victim.join(FILE_NAME), VICTIM).expect("victim fragment");
- let result = read_fragment_impl(&fixture.data, SESSION, FILE_NAME, || {
- // Attribute-only handles bypass the share mask, but must not be able
- // to set a reparse point through an actual, well-formed native FSCTL.
- let attributes = open_directory_access(&fixture.session, FILE_WRITE_ATTRIBUTES)
- .expect("attribute-only handle");
- set_junction(&attributes, &victim).expect_err("attributes cannot redirect pinned session");
- drop(attributes);
- let error = open_directory_access(&fixture.session, GENERIC_WRITE)
- .expect_err("junction mutation requires blocked write access");
- assert_eq!(error.raw_os_error(), Some(ERROR_SHARING_VIOLATION as i32));
- let held = fixture.session.with_file_name("held-session");
- fs::rename(&fixture.session, &held).expect_err("pinned session cannot be replaced");
- });
- assert_eq!(result, Err(FragmentReadError::NotFound));
- let metadata = fs::symlink_metadata(&fixture.session).expect("original session metadata");
- assert!(metadata.is_dir());
- assert_eq!(metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT, 0);
+ assert_attribute_junction_attack_contained(
+ &fixture.data,
+ &fixture.session,
+ &victim,
+ DirectoryPin::Session,
+ );
+ assert_eq!(
+ fs::read(victim.join(FILE_NAME)).expect("intact victim"),
+ VICTIM
+ );
+}
- // Control on the same now-unpinned, empty directory: attributes alone
- // lack mutation rights, whereas a writable handle really can redirect it.
- let attributes = open_directory_access(&fixture.session, FILE_WRITE_ATTRIBUTES)
- .expect("unpinned attribute-only handle");
- let error =
- set_junction(&attributes, &victim).expect_err("reparse FSCTL requires write access");
- assert_eq!(error.raw_os_error(), Some(ERROR_ACCESS_DENIED as i32));
- drop(attributes);
- let writable = open_directory_access(&fixture.session, GENERIC_WRITE)
- .expect("unpinned junction mutation handle");
- set_junction(&writable, &victim).expect("unpinned native junction control");
- drop(writable);
+#[test]
+fn relative_session_open_survives_attribute_only_base_junction_mutation() {
+ let fixture = fixture();
+ fs::remove_dir_all(&fixture.session).expect("empty original base");
+ let base = fixture.data.join("visualizations");
+ let victim = fixture.temp.path().join("victim-base");
+ fs::create_dir_all(victim.join(SESSION)).expect("victim base");
+ fs::write(victim.join(SESSION).join(FILE_NAME), VICTIM).expect("victim fragment");
+ assert_attribute_junction_attack_contained(&fixture.data, &base, &victim, DirectoryPin::Base);
assert_eq!(
- fs::read(fixture.session.join(FILE_NAME)).expect("attack control"),
+ fs::read(victim.join(SESSION).join(FILE_NAME)).expect("intact victim"),
VICTIM
);
+}
+
+#[test]
+fn relative_base_open_survives_attribute_only_data_ancestor_junction_mutation() {
+ let fixture = fixture();
+ fs::remove_dir_all(fixture.data.join("visualizations")).expect("empty original data");
+ let victim = fixture.temp.path().join("victim-data");
+ let victim_session = victim.join("visualizations").join(SESSION);
+ fs::create_dir_all(&victim_session).expect("victim data");
+ fs::write(victim_session.join(FILE_NAME), VICTIM).expect("victim fragment");
+ assert_attribute_junction_attack_contained(
+ &fixture.data,
+ &fixture.data,
+ &victim,
+ DirectoryPin::Data,
+ );
assert_eq!(
- read_fragment(&fixture.data, SESSION, FILE_NAME),
- Err(FragmentReadError::NotFound)
+ fs::read(victim_session.join(FILE_NAME)).expect("intact victim"),
+ VICTIM
);
- fs::remove_dir(&fixture.session).expect("remove native junction");
+}
+
+fn assert_attribute_junction_attack_contained(
+ data: &Path,
+ directory: &Path,
+ victim: &Path,
+ stage: DirectoryPin,
+) {
+ let exposed_leaf = data.join("visualizations").join(SESSION).join(FILE_NAME);
+ let mut attacked = false;
+ let result = read_fragment_impl(data, SESSION, FILE_NAME, |current| {
+ if current != stage {
+ return;
+ }
+ let attributes = open_directory_access(directory, FILE_WRITE_ATTRIBUTES)
+ .expect("attribute-only attacker handle while read pins are held");
+ // Windows CI proves this succeeds despite read/delete share pins.
+ // Preserve that mutation as a positive control, not a denial assumption.
+ set_junction(&attributes, victim).expect("attribute-only junction mutation succeeds");
+ drop(attributes);
+ attacked = true;
+ let metadata = fs::symlink_metadata(directory).expect("mutated directory metadata");
+ assert_ne!(metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT, 0);
+ let old_absolute = OpenOptions::new()
+ .read(true)
+ .share_mode(FILE_SHARE_READ)
+ .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
+ .open(&exposed_leaf)
+ .expect("old absolute leaf open, including its no-follow/share flags");
+ assert_eq!(
+ super::super::read_open_file(old_absolute)
+ .expect("old bounded absolute lookup control"),
+ VICTIM
+ );
+ });
+ assert!(attacked, "the real filesystem mutation hook must have run");
+ // The original pinned directory was empty. A relative open must fail;
+ // the old absolute lookup above demonstrably reads the victim instead.
+ assert_eq!(result, Err(FragmentReadError::NotFound));
+ fs::remove_dir(directory).expect("remove only the attack junction after pins release");
}
#[test]
diff --git a/docs/adr/gen-ui-inline-visualization.md b/docs/adr/gen-ui-inline-visualization.md
index f437e6303..0b8b2f56d 100644
--- a/docs/adr/gen-ui-inline-visualization.md
+++ b/docs/adr/gen-ui-inline-visualization.md
@@ -108,9 +108,13 @@ fallback for older messages.
`visualizations.readFragment` RPC returns bounded base64 bytes for a session
and filename only. Unix Host Core opens base/session/leaf relative to pinned
directory descriptors with no-follow flags and a nonblocking leaf. Windows
- pins the full canonical directory chain without write/delete sharing and
- rejects reparse points. Ancestor rename or ABA replacement cannot redirect
- the leaf to another session. No renderer IPC or Plugin SDK surface is added.
+ opens every canonical ancestor and owned child through `NtCreateFile` with
+ `RootDirectory`, retaining handles through the bounded leaf read. It rejects
+ reparse entries and keeps read-only share masks as additional defense, not
+ the security boundary: attribute handles can mutate reparse points despite
+ those masks. Relative opens stay bound to the pinned directory objects.
+ Ancestor rename, attribute-junction mutation, or ABA cannot redirect the leaf.
+ No renderer IPC or Plugin SDK surface is added.
This replaces path snapshots, which cannot establish an atomic directory
capability. Main validates the private reply before constructing the shell.
4. Main wraps the fragment in a host shell: the kit stylesheet
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index d0c105252..7c33922f9 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -326,9 +326,10 @@ visualization lives as long as its session:
the fragment in a host shell with a strict CSP.
Both the iframe and the response CSP header enforce `sandbox allow-scripts`,
so omitting the caller's sandbox cannot enable cross-session DOM reads.
- Unix uses relative `openat` and a nonblocking leaf; Windows holds the ancestor
- chain without write/delete sharing and rejects reparse points. Directory
- replacement/restoration cannot redirect serving to a different session.
+ Unix uses relative `openat` and a nonblocking leaf; Windows uses relative
+ `NtCreateFile` directory handles, rejects reparse entries, and keeps share
+ restrictions as an additional defense. Attribute-only junction mutation or
+ directory replacement/restoration cannot redirect serving to another session.
Fetches, frames, forms, and remote assets are blocked. WebRTC ICE remains
the explicitly documented v1 residual channel (see the ADR).
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index a2fc6f024..63e5c4c2a 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -342,9 +342,11 @@ to later refresh and inference; the vendor picker does not collect them.
is added. Parameters contain only a validated session ID and direct `.html`
basename; caller-supplied roots and extra fields are rejected. Host resolves
against its current data directory and pins native directory capabilities:
- Unix uses relative `openat` with no-follow/nonblocking flags; Windows pins the
- complete ancestor chain without write/delete sharing and refuses reparse
- points. Returns `{ ok: true, base64 }` for at most 2 MiB of file bytes, or
+ Unix uses relative `openat` with no-follow/nonblocking flags; Windows uses
+ `NtCreateFile` with a pinned `RootDirectory` for every ancestor/owned child
+ and refuses opened reparse entries. Share masks are an extra defense, not a
+ substitute for relative capabilities. Returns `{ ok: true, base64 }` for at
+ most 2 MiB of file bytes, or
`{ ok: false, code: "not-found" | "too-large" }`. Main validates this payload,
decodes bytes, rejects full HTML documents, and supplies the response sandbox.
Filesystem work does not hold the state/database lock. Additive to v11; no