返回 CodeWhale
windows_tests.rs
根目录 / crates / engine / src / extension_host / windows_tests.rs
1 //! Real Windows kernel/host receipts. These are not source-only substitutes.
2 use super::*;
3 use crate::extension_host::supervisor::{HostSandbox, MemoryEnforcement};
4 use crate::extension_host::test_support::{FixturePlugins, host_tool};
5 use crate::extension_host::{ExtensionHostManager, ExtensionHostOptions, HostStatus};
6 use crate::tools::spec::ToolContext;
7 use codewhale_config::extension_host::ExtensionHostRuntime;
8 use codewhale_plugins::activation::TestPolicyGuard;
9 use serde_json::json;
10
11 const ACL_LOCK_FIXTURE_DIR: &str = "CODEWHALE_WINDOWS_ACL_LOCK_FIXTURE_DIR";
12
13 #[test]
14 fn windows_acl_edit_guard_fixture() {
15 let Some(root) = std::env::var_os(ACL_LOCK_FIXTURE_DIR).map(PathBuf::from) else {
16 return;
17 };
18 fs::write(root.join("ready"), b"ready").unwrap();
19 let _guard = AclEditGuard::acquire().unwrap();
20 fs::write(root.join("acquired"), b"acquired").unwrap();
21 }
22
23 #[test]
24 fn windows_acl_edit_guard_serializes_processes() {
25 // Retain the owned child even during an assertion panic. This fixture
26 // starts no descendants; cleanup never targets any other process.
27 struct FixtureChild(std::process::Child);
28 impl Drop for FixtureChild {
29 fn drop(&mut self) {
30 if !matches!(self.0.try_wait(), Ok(Some(_))) {
31 let _ = self.0.kill();
32 }
33 let _ = self.0.wait();
34 }
35 }
36
37 let root = tempfile::tempdir().unwrap();
38 let ready = root.path().join("ready");
39 let acquired = root.path().join("acquired");
40 let guard = AclEditGuard::acquire().unwrap();
41 let mut child = FixtureChild(
42 std::process::Command::new(std::env::current_exe().unwrap())
43 .args([
44 "--exact",
45 "extension_host::windows::tests::windows_acl_edit_guard_fixture",
46 "--nocapture",
47 "--test-threads=1",
48 ])
49 // The unique marker directory is supplied only to this child.
50 // No process-global environment mutation or env lock is needed.
51 .env(ACL_LOCK_FIXTURE_DIR, root.path())
52 .spawn()
53 .unwrap(),
54 );
55 let deadline = std::time::Instant::now() + Duration::from_secs(5);
56 while !ready.exists() {
57 assert!(
58 child.0.try_wait().unwrap().is_none(),
59 "ACL fixture exited before its ready marker; exact fixture must run"
60 );
61 assert!(
62 std::time::Instant::now() < deadline,
63 "ACL fixture was not ready"
64 );
65 std::thread::sleep(Duration::from_millis(10));
66 }
67 let held_until = std::time::Instant::now() + Duration::from_millis(200);
68 while std::time::Instant::now() < held_until {
69 assert!(
70 !acquired.exists(),
71 "child acquired the parent's held ACL lock"
72 );
73 assert!(
74 child.0.try_wait().unwrap().is_none(),
75 "ACL fixture exited while the parent still held the lock"
76 );
77 std::thread::sleep(Duration::from_millis(10));
78 }
79 assert!(!acquired.exists(), "child acquired before parent release");
80 drop(guard);
81
82 let deadline = std::time::Instant::now() + Duration::from_secs(5);
83 loop {
84 if let Some(status) = child.0.try_wait().unwrap() {
85 assert!(status.success(), "ACL fixture failed: {status}");
86 assert!(
87 acquired.exists(),
88 "fixture exited without acquiring the lock"
89 );
90 break;
91 }
92 assert!(
93 std::time::Instant::now() < deadline,
94 "ACL fixture did not acquire and exit after parent release"
95 );
96 std::thread::sleep(Duration::from_millis(10));
97 }
98 }
99
100 fn runtime(choice: ExtensionHostRuntime, override_path: Option<&Path>) -> Option<HostRuntime> {
101 let resolution = codewhale_dependencies::resolve_extension_host_runtime(
102 choice,
103 (choice == ExtensionHostRuntime::Node)
104 .then_some(override_path)
105 .flatten(),
106 (choice == ExtensionHostRuntime::Bun)
107 .then_some(override_path)
108 .flatten(),
109 crate::extension_host::bundle_sha256(),
110 );
111 match resolution.selected {
112 Some(runtime) => Some(runtime),
113 None if std::env::var_os("CODEWHALE_EXT_HOST_TESTS").is_some()
114 || std::env::var_os("CODEWHALE_EXT_HOST_BUN_TESTS").is_some() =>
115 {
116 panic!("required Windows runtime: {}", resolution.failure())
117 }
118 None => {
119 eprintln!(
120 "Windows runtime receipt unavailable: {}",
121 resolution.failure()
122 );
123 None
124 }
125 }
126 }
127
128 #[cfg(any(test, feature = "test-support"))]
129 async fn owner_boundary(runtime: HostRuntime) {
130 let _policy = TestPolicyGuard::extension_host(true);
131 let fixture = FixturePlugins::new(&["secret-probe"]).await;
132 let choice = match runtime.kind {
133 codewhale_dependencies::HostRuntimeKind::Node => ExtensionHostRuntime::Node,
134 codewhale_dependencies::HostRuntimeKind::Bun => ExtensionHostRuntime::Bun,
135 };
136 let registry = fixture.registry();
137 let plugin = registry.get("secret-probe").unwrap();
138 let source = plugin.base_path.join("index.mjs");
139 let staged = plugin.staged_root.as_ref().unwrap().join("index.mjs");
140 assert_ne!(source, staged);
141 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
142 runtime: choice,
143 node_override: (choice == ExtensionHostRuntime::Node).then_some(runtime.path.clone()),
144 bun_override: (choice == ExtensionHostRuntime::Bun).then_some(runtime.path),
145 root: Some(fixture.root.clone()),
146 ..Default::default()
147 }));
148 let engine = manager.attach(registry);
149 engine.sync().await.unwrap();
150 let HostStatus::Ready {
151 sandbox, memory, ..
152 } = manager.status()
153 else {
154 panic!(
155 "Windows Native failed: {:?}; {:?}",
156 manager.status(),
157 manager.diagnostics()
158 );
159 };
160 assert_eq!(sandbox, HostSandbox::Wrapped("windows-lpac".into()));
161 assert_eq!(memory, MemoryEnforcement::JobObject);
162 let context = ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view());
163 let read = host_tool(&engine, fixture.workspace(), "probe_read");
164 let write = host_tool(&engine, fixture.workspace(), "probe_write");
165 let staged_read = read
166 .execute(json!({"path":staged}), &context)
167 .await
168 .unwrap();
169 assert_eq!(
170 serde_json::from_str::<serde_json::Value>(&staged_read.content).unwrap()["ok"],
171 true,
172 "reviewed runtime root must be readable by the real Native module"
173 );
174 for path in [
175 source,
176 fixture.workspace().join("ungranted.txt"),
177 fixture
178 .root
179 .join("extension-host/builtin-data/private.json"),
180 ] {
181 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
182 if !path.exists() {
183 std::fs::write(&path, b"synthetic-private-control").unwrap();
184 }
185 let result = read.execute(json!({"path":path}), &context).await.unwrap();
186 let result: serde_json::Value = serde_json::from_str(&result.content).unwrap();
187 assert_eq!(
188 result["ok"], false,
189 "mutable/ungranted roots must remain unreadable"
190 );
191 assert!(
192 matches!(result["code"].as_str(), Some("EACCES" | "EPERM")),
193 "must be an access denial, not a missing file"
194 );
195 }
196 let data = fixture.root.join("extension-host/data/positive-write.txt");
197 let result = write.execute(json!({"path":data}), &context).await.unwrap();
198 assert_eq!(
199 serde_json::from_str::<serde_json::Value>(&result.content).unwrap()["ok"],
200 true
201 );
202 let denied = staged.parent().unwrap().join("forbidden-write.txt");
203 let result = write
204 .execute(json!({"path":denied}), &context)
205 .await
206 .unwrap();
207 assert_eq!(
208 serde_json::from_str::<serde_json::Value>(&result.content).unwrap()["ok"],
209 false
210 );
211 assert!(!denied.exists(), "readonly snapshot was modified");
212 engine.set_plugins(fixture.disable("secret-probe"));
213 engine.sync().await.unwrap();
214 assert!(
215 read.execute(json!({"path":staged}), &context)
216 .await
217 .is_err(),
218 "revoked caller cannot use an earlier handle"
219 );
220 manager.shutdown().await;
221 }
222
223 #[tokio::test(flavor = "current_thread")]
224 async fn windows_native_lpac_node_owner_boundary() {
225 if let Some(runtime) = runtime(ExtensionHostRuntime::Node, None) {
226 owner_boundary(runtime).await;
227 }
228 }
229
230 #[tokio::test(flavor = "current_thread")]
231 async fn windows_native_lpac_bun_owner_boundary() {
232 if let Some(runtime) = runtime(ExtensionHostRuntime::Bun, None) {
233 owner_boundary(runtime).await;
234 }
235 }
236
237 #[tokio::test(flavor = "current_thread")]
238 async fn windows_native_lpac_compiled_owner_boundary() {
239 let Some(binary) = std::env::var_os("CODEWHALE_COMPILED_HOST_TEST_BINARY") else {
240 assert!(
241 std::env::var_os("CODEWHALE_EXT_HOST_TESTS").is_none(),
242 "required Windows compiled-host receipt is missing"
243 );
244 eprintln!(
245 "compiled Windows receipt unavailable: compile the canonical bundle and name its image"
246 );
247 return;
248 };
249 let runtime = runtime(ExtensionHostRuntime::Bun, Some(Path::new(&binary))).unwrap();
250 assert!(
251 runtime.compiled,
252 "test must use the exact canonical compiled-host filename/identity"
253 );
254 owner_boundary(runtime).await;
255 }
256
257 #[test]
258 fn windows_native_profiles_are_distinct_and_acl_grant_refuses_junctions() {
259 let first = Profile::create().unwrap();
260 let second = Profile::create().unwrap();
261 assert_ne!(first.name, second.name);
262 assert_eq!(
263 unsafe { EqualSid(first.sid, second.sid) },
264 0,
265 "retired profile ACLs cannot be inherited by a new host"
266 );
267 let root = tempfile::tempdir().unwrap();
268 let outside = tempfile::tempdir().unwrap();
269 let link = root.path().join("junction");
270 let outside_file = outside.path().join("ungranted.txt");
271 std::fs::write(&outside_file, b"outside control").unwrap();
272 // Junction creation needs no symlink privilege; every failure is a red
273 // Windows receipt, never a silent environment skip.
274 let status = std::process::Command::new("cmd.exe")
275 .args(["/d", "/c", "mklink", "/J"])
276 .arg(&link)
277 .arg(outside.path())
278 .output()
279 .unwrap();
280 assert!(
281 status.status.success(),
282 "cannot create the actual junction control"
283 );
284 assert!(WindowsDirectory::open(&link).is_err());
285 let sandbox = NativeSandbox {
286 profile: Arc::new(first),
287 _assets: Arc::new(tempfile::tempdir().unwrap()),
288 program: PathBuf::new(),
289 data: root.path().to_path_buf(),
290 };
291 let result = sandbox.admit_root(root.path());
292 // Remove only the exact junction we created before tempfile cleanup.
293 std::fs::remove_dir(&link).unwrap();
294 assert!(
295 result.is_err(),
296 "grant traversal must refuse reparse points"
297 );
298 assert_no_profile_grant(outside.path(), sandbox.profile.sid);
299 assert_no_profile_grant(&outside_file, sandbox.profile.sid);
300 }
301
302 #[test]
303 fn windows_sandbox_args_use_granted_bun_config_without_changing_other_values() {
304 let runtime_dir = Path::new("runtime copy 鲸鱼");
305 let args = vec![
306 "--no-addons".into(),
307 "--config=NUL".into(),
308 "--input-type=module".into(),
309 "-e".into(),
310 "console.log('--config=NUL')".into(),
311 String::new(),
312 ];
313 let mapped = sandbox_args(&args, runtime_dir);
314 let mut expected = args.clone();
315 expected[1] = format!("--config={}", runtime_dir.join(EMPTY_BUN_CONFIG).display());
316 assert_eq!(mapped, expected);
317 assert_eq!(sandbox_args(&mapped, runtime_dir), mapped);
318 }
319
320 #[test]
321 fn windows_sandbox_args_preserve_node_and_compiled_arguments() {
322 for args in [
323 vec!["--no-addons".into(), "--input-type=module".into()],
324 vec!["--tier=plugin".into(), "--windows-sandbox-probe".into()],
325 vec!["--config=NUL.toml".into(), "--config=custom.toml".into()],
326 Vec::new(),
327 ] {
328 assert_eq!(sandbox_args(&args, Path::new("runtime copy")), args);
329 }
330 }
331
332 #[test]
333 fn windows_argv_and_environment_keep_exact_values_and_reject_nul() {
334 let args = vec![
335 String::new(),
336 "C:\\folder with space\\".into(),
337 "a\"b".into(),
338 "鲸鱼".into(),
339 ];
340 let line = command_line(OsStr::new("C:\\runtime folder\\node.exe"), &args).unwrap();
341 assert_eq!(
342 String::from_utf16(&line[..line.len() - 1]).unwrap(),
343 "\"C:\\runtime folder\\node.exe\" \"\" \"C:\\folder with space\\\\\" \"a\\\"b\" \"鲸鱼\""
344 );
345 assert!(command_line(OsStr::new("node.exe"), &["x\0y".into()]).is_err());
346 assert!(environment_block(&[("A".into(), "value\0tail".into())]).is_err());
347 assert!(environment_block(&[("A=B".into(), "value".into())]).is_err());
348 let env = environment_block(&[
349 ("Z".into(), "last".into()),
350 ("a".into(), "first=literal".into()),
351 ])
352 .unwrap();
353 assert_eq!(
354 String::from_utf16(&env).unwrap(),
355 "a=first=literal\0Z=last\0\0"
356 );
357 }
358
359 // Check the actual external ACL, not only the resolver's return value. The
360 // current user still owns these controls; our AppContainer SID must never gain
361 // an allow ACE through SetSecurityInfo's descendant propagation.
362 fn assert_no_profile_grant(path: &Path, profile: PSID) {
363 assert_eq!(
364 acl_snapshot(path, None),
365 acl_snapshot(path, Some(profile)),
366 "outside control {} received the sandbox SID",
367 path.display()
368 );
369 }
370 fn acl_snapshot(path: &Path, exclude: Option<PSID>) -> Vec<Vec<u8>> {
371 acl_snapshot_view(path, exclude, false).1
372 }
373 fn acl_snapshot_view(path: &Path, exclude: Option<PSID>, raw: bool) -> (u16, Vec<Vec<u8>>) {
374 use windows_sys::Win32::Security::Authorization::{GetSecurityInfo, SE_FILE_OBJECT};
375 use windows_sys::Win32::Security::{
376 ACCESS_ALLOWED_ACE, ACE_HEADER, GetAce, GetSecurityDescriptorControl,
377 };
378 use windows_sys::Win32::System::SystemServices::ACCESS_ALLOWED_ACE_TYPE;
379 let directory;
380 let file;
381 let opened = if path.is_dir() {
382 directory = WindowsDirectory::open(path).unwrap();
383 directory.acl_handle().unwrap()
384 } else {
385 file = fs::OpenOptions::new()
386 .access_mode(READ_CONTROL | FILE_READ_ATTRIBUTES)
387 .share_mode(1)
388 .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
389 .open(path)
390 .unwrap();
391 &file
392 };
393 let raw_descriptor = raw.then(|| RawDacl::read(opened).unwrap());
394 let mut _descriptor = None;
395 let mut control = 0_u16;
396 let mut dacl = null_mut();
397 if let Some(raw) = &raw_descriptor {
398 dacl = raw.acl();
399 control = raw.control;
400 } else {
401 let mut descriptor = null_mut();
402 let error = unsafe {
403 GetSecurityInfo(
404 opened.as_raw_handle(),
405 SE_FILE_OBJECT,
406 DACL_SECURITY_INFORMATION,
407 null_mut(),
408 null_mut(),
409 &mut dacl,
410 null_mut(),
411 &mut descriptor,
412 )
413 };
414 assert_eq!(error, 0, "cannot inspect control ACL");
415 _descriptor = Some(LocalAllocation(descriptor));
416 let mut revision = 0;
417 assert_ne!(
418 unsafe { GetSecurityDescriptorControl(descriptor, &mut control, &mut revision) },
419 0
420 );
421 }
422 let dacl = std::ptr::NonNull::new(dacl).expect("control must have an actual DACL");
423 let mut result = Vec::new();
424 for index in 0..unsafe { dacl.as_ref().AceCount as u32 } {
425 let mut ace = null_mut();
426 assert_ne!(unsafe { GetAce(dacl.as_ptr(), index, &mut ace) }, 0);
427 let ace = std::ptr::NonNull::new(ace).expect("GetAce must return an actual ACE");
428 let header = unsafe { ace.cast::<ACE_HEADER>().as_ref() };
429 assert!(header.AceSize as usize >= std::mem::size_of::<ACE_HEADER>());
430 if header.AceType as u32 == ACCESS_ALLOWED_ACE_TYPE {
431 assert!(header.AceSize as usize >= std::mem::size_of::<ACCESS_ALLOWED_ACE>());
432 let sid = unsafe {
433 std::ptr::addr_of_mut!((*ace.cast::<ACCESS_ALLOWED_ACE>().as_ptr()).SidStart)
434 };
435 if exclude.is_some_and(|profile| unsafe { EqualSid(profile, sid.cast()) } != 0) {
436 continue;
437 }
438 }
439 result.push(
440 unsafe {
441 std::slice::from_raw_parts(ace.cast::<u8>().as_ptr(), header.AceSize as usize)
442 }
443 .to_vec(),
444 );
445 }
446 (control, result)
447 }
448
449 #[test]
450 fn windows_raw_dacl_rejects_truncated_unrestricted_and_malformed_descriptors() {
451 use windows_sys::Win32::Security::{
452 ACL_REVISION, InitializeAcl, SE_DACL_PRESENT, SE_SELF_RELATIVE,
453 SECURITY_DESCRIPTOR_RELATIVE,
454 };
455 fn fixture() -> Vec<u32> {
456 let length = size_of::<SECURITY_DESCRIPTOR_RELATIVE>() + size_of::<ACL>();
457 let mut storage = vec![0_u32; length.div_ceil(size_of::<u32>())];
458 let descriptor = storage.as_mut_ptr().cast::<SECURITY_DESCRIPTOR_RELATIVE>();
459 // SAFETY: the aligned allocation contains both complete structures.
460 unsafe {
461 (*descriptor).Revision = 1;
462 (*descriptor).Control = SE_SELF_RELATIVE | SE_DACL_PRESENT;
463 (*descriptor).Dacl = size_of::<SECURITY_DESCRIPTOR_RELATIVE>() as u32;
464 let acl = storage
465 .as_mut_ptr()
466 .cast::<u8>()
467 .add(size_of::<SECURITY_DESCRIPTOR_RELATIVE>())
468 .cast::<ACL>();
469 assert_ne!(InitializeAcl(acl, size_of::<ACL>() as u32, ACL_REVISION), 0);
470 }
471 storage
472 }
473 let valid = fixture();
474 let length = valid.len() * size_of::<u32>();
475 let descriptor = RawDacl::from_storage(valid.clone(), length).unwrap();
476 assert_eq!(descriptor.control, SE_SELF_RELATIVE | SE_DACL_PRESENT);
477 assert_eq!(
478 unsafe { (*descriptor.acl()).AceCount },
479 0,
480 "an empty restrictive ACL is valid"
481 );
482 assert!(RawDacl::from_storage(Vec::new(), 0).is_err());
483 assert!(RawDacl::from_storage(valid.clone(), length + 1).is_err());
484 assert!(
485 RawDacl::from_storage(valid.clone(), size_of::<SECURITY_DESCRIPTOR_RELATIVE>() - 1)
486 .is_err()
487 );
488 for (control, offset) in [
489 (
490 SE_DACL_PRESENT,
491 size_of::<SECURITY_DESCRIPTOR_RELATIVE>() as u32,
492 ),
493 (SE_SELF_RELATIVE, 0),
494 (SE_SELF_RELATIVE | SE_DACL_PRESENT, 0),
495 (SE_SELF_RELATIVE | SE_DACL_PRESENT, 4),
496 (SE_SELF_RELATIVE | SE_DACL_PRESENT, 21),
497 (SE_SELF_RELATIVE | SE_DACL_PRESENT, length as u32),
498 ] {
499 let mut storage = valid.clone();
500 let header = storage.as_mut_ptr().cast::<SECURITY_DESCRIPTOR_RELATIVE>();
501 unsafe {
502 (*header).Control = control;
503 (*header).Dacl = offset;
504 }
505 assert!(
506 RawDacl::from_storage(storage, length).is_err(),
507 "control={control:#x}, offset={offset}"
508 );
509 }
510 for (size, count) in [(0, 0), (u16::MAX, 0), (size_of::<ACL>() as u16, 1)] {
511 let mut storage = valid.clone();
512 let acl = unsafe {
513 storage
514 .as_mut_ptr()
515 .cast::<u8>()
516 .add(size_of::<SECURITY_DESCRIPTOR_RELATIVE>())
517 .cast::<ACL>()
518 };
519 unsafe {
520 (*acl).AclSize = size;
521 (*acl).AceCount = count;
522 }
523 assert!(
524 RawDacl::from_storage(storage, length).is_err(),
525 "size={size}, count={count}"
526 );
527 }
528 // A complete allow ACE with S-1-5-32 provides the positive control. A
529 // bounded ACL alone must not authorize EqualSid to read past that ACE.
530 let mut allowed = fixture();
531 let entry_offset = length;
532 allowed.resize(allowed.len() + 5, 0);
533 let allowed_length = allowed.len() * size_of::<u32>();
534 unsafe {
535 let bytes =
536 std::slice::from_raw_parts_mut(allowed.as_mut_ptr().cast::<u8>(), allowed_length);
537 bytes[size_of::<SECURITY_DESCRIPTOR_RELATIVE>() + 2..][..2]
538 .copy_from_slice(&((size_of::<ACL>() + 20) as u16).to_le_bytes());
539 bytes[size_of::<SECURITY_DESCRIPTOR_RELATIVE>() + 4] = 1; // AceCount
540 bytes[entry_offset + 2..][..2].copy_from_slice(&20_u16.to_le_bytes());
541 bytes[entry_offset + 4] = 1; // Mask
542 bytes[entry_offset + 8..][..12].copy_from_slice(&[1, 1, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0]);
543 }
544 assert!(RawDacl::from_storage(allowed.clone(), allowed_length).is_ok());
545 for (offset, value) in [(2, 12), (8, 2), (9, 2)] {
546 let mut malformed = allowed.clone();
547 unsafe {
548 *malformed
549 .as_mut_ptr()
550 .cast::<u8>()
551 .add(entry_offset + offset) = value;
552 }
553 assert!(
554 RawDacl::from_storage(malformed, allowed_length).is_err(),
555 "malformed allow ACE at byte {offset}"
556 );
557 }
558 }
559
560 #[test]
561 fn windows_profile_retirement_removes_only_its_grants_and_inherited_data_on_restarts() {
562 use windows_sys::Win32::Security::GetLengthSid;
563 let data = tempfile::tempdir().unwrap();
564 let original_file = data.path().join("existing-state.json");
565 fs::write(&original_file, b"retained user state").unwrap();
566 let original_root_acl = acl_snapshot(data.path(), None);
567 let original_file_acl = acl_snapshot(&original_file, None);
568 let original_raw_root_acl = acl_snapshot_view(data.path(), None, true);
569 let original_raw_file_acl = acl_snapshot_view(&original_file, None, true);
570 let make = || NativeSandbox {
571 profile: Arc::new(Profile::create().unwrap()),
572 _assets: Arc::new(tempfile::tempdir().unwrap()),
573 program: PathBuf::new(),
574 data: data.path().to_path_buf(),
575 };
576 // A concurrent/new profile's exact grants must survive old-profile cleanup.
577 let other = make();
578 other.grant_tree(data.path(), true).unwrap();
579 // Check stored ACE bytes and all control bits before taking a later
580 // baseline. GetSecurityInfo can temporarily normalize the child's view
581 // while its parent carries a grant; no flag masking is allowed here.
582 assert_eq!(
583 acl_snapshot_view(data.path(), Some(other.profile.sid), true),
584 original_raw_root_acl,
585 "first profile grant changed pre-existing directory ACEs"
586 );
587 assert_eq!(
588 acl_snapshot_view(&original_file, Some(other.profile.sid), true),
589 original_raw_file_acl,
590 "first profile grant changed pre-existing file ACEs"
591 );
592 for turn in 0..8 {
593 let current = make();
594 current.grant_tree(data.path(), true).unwrap();
595 let root_without_current = acl_snapshot(data.path(), Some(current.profile.sid));
596 let file_without_current = acl_snapshot(&original_file, Some(current.profile.sid));
597 // Creation after admission exercises inherited grants, not only the
598 // immutable list of files that happened to exist during prepare.
599 let nested = data.path().join(format!("new-state-{turn}"));
600 fs::create_dir(&nested).unwrap();
601 let created = nested.join("state.json");
602 fs::write(&created, b"new persisted state").unwrap();
603 let length = unsafe { GetLengthSid(current.profile.sid) } as usize;
604 let mut sid_copy = vec![0_usize; length.div_ceil(std::mem::size_of::<usize>())];
605 unsafe {
606 std::ptr::copy_nonoverlapping(
607 current.profile.sid as *const u8,
608 sid_copy.as_mut_ptr().cast::<u8>(),
609 length,
610 );
611 }
612 let retired_sid = sid_copy.as_mut_ptr().cast();
613 assert_ne!(
614 acl_snapshot(&created, None),
615 acl_snapshot(&created, Some(retired_sid)),
616 "control must really inherit the current profile grant"
617 );
618 // A new/live owner may still have a data writer open. Exact ACL
619 // retirement must not fail only because legitimate writes continue.
620 let writer = fs::OpenOptions::new()
621 .write(true)
622 .open(&original_file)
623 .unwrap();
624 drop(current); // no Tokio context here: exact retirement is synchronous
625 drop(writer);
626 assert_eq!(acl_snapshot(data.path(), None), root_without_current);
627 assert_eq!(acl_snapshot(&original_file, None), file_without_current);
628 assert_no_profile_grant(&nested, retired_sid);
629 assert_no_profile_grant(&created, retired_sid);
630 assert_eq!(fs::read(&created).unwrap(), b"new persisted state");
631 assert_eq!(fs::read(&original_file).unwrap(), b"retained user state");
632 }
633 drop(other);
634 assert_eq!(
635 acl_snapshot(data.path(), None),
636 original_root_acl,
637 "final profile retirement changed pre-existing directory ACEs"
638 );
639 assert_eq!(
640 acl_snapshot(&original_file, None),
641 original_file_acl,
642 "final profile retirement changed pre-existing file ACEs"
643 );
644 }
645
646 #[test]
647 fn windows_bundle_directory_listing_never_grants_children_and_retires_exactly() {
648 let root = tempfile::tempdir().unwrap();
649 let sibling = root.path().join("builtin-private.json");
650 fs::write(&sibling, b"retained private data").unwrap();
651 let before = acl_snapshot_view(root.path(), None, true);
652 let sibling_before = acl_snapshot_view(&sibling, None, true);
653 let sandbox = NativeSandbox {
654 profile: Arc::new(Profile::create().unwrap()),
655 _assets: Arc::new(tempfile::tempdir().unwrap()),
656 program: PathBuf::new(),
657 data: root.path().to_path_buf(),
658 };
659 sandbox.grant_directory(root.path()).unwrap();
660 assert_ne!(acl_snapshot_view(root.path(), None, true), before);
661 assert_eq!(
662 acl_snapshot_view(root.path(), Some(sandbox.profile.sid), true),
663 before,
664 "directory listing must preserve every pre-existing ACE and control bit"
665 );
666 assert_no_profile_grant(&sibling, sandbox.profile.sid);
667 let created = root.path().join("created-after-grant.json");
668 fs::write(&created, b"private after admission").unwrap();
669 assert_no_profile_grant(&created, sandbox.profile.sid);
670 drop(sandbox);
671 assert_eq!(acl_snapshot_view(root.path(), None, true), before);
672 assert_eq!(acl_snapshot_view(&sibling, None, true), sibling_before);
673 assert_eq!(fs::read(&created).unwrap(), b"private after admission");
674 }
675
676 #[test]
677 fn windows_profile_directory_budget_and_recorded_identity_refuse_before_overwrite() {
678 let root = tempfile::tempdir().unwrap();
679 fs::write(root.path().join("first"), b"one").unwrap();
680 fs::write(root.path().join("second"), b"two").unwrap();
681 // Budget includes pending paths, so even a flat directory fails before
682 // growing the allocation past the bound. Admission and retirement share
683 // this exact production helper.
684 let mut pending = vec![PathBuf::from("already-pending"); MAX_GRANT_ENTRIES - 3];
685 assert!(enqueue_children(root.path(), &mut pending, 2).is_err());
686 assert_eq!(2 + pending.len(), MAX_GRANT_ENTRIES);
687 let profile = Profile::create().unwrap();
688 let path = root.path().join("first");
689 let original = File::open(&path).unwrap();
690 profile.remember(&path, &original, GrantKind::File).unwrap();
691 let identity = profile.grants.lock().unwrap().get(&path).unwrap().identity;
692 drop(original);
693 fs::rename(&path, root.path().join("moved-original")).unwrap();
694 fs::write(&path, b"different object").unwrap();
695 let replacement = File::open(&path).unwrap();
696 assert!(
697 profile
698 .remember(&path, &replacement, GrantKind::File)
699 .is_err()
700 );
701 assert_eq!(
702 profile.grants.lock().unwrap().get(&path).unwrap().identity,
703 identity
704 );
705 // No ACL was granted in this accounting-only check. Do not schedule an
706 // irrelevant retirement against the deliberately replaced fixture path.
707 profile.grants.lock().unwrap().clear();
708 }
709
709 lines RUST