From 958a7608f700d35471a024a90ae082a4de62e9f8 Mon Sep 17 00:00:00 2001 From: Nicholas023 <498594526@qq.com> Date: Thu, 19 Nov 2026 04:51:16 +0800 Subject: [PATCH 1/3] fix(files): diagnose Electron archive member paths (#836) --- native/crates/ops-files/src/file_path.rs | 29 ++++++++++- .../crates/ops-files/src/file_path_tests.rs | 43 ++++++++++++++++ test/file-asar-path.test.mjs | 51 +++++++++++++++++++ 3 files changed, 122 insertions(+), 1 deletion(-) create mode 100644 test/file-asar-path.test.mjs diff --git a/native/crates/ops-files/src/file_path.rs b/native/crates/ops-files/src/file_path.rs index eaa4e36e..64a55d74 100644 --- a/native/crates/ops-files/src/file_path.rs +++ b/native/crates/ops-files/src/file_path.rs @@ -83,7 +83,27 @@ pub fn checked_leaf(raw: &str, allow_missing: bool) -> Result { let mut parent = Dir::open_ambient_dir(&anchor, ambient_authority())?; let name = names.pop().unwrap_or_else(|| ".".into()); for component in names { - regular(&parent.symlink_metadata(&component)?, true)?; + let metadata = parent.symlink_metadata(&component)?; + if regular(&metadata, true).is_err() + && metadata.is_file() + && asar_archive(&component) + { + // #836: Electron presents .asar archives as directories only through + // its own patched in-process filesystem. The standalone worker sees + // a regular file, so a member path can never resolve; name the + // archive instead of implying a no-follow bypass. + return Err(Failure::new( + "ARCHIVE_MEMBER_UNSUPPORTED", + format!( + "Path routes inside '{component}': an Electron .asar archive is a \ + virtual directory only for its host process; this standalone \ + worker cannot read archive members. Inspect the archive file \ + itself (hex view) or use an unpacked copy; no other tool here \ + can open it either." + ), + )); + } + regular(&metadata, true)?; parent = parent.open_dir_nofollow(&component)?; } regular(&parent.dir_metadata()?, true)?; @@ -115,6 +135,13 @@ pub fn validate_name(name: &str) -> Result<()> { ops_protocol::windows_paths::validate_name(name)?; Ok(()) } +/// Electron's asar archive spelling: a regular file whose name ends in ".asar". +/// A directory with the same spelling stays an ordinary directory. +fn asar_archive(name: &str) -> bool { + let bytes = name.as_bytes(); + bytes.len() >= 5 && bytes[bytes.len() - 5..].eq_ignore_ascii_case(b".asar") +} + pub fn link(metadata: &Metadata) -> bool { if metadata.file_type().is_symlink() { return true; diff --git a/native/crates/ops-files/src/file_path_tests.rs b/native/crates/ops-files/src/file_path_tests.rs index a66a84bb..3ac68447 100644 --- a/native/crates/ops-files/src/file_path_tests.rs +++ b/native/crates/ops-files/src/file_path_tests.rs @@ -36,3 +36,46 @@ fn near_audit_names_are_not_reserved_components() { crate::paths::relative(name).unwrap(); } } + +#[test] +fn asar_file_components_are_archive_members_not_traversal_bypasses() { + let root = std::env::temp_dir().join(format!("dsh-ops-asar-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&root).unwrap(); + std::fs::write(root.join("bundle.asar"), b"archive bytes").unwrap(); + // #836: Electron presents a real .asar FILE as a directory only through its + // own patched filesystem; the worker names the archive member instead of + // implying a no-follow bypass. + let failure = match checked_leaf(root.join("bundle.asar").join("app.js").to_str().unwrap(), true) + { + Err(failure) => failure, + Ok(_) => panic!("a file component must not become a traversable directory"), + }; + assert_eq!(failure.code, "ARCHIVE_MEMBER_UNSUPPORTED"); + assert!(failure.message.contains("bundle.asar"), "{}", failure.message); + // A genuine directory keeps working: the .asar spelling is not reserved. + std::fs::create_dir(root.join("folder.asar")).unwrap(); + std::fs::write(root.join("folder.asar").join("inner.js"), b"real").unwrap(); + let directory = checked_leaf( + root.join("folder.asar").join("inner.js").to_str().unwrap(), + false, + ) + .unwrap(); + assert_eq!(directory.name, "inner.js"); + // A plain file component that is not an archive keeps the traversal refusal. + std::fs::write(root.join("readme.txt"), b"text").unwrap(); + let plain = match checked_leaf( + root.join("readme.txt").join("inner.js").to_str().unwrap(), + true, + ) { + Err(failure) => failure, + Ok(_) => panic!("a plain file must not become a traversable directory"), + }; + assert_eq!(plain.code, "PATH_RESTRICTED"); + // The archive itself stays a readable regular file. + let archive = checked_leaf(root.join("bundle.asar").to_str().unwrap(), false).unwrap(); + assert_eq!(archive.name, "bundle.asar"); + // The Targets hold directory handles on Windows; drop them before removing. + drop(directory); + drop(archive); + std::fs::remove_dir_all(&root).unwrap(); +} diff --git a/test/file-asar-path.test.mjs b/test/file-asar-path.test.mjs new file mode 100644 index 00000000..586737f9 --- /dev/null +++ b/test/file-asar-path.test.mjs @@ -0,0 +1,51 @@ +/** #836: a path that routes through a real .asar FILE is a virtual directory + * only inside Electron's own patched filesystem. The standalone worker cannot read + * archive members, so the refusal must say exactly that instead of a generic + * no-follow PATH_RESTRICTED. A genuine directory named *.asar keeps traversing. */ +import fs from 'node:fs' +import path from 'node:path' +import { assert, test, report, withTempDir } from './lib/harness.mjs' +import { callTool, envelopeOf, requireWorker } from './lib/boundary.mjs' +requireWorker('file-asar-path') +const call = async (tool, args, root, options = {}) => + envelopeOf(await callTool(tool, args, { root, readOnly: true, ...options }), assert) + +await test('an .asar file component is an archive member, not a traversal bypass', async () => { + await withTempDir('file-asar-path', async root => { + fs.writeFileSync(path.join(root, 'bundle.asar'), Buffer.from([4, 0, 0, 0, 16, 0, 0, 0, 0xde, 0xad, 0xbe, 0xef])) + const inside = await call('inspect_local_file', { path: path.join(root, 'bundle.asar', 'app.js'), limit: 5 }, root) + assert.equal(inside.error?.code, 'ARCHIVE_MEMBER_UNSUPPORTED', JSON.stringify(inside)) + assert.match(inside.error.message, /bundle\.asar/) + assert.match(inside.error.message, /archive/i) + assert.equal(inside.error.effectState, 'none') + // A real directory keeps working: nothing about the .asar spelling is reserved. + fs.mkdirSync(path.join(root, 'folder.asar')) + fs.writeFileSync(path.join(root, 'folder.asar', 'inner.js'), 'real') + const directory = await call('inspect_local_file', { path: path.join(root, 'folder.asar', 'inner.js'), limit: 5 }, root) + assert.equal(directory.error, undefined, JSON.stringify(directory)) + assert.equal(directory.items[0].text, 'real') + // A non-archive file component keeps the ordinary traversal refusal. + fs.writeFileSync(path.join(root, 'readme.txt'), 'text') + const plain = await call('inspect_local_file', { path: path.join(root, 'readme.txt', 'inner.js'), limit: 5 }, root) + assert.equal(plain.error?.code, 'PATH_RESTRICTED', JSON.stringify(plain)) + // The archive itself stays readable as a regular binary file. + const hex = await call('inspect_local_file', { path: path.join(root, 'bundle.asar'), view: 'hex', limit: 2 }, root) + assert.equal(hex.error, undefined, JSON.stringify(hex)) + assert.equal(hex.items.length, 1) + }) +}) + +await test('the installed host archive is diagnosed the same way', async () => { + await withTempDir('file-asar-host', async root => { + const archive = 'D:\\deepseek_harness\\resources\\app.asar' + if (!fs.existsSync(archive)) { + console.log(' (host archive absent on this machine; live-host assertion not run)') + return + } + const body = await call('inspect_local_file', { path: path.join(archive, 'dsh', 'package.json'), limit: 5 }, root) + assert.equal(body.error?.code, 'ARCHIVE_MEMBER_UNSUPPORTED', JSON.stringify(body)) + assert.match(body.error.message, /app\.asar/) + }) +}) + +report('file-asar-path') From 126cfd0f57cf650b05ea4c8222f97e9b245df765 Mon Sep 17 00:00:00 2001 From: Nicholas023 <498594526@qq.com> Date: Thu, 19 Nov 2026 04:51:16 +0800 Subject: [PATCH 2/3] fix(windows): preserve restorable extended attributes (#874) --- native/windows-metadata/src/ea.rs | 387 +++++++++++++++++++++++++++++ native/windows-metadata/src/lib.rs | 190 ++++++++++++-- 2 files changed, 553 insertions(+), 24 deletions(-) create mode 100644 native/windows-metadata/src/ea.rs diff --git a/native/windows-metadata/src/ea.rs b/native/windows-metadata/src/ea.rs new file mode 100644 index 00000000..09ab5621 --- /dev/null +++ b/native/windows-metadata/src/ea.rs @@ -0,0 +1,387 @@ +//! Bounded NTFS extended-attribute capture, restore and verification. +//! +//! Kernel EA names (the "$KERNEL." prefix, e.g. EFS's PurgeEFSProxyCache or +//! SmartLocker tags) are written by kernel components and cannot be recreated +//! from user mode. They are captured as names and reported per name in the +//! publication warnings; nothing is silently dropped (#874). Every other EA +//! is captured byte-exactly, restored on the staged file and re-verified +//! after restore; a mismatch, an unreadable or an unsettable set aborts +//! publication. + +use super::{IoStatus, nt_error, unsupported}; +use std::{ + ffi::c_void, + fs::File, + io, + os::windows::io::AsRawHandle, + ptr::{null, null_mut}, +}; +use windows_sys::Win32::Foundation::HANDLE; + +/// One bounded capture budget, matching the named-stream capture in lib.rs. +pub const MAX_EA_BYTES: usize = 64 * 1024; +pub const MAX_EA_ENTRIES: usize = 4096; +/// The kernel-mode EA name prefix; user-mode NtSetEaFile refuses these names. +const KERNEL_EA_PREFIX: &[u8] = b"$kernel."; +const FILE_EA_INFORMATION: u32 = 7; +const NO_MORE_EAS: i32 = 0xC000_191u32 as i32; +const BUFFER_OVERFLOW: i32 = 0x8000_0005u32 as i32; + +#[link(name = "ntdll")] +unsafe extern "system" { + fn NtQueryEaFile( + handle: HANDLE, + status: *mut IoStatus, + buffer: *mut c_void, + length: u32, + return_single_entry: u8, + ea_list: *const c_void, + ea_list_length: u32, + ea_index: *mut u32, + restart_scan: u8, + ) -> i32; + fn NtSetEaFile( + handle: HANDLE, + status: *mut IoStatus, + buffer: *const c_void, + length: u32, + ) -> i32; +} + +/// One FILE_FULL_EA_INFORMATION entry, in a canonical owned spelling. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EaEntry { + pub flags: u8, + pub name: Vec, + pub value: Vec, +} + +#[derive(Default, Debug)] +pub struct CapturedEas { + /// Restorable entries only; kernel names never reach a set call. + pub entries: Vec, + /// Names of kernel-owned EAs, reported as unpreservable evidence. + pub kernel: Vec>, +} + +impl CapturedEas { + /// Warnings state exactly what will not be preserved, before anything is + /// written, so a caller can stop instead of silently losing metadata. + pub fn warnings(&self) -> Vec { + self.kernel + .iter() + .map(|name| { + format!( + "Kernel extended attribute '{}' is owned by a kernel component \ + and cannot be restored from user mode; not preserved", + String::from_utf8_lossy(name) + ) + }) + .collect() + } + /// One canonical FILE_FULL_EA_INFORMATION list for NtSetEaFile. + pub fn restorable_buffer(&self) -> Vec { + let mut buffer = Vec::new(); + for (index, entry) in self.entries.iter().enumerate() { + let start = buffer.len(); + buffer.extend_from_slice(&0u32.to_le_bytes()); + buffer.push(entry.flags); + buffer.push(entry.name.len() as u8); + buffer.extend_from_slice(&(entry.value.len() as u16).to_le_bytes()); + buffer.extend_from_slice(&entry.name); + buffer.push(0); + buffer.extend_from_slice(&entry.value); + while buffer.len() % 4 != 0 { + buffer.push(0); + } + if index + 1 < self.entries.len() { + let size = (buffer.len() - start) as u32; + buffer[start..start + 4].copy_from_slice(&size.to_le_bytes()); + } + } + buffer + } +} + +/// Kernel EA names are matched case-insensitively: the kernel itself folds EA +/// names to uppercase, so either spelling must classify. +pub fn is_kernel_ea_name(name: &[u8]) -> bool { + name.len() >= KERNEL_EA_PREFIX.len() + && name[..KERNEL_EA_PREFIX.len()].eq_ignore_ascii_case(KERNEL_EA_PREFIX) +} + +/// Byte-exact restorable comparison. Order stays out of the contract because +/// EA query order is a kernel detail; names, flags and values are not. +pub fn same_restorable(a: &[EaEntry], b: &[EaEntry]) -> bool { + let mut a: Vec<_> = a.to_vec(); + let mut b: Vec<_> = b.to_vec(); + a.sort_by(|x, y| x.name.cmp(&y.name)); + b.sort_by(|x, y| x.name.cmp(&y.name)); + a == b +} + +/// Capture the full EA set of one file. The kernel reports the exact list +/// size first, so the scan budget is known before any buffer is read; an +/// oversized, malformed or unreadable set fails closed instead of being +/// discarded. +pub fn capture(file: &File) -> io::Result { + let mut size = 0u32; + let mut status = IoStatus { + status: 0, + information: 0, + }; + // SAFETY: FileEaInformation (7) writes one ULONG into size for a borrowed + // handle. + let result = unsafe { + super::NtQueryInformationFile( + file.as_raw_handle(), + &mut status, + (&mut size as *mut u32).cast(), + 4, + FILE_EA_INFORMATION, + ) + }; + if result < 0 { + return Err(nt_error(result)); + } + if size == 0 { + return Ok(CapturedEas::default()); + } + if size as usize > MAX_EA_BYTES { + return Err(unsupported( + "Windows extended-attribute metadata exceeds the bounded capture budget", + )); + } + let mut captured = CapturedEas::default(); + // The size probe bounds the whole list; the loop only resumes a partial + // buffer, and an entry larger than the budget fails closed at the call. + let mut buffer = vec![0u8; size as usize + 512]; + let mut restart = 1u8; + for _ in 0..64 { + let mut status = IoStatus { + status: 0, + information: 0, + }; + // SAFETY: borrowed handle; buffer and status outlive the call. + let result = unsafe { + NtQueryEaFile( + file.as_raw_handle(), + &mut status, + buffer.as_mut_ptr().cast(), + buffer.len() as u32, + 0, + null(), + 0, + null_mut(), + restart, + ) + }; + restart = 0; + if result == NO_MORE_EAS { + break; + } + if result < 0 && result != BUFFER_OVERFLOW { + return Err(nt_error(result)); + } + let used = status.information.min(buffer.len()); + append_entries(&buffer[..used], &mut captured)?; + if result >= 0 && used < buffer.len() { + break; + } + if used == 0 { + return Err(unsupported( + "Windows extended-attribute scan made no progress", + )); + } + } + Ok(captured) +} + +/// Parse one FILE_FULL_EA_INFORMATION list into the canonical capture. Every +/// length and offset is bounds-checked before use; a malformed record fails +/// closed rather than being partially accepted. +fn append_entries(bytes: &[u8], captured: &mut CapturedEas) -> io::Result<()> { + let mut at = 0usize; + loop { + if at + 8 > bytes.len() { + if at == bytes.len() { + return Ok(()); + } + return Err(unsupported( + "Truncated Windows extended-attribute record", + )); + } + let next = + u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]) as usize; + let flags = bytes[at + 4]; + let name_length = bytes[at + 5] as usize; + let value_length = u16::from_le_bytes([bytes[at + 6], bytes[at + 7]]) as usize; + let name_at = at + 8; + let value_at = name_at + name_length + 1; + if value_at + value_length > bytes.len() || bytes.get(name_at + name_length) != Some(&0) { + return Err(unsupported( + "Truncated Windows extended-attribute record", + )); + } + let name = &bytes[name_at..name_at + name_length]; + if name.is_empty() || name.iter().any(|b| !b.is_ascii()) { + return Err(unsupported("Invalid Windows extended-attribute name")); + } + if flags > 1 { + return Err(unsupported("Unsupported Windows extended-attribute flags")); + } + if is_kernel_ea_name(name) { + captured.kernel.push(name.to_vec()); + } else { + if captured.entries.len() >= MAX_EA_ENTRIES { + return Err(unsupported( + "Windows extended-attribute count exceeds the bounded capture budget", + )); + } + captured.entries.push(EaEntry { + flags, + name: name.to_vec(), + value: bytes[value_at..value_at + value_length].to_vec(), + }); + } + if next == 0 { + return Ok(()); + } + if next < 8 || at + next > bytes.len() { + return Err(unsupported( + "Invalid Windows extended-attribute record chain", + )); + } + at += next; + } +} + +/// Set the captured restorable EAs on one staged destination file. The +/// destination is always our own freshly created private sibling, so a kernel +/// refusal aborts publication instead of touching the source. +pub fn restore(file: &File, captured: &CapturedEas) -> io::Result<()> { + let buffer = captured.restorable_buffer(); + if buffer.is_empty() { + return Ok(()); + } + let mut status = IoStatus { + status: 0, + information: 0, + }; + // SAFETY: borrowed handle; the buffer outlives the call. + let result = unsafe { + NtSetEaFile( + file.as_raw_handle(), + &mut status, + buffer.as_ptr().cast(), + buffer.len() as u32, + ) + }; + if result < 0 { + return Err(nt_error(result)); + } + Ok(()) +} + +/// Re-query the destination and compare the restorable set byte-exactly. +/// Kernel entries on either side stay out of the comparison: their lifecycle +/// belongs to the kernel and is reported at capture time instead. +pub fn verify(file: &File, captured: &CapturedEas) -> io::Result<()> { + if captured.entries.is_empty() { + return Ok(()); + } + let actual = capture(file)?; + if !same_restorable(&captured.entries, &actual.entries) { + return Err(unsupported( + "Windows extended-attribute preservation verification failed", + )); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn kernel_names_classify_and_degrade_with_named_evidence() { + assert!(is_kernel_ea_name(b"$KERNEL.PurgeEFSProxyCache")); + assert!(is_kernel_ea_name(b"$kernel.Custom")); + assert!(!is_kernel_ea_name(b"dsh-ops.test")); + assert!(!is_kernel_ea_name(b"$KERNEX.x")); + assert!(!is_kernel_ea_name(b"")); + let captured = CapturedEas { + entries: vec![EaEntry { + flags: 0, + name: b"DSH-OPS.TEST".to_vec(), + value: b"fixture".to_vec(), + }], + kernel: vec![b"$KERNEL.SIM".to_vec()], + }; + let warnings = captured.warnings(); + assert_eq!(warnings.len(), 1); + assert!(warnings[0].contains("$KERNEL.SIM"), "{}", warnings[0]); + // The restorable buffer carries only the user entry; kernel names + // never reach a set call. + let buffer = captured.restorable_buffer(); + assert!(buffer.windows(12).any(|w| w == b"DSH-OPS.TEST")); + assert!(!buffer.windows(10).any(|w| w == b"$KERNEL.SIM")); + } + + #[test] + fn restorable_comparison_is_byte_exact_and_strict() { + let entry = |name: &[u8], value: &[u8]| EaEntry { + flags: 0, + name: name.to_vec(), + value: value.to_vec(), + }; + let a = vec![entry(b"A.ONE", b"v1"), entry(b"B.TWO", b"v2")]; + let reordered = vec![entry(b"B.TWO", b"v2"), entry(b"A.ONE", b"v1")]; + assert!(same_restorable(&a, &reordered)); + assert!(!same_restorable(&a, &vec![entry(b"A.ONE", b"different")])); + assert!(!same_restorable(&a, &vec![entry(b"A.ONE", b"v1")])); + assert!(!same_restorable( + &a, + &vec![ + entry(b"A.ONE", b"v1"), + entry(b"B.TWO", b"v2"), + entry(b"C.NEW", b"v"), + ], + )); + let flagged = vec![EaEntry { + flags: 1, + name: b"A.ONE".to_vec(), + value: b"v1".to_vec(), + }]; + assert!(!same_restorable(&a[..1], &flagged)); + } + + #[test] + fn buffers_chain_entries_with_aligned_offsets_and_a_zero_tail() { + let captured = CapturedEas { + entries: vec![ + EaEntry { + flags: 0, + name: b"FIRST.X".to_vec(), + value: b"one".to_vec(), + }, + EaEntry { + flags: 1, + name: b"SECOND.Y".to_vec(), + value: b"two!".to_vec(), + }, + ], + kernel: Vec::new(), + }; + let buffer = captured.restorable_buffer(); + let first = u32::from_le_bytes([buffer[0], buffer[1], buffer[2], buffer[3]]) as usize; + assert_eq!(first % 4, 0); + assert!(first + 8 <= buffer.len()); + assert_eq!(buffer[4], 0); + assert_eq!(buffer[5], 7); + assert_eq!(buffer[first + 4], 1); + assert_eq!(buffer[first + 5], 8); + // The last entry terminates the chain with a zero NextEntryOffset. + assert_eq!(buffer[first..first + 4], [0, 0, 0, 0]); + } +} diff --git a/native/windows-metadata/src/lib.rs b/native/windows-metadata/src/lib.rs index 405bdb0e..99811212 100644 --- a/native/windows-metadata/src/lib.rs +++ b/native/windows-metadata/src/lib.rs @@ -1,6 +1,7 @@ //! Windows-only FFI boundary. Callers supply owned/borrowed file handles; no //! model paths, shells, privilege enabling, or publication policy live here. #![cfg(windows)] +mod ea; mod inheritance; pub use inheritance::inherit_new_file_dacl; use std::{ @@ -318,6 +319,7 @@ pub fn verify_cache(file: &File, write_sid: Option<&str>) -> io::Result<()> { pub struct Metadata { sd: Option>, basic: FILE_BASIC_INFO, + eas: ea::CapturedEas, warnings: Vec, } impl Metadata { @@ -374,29 +376,15 @@ impl Metadata { return Err(unsupported("Unknown Windows stream metadata")); } } - if capabilities.extended_attributes() { - let mut ea_size = 0u32; - let mut status = IoStatus { - status: 0, - information: 0, - }; - // SAFETY: FileEaInformation (7) writes one ULONG into ea_size. - let result = unsafe { - NtQueryInformationFile( - file.as_raw_handle(), - &mut status, - addr_of_mut!(ea_size).cast(), - 4, - 7, - ) - }; - if result < 0 { - return Err(nt_error(result)); - } - if ea_size != 0 { - return Err(unsupported("Windows extended attributes are not supported")); - } - } + // #874: user EAs are captured for an exact restore instead of refusing + // the whole write; kernel-owned EAs degrade with named evidence. + let eas = if capabilities.extended_attributes() { + ea::capture(file)? + } else { + ea::CapturedEas::default() + }; + let mut warnings = capabilities.warnings(); + warnings.extend(eas.warnings()); Ok(Self { sd: if capabilities.persistent_acls() { Some(descriptor(file)?) @@ -404,7 +392,8 @@ impl Metadata { None }, basic, - warnings: capabilities.warnings(), + eas, + warnings, }) } pub fn warnings(&self) -> &[String] { @@ -461,6 +450,8 @@ impl Metadata { { return Err(io::Error::last_os_error()); } + // Restored before verification: the destination is our own staged file. + ea::restore(file, &self.eas)?; self.verify(file) } pub fn verify(&self, file: &File) -> io::Result<()> { @@ -495,6 +486,7 @@ impl Metadata { { return Err(unsupported("Windows basic metadata verification failed")); } + ea::verify(file, &self.eas)?; Ok(()) } } @@ -651,4 +643,154 @@ mod tests { assert!(!root.join("private").exists()); std::fs::remove_dir(root).unwrap(); } + + // Test-local fixture FFI: it only creates the EA set; the capture and + // restore code under test never calls it, and the signature matches the + // crate's own NtSetEaFile declaration exactly. + #[link(name = "ntdll")] + unsafe extern "system" { + fn NtSetEaFile( + handle: HANDLE, + status: *mut IoStatus, + buffer: *const c_void, + length: u32, + ) -> i32; + } + fn probe_error(result: i32) -> io::Error { + // SAFETY: total scalar conversion, no pointer arguments. + io::Error::from_raw_os_error(unsafe { RtlNtStatusToDosError(result) } as i32) + } + /// Build one FILE_FULL_EA_INFORMATION entry and set it on a file. + fn set_ea(path: &std::path::Path, name: &[u8], value: &[u8]) -> io::Result<()> { + let mut buffer = Vec::with_capacity(8 + name.len() + 1 + value.len()); + buffer.extend_from_slice(&0u32.to_le_bytes()); + buffer.push(0); + buffer.push(name.len() as u8); + buffer.extend_from_slice(&(value.len() as u16).to_le_bytes()); + buffer.extend_from_slice(name); + buffer.push(0); + buffer.extend_from_slice(value); + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(path)?; + let mut status = IoStatus { + status: 0, + information: 0, + }; + // SAFETY: borrowed handle; buffer and status outlive the call. + let result = unsafe { + NtSetEaFile( + file.as_raw_handle(), + &mut status, + buffer.as_ptr().cast(), + buffer.len() as u32, + ) + }; + if result < 0 { + return Err(probe_error(result)); + } + Ok(()) + } + #[test] + fn user_extended_attributes_round_trip_instead_of_refusing_the_write() { + // #874: files carrying user EAs were all refused; they must round-trip. + let root = std::env::temp_dir().join(format!( + "dsh-metadata-ea-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir(&root).unwrap(); + let path = root.join("tagged"); + std::fs::write(&path, b"payload").unwrap(); + set_ea(&path, b"dsh-ops.test", b"fixture") + .expect("this volume must accept user EAs for the fixture"); + // NTFS folds user EA names to uppercase when storing and querying them. + let observed = ea::capture(&File::open(&path).unwrap()).unwrap(); + assert_eq!(observed.entries.len(), 1); + assert_eq!(observed.entries[0].name, b"DSH-OPS.TEST".to_vec()); + assert_eq!(observed.entries[0].value, b"fixture".to_vec()); + assert!(observed.kernel.is_empty()); + // #874: capture must describe the EA set instead of refusing the file. + let file = File::open(&path).unwrap(); + assert!(VolumeCapabilities::query(&file).unwrap().extended_attributes()); + let captured = + Metadata::capture(&file).expect("user EAs must be captured, not rejected"); + let parent = std::fs::OpenOptions::new() + .read(true) + .custom_flags(0x02000000) + .open(&root) + .unwrap(); + let mut staging = create_private(&parent, "staged").unwrap(); + staging.write_all(b"payload").unwrap(); + captured.restore(&staging).unwrap(); + captured.verify(&staging).unwrap(); + drop(staging); + drop(file); + let restored = ea::capture(&File::open(root.join("staged")).unwrap()).unwrap(); + assert_eq!(restored.entries.len(), 1); + assert_eq!(restored.entries[0].name, b"DSH-OPS.TEST".to_vec()); + assert_eq!(restored.entries[0].value, b"fixture".to_vec()); + assert_eq!(std::fs::read(&root.join("staged")).unwrap(), b"payload"); + drop(parent); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn kernel_named_eas_belong_to_the_kernel_not_user_mode() { + // The $KERNEL.* namespace is kernel-owned. A user-mode NtSetEaFile with + // such a name is either refused or silently dropped (observed here: + // the call succeeds and nothing is stored), so real kernel EAs on disk + // (EFS's PurgeEFSProxyCache, SmartLocker tags) can never be restored + // from user mode. Capture therefore classifies them by name and the + // publication reports each one; that classification and its warnings + // are asserted in the ea:: unit tests (#874). + let root = std::env::temp_dir().join(format!( + "dsh-metadata-kernel-ea-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir(&root).unwrap(); + let path = root.join("kernel-tagged"); + std::fs::write(&path, b"payload").unwrap(); + let parent = std::fs::OpenOptions::new() + .read(true) + .custom_flags(0x02000000) + .open(&root) + .unwrap(); + if let Err(refusal) = set_ea(&path, b"$KERNEL.SimTag", b"v") { + // The kernel refused user-mode $KERNEL.* creation itself: that is + // the documented reason no restore path can preserve them either. + assert!(refusal.raw_os_error().is_some(), "{refusal}"); + drop(parent); + std::fs::remove_dir_all(&root).unwrap(); + return; + } + // On this build the user-mode set reports success while the kernel + // silently drops the reserved name: nothing exists to capture, and an + // empty EA set must not be refused either. + let observed = ea::capture(&File::open(&path).unwrap()).unwrap(); + assert!( + observed.entries.is_empty() && observed.kernel.is_empty(), + "the kernel must own the $KERNEL namespace: {observed:?}" + ); + let file = File::open(&path).unwrap(); + let captured = Metadata::capture(&file).expect("an empty EA set must not be refused"); + assert!(captured.warnings().is_empty()); + let mut staging = create_private(&parent, "kernel-staged").unwrap(); + staging.write_all(b"payload").unwrap(); + captured.restore(&staging).unwrap(); + captured.verify(&staging).unwrap(); + drop(staging); + drop(file); + assert_eq!(std::fs::read(root.join("kernel-staged")).unwrap(), b"payload"); + drop(parent); + std::fs::remove_dir_all(&root).unwrap(); + } } From 6d2a55f3be4014ee003000c75b99e1d624f88910 Mon Sep 17 00:00:00 2001 From: Nicholas023 <498594526@qq.com> Date: Thu, 19 Nov 2026 10:15:34 +0800 Subject: [PATCH 3/3] docs: record Windows metadata and archive diagnostics (#874, #836) --- docs/CHANGELOG.md | 5 +++++ docs/file-contracts.md | 4 +++- ...3\266\350\257\273\345\206\231\345\245\221\347\272\246.md" | 4 +++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index d66194e1..87a8983f 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -15,6 +15,11 @@ this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - Replace the `global.forceDefaultOpsPtc` switch with one explicit action: the row's detail page carries a **Make OPS (PTC) the default** button that writes `selectedDefault: ops-ptc` once and answers `applied`/`no-update`/`unavailable`/`failed`. Apply, remount and unload no longer write the default, so a preset chosen on the settings page is not overridden on the next apply, and a saved `global.forceDefaultOpsPtc` key still loads with no effect. - 用一次显式操作取代 `global.forceDefaultOpsPtc` 开关:行详情页有一个「设为 OPS (PTC) 默认」按钮,点一次写 `selectedDefault: ops-ptc`,并回报 `applied`/`no-update`/`unavailable`/`failed`。apply、重挂载与卸载都不再改写默认,设置页选定的预设不会在下一次 apply 被覆盖;已保存的 `global.forceDefaultOpsPtc` 键仍可加载但不再生效。 +- Paths through an Electron `.asar` archive now fail with the explicit `ARCHIVE_MEMBER_UNSUPPORTED` diagnosis: only Electron's patched in-process filesystem presents the archive as a directory, so the standalone worker cannot read its members. This is an actionable diagnostic, not a virtual-filesystem fallback (#836). +- 穿过 Electron `.asar` 的路径现在明确返回 `ARCHIVE_MEMBER_UNSUPPORTED`:只有 Electron 进程内经补丁的文件系统会把归档呈现为目录,独立 worker 无法读取成员。这是可操作的诊断,不是虚拟文件系统回退(#836)。 +- Windows mutations capture, restore and byte-verify every user-restorable extended attribute. `$KERNEL.*` names are reported individually in `metadataWarnings` because user mode cannot recreate them; every other capture/restore/verification failure still aborts publication instead of silently dropping metadata (#874). +- Windows 写入现在捕获、恢复并逐字节核验所有用户态可恢复的扩展属性。`$KERNEL.*` 名称因用户态无法重建而逐名写入 `metadataWarnings`;其他任何捕获、恢复或核验失败仍会中止发布,不会静默丢弃元数据(#874)。 + ## [0.5.5] — 2026-11-13 — Patch release - A loader-less PTC scope no longer registers the configured `allowedTools` pool: with dynamic loading off nothing could ever select those APIs, and a host assembly without a step tool set declared all sixteen in `tools:sdk`. Resident publication, the default inspect + loader set and selection behavior are unchanged (#887). diff --git a/docs/file-contracts.md b/docs/file-contracts.md index dbb6916a..6292e93f 100644 --- a/docs/file-contracts.md +++ b/docs/file-contracts.md @@ -16,7 +16,9 @@ These are the current contracts, including deliberate differences between tools. Revision computation for `stat`, `copy`, `move` and `remove` streams SHA-256 instead of loading the whole file, so those operations accept files over 32 MiB. Hex inspection streams whole-file facts without buffering them, then seeks to and buffers only its requested window. Whole-content text inspection, `diff` and mutation buffers retain their explicit content budgets. -On Windows volumes without named-stream or ACL support, mutations preserve available basic metadata and return `metadataWarnings` instead of `METADATA_UNSUPPORTED`. Windows source metadata that is present but unsupported, such as NTFS alternate data streams, still fails closed. +On Windows volumes without named-stream or ACL support, mutations preserve available basic metadata and return `metadataWarnings` instead of `METADATA_UNSUPPORTED`. On NTFS, user-restorable extended attributes are captured, restored and byte-verified. `$KERNEL.*` names are listed individually in `metadataWarnings` because user mode cannot recreate them; any other EA capture, restore or verification failure fails closed. Unsupported source metadata such as NTFS alternate data streams also fails closed. + +A path through an Electron `.asar` file returns `ARCHIVE_MEMBER_UNSUPPORTED`. Electron presents that archive as a directory only inside its own patched process filesystem; the standalone worker sees a regular file and cannot read archive members. Inspect the archive itself in hex view or use an unpacked copy. `replace` is not bound to an earlier `inspect_local_file` result. Use `edit_file` when a single-file change must depend on that exact read. A `replace` preview is not a reservation: execution rescans. `changed` counts applied literal replacements, not files. A preview has `dryRun: true`; planned hashes alone do not establish that writes happened. Directory replacement records permission-denied reads in `skippedPaths` and returns `complete: false` with `truncated: true` while continuing eligible neighbors; ordinary binary-file skips do not by themselves make the result incomplete. Update-lock, staging and publication denials still fail the call, and sharing violations or other IO failures retain their structured error instead of becoming skips. diff --git "a/docs/\346\226\207\344\273\266\350\257\273\345\206\231\345\245\221\347\272\246.md" "b/docs/\346\226\207\344\273\266\350\257\273\345\206\231\345\245\221\347\272\246.md" index d9570ee9..5be50c96 100644 --- "a/docs/\346\226\207\344\273\266\350\257\273\345\206\231\345\245\221\347\272\246.md" +++ "b/docs/\346\226\207\344\273\266\350\257\273\345\206\231\345\245\221\347\272\246.md" @@ -16,7 +16,9 @@ English: [File read and mutation contracts](file-contracts.md). `stat`、`copy`、`move` 与 `remove` 以流式 SHA-256 计算 revision,不再整读文件,因此可处理超过 32 MiB 的文件。hex 检查会在不缓冲完整内容的情况下流式计算整文件事实,随后只定位并缓冲请求窗口。需要完整内容的文本检查、`diff` 与写入缓冲仍保留各自明确的内容预算。 -在不支持命名流或 ACL 的 Windows 卷上,写入会保留可用的基本元数据并返回 `metadataWarnings`,不再返回 `METADATA_UNSUPPORTED`。Windows 上真实存在但不受支持的源元数据(例如 NTFS 备用数据流)仍会闭锁拒绝。 +在不支持命名流或 ACL 的 Windows 卷上,写入会保留可用的基本元数据并返回 `metadataWarnings`,不再返回 `METADATA_UNSUPPORTED`。在 NTFS 上,用户态可恢复的扩展属性会被捕获、恢复并逐字节核验;`$KERNEL.*` 名称因用户态无法重建而逐名写入 `metadataWarnings`。其他任何 EA 捕获、恢复或核验失败都会闭锁拒绝;不受支持的源元数据(例如 NTFS 备用数据流)同样闭锁拒绝。 + +穿过 Electron `.asar` 文件的路径会返回 `ARCHIVE_MEMBER_UNSUPPORTED`。只有 Electron 进程内经补丁的文件系统会把归档呈现为目录,独立 worker 看到的仍是普通文件,无法读取归档成员。请用 hex 视图检查归档本身,或改用解包后的副本。 `replace` 不绑定之前 `inspect_local_file` 的读取结果。单文件变更必须依赖该次读取时使用 `edit_file`。replace 预览不会预留文件,执行时重新扫描。`changed` 是已应用字面替换次数,不是文件数。预览带 `dryRun: true`,仅有计划 hash 不能证明已经写入。目录替换遇到读取权限拒绝时会记录 `skippedPaths`,返回 `complete: false` 与 `truncated: true`,并继续处理其他合格文件;普通的二进制文件跳过本身不会使结果不完整。更新锁、暂存与发布阶段的权限拒绝仍使调用失败,共享冲突及其他 IO 故障也保留结构化错误,不会改记为跳过。