mxc-sdk 1.1.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Tighten conflicting policy paths that refer to the same filesystem object.

use crate::mxc_common::filesystem_probe::FilesystemProbe;
use crate::mxc_common::logger::Logger;
use crate::mxc_common::models::{ContainerPolicy, ScriptResponse};
use std::path::Path;

/// Intent class for a policy path, ordered least → most restrictive so that
/// `max()` yields the strictest intent in a group of aliases.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
enum Intent {
    ReadWrite,
    ReadOnly,
    Denied,
}

impl Intent {
    /// The JSON config list name this intent maps to (for diagnostics).
    fn list_name(self) -> &'static str {
        match self {
            Intent::ReadWrite => "readwritePaths",
            Intent::ReadOnly => "readonlyPaths",
            Intent::Denied => "deniedPaths",
        }
    }
}

/// Opaque identity of a filesystem object. Two paths with the same `ObjectId`
/// refer to the same underlying object even if reached via different names
/// (bind mount, symlink, or hard link).
#[cfg(unix)]
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
struct ObjectId {
    dev: u64,
    ino: u64,
}

#[cfg(windows)]
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
struct ObjectId {
    volume_serial: u64,
    file_id: u128,
}

#[cfg(not(any(unix, windows)))]
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
struct ObjectId {
    _unused: u8,
}

/// Outcome of resolving a policy path to its filesystem-object identity.
enum PathResolution {
    /// The path resolved to a concrete object.
    Object(ObjectId),
    /// The path is cleanly missing (`ENOENT`/`ENOTDIR` or `ERROR_*_NOT_FOUND`).
    /// Nothing to alias; safe to skip. (Existence is surfaced separately by the
    /// parse-time existence warning.)
    Absent,
    /// The caller is denied access to the path, so its identity cannot be read.
    Inaccessible,
    /// The path exists (or may exist) but its identity could not be determined —
    /// an unreachable mount or another I/O error.
    Unknown,
}

/// Why a filesystem policy was refused.
#[derive(Debug, PartialEq, Eq)]
pub enum FilesystemPolicyError {
    /// The request is at fault, e.g. a policy path the caller cannot access.
    Policy(String),
    /// A policy path could not be examined; the same request may succeed later.
    Host(String),
}

impl FilesystemPolicyError {
    pub fn message(&self) -> &str {
        match self {
            Self::Policy(message) | Self::Host(message) => message,
        }
    }

    // SDK v2: Policy -> rejected (policy_validation), Host -> failed(LaunchFailed).
    // See docs/development/plans/sdk-v2-error-codes.md.
    pub fn into_response(self) -> ScriptResponse {
        ScriptResponse::error(self.message())
    }
}

/// Result of comparing two paths by filesystem-object identity.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ExistingObjectComparison {
    /// Both paths resolved to the same object.
    Same,
    /// At least one path is absent (on Windows, with neither path unknown), or
    /// both resolved to different objects.
    Different,
    /// At least one existing or potentially existing path could not be examined.
    Unknown,
}

/// Resolve a path to its filesystem-object identity, following symlinks so two
/// names for the same target collide.
///
/// Distinguishes a *cleanly missing* path ([`PathResolution::Absent`]) from one
/// that exists-or-might-exist but cannot be examined
/// ([`PathResolution::Unknown`]), so the caller can fail closed on the latter
/// without rejecting the common "path created at mount time" case.
#[cfg(unix)]
fn resolve_object(path: &Path) -> PathResolution {
    use std::os::unix::fs::MetadataExt;

    #[cfg(test)]
    super::filesystem_probe::launch_tests::stall("object", path);

    // `metadata` follows symlinks, giving the target object's identity.
    match std::fs::metadata(path) {
        Ok(md) => PathResolution::Object(ObjectId {
            dev: md.dev(),
            ino: md.ino(),
        }),
        // Genuine non-existence is safe to skip; any other errno (EACCES from an
        // untraversable parent, ESTALE/ETIMEDOUT from a dead mount, ...) means we
        // could not examine the path.
        Err(e) => match e.raw_os_error() {
            Some(libc::ENOENT) | Some(libc::ENOTDIR) => PathResolution::Absent,
            Some(libc::EACCES) | Some(libc::EPERM) => PathResolution::Inaccessible,
            _ => PathResolution::Unknown,
        },
    }
}

