disk-core 0.2.0

Shared base for the rusty-backup filesystem, partition-table and disk-image crates
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
//! Where a new file's POSIX mode / uid / gid actually come from.
//!
//! Every Unix filesystem we can edit — ext, UFS, XFS, EFS, Minix, and SquashFS
//! once its edit path lands — already honours `CreateFileOptions`'s `mode`,
//! `uid` and `gid`. Until now *nothing set them*: `rb-cli put` left all three at
//! `None`, so each driver fell back to its own `unwrap_or` and every added file
//! silently became **root:root 0644**.
//!
//! That is defensible as a last resort and wrong as a default. Replacing
//! `/etc/shadow` should not turn it world-readable; dropping a script into
//! `/usr/local/bin` should not make it non-executable; and replacing a
//! capability-bearing binary should not quietly strip its ownership.
//!
//! This module is the one place that decides, so the CLI, GUI and TUI cannot
//! drift. The rule, highest priority first:
//!
//! | Attribute | Precedence |
//! |---|---|
//! | `mode` | explicit flag -> file being replaced -> host file's own bits -> fallback |
//! | `uid`  | explicit flag -> file being replaced -> parent directory -> 0 |
//! | `gid`  | explicit flag -> file being replaced -> parent directory -> 0 |
//!
//! **Replacing an existing file inherits from it**, because that is the common
//! edit — swap a config, replace a binary — and the file already carries the
//! answer. **A genuinely new file takes ownership from its parent directory**,
//! which is how the surrounding tree is almost always laid out. The host file's
//! permission bits are consulted for `mode` only: macOS carries those faithfully,
//! but its uid/gid (typically 501:20) are meaningless inside a Linux image.
//!
//! Each resolved value records *where it came from* so the operation can say so
//! rather than guessing silently — see [`ResolvedAttrs::describe`].

use crate::entry::FileEntry;

/// Which input supplied a resolved attribute.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttrSource {
    /// An explicit `--mode` / `--uid` / `--gid`, or the GUI's equivalent field.
    Explicit,
    /// Inherited from the file being overwritten.
    Replaced,
    /// Inherited from the containing directory.
    Parent,
    /// Taken from the host file's own permission bits (`mode` only).
    HostFile,
    /// Nothing else applied.
    Fallback,
}

impl AttrSource {
    /// ASCII-only label for log lines (no Unicode glyphs — see CONTRIBUTING).
    pub fn label(self) -> &'static str {
        match self {
            Self::Explicit => "explicit",
            Self::Replaced => "from replaced file",
            Self::Parent => "from parent dir",
            Self::HostFile => "from host file",
            Self::Fallback => "default",
        }
    }
}

/// Caller-supplied overrides. `None` means "decide for me".
#[derive(Debug, Default, Clone, Copy)]
pub struct AttrOverrides {
    /// Permission bits; the file-type bits are the driver's business.
    pub mode: Option<u32>,
    pub uid: Option<u32>,
    pub gid: Option<u32>,
    /// Preserved Unix mtime/atime/ctime from the source (host file,
    /// tar Header, or source-image inode). Threaded through the shared
    /// importer so `create_file` records the source's dates instead of
    /// stamping the current time. See [`crate::times::UnixTimes`].
    pub unix_times: Option<crate::times::UnixTimes>,
}

impl AttrOverrides {
    /// True when the caller specified nothing at all.
    pub fn is_empty(&self) -> bool {
        self.mode.is_none() && self.uid.is_none() && self.gid.is_none() && self.unix_times.is_none()
    }

    /// True when a mode or owner was specified; a date alone is not a permission.
    pub fn has_permissions(&self) -> bool {
        self.mode.is_some() || self.uid.is_some() || self.gid.is_some()
    }
}

/// The decision, with provenance per field.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResolvedAttrs {
    /// Permission bits only (`0o7777`).
    pub mode: u32,
    pub uid: u32,
    pub gid: u32,
    pub mode_from: AttrSource,
    pub uid_from: AttrSource,
    pub gid_from: AttrSource,
}

