cloudfox-coreshift-core 1.2.23

Low-level Linux and Android systems primitives for CoreShift (CloudFox)
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Symlink-safe file primitives.
//!
//! The daemon runs as root and writes state into `/data/local/tmp`
//! (attacker-writable). Plain `fs::write`/`OpenOptions` follow symlinks, so an
//! attacker who pre-creates a symlink at the target path — or swaps an
//! intermediate directory for a symlink — causes a root write-through to an
//! arbitrary file (N5).
//!
//! Every primitive here is fd-anchored: the parent directory is resolved with
//! `O_NOFOLLOW` at every path component and held as an open directory fd, then
//! all operations (`openat`/`renameat`/`unlinkat`) run relative to that fd.
//! A swapped parent directory or symlink therefore cannot redirect the write.

use std::ffi::CString;
use std::fs;
use std::io::{self, Read, Write};
use std::os::unix::io::{AsRawFd, FromRawFd, OwnedFd, RawFd};
use std::path::Path;

const TEMP_ATTEMPTS: usize = 32;

fn cstr(s: &str) -> io::Result<CString> {
    CString::new(s)
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "NUL byte in path component"))
}

fn openat_raw(dirfd: RawFd, name: &str, flags: i32, mode: u32) -> io::Result<RawFd> {
    let c = cstr(name)?;
    // SAFETY: `name` is a single path component (no `/`) converted to a
    // NUL-terminated string, and `dirfd` is a valid open directory fd.
    let fd = unsafe { libc::openat(dirfd, c.as_ptr(), flags, mode as libc::c_uint) };
    if fd < 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(fd)
    }
}

fn openat_dir(dirfd: RawFd, name: &str) -> io::Result<OwnedFd> {
    let fd = openat_raw(
        dirfd,
        name,
        libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
        0,
    )?;
    // SAFETY: `fd` came from openat and is uniquely owned here.
    Ok(unsafe { OwnedFd::from_raw_fd(fd) })
}

/// Resolve `path` from the root down to a directory fd, refusing to traverse
/// Walk `path` from the root down to a directory fd, refusing to traverse any
/// symlink component (ELOOP) or non-directory (ENOTDIR). When `create_mode` is
/// `Some(mode)`, missing components are created via `mkdirat` relative to the
/// previously held fd — never by re-resolving a path, so an attacker link can
/// never make root create a directory at an attacker-chosen location (N5).
fn walk_dir(path: &Path, create_mode: Option<u32>) -> io::Result<OwnedFd> {
    let abs = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()?.join(path)
    };
    let mut dir = openat_dir(libc::AT_FDCWD, "/")?;
    for comp in abs.components() {
        use std::path::Component;
        match comp {
            Component::RootDir | Component::CurDir => {}
            Component::Normal(name) => {
                let name = name.to_str().ok_or_else(|| {
                    io::Error::new(io::ErrorKind::InvalidInput, "non-UTF-8 path component")
                })?;
                let next = match openat_dir(dir.as_raw_fd(), name) {
                    Ok(fd) => fd,
                    Err(e) if e.kind() == io::ErrorKind::NotFound && create_mode.is_some() => {
                        let c = cstr(name)?;
                        // SAFETY: mkdirat creates a single directory entry
                        // relative to the held fd; no pathname resolution of
                        // attacker components.
                        if unsafe {
                            libc::mkdirat(dir.as_raw_fd(), c.as_ptr(), create_mode.unwrap() as libc::mode_t)
                        } != 0
                        {
                            // Raced with another creator; if it now exists as a
                            // real directory, use it. A symlink raced into place
                            // still fails O_NOFOLLOW below.
                            if io::Error::last_os_error().raw_os_error() == Some(libc::EEXIST) {
                                openat_dir(dir.as_raw_fd(), name)?
                            } else {
                                return Err(io::Error::last_os_error());
                            }
                        } else {
                            openat_dir(dir.as_raw_fd(), name)?
                        }
                    }
                    Err(e) => return Err(e),
                };
                dir = next;
            }
            Component::ParentDir => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    ".. in state path not allowed",
                ))
            }
            Component::Prefix(_) => unreachable!("non-Windows path"),
        }
    }
    Ok(dir)
}

/// Resolve `path` from the root down to a directory fd, refusing to traverse
/// any symlink component (ELOOP) or non-directory (ENOTDIR).
fn open_dir_nofollow(path: &Path) -> io::Result<OwnedFd> {
    walk_dir(path, None)
}