#[cfg(windows)]
fn resolve_object(path: &Path) -> PathResolution {
    use std::os::windows::ffi::OsStrExt;
    use windows::core::PCWSTR;
    use windows::Win32::Foundation::{
        CloseHandle, GetLastError, ERROR_ACCESS_DENIED, ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND,
    };
    use windows::Win32::Storage::FileSystem::{
        CreateFileW, FileIdInfo, GetFileInformationByHandleEx, FILE_FLAG_BACKUP_SEMANTICS,
        FILE_ID_INFO, FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
        OPEN_EXISTING,
    };

    #[cfg(test)]
    super::filesystem_probe::launch_tests::stall("object", path);

    let wide: Vec<u16> = path
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    let share = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;

    // FILE_READ_ATTRIBUTES is the minimum access GetFileInformationByHandleEx
    // (FileIdInfo) needs to read the object identity; a zero-access handle can
    // be rejected (ERROR_ACCESS_DENIED) on some filesystems. We deliberately do
    // NOT request data-read access. FILE_FLAG_BACKUP_SEMANTICS lets the same
    // call open directories as well as files. SAFETY: `wide` is a local
    // NUL-terminated buffer; all other pointers are NULL.
    let handle = unsafe {
        CreateFileW(
            PCWSTR(wide.as_ptr()),
            FILE_READ_ATTRIBUTES.0,
            share,
            None,
            OPEN_EXISTING,
            FILE_FLAG_BACKUP_SEMANTICS,
            None,
        )
    };
    let handle = match handle {
        Ok(h) if !h.is_invalid() => h,
        _ => {
            // Distinguish a cleanly-missing path from an unexaminable one.
            // SAFETY: reads the thread-local last error set by the failed call.
            let err = unsafe { GetLastError() };
            return if err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND {
                classify_not_found_leaf_windows(path)
            } else if err == ERROR_ACCESS_DENIED {
                PathResolution::Inaccessible
            } else {
                PathResolution::Unknown
            };
        }
    };

    let mut info = FILE_ID_INFO::default();
    // SAFETY: `handle` is valid; `info` is a correctly sized out-param.
    let rc = unsafe {
        GetFileInformationByHandleEx(
            handle,
            FileIdInfo,
            &mut info as *mut FILE_ID_INFO as *mut core::ffi::c_void,
            std::mem::size_of::<FILE_ID_INFO>() as u32,
        )
    };
    // SAFETY: `handle` came from a successful CreateFileW above.
    unsafe {
        let _ = CloseHandle(handle);
    }
    if rc.is_err() {
        // We opened the object but couldn't read its identity — treat as
        // unexaminable rather than absent.
        return PathResolution::Unknown;
    }
    PathResolution::Object(ObjectId {
        volume_serial: info.VolumeSerialNumber,
        file_id: u128::from_le_bytes(info.FileId.Identifier),
    })
}

#[cfg(windows)]
fn classify_not_found_leaf_windows(path: &Path) -> PathResolution {
    use windows::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND};

    match std::fs::symlink_metadata(path) {
        // `symlink_metadata` examines the leaf without following its reparse
        // point. Success here means the followed open may have failed because
        // the leaf is a dangling symlink/junction, which must fail closed.
        Ok(_) => PathResolution::Unknown,
        Err(error) => match error.raw_os_error() {
            Some(code)
                if code == ERROR_FILE_NOT_FOUND.0 as i32
                    || code == ERROR_PATH_NOT_FOUND.0 as i32 =>
            {
                PathResolution::Absent
            }
            _ => PathResolution::Unknown,
        },
    }
}

#[cfg(not(any(unix, windows)))]
fn resolve_object(_path: &Path) -> PathResolution {
    // No way to determine object identity on unsupported platforms; treat as
    // unexaminable so the fail-closed path applies when deniedPaths are present.
    PathResolution::Unknown
}