impl ResolvedAttrs {
    /// One-line ASCII summary naming where each value came from, so a `put`
    /// that inherits `0600 root:root` from the file it replaced says so instead
    /// of leaving the user to discover it later.
    pub fn describe(&self) -> String {
        format!(
            "mode {:04o} ({}), uid {} ({}), gid {} ({})",
            self.mode,
            self.mode_from.label(),
            self.uid,
            self.uid_from.label(),
            self.gid,
            self.gid_from.label(),
        )
    }

    /// The mode as `CreateFileOptions::mode` wants it for a **regular file** —
    /// permission bits OR'd with `S_IFREG`.
    ///
    /// Every driver takes that field as the *complete* mode (ext, UFS and EFS
    /// default it to `0o100644` and write it straight into the inode), so
    /// handing them bare permission bits would produce an inode with no type.
    /// Going through these two helpers keeps that from being rediscovered.
    pub fn file_mode(&self) -> u32 {
        0o100_000 | (self.mode & 0o7777)
    }

    /// The mode for a **directory** — permission bits OR'd with `S_IFDIR`.
    pub fn dir_mode(&self) -> u32 {
        0o040_000 | (self.mode & 0o7777)
    }

    /// True when every field fell through to its last-resort value — the case
    /// worth warning about, because it is the old silent `root:root 0644`.
    pub fn is_all_fallback(&self) -> bool {
        self.mode_from == AttrSource::Fallback
            && self.uid_from == AttrSource::Fallback
            && self.gid_from == AttrSource::Fallback
    }
}

/// Permission bits carried by a browse entry, if it has any.
fn perms_of(entry: &FileEntry) -> Option<u32> {
    entry.mode.map(|m| m & 0o7777)
}

/// Resolve the POSIX attributes for a file about to be created.
///
/// * `replacing` — the entry being overwritten, when this is a replace.
/// * `parent` — the directory it is being created in.
/// * `host_mode` — the source host file's mode, when the content came from one.
/// * `fallback_mode` — last resort (`0o644` for files, `0o755` for directories).
///
/// See the module docs for the precedence table.
pub fn resolve_attrs(
    overrides: &AttrOverrides,
    replacing: Option<&FileEntry>,
    parent: Option<&FileEntry>,
    host_mode: Option<u32>,
    fallback_mode: u32,
) -> ResolvedAttrs {
    let (mode, mode_from) = if let Some(m) = overrides.mode {
        (m & 0o7777, AttrSource::Explicit)
    } else if let Some(m) = replacing.and_then(perms_of) {
        (m, AttrSource::Replaced)
    } else if let Some(m) = host_mode {
        (m & 0o7777, AttrSource::HostFile)
    } else {
        (fallback_mode & 0o7777, AttrSource::Fallback)
    };

    let (uid, uid_from) = resolve_id(
        overrides.uid,
        replacing.and_then(|e| e.uid),
        parent.and_then(|e| e.uid),
    );
    let (gid, gid_from) = resolve_id(
        overrides.gid,
        replacing.and_then(|e| e.gid),
        parent.and_then(|e| e.gid),
    );

    ResolvedAttrs {
        mode,
        uid,
        gid,
        mode_from,
        uid_from,
        gid_from,
    }
}

/// Add execute wherever read is already granted — exactly `chmod a+X`.
///
/// A directory's execute bit means "may be traversed", so a directory with read
/// but no execute can be listed and not entered, which is almost never what
/// anyone wants. Note this deliberately does **not** grant execute to classes
/// that have no read: forcing `o+x` on everything would widen `/root` (0700),
/// `~/.ssh` (0700) and `/etc/ssl/private` — a real security regression, not a
/// convenience.
pub fn add_execute_where_read(mode: u32) -> u32 {
    let mut out = mode;
    for shift in [6, 3, 0] {
        if mode >> shift & 0o4 != 0 {
            out |= 0o1 << shift;
        }
    }
    out
}