fn fstat(fd: RawFd) -> io::Result<libc::stat> {
    let mut st: libc::stat = unsafe { std::mem::zeroed() };
    // SAFETY: `fd` is valid and `st` remains alive for the call.
    if unsafe { libc::fstat(fd, &mut st) } != 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(st)
    }
}

fn unlink_name(dirfd: RawFd, name: &str) -> io::Result<()> {
    let c = cstr(name)?;
    // SAFETY: unlinkat without AT_SYMLINK_FOLLOW removes the directory entry
    // itself and never follows a final symlink.
    if unsafe { libc::unlinkat(dirfd, c.as_ptr(), 0) } != 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

fn basename(target: &Path) -> io::Result<String> {
    target
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no file name"))
}

fn parent_dir(target: &Path) -> &Path {
    target
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."))
}

/// Open the parent directory of `target` fd-anchored (O_NOFOLLOW walk) and
/// verify it is owned by the current effective uid.
///
/// Requiring ownership on every operation closes the directory-swap vector:
/// an attacker who renames the state dir and substitutes their own can never
/// make the daemon read from or write into the substituted directory, because
/// the substituted dir fails the ownership check regardless of the path.
fn open_parent_nofollow(target: &Path) -> io::Result<OwnedFd> {
    let dir = open_dir_nofollow(parent_dir(target))?;
    let st = fstat(dir.as_raw_fd())?;
    let euid = unsafe { libc::geteuid() };
    if st.st_uid != euid {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!(
                "parent directory is owned by uid {}, not euid {}",
                st.st_uid, euid
            ),
        ));
    }
    Ok(dir)
}

struct TmpGuard {
    dirfd: RawFd,
    name: String,
}

impl Drop for TmpGuard {
    fn drop(&mut self) {
        let _ = unlink_name(self.dirfd, &self.name);
    }
}

/// Atomically replace `path` with `content`.
///
/// The parent directory is opened `O_NOFOLLOW` component-by-component and held
/// as a directory fd; the content is written to a fresh `O_CREAT|O_EXCL`
/// temp file via `openat` and then `renameat`d over the destination. A symlink
/// anywhere in the parent path fails the open; a symlink at the destination is
/// replaced by the rename, never followed (N5).
pub fn write_atomic(path: impl AsRef<Path>, content: &[u8]) -> io::Result<()> {
    let target = path.as_ref();
    let file_name = basename(target)?;
    let dir = open_parent_nofollow(target)?;
    let dirfd = dir.as_raw_fd();

    for attempt in 0..TEMP_ATTEMPTS {
        let tmp_name = format!(".{file_name}.{}.{attempt}", std::process::id());
        match openat_raw(
            dirfd,
            &tmp_name,
            libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_CLOEXEC,
            0o600,
        ) {
            Ok(raw) => {
                // SAFETY: `raw` came from openat with O_EXCL and is uniquely
                // owned; it becomes an owned File for the write.
                let mut file = unsafe { fs::File::from_raw_fd(raw) };
                let _guard = TmpGuard {
                    dirfd,
                    name: tmp_name.clone(),
                };
                file.write_all(content)?;
                file.sync_all()?;
                drop(file);
                let c_tmp = cstr(&tmp_name)?;
                let c_final = cstr(&file_name)?;
                // SAFETY: renameat replaces the destination entry and never
                // follows a final symlink; both names are single components
                // relative to the anchored directory fd.
                if unsafe { libc::renameat(dirfd, c_tmp.as_ptr(), dirfd, c_final.as_ptr()) } != 0 {
                    return Err(io::Error::last_os_error());
                }
                // rename succeeded; the temp entry no longer exists.
                std::mem::forget(_guard);
                return Ok(());
            }
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
            Err(e) => return Err(e),
        }
    }

    Err(io::Error::new(
        io::ErrorKind::AlreadyExists,
        "could not reserve a unique temp name",
    ))
}

/// Read a file to a string, refusing to follow a symlink at the final or any
/// parent component.
///
/// Fails with `ELOOP` if `path` is a symlink or passes through one. Used for
/// reading attacker-placed state files so their contents can never be injected
/// through a link.
pub fn read_nofollow(path: impl AsRef<Path>) -> io::Result<String> {
    let target = path.as_ref();
    let file_name = basename(target)?;
    let dir = open_parent_nofollow(target)?;
    let fd = openat_raw(
        dir.as_raw_fd(),
        &file_name,
        libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
        0,
    )?;
    // SAFETY: `fd` is uniquely owned; it becomes an owned File.
    let mut file = unsafe { fs::File::from_raw_fd(fd) };
    let mut content = String::new();
    file.read_to_string(&mut content)?;
    Ok(content)
}