/// Compare two paths by filesystem-object identity.
pub fn compare_existing_filesystem_objects(a: &Path, b: &Path) -> ExistingObjectComparison {
    compare_resolved_filesystem_objects(resolve_object(a), resolve_object(b))
}

fn compare_resolved_filesystem_objects(
    a: PathResolution,
    b: PathResolution,
) -> ExistingObjectComparison {
    match (a, b) {
        (PathResolution::Object(a), PathResolution::Object(b)) if a == b => {
            ExistingObjectComparison::Same
        }
        // Unknown must take precedence over Absent on every platform. Treating
        // an unexaminable path as merely different would let callers proceed
        // without proving that the policy paths refer to distinct objects.
        (PathResolution::Unknown | PathResolution::Inaccessible, _)
        | (_, PathResolution::Unknown | PathResolution::Inaccessible) => {
            ExistingObjectComparison::Unknown
        }
        (PathResolution::Absent, _) | (_, PathResolution::Absent) => {
            ExistingObjectComparison::Different
        }
        (PathResolution::Object(_), PathResolution::Object(_)) => {
            ExistingObjectComparison::Different
        }
    }
}

pub fn normalize_object_conflicts(
    policy: &ContainerPolicy,
    logger: &mut Logger,
) -> Result<Option<ContainerPolicy>, FilesystemPolicyError> {
    let mut probe = FilesystemProbe::default();
    normalize_object_conflicts_with(policy, logger, |path| {
        probe.run(path, |path| resolve_object(Path::new(path)))
    })
}