/// The extended attributes a replacement file should inherit from the file it
/// displaces.
///
/// The counterpart of [`resolve_attrs`] for the attributes that don't live in
/// the inode. Overwriting is delete-then-create, and the create knows nothing
/// about what was there — so on a filesystem that stores xattrs, replacing a
/// binary that carried `security.capability` produced one without it: a file
/// that still runs, still looks right, and no longer has the privilege it needs.
/// The mode and ownership rules already say a replacement inherits from what it
/// replaces; this applies the same rule to xattrs.
///
/// Pass the result to [`CreateFileOptions::xattrs`](
/// crate::filesystem::CreateFileOptions::xattrs). Returns empty for a new
/// file, or on a filesystem that stores no xattrs — both correctly meaning
/// "nothing to carry over".
///
/// Note the caller must capture this **before** deleting the old entry.
pub fn inherited_xattrs(
    fs: &mut dyn crate::filesystem::Filesystem,
    replacing: Option<&FileEntry>,
) -> Vec<crate::xattr::Xattr> {
    let Some(entry) = replacing else {
        return Vec::new();
    };
    if !fs.supports_xattrs() {
        return Vec::new();
    }
    // A file we cannot read attributes off is not a reason to abort the write;
    // the worst case is the status quo, which is that they are dropped.
    fs.list_xattrs(entry).unwrap_or_default()
}

/// Resolve the POSIX attributes for a **directory** about to be created.
///
/// Differs from [`resolve_attrs`] in two ways that matter:
///
/// * a new directory inherits its mode from the **parent directory**, so a
///   subdirectory created inside a 0700 tree stays 0700 instead of being
///   widened to a blanket 0755;
/// * any non-explicit mode gets [`add_execute_where_read`] applied, so a
///   directory is always traversable by whoever can read it.
///
/// An explicit `--mode` is obeyed verbatim, including a mode with no execute
/// bits: the caller asked for it, and silently "fixing" an explicit request is
/// worse than honouring a strange one.
pub fn resolve_dir_attrs(
    overrides: &AttrOverrides,
    replacing: Option<&FileEntry>,
    parent: Option<&FileEntry>,
) -> ResolvedAttrs {
    let (mode, mode_from) = if let Some(m) = overrides.mode {
        (m & 0o7777, AttrSource::Explicit)
    } else if let Some(m) = replacing.and_then(perms_of) {
        (add_execute_where_read(m), AttrSource::Replaced)
    } else if let Some(m) = parent.and_then(perms_of) {
        (add_execute_where_read(m), AttrSource::Parent)
    } else {
        (0o755, AttrSource::Fallback)
    };

    let (uid, uid_from) = resolve_id(
        overrides.uid,
        replacing.and_then(|e| e.uid),
        parent.and_then(|e| e.uid),
    );
    let (gid, gid_from) = resolve_id(
        overrides.gid,
        replacing.and_then(|e| e.gid),
        parent.and_then(|e| e.gid),
    );

    ResolvedAttrs {
        mode,
        uid,
        gid,
        mode_from,
        uid_from,
        gid_from,
    }
}

/// Shared precedence for uid and gid: explicit, then the replaced file, then
/// the parent directory, then 0. The host file's ids are deliberately not
/// consulted — a macOS 501:20 means nothing inside a Linux image.
fn resolve_id(
    explicit: Option<u32>,
    replaced: Option<u32>,
    parent: Option<u32>,
) -> (u32, AttrSource) {
    if let Some(v) = explicit {
        (v, AttrSource::Explicit)
    } else if let Some(v) = replaced {
        (v, AttrSource::Replaced)
    } else if let Some(v) = parent {
        (v, AttrSource::Parent)
    } else {
        (0, AttrSource::Fallback)
    }
}