/// Open an existing-or-create append stream that refuses to follow symlinks.
///
/// Appends to a regular file at `path`. If `path` is a symlink — or sits under
/// a symlinked parent — the open fails with `ELOOP` rather than writing
/// through it.
pub fn open_append_nofollow(path: impl AsRef<Path>) -> io::Result<fs::File> {
    let target = path.as_ref();
    let file_name = basename(target)?;
    let dir = open_parent_nofollow(target)?;
    let fd = openat_raw(
        dir.as_raw_fd(),
        &file_name,
        libc::O_WRONLY | libc::O_CREAT | libc::O_APPEND | libc::O_NOFOLLOW | libc::O_CLOEXEC,
        0o644,
    )?;
    // SAFETY: `fd` is uniquely owned; it becomes an owned File.
    Ok(unsafe { fs::File::from_raw_fd(fd) })
}

/// Remove a directory entry without following a final symlink, anchored to its
/// (symlink-free) parent. The entry itself is removed even if it is a symlink;
/// its target is never touched.
pub fn remove_nofollow(path: impl AsRef<Path>) -> io::Result<()> {
    let target = path.as_ref();
    let file_name = basename(target)?;
    let dir = open_parent_nofollow(target)?;
    unlink_name(dir.as_raw_fd(), &file_name)
}