fn normalize_object_conflicts_with(
    policy: &ContainerPolicy,
    logger: &mut Logger,
    mut resolve: impl FnMut(&str) -> Result<PathResolution, String>,
) -> Result<Option<ContainerPolicy>, FilesystemPolicyError> {
    let total =
        policy.readwrite_paths.len() + policy.readonly_paths.len() + policy.denied_paths.len();
    // A conflict needs at least two paths resolving to the same object, so a
    // policy with 0 or 1 total paths can never tighten — skip the file I/O.
    if total <= 1 {
        return Ok(None);
    }

    use std::collections::{HashMap, HashSet};

    // Flatten every (path, intent) in a stable order: rw, then ro, then denied.
    let mut entries: Vec<(String, Intent)> = Vec::with_capacity(total);
    for p in &policy.readwrite_paths {
        entries.push((p.clone(), Intent::ReadWrite));
    }
    for p in &policy.readonly_paths {
        entries.push((p.clone(), Intent::ReadOnly));
    }
    for p in &policy.denied_paths {
        entries.push((p.clone(), Intent::Denied));
    }

    // Group entry indices by object identity. Resolution has three outcomes:
    // - `Object`: grouped for conflict detection.
    // - `Absent` (cleanly missing): skipped — nothing to alias.
    // - `Inaccessible` / `Unknown` (exists/maybe-exists but unexaminable): when
    //   `deniedPaths` are present we cannot prove this path is not an
    //   undetectable alias that would bypass a deny, so we FAIL CLOSED. Without
    //   `deniedPaths` there is no deny to bypass, so we log it and leave it in
    //   place.
    let has_denied = !policy.denied_paths.is_empty();
    let mut groups: HashMap<ObjectId, Vec<usize>> = HashMap::new();
    for (i, (path, intent)) in entries.iter().enumerate() {
        match resolve(path).map_err(FilesystemPolicyError::Host)? {
            PathResolution::Object(id) => {
                groups.entry(id).or_default().push(i);
            }
            PathResolution::Absent => {}
            PathResolution::Inaccessible if has_denied => {
                return Err(FilesystemPolicyError::Policy(unresolvable_message(
                    path,
                    *intent,
                    "permission denied",
                    "Grant access to the path, or remove the offending entry.",
                )));
            }
            PathResolution::Unknown if has_denied => {
                return Err(FilesystemPolicyError::Host(unresolvable_message(
                    path,
                    *intent,
                    "unreachable mount or I/O error",
                    "Retry once the path is reachable, or remove the offending entry.",
                )));
            }
            PathResolution::Inaccessible | PathResolution::Unknown => {
                logger.log_line(&format!(
                    "WARNING: filesystem path '{}' ({}) could not be resolved to a filesystem \
                     object and was not checked for aliasing",
                    path,
                    intent.list_name(),
                ));
            }
        }
    }

    // Final intent per entry (defaults to its declared intent).
    let mut final_intent: Vec<Intent> = entries.iter().map(|(_, it)| *it).collect();
    let mut changed = false;

    for members in groups.values() {
        if members.len() < 2 {
            continue;
        }
        // Strictest intent among the aliases.
        let target = members.iter().map(|&i| entries[i].1).max().unwrap();
        if members.iter().all(|&i| entries[i].1 == target) {
            // All aliases already share the strictest intent — redundant, not a
            // conflict.
            continue;
        }
        // A representative alias already at the strictest intent (for the message).
        let rep = members
            .iter()
            .copied()
            .find(|&i| entries[i].1 == target)
            .unwrap();
        let rep_path = entries[rep].0.clone();
        for &i in members {
            if entries[i].1 < target {
                logger.log_line(&format!(
                    "Filesystem path '{}' ({}) and '{}' ({}) resolve to the same filesystem \
                     object; applying most-restrictive intent ({}) to '{}'",
                    entries[i].0,
                    entries[i].1.list_name(),
                    rep_path,
                    target.list_name(),
                    target.list_name(),
                    entries[i].0,
                ));
                final_intent[i] = target;
                changed = true;
            }
        }
    }

    // Nothing was tightened: no aliasing conflict, so the caller can keep using
    // the original policy without cloning.
    if !changed {
        return Ok(None);
    }

    // Rebuild the three lists from the resolved intents. Within each list,
    // entries keep first-seen order across the flattened rw → ro → denied
    // sequence — so a path tightened from rw to denied lands ahead of paths
    // originally in denied — de-duplicating within each list.
    let mut rw = Vec::new();
    let mut ro = Vec::new();
    let mut dn = Vec::new();
    let mut seen_rw = HashSet::new();
    let mut seen_ro = HashSet::new();
    let mut seen_dn = HashSet::new();
    for (i, (path, _)) in entries.into_iter().enumerate() {
        match final_intent[i] {
            Intent::ReadWrite => {
                if seen_rw.insert(path.clone()) {
                    rw.push(path);
                }
            }
            Intent::ReadOnly => {
                if seen_ro.insert(path.clone()) {
                    ro.push(path);
                }
            }
            Intent::Denied => {
                if seen_dn.insert(path.clone()) {
                    dn.push(path);
                }
            }
        }
    }
    let mut new_policy = policy.clone();
    new_policy.readwrite_paths = rw;
    new_policy.readonly_paths = ro;
    new_policy.denied_paths = dn;
    Ok(Some(new_policy))
}