/// Everything worth carrying from a file that is about to be replaced.
///
/// Replacing a file writes new *contents*; it is not a request to reset who may
/// read it, when it was made, or what application owns it. But a replace is
/// implemented as delete-then-create on every filesystem here, so unless these
/// are captured first they are simply gone. Only xattrs used to be carried,
/// which meant fixing one line of a config file silently reset its permissions,
/// owner and timestamps.
///
/// Capture with [`preserved_meta`] **before** the delete, apply with
/// [`PreservedMeta::apply_to_options`] and [`PreservedMeta::reapply_dates`].
///
/// Deliberately *not* preserved: the resource fork. That is content rather than
/// metadata, and pairing a new data fork with the previous resource fork
/// produces a file that is neither of the two things it came from.
#[derive(Debug, Clone, Default)]
pub struct PreservedMeta {
    pub mode: Option<u32>,
    pub uid: Option<u32>,
    pub gid: Option<u32>,
    /// Classic-Mac OSType / creator, kept raw so a non-ASCII code survives.
    pub os_type: Option<[u8; 4]>,
    pub os_creator: Option<[u8; 4]>,
    /// ProDOS auxiliary type (a file's load address, say).
    pub aux_type: Option<u16>,
    /// FAT attribute bits: read-only, hidden, system, archive.
    pub dos_attributes: Option<u16>,
    pub amiga_protection: Option<u32>,
    pub amiga_comment: Option<String>,
    pub amiga_dates: Option<(i32, i32, i32)>,
    /// `(created, modified, backup)` in Mac epoch seconds.
    pub mac_dates: Option<(u32, u32, u32)>,
    pub xattrs: Vec<crate::xattr::Xattr>,
}

impl PreservedMeta {
    /// Whether anything was actually captured, so callers can stay quiet when
    /// there is nothing to say.
    pub fn is_empty(&self) -> bool {
        self.mode.is_none()
            && self.uid.is_none()
            && self.gid.is_none()
            && self.os_type.is_none()
            && self.os_creator.is_none()
            && self.aux_type.is_none()
            && self.dos_attributes.is_none()
            && self.amiga_protection.is_none()
            && self.amiga_comment.is_none()
            && self.amiga_dates.is_none()
            && self.mac_dates.is_none()
            && self.xattrs.is_empty()
    }

    /// A short, ASCII-only summary for the log line — the GUI font has no
    /// glyph coverage beyond ASCII.
    pub fn summary(&self) -> String {
        let mut parts: Vec<String> = Vec::new();
        if let Some(m) = self.mode {
            parts.push(format!("mode {:04o}", m & 0o7777));
        }
        if let (Some(u), Some(g)) = (self.uid, self.gid) {
            parts.push(format!("owner {u}:{g}"));
        }
        if let (Some(t), Some(c)) = (self.os_type, self.os_creator) {
            parts.push(format!("type/creator {}/{}", ascii4(&t), ascii4(&c)));
        }
        if let Some(a) = self.dos_attributes {
            parts.push(format!("DOS attrs 0x{a:02x}"));
        }
        if self.amiga_protection.is_some() {
            parts.push("Amiga protection".to_string());
        }
        if self.mac_dates.is_some() || self.amiga_dates.is_some() {
            parts.push("dates".to_string());
        }
        if !self.xattrs.is_empty() {
            parts.push(format!("{} xattr(s)", self.xattrs.len()));
        }
        if parts.is_empty() {
            "nothing to preserve".to_string()
        } else {
            parts.join(", ")
        }
    }