/// Create `dir` if needed, then verify it is a real directory with no symlink
/// component and that it is owned by the current effective uid. Returning the
/// anchored fd lets callers refuse to operate inside an attacker-pre-created
/// or attacker-redirected state directory.
pub fn ensure_state_dir(dir: impl AsRef<Path>) -> io::Result<OwnedFd> {
    let dir = dir.as_ref();
    // Anchored create-then-verify: missing components are made with mkdirat
    // relative to the held fd; a symlink at any component ELOOPs rather than
    // being followed, and the opened fd below is the authority for ownership.
    let fd = walk_dir(dir, Some(0o700))?;
    let st = fstat(fd.as_raw_fd())?;
    let euid = unsafe { libc::geteuid() };
    if st.st_uid != euid {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!("state directory is owned by uid {}, not euid {}", st.st_uid, euid),
        ));
    }
    Ok(fd)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::os::unix::fs::symlink;
    use std::path::PathBuf;

    fn tmpdir(name: &str) -> PathBuf {
        let d = std::env::temp_dir().join(format!(
            "coreshift_safe_fs_dir_{}_{name}",
            std::process::id()
        ));
        let _ = fs::remove_dir_all(&d);
        fs::create_dir_all(&d).unwrap();
        d
    }

    #[test]
    fn test_write_atomic_creates_regular_file() {
        let dir = tmpdir("w");
        let p = dir.join("out.txt");

        write_atomic(&p, b"hello").unwrap();
        assert_eq!(fs::read_to_string(&p).unwrap(), "hello");
        assert!(fs::symlink_metadata(&p).unwrap().file_type().is_file());
    }

    #[test]
    fn test_write_atomic_replaces_existing_symlink_not_target() {
        let dir = tmpdir("s1");
        let target = dir.join("victim");
        let link = dir.join("link");

        fs::write(&target, b"precious").unwrap();
        symlink(&target, &link).unwrap();

        // Write through the symlink: the victim must stay untouched and the
        // path must become a regular file (the symlink is replaced).
        write_atomic(&link, b"new").unwrap();

        assert_eq!(fs::read_to_string(&target).unwrap(), "precious");
        assert_eq!(fs::read_to_string(&link).unwrap(), "new");
        assert!(fs::symlink_metadata(&link).unwrap().file_type().is_file());
    }

    #[test]
    fn test_read_nofollow_refuses_symlink() {
        let dir = tmpdir("r");
        let target = dir.join("victim2");
        let link = dir.join("link2");

        fs::write(&target, b"secret").unwrap();
        symlink(&target, &link).unwrap();

        assert_eq!(read_nofollow(&target).unwrap(), "secret");
        assert!(read_nofollow(&link).is_err());
    }

    #[test]
    fn test_open_append_nofollow_refuses_symlink() {
        let dir = tmpdir("a");
        let target = dir.join("target3");
        let link = dir.join("link3");

        fs::write(&target, b"x").unwrap();
        symlink(&target, &link).unwrap();

        // Append to the regular file is fine.
        assert!(open_append_nofollow(&target).is_ok());
        // Appending through a symlink must fail.
        assert!(open_append_nofollow(&link).is_err());

        let _ = fs::remove_file(&target);
        let _ = fs::remove_file(&link);
    }

    #[test]
    fn test_write_atomic_refuses_symlinked_parent() {
        // An intermediate directory replaced by a symlink must make the
        // anchored open fail, and nothing may be written through to the
        // linked directory.
        let dir = tmpdir("parent_symlink");
        let elsewhere = tmpdir("parent_dest");
        let link = dir.join("coreshift");
        symlink(&elsewhere, &link).unwrap();

        assert!(write_atomic(link.join("payload.txt"), b"boom").is_err());
        assert!(!elsewhere.join("payload.txt").exists());
        assert!(!link.join("payload.txt").exists());
    }

    #[test]
    fn test_read_nofollow_refuses_symlinked_parent() {
        let dir = tmpdir("read_parent_symlink");
        let elsewhere = tmpdir("read_parent_dest");
        fs::write(elsewhere.join("conf"), b"injected").unwrap();
        let link = dir.join("coreshift");
        symlink(&elsewhere, &link).unwrap();

        assert!(read_nofollow(link.join("conf")).is_err());
    }

    #[test]
    fn test_open_append_nofollow_refuses_symlinked_parent() {
        let dir = tmpdir("append_parent_symlink");
        let elsewhere = tmpdir("append_parent_dest");
        let link = dir.join("coreshift");
        symlink(&elsewhere, &link).unwrap();

        assert!(open_append_nofollow(link.join("daemon.log")).is_err());
        assert!(!elsewhere.join("daemon.log").exists());
    }

    #[test]
    fn test_ensure_state_dir_refuses_symlink() {
        let dir = tmpdir("state_symlink");
        let elsewhere = tmpdir("state_dest");
        let link = dir.join("state");
        symlink(&elsewhere, &link).unwrap();

        assert!(ensure_state_dir(&link).is_err());
        // A real directory is accepted (owned by the current euid).
        let real = tmpdir("state_real");
        assert!(ensure_state_dir(&real).is_ok());
    }

    #[test]
    fn test_remove_nofollow_removes_entry_not_target() {
        let dir = tmpdir("unlink");
        let target = dir.join("victim4");
        let link = dir.join("link4");
        fs::write(&target, b"keep").unwrap();
        symlink(&target, &link).unwrap();

        remove_nofollow(&link).unwrap();
        assert!(!link.exists());
        assert_eq!(fs::read_to_string(&target).unwrap(), "keep");
    }

    #[test]
    fn test_write_atomic_requires_parent_to_exist() {
        let dir = tmpdir("missing_parent");
        let p = dir.join("nope").join("file.txt");

        assert!(write_atomic(&p, b"x").is_err());
        assert!(!p.exists());
    }

    #[test]
    fn test_ops_refuse_foreign_owned_parent() {
        // Simulates an attacker who renames the root-owned state dir and
        // substitutes their own: the real (non-symlink) substituted dir must
        // fail every operation because it is not owned by the effective uid.
        // Only exercisable as root (chown); otherwise skipped.
        if unsafe { libc::geteuid() } != 0 {
            return;
        }
        let dir = tmpdir("foreign_owner");
        let path = dir.join("f");
        let owned = cstr(&dir.to_string_lossy()).unwrap();
        // SAFETY: chown to 65534 (nobody) while running as root.
        assert_eq!(unsafe { libc::chown(owned.as_ptr(), 65534, 65534) }, 0);

        assert!(write_atomic(&path, b"x").is_err());
        assert!(read_nofollow(&path).is_err());
        assert!(open_append_nofollow(&path).is_err());
        assert!(remove_nofollow(&path).is_err());
        assert!(ensure_state_dir(&dir).is_err());
        assert!(!path.exists());
    }

    fn temp_leftovers(dir: &Path, file_name: &str) -> Vec<String> {
        let prefix = format!(".{file_name}.");
        fs::read_dir(dir)
            .map(|rd| {
                rd.filter_map(|e| e.ok())
                    .filter_map(|e| e.file_name().to_str().map(str::to_owned))
                    .filter(|n| n.starts_with(&prefix))
                    .collect()
            })
            .unwrap_or_default()
    }

    #[test]
    fn test_write_atomic_cleans_temp_on_rename_failure() {
        // A non-empty directory at the destination forces renameat to fail
        // (EISDIR/ENOTEMPTY) after the temp file has been fully written; the
        // TmpGuard must remove the temp entry.
        let dir = tmpdir("rename_fail");
        let dest = dir.join("dest");
        fs::create_dir_all(&dest).unwrap();
        fs::write(dest.join("keep"), b"x").unwrap();

        assert!(write_atomic(&dest, b"boom").is_err());
        assert_eq!(fs::read_to_string(dest.join("keep")).unwrap(), "x");
        assert!(temp_leftovers(&dir, "dest").is_empty(), "temp file must be cleaned up");
    }

    #[test]
    fn test_write_atomic_leaves_no_temp_on_success() {
        let dir = tmpdir("no_temp_success");
        let p = dir.join("out.txt");

        write_atomic(&p, b"hello").unwrap();
        assert_eq!(fs::read_to_string(&p).unwrap(), "hello");
        assert!(temp_leftovers(&dir, "out.txt").is_empty(), "no temp left behind");
    }

    #[test]
    fn test_write_atomic_retries_when_temp_name_exists() {
        let dir = tmpdir("temp_collision");
        let p = dir.join("out.txt");
        let pid = std::process::id();
        let collided = dir.join(format!(".out.txt.{pid}.0"));
        fs::write(&collided, b"not mine").unwrap();

        write_atomic(&p, b"hello").unwrap();
        assert_eq!(fs::read_to_string(&p).unwrap(), "hello");
        // The pre-existing colliding temp is neither clobbered nor mistaken for
        // ours; a later attempt slot is used.
        assert_eq!(fs::read_to_string(&collided).unwrap(), "not mine");
        let leftovers = temp_leftovers(&dir, "out.txt");
        assert_eq!(leftovers.len(), 1, "only the pre-existing colliding temp remains");
        assert_eq!(leftovers[0], format!(".out.txt.{pid}.0"));
    }

    #[test]
    fn test_ops_refuse_foreign_owned_writable_parent() {
        // A world-writable directory owned by a uid != euid (e.g. /tmp owned by
        // root) is a privilege-free proxy for a swapped state dir: a vulnerable
        // implementation with no ownership check would happily write into it,
        // while the fixed one must refuse every operation. Runs whenever such a
        // directory is available; skips as root (root owns /tmp).
        use std::os::unix::fs::MetadataExt;
        let euid = unsafe { libc::geteuid() };
        if euid == 0 {
            return;
        }
        let tmp = std::env::temp_dir();
        let meta = match fs::symlink_metadata(&tmp) {
            Ok(m) => m,
            Err(_) => return,
        };
        if meta.uid() == euid {
            return; // no ownership mismatch available in this environment
        }
        if meta.mode() & 0o002 == 0 && meta.mode() & 0o020 == 0 {
            return; // not writable by us; the proxy doesn't apply
        }
        let p = tmp.join(format!("coreshift_fs_foreign_{}_{}", std::process::id(), "out"));
        let _ = fs::remove_file(&p);
        fs::write(&p, b"probe").unwrap();

        assert!(read_nofollow(&p).is_err());
        assert!(open_append_nofollow(&p).is_err());
        assert!(write_atomic(&p, b"boom").is_err());
        assert!(remove_nofollow(&p).is_err());
        assert!(ensure_state_dir(&tmp).is_err());
        assert_eq!(fs::read_to_string(&p).unwrap(), "probe");
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn test_ensure_state_dir_creates_fresh_dir() {
        let base = tmpdir("fresh_base");
        let nested = base.join("a").join("b").join("state");

        let fd = ensure_state_dir(&nested).unwrap();
        assert!(nested.is_dir());
        drop(fd);
        assert!(ensure_state_dir(&nested).is_ok());
    }

    #[test]
    fn test_open_append_nofollow_refuses_dangling_symlink() {
        let dir = tmpdir("dangling_append");
        let missing = dir.join("not_there.txt");
        let link = dir.join("linkd");
        symlink(&missing, &link).unwrap();

        assert!(open_append_nofollow(&link).is_err());
        assert!(!missing.exists(), "must not create the target through a dangling link");
    }

    #[test]
    fn test_read_nofollow_refuses_dangling_symlink() {
        let dir = tmpdir("dangling_read");
        let missing = dir.join("not_there2.txt");
        let link = dir.join("linkd2");
        symlink(&missing, &link).unwrap();

        assert!(read_nofollow(&link).is_err());
        assert!(!missing.exists());
    }

    #[test]
    fn test_ops_refuse_regular_file_parent() {
        // A parent component that is a regular file must yield ENOTDIR for
        // every anchored operation — no write-through, no creation.
        let dir = tmpdir("regfile_parent");
        let f = dir.join("notadir");
        fs::write(&f, b"x").unwrap();

        assert!(write_atomic(f.join("out"), b"y").is_err());
        assert!(read_nofollow(f.join("out")).is_err());
        assert!(open_append_nofollow(f.join("out")).is_err());
        assert!(remove_nofollow(f.join("out")).is_err());
        assert!(ensure_state_dir(&f).is_err());
        assert_eq!(fs::read_to_string(&f).unwrap(), "x");
    }
}