fn unresolvable_message(path: &str, intent: Intent, cause: &str, remedy: &str) -> String {
    format!(
        "Filesystem path '{path}' ({}) could not be resolved to a filesystem object ({cause}). \
         Because deniedPaths are present, MXC cannot verify it does not alias a denied object \
         and refuses to run rather than risk bypassing the deny. {remedy}",
        intent.list_name(),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unknown_resolution_takes_precedence_over_absent() {
        assert_eq!(
            compare_resolved_filesystem_objects(PathResolution::Absent, PathResolution::Unknown),
            ExistingObjectComparison::Unknown
        );
        assert_eq!(
            compare_resolved_filesystem_objects(PathResolution::Unknown, PathResolution::Absent),
            ExistingObjectComparison::Unknown
        );
    }
    use crate::mxc_common::logger::{Logger, Mode};

    fn policy(rw: &[&str], ro: &[&str], dn: &[&str]) -> ContainerPolicy {
        ContainerPolicy {
            readwrite_paths: rw.iter().map(|s| s.to_string()).collect(),
            readonly_paths: ro.iter().map(|s| s.to_string()).collect(),
            denied_paths: dn.iter().map(|s| s.to_string()).collect(),
            ..Default::default()
        }
    }

    /// Run normalization asserting it does not reject, returning the (optional)
    /// tightened policy.
    fn normalize_ok(p: &ContainerPolicy, logger: &mut Logger) -> Option<ContainerPolicy> {
        normalize_object_conflicts(p, logger).expect("normalization must not reject")
    }

    #[test]
    fn empty_policy_is_noop() {
        let p = ContainerPolicy::default();
        let mut logger = Logger::new(Mode::Buffer);
        assert!(normalize_ok(&p, &mut logger).is_none());
    }

    #[test]
    fn probe_failure_rejects_even_without_denied_paths() {
        for p in [
            policy(&["slow"], &["readable"], &[]),
            policy(&["slow"], &[], &["denied"]),
        ] {
            let mut logger = Logger::new(Mode::Buffer);
            let error = normalize_object_conflicts_with(&p, &mut logger, |path| {
                Err(format!("probe for {path} timed out"))
            })
            .unwrap_err();
            assert_eq!(
                error,
                FilesystemPolicyError::Host("probe for slow timed out".to_string())
            );
            assert!(logger.get_buffer().is_empty());
        }
    }

    #[test]
    fn single_path_does_not_start_a_probe() {
        let mut logger = Logger::new(Mode::Buffer);
        let result =
            normalize_object_conflicts_with(&policy(&["single"], &[], &[]), &mut logger, |_| {
                panic!("one path cannot alias another policy entry")
            });
        assert!(result.unwrap().is_none());
    }

    #[test]
    fn missing_paths_left_untouched() {
        // Cleanly-missing paths resolve to Absent — no grouping, no change, and
        // (crucially) no fail-closed rejection even with deniedPaths present.
        let p = policy(
            &["/nonexistent/mxc-test-rw"],
            &["/nonexistent/mxc-test-ro"],
            &["/nonexistent/mxc-test-dn"],
        );
        let mut logger = Logger::new(Mode::Buffer);
        assert!(
            normalize_ok(&p, &mut logger).is_none(),
            "cleanly-missing paths must not trigger a change or a rejection"
        );
    }

    #[test]
    fn absent_paths_do_not_warn_or_reject() {
        // Absent (not Unknown) paths are the benign "created at mount time" case:
        // no warning, no rejection, even alongside deniedPaths.
        let p = policy(&["/nonexistent/mxc-a"], &[], &["/nonexistent/mxc-b"]);
        let mut logger = Logger::new(Mode::Buffer);
        assert!(normalize_ok(&p, &mut logger).is_none());
        assert!(
            !logger.get_buffer().contains("could not be resolved"),
            "absent paths must not warn about being unresolved"
        );
    }

    #[test]
    fn single_path_skips_all_io() {
        // A policy with a single path can never form a conflict; the early-return
        // must avoid touching the filesystem entirely (returns Ok(None)).
        let p = policy(&["/nonexistent/only-one"], &[], &[]);
        let mut logger = Logger::new(Mode::Buffer);
        assert!(normalize_ok(&p, &mut logger).is_none());
        assert!(logger.get_buffer().is_empty());
    }

    #[test]
    fn distinct_objects_with_different_intents_preserved() {
        let dir = tempfile::tempdir().unwrap();
        let a = dir.path().join("a");
        let b = dir.path().join("b");
        std::fs::write(&a, b"a").unwrap();
        std::fs::write(&b, b"b").unwrap();
        let (a, b) = (a.to_str().unwrap(), b.to_str().unwrap());

        let p = policy(&[a], &[b], &[]);
        let mut logger = Logger::new(Mode::Buffer);
        // Distinct objects, no aliasing: nothing to tighten.
        assert!(normalize_ok(&p, &mut logger).is_none());
    }

    #[test]
    fn same_object_same_intent_is_not_a_conflict() {
        // Two distinct path strings to the same object via a hard link (works on
        // both Unix and Windows, and exercises the platform object identity
        // grouping), both read-write — redundant but not a conflict, nothing moves.
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("target");
        std::fs::write(&target, b"x").unwrap();
        let alias = dir.path().join("alias");
        std::fs::hard_link(&target, &alias).unwrap();

        let (t, a) = (target.to_str().unwrap(), alias.to_str().unwrap());
        let p = policy(&[t, a], &[], &[]);
        let mut logger = Logger::new(Mode::Buffer);
        assert!(normalize_ok(&p, &mut logger).is_none());
    }

    #[cfg(unix)]
    #[test]
    fn symlink_rw_and_denied_tightens_to_denied() {
        // `target` is RW, `link` (a symlink to it) is denied → both become denied.
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("target");
        std::fs::write(&target, b"secret").unwrap();
        let link = dir.path().join("link");
        std::os::unix::fs::symlink(&target, &link).unwrap();
        let (t, l) = (target.to_str().unwrap(), link.to_str().unwrap());

        let p = policy(&[t], &[], &[l]);
        let mut logger = Logger::new(Mode::Buffer);
        let out = normalize_ok(&p, &mut logger)
            .expect("rw+denied aliases of one object must produce a tightened policy");

        assert!(
            out.readwrite_paths.is_empty(),
            "rw alias of a denied object must be tightened to denied"
        );
        assert!(out.denied_paths.contains(&t.to_string()));
        assert!(out.denied_paths.contains(&l.to_string()));
    }

    // Not unix-gated: `std::fs::hard_link` works on Windows too, so this gives
    // the Windows object identity (FileIdInfo) grouping + rebuild path real
    // tightening coverage (the symlink-based tightening tests are unix-only).
    #[test]
    fn hardlink_rw_and_readonly_tightens_to_readonly() {
        // Hard link: two names, same object. RW + RO → both read-only.
        let dir = tempfile::tempdir().unwrap();
        let a = dir.path().join("a");
        std::fs::write(&a, b"data").unwrap();
        let b = dir.path().join("b");
        std::fs::hard_link(&a, &b).unwrap();
        let (a, b) = (a.to_str().unwrap(), b.to_str().unwrap());

        let p = policy(&[a], &[b], &[]);
        let mut logger = Logger::new(Mode::Buffer);
        let out = normalize_ok(&p, &mut logger)
            .expect("rw+ro aliases of one object must produce a tightened policy");

        assert!(
            out.readwrite_paths.is_empty(),
            "rw alias of a read-only object must be tightened to read-only"
        );
        assert!(out.readonly_paths.contains(&a.to_string()));
        assert!(out.readonly_paths.contains(&b.to_string()));
    }

    #[cfg(windows)]
    #[test]
    fn dangling_symlink_is_unknown_even_when_target_is_absent() {
        use std::os::windows::fs::symlink_file;

        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("missing-target");
        let link = dir.path().join("dangling-link");
        if let Err(error) = symlink_file(&target, &link) {
            // Creating symlinks requires Developer Mode or SeCreateSymbolicLink
            // privilege on some supported Windows hosts.
            if error.raw_os_error() == Some(1314) {
                return;
            }
            panic!("failed to create dangling symlink: {error}");
        }

        assert!(matches!(resolve_object(&link), PathResolution::Unknown));
        assert_eq!(
            compare_existing_filesystem_objects(&link, &target),
            ExistingObjectComparison::Unknown
        );
    }

    #[cfg(unix)]
    #[test]
    fn denied_wins_over_both_rw_and_ro_aliases() {
        // Three aliases of one object across all three lists → all denied.
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("obj");
        std::fs::write(&target, b"x").unwrap();
        let l1 = dir.path().join("l1");
        let l2 = dir.path().join("l2");
        std::os::unix::fs::symlink(&target, &l1).unwrap();
        std::os::unix::fs::symlink(&target, &l2).unwrap();
        let (t, a, b) = (
            target.to_str().unwrap(),
            l1.to_str().unwrap(),
            l2.to_str().unwrap(),
        );

        // t = rw, a = ro, b = denied.
        let p = policy(&[t], &[a], &[b]);
        let mut logger = Logger::new(Mode::Buffer);
        let out = normalize_ok(&p, &mut logger)
            .expect("three aliases across all lists must produce a tightened policy");

        assert!(out.readwrite_paths.is_empty());
        assert!(out.readonly_paths.is_empty());
        assert_eq!(out.denied_paths.len(), 3);
    }

    #[cfg(unix)]
    #[test]
    fn unresolvable_path_with_denied_fails_closed() {
        use std::os::unix::fs::PermissionsExt;

        // Root bypasses traversal permission, so this case is only meaningful as
        // a non-root user.
        if unsafe { libc::geteuid() } == 0 {
            return;
        }

        // A file inside a directory the caller can't traverse: it exists but
        // can't be examined (EACCES → Unknown, not Absent). With deniedPaths
        // present, we cannot rule out an alias bypass, so the config is rejected.
        let dir = tempfile::tempdir().unwrap();
        let locked = dir.path().join("locked");
        std::fs::create_dir(&locked).unwrap();
        let hidden = locked.join("data.txt");
        std::fs::write(&hidden, b"data").unwrap();
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();

        // The unexaminable path is read-write; a separate denied path is present.
        let denied = dir.path().join("denied");
        std::fs::write(&denied, b"x").unwrap();
        let p = policy(
            &[hidden.to_str().unwrap()],
            &[],
            &[denied.to_str().unwrap()],
        );
        let mut logger = Logger::new(Mode::Buffer);
        let err = normalize_object_conflicts(&p, &mut logger)
            .expect_err("an unexaminable path with deniedPaths present must fail closed");
        assert!(
            matches!(&err, FilesystemPolicyError::Policy(message)
                if message.contains("could not be resolved") && message.contains("deniedPaths")),
            "expected a fail-closed policy rejection, got: {err:?}"
        );

        // Restore traversal so the tempdir can recurse in during cleanup.
        let _ = std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755));
    }

    #[cfg(unix)]
    #[test]
    fn unresolvable_path_without_denied_does_not_reject() {
        use std::os::unix::fs::PermissionsExt;

        if unsafe { libc::geteuid() } == 0 {
            return;
        }

        // Same unexaminable path, but NO deniedPaths: there is no deny to bypass,
        // so it must NOT reject — it is logged and left in place.
        let dir = tempfile::tempdir().unwrap();
        let locked = dir.path().join("locked");
        std::fs::create_dir(&locked).unwrap();
        let hidden = locked.join("data.txt");
        std::fs::write(&hidden, b"data").unwrap();
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();

        let other = dir.path().join("other");
        std::fs::write(&other, b"y").unwrap();
        let p = policy(&[hidden.to_str().unwrap()], &[other.to_str().unwrap()], &[]);
        let mut logger = Logger::new(Mode::Buffer);
        assert!(
            normalize_ok(&p, &mut logger).is_none(),
            "unexaminable path without deniedPaths must not reject or tighten"
        );
        assert!(
            logger.get_buffer().contains("could not be resolved"),
            "unexaminable path should be logged"
        );

        let _ = std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755));
    }

    #[cfg(windows)]
    #[test]
    fn unresolvable_path_with_denied_fails_closed_windows() {
        use std::process::Command;

        // A file with an explicit deny-read ACE cannot be opened even for
        // FILE_READ_ATTRIBUTES, so resolve_object returns Unknown (ACCESS_DENIED,
        // not NOT_FOUND). With deniedPaths present, the config must fail closed.
        let dir = tempfile::tempdir().unwrap();
        let hidden = dir.path().join("hidden.txt");
        std::fs::write(&hidden, b"data").unwrap();
        let h = hidden.to_str().unwrap();
        let status = Command::new("icacls")
            .args([h, "/deny", "*S-1-1-0:(R)"])
            .output()
            .expect("icacls should run");
        assert!(status.status.success());

        let denied = dir.path().join("denied.txt");
        std::fs::write(&denied, b"x").unwrap();
        let p = policy(&[h], &[], &[denied.to_str().unwrap()]);
        let mut logger = Logger::new(Mode::Buffer);
        let err = normalize_object_conflicts(&p, &mut logger)
            .expect_err("an unexaminable path with deniedPaths present must fail closed");
        assert!(
            matches!(&err, FilesystemPolicyError::Policy(message)
                if message.contains("could not be resolved") && message.contains("deniedPaths")),
            "expected a fail-closed policy rejection, got: {err:?}"
        );

        // Remove the deny ACE so the tempdir can clean up.
        let _ = Command::new("icacls")
            .args([h, "/remove:d", "*S-1-1-0"])
            .output();
    }
}