    /// Fill a [`CreateFileOptions`] with the preserved values, leaving anything
    /// the caller already set alone.
    ///
    /// An explicit `--type`/`--mode` is an instruction and must win; preserved
    /// metadata is only the default for fields nobody spoke about.
    pub fn apply_to_options(&self, opts: &mut crate::filesystem::CreateFileOptions) {
        if opts.mode.is_none() {
            opts.mode = self.mode;
        }
        if opts.uid.is_none() {
            opts.uid = self.uid;
        }
        if opts.gid.is_none() {
            opts.gid = self.gid;
        }
        // Only when the caller named neither form of type/creator, since the
        // string and raw forms are two spellings of one field.
        if opts.type_code.is_none() && opts.os_type.is_none() {
            opts.os_type = self.os_type;
        }
        if opts.creator_code.is_none() && opts.os_creator.is_none() {
            opts.os_creator = self.os_creator;
        }
        if opts.aux_type.is_none() {
            opts.aux_type = self.aux_type;
        }
        if opts.dos_attributes.is_none() {
            opts.dos_attributes = self.dos_attributes;
        }
        if opts.amiga_protection.is_none() {
            opts.amiga_protection = self.amiga_protection;
        }
        if opts.amiga_comment.is_none() {
            opts.amiga_comment = self.amiga_comment.clone();
        }
        if opts.amiga_dates.is_none() {
            opts.amiga_dates = self.amiga_dates;
        }
        if opts.xattrs.is_empty() {
            opts.xattrs = self.xattrs.clone();
        }
    }

    /// Restore timestamps, which no filesystem here accepts at creation time.
    ///
    /// Best-effort by design: a filesystem with no date setter answers
    /// `Unsupported`, and failing the whole write over a timestamp would be a
    /// worse outcome than the file keeping today's date. Returns whether the
    /// dates were actually applied so the caller can report honestly.
    pub fn reapply_dates(
        &self,
        fs: &mut dyn crate::filesystem::EditableFilesystem,
        entry: &FileEntry,
    ) -> bool {
        let Some((create, modify, backup)) = self.mac_dates else {
            return false;
        };
        fs.set_dates(entry, create, modify, backup).is_ok()
    }
}

/// Render a four-byte OSType for display, non-printables as `.`.
fn ascii4(v: &[u8; 4]) -> String {
    v.iter()
        .map(|&b| {
            if (0x20..0x7f).contains(&b) {
                b as char
            } else {
                '.'
            }
        })
        .collect()
}

/// Capture the metadata of a file about to be replaced.
///
/// Returns an empty set for a new file, which correctly means "nothing to carry
/// over". Must be called **before** the delete: afterwards there is nothing left
/// to ask.
pub fn preserved_meta(
    fs: &mut dyn crate::filesystem::Filesystem,
    replacing: Option<&FileEntry>,
) -> PreservedMeta {
    let Some(entry) = replacing else {
        return PreservedMeta::default();
    };
    PreservedMeta {
        mode: entry.mode,
        uid: entry.uid,
        gid: entry.gid,
        os_type: entry.type_code,
        os_creator: entry.creator_code,
        aux_type: entry.aux_type,
        dos_attributes: entry.dos_attributes,
        amiga_protection: entry.amiga_protection,
        amiga_comment: entry.amiga_comment.clone(),
        amiga_dates: entry.amiga_date,
        mac_dates: entry.mac_dates,
        xattrs: inherited_xattrs(fs, Some(entry)),
    }
}

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

    fn entry_with(mode: u32, uid: u32, gid: u32) -> FileEntry {
        let mut e = FileEntry::new_file("f".into(), "/f".into(), 0, 0);
        e.mode = Some(mode);
        e.uid = Some(uid);
        e.gid = Some(gid);
        e
    }

    fn bare_dir() -> FileEntry {
        FileEntry::new_directory("d".into(), "/d".into(), 0)
    }

    #[test]
    fn explicit_overrides_win_over_everything() {
        let replaced = entry_with(0o100_600, 7, 8);
        let parent = entry_with(0o040_755, 9, 10);
        let got = resolve_attrs(
            &AttrOverrides {
                mode: Some(0o755),
                uid: Some(1),
                gid: Some(2),
                unix_times: None,
            },
            Some(&replaced),
            Some(&parent),
            Some(0o644),
            0o644,
        );
        assert_eq!((got.mode, got.uid, got.gid), (0o755, 1, 2));
        assert_eq!(got.mode_from, AttrSource::Explicit);
        assert_eq!(got.uid_from, AttrSource::Explicit);
        assert_eq!(got.gid_from, AttrSource::Explicit);
    }

    /// The case that matters most: replacing a file keeps its permissions and
    /// ownership. Overwriting /etc/shadow must not widen it to 0644.
    #[test]
    fn replacing_a_file_inherits_its_mode_and_ownership() {
        let shadow = entry_with(0o100_600, 0, 42);
        let parent = entry_with(0o040_755, 0, 0);
        let got = resolve_attrs(
            &AttrOverrides::default(),
            Some(&shadow),
            Some(&parent),
            // The host copy is a world-readable 0644 -- must NOT win.
            Some(0o644),
            0o644,
        );
        assert_eq!(got.mode, 0o600, "replaced file's mode must win over host's");
        assert_eq!(got.uid, 0);
        assert_eq!(got.gid, 42);
        assert_eq!(got.mode_from, AttrSource::Replaced);
        assert_eq!(got.gid_from, AttrSource::Replaced);
    }

    /// A genuinely new file takes ownership from the directory it lands in, and
    /// its mode from the host file (macOS does carry those bits faithfully).
    #[test]
    fn new_file_takes_parent_ownership_and_host_mode() {
        let parent = entry_with(0o040_755, 0, 20);
        let got = resolve_attrs(
            &AttrOverrides::default(),
            None,
            Some(&parent),
            Some(0o755),
            0o644,
        );
        assert_eq!(got.mode, 0o755);
        assert_eq!(got.mode_from, AttrSource::HostFile);
        assert_eq!(got.uid, 0);
        assert_eq!(got.gid, 20);
        assert_eq!(got.gid_from, AttrSource::Parent);
    }

    /// A filesystem whose entries carry no POSIX metadata at all (FAT, HFS)
    /// must still resolve to something sane rather than panicking.
    #[test]
    fn falls_back_when_nothing_carries_metadata() {
        let parent = bare_dir();
        let got = resolve_attrs(&AttrOverrides::default(), None, Some(&parent), None, 0o644);
        assert_eq!((got.mode, got.uid, got.gid), (0o644, 0, 0));
        assert!(got.is_all_fallback());
    }

    /// Inheriting must strip the file-type bits: a replaced *file* entry
    /// carries 0o100600, and only the 0o600 belongs in the new file's mode.
    #[test]
    fn inherited_mode_drops_the_type_bits() {
        let replaced = entry_with(0o100_640, 0, 0);
        let got = resolve_attrs(
            &AttrOverrides::default(),
            Some(&replaced),
            None,
            None,
            0o644,
        );
        assert_eq!(got.mode, 0o640);
        assert_eq!(got.mode & 0o170_000, 0, "type bits must not survive");
    }

    /// Setuid and sticky bits live in the 0o7777 range and must be preserved
    /// when inheriting -- dropping the setuid bit off /bin/mount would break it.
    #[test]
    fn inherited_mode_keeps_setuid_and_sticky() {
        let replaced = entry_with(0o104_755, 0, 0);
        let got = resolve_attrs(
            &AttrOverrides::default(),
            Some(&replaced),
            None,
            None,
            0o644,
        );
        assert_eq!(got.mode, 0o4755);
    }

    /// `+X` grants execute only where read already is, so it can never widen a
    /// private directory.
    #[test]
    fn add_execute_where_read_never_widens_a_private_dir() {
        // /root and ~/.ssh: owner-only, and must stay that way.
        assert_eq!(add_execute_where_read(0o700), 0o700);
        assert_eq!(add_execute_where_read(0o600), 0o700, "owner r -> owner x");
        // A group-readable, other-invisible dir gains group x, not other x.
        assert_eq!(add_execute_where_read(0o640), 0o750);
        // Already-correct modes are untouched.
        assert_eq!(add_execute_where_read(0o755), 0o755);
        // Nothing readable, nothing granted.
        assert_eq!(add_execute_where_read(0o000), 0o000);
        // setuid/sticky bits ride along unchanged.
        assert_eq!(add_execute_where_read(0o1644), 0o1755);
    }

    /// A new directory inside a 0700 tree must stay 0700, not become 0755.
    #[test]
    fn new_dir_inherits_parent_mode_rather_than_a_blanket_0755() {
        let private = entry_with(0o040_700, 0, 0);
        let got = resolve_dir_attrs(&AttrOverrides::default(), None, Some(&private));
        assert_eq!(got.mode, 0o700, "a subdir of /root must not be widened");
        assert_eq!(got.mode_from, AttrSource::Parent);
    }

    /// A directory that would otherwise be readable-but-not-enterable gets its
    /// execute bits fixed up.
    #[test]
    fn new_dir_becomes_traversable_by_whoever_can_read_it() {
        let odd = entry_with(0o040_644, 0, 0);
        let got = resolve_dir_attrs(&AttrOverrides::default(), None, Some(&odd));
        assert_eq!(got.mode, 0o755);
    }

    /// An explicit mode is obeyed verbatim, even a strange one -- silently
    /// "fixing" what the caller asked for is worse than honouring it.
    #[test]
    fn explicit_dir_mode_is_not_second_guessed() {
        let got = resolve_dir_attrs(
            &AttrOverrides {
                mode: Some(0o644),
                ..Default::default()
            },
            None,
            None,
        );
        assert_eq!(got.mode, 0o644);
        assert_eq!(got.mode_from, AttrSource::Explicit);
    }

    /// One `AttrOverrides` is `Copy`, so a bulk import applies the same
    /// decision to every member without re-deriving it per file.
    #[test]
    fn overrides_apply_uniformly_across_a_batch() {
        let ov = AttrOverrides {
            mode: Some(0o640),
            uid: Some(0),
            gid: Some(0),
            unix_times: None,
        };
        let parents = [entry_with(0o040_755, 99, 99), entry_with(0o040_700, 5, 5)];
        for parent in &parents {
            let got = resolve_attrs(&ov, None, Some(parent), Some(0o777), 0o644);
            assert_eq!((got.mode, got.uid, got.gid), (0o640, 0, 0));
        }
    }

    /// The drivers write `CreateFileOptions::mode` straight into the inode, so
    /// the type bits have to be there. A file created with bare `0o644` would
    /// have no type at all.
    #[test]
    fn mode_helpers_carry_the_type_bits() {
        let got = resolve_attrs(
            &AttrOverrides {
                mode: Some(0o640),
                ..Default::default()
            },
            None,
            None,
            None,
            0o644,
        );
        assert_eq!(got.file_mode(), 0o100_640);
        assert_eq!(got.dir_mode(), 0o040_640);
        // ext / UFS / EFS all default this field to 0o100644; our file mode has
        // to be the same shape.
        assert_eq!(got.file_mode() & 0o170_000, 0o100_000);
    }

    #[test]
    fn describe_names_every_source() {
        let replaced = entry_with(0o100_600, 0, 42);
        let parent = entry_with(0o040_755, 0, 20);
        let got = resolve_attrs(
            &AttrOverrides {
                uid: Some(5),
                ..Default::default()
            },
            Some(&replaced),
            Some(&parent),
            None,
            0o644,
        );
        let text = got.describe();
        assert!(text.contains("mode 0600 (from replaced file)"), "{text}");
        assert!(text.contains("uid 5 (explicit)"), "{text}");
        assert!(text.contains("gid 42 (from replaced file)"), "{text}");
        // ASCII only -- the GUI font has no glyph coverage beyond it.
        assert!(text.is_ascii(), "log text must stay ASCII: {text}");
    }
}