debrepo 0.4.0

Library for manifest-driven Debian/Ubuntu bootstrap and APT archive resolution.
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
use {
    rustix::fs::{
        chown, chownat, fallocate, fchown, fstat, futimens, link, linkat, openat, stat, symlinkat,
        unlink, utimensat, AtFlags, FallocateFlags, Gid, Mode, OFlags, Timespec, Timestamps, Uid,
        CWD, UTIME_OMIT,
    },
    smol::prelude::*,
    std::{
        io,
        os::unix::fs::PermissionsExt,
        path::{Path, PathBuf},
        pin::Pin,
        sync::Arc,
    },
    tempfile::TempPath,
};

pub trait Stage {
    type Output;
    type Target: StagingFileSystem + ?Sized;
    fn stage<'a>(
        &'a mut self,
        fs: &'a Self::Target,
    ) -> Pin<Box<dyn Future<Output = io::Result<Self::Output>> + 'a>>;
}

pub trait StagingFile {
    fn persist<P>(self, path: P) -> impl Future<Output = io::Result<()>>
    where
        P: AsRef<Path>;
}

/// Defines a file system interface to deploy packages.
#[allow(clippy::too_many_arguments)]
pub trait StagingFileSystem {
    type File: StagingFile;
    /// Create a directory at `path`, optionaly owned by (`uid`, `gid`) and using mode bits `mode`
    fn create_dir<P: AsRef<Path>>(
        &self,
        path: P,
        uid: u32,
        gid: u32,
        mode: u32,
    ) -> impl Future<Output = io::Result<()>>;
    /// Create a directory at `path`, including all the parent directories if necessary,
    /// optionall owned by (`uid`, `gid`) using mode bits `mode`
    fn create_dir_all<P: AsRef<Path>>(
        &self,
        path: P,
        uid: u32,
        gid: u32,
        mode: u32,
    ) -> impl Future<Output = io::Result<()>>;
    fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(
        &self,
        target: P,
        link: Q,
        uid: u32,
        gid: u32,
    ) -> impl Future<Output = io::Result<()>>;
    fn hardlink<P: AsRef<Path>, Q: AsRef<Path>>(
        &self,
        target: P,
        link: Q,
    ) -> impl Future<Output = io::Result<()>>;
    /// Creates a file using content provided by the reader `r`.
    /// The resulting file must later be made persistent by calling `file.persist(path)`.
    ///
    /// If `path` is specified, committing the file to the same path will be a no-op.
    ///
    /// Additional parameters allow for optional specification of ownership (`owner` as a
    /// `(uid, gid)` tuple), file permissions (`mode`), modification time (`mtime`),
    /// and a size hint (`size`).
    ///
    /// # Parameters
    /// - `r`: A reader that provides the content for the file.
    /// - `path`: An optional path for the file. If provided, committing to the same path is a no-op.
    /// - `owner`: An optional `(uid, gid)` tuple specifying the file's ownership.
    /// - `mode`: An optional `u32` specifying the file's permission mode.
    /// - `mtime`: An optional `SystemTime` specifying thetree  tree file's modification time.
    /// - `size`: An optional size hint for the file.
    ///
    /// # Returns
    /// A result containing the created file on success, or an I/O error on failure.
    ///
    /// # Errors
    /// This method may return an I/O error if the file creation or any of the specified
    /// parameters are invalid or if there are issues during the operation.
    fn create_file<'a, R: AsyncRead + Send + 'a>(
        &'a self,
        r: R,
        uid: u32,
        gid: u32,
        mode: u32,
        size: Option<usize>,
    ) -> impl Future<Output = io::Result<Self::File>> + 'a;
    fn create_file_from_bytes<'a>(
        &'a self,
        r: &'a [u8],
        uid: u32,
        gid: u32,
        mode: u32,
    ) -> impl Future<Output = io::Result<Self::File>> + 'a {
        self.create_file(r, uid, gid, mode, Some(r.len()))
    }
    fn remove_file<P: AsRef<Path>>(&self, path: P) -> impl Future<Output = io::Result<()>>;
    fn stage<T>(
        &self,
        artifact: Box<dyn Stage<Target = Self, Output = T>>,
    ) -> impl Future<Output = io::Result<T>>
    where
        T: Send + 'static;
}

#[derive(Clone)]
/// Staging filesystem implementation backed by the host OS.
pub struct HostFileSystem {
    root: Arc<Path>,
    chown_allowed: bool,
}

fn clean_path(target: &Path) -> io::Result<&Path> {
    let target = if target.has_root() {
        target.strip_prefix("/").map_err(|err| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("invalid path {:?}: {}", target.as_os_str(), err),
            )
        })?
    } else {
        target
    };
    for c in target.components() {
        if c.as_os_str().eq("..") {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("invalid path {:?}", target.as_os_str()),
            ));
        }
    }
    Ok(target)
}

impl HostFileSystem {
    pub async fn new<P: AsRef<Path>>(root: P, allow_chown: bool) -> io::Result<Self> {
        smol::fs::create_dir_all(root.as_ref()).await?;
        let root = smol::fs::canonicalize(root.as_ref()).await?;
        Ok(Self {
            root: root.into(),
            chown_allowed: allow_chown,
        })
    }
    fn target_path(&self, target: &Path) -> io::Result<PathBuf> {
        Ok(self.root.join(clean_path(target)?))
    }
}

/// Staged file handle backed by the host OS.
pub struct HostFile {
    base: Arc<Path>,
    path: TempPath,
    file: smol::fs::File,
}

impl StagingFile for HostFile {
    async fn persist<P: AsRef<Path>>(self, name: P) -> io::Result<()> {
        tracing::debug!(
            "persisting file {} to {}",
            self.path.display(),
            name.as_ref().display()
        );
        let to = self.base.as_ref().join(clean_path(name.as_ref())?);
        if to.parent().is_none() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("invalid path {}", name.as_ref().display()),
            ));
        }
        let file = self.file;
        let path = self.path;
        match blocking::unblock(move || {
            let file_meta = fstat(&file).inspect_err(|err| {
                tracing::error!("failed to stat file {}: {}", path.display(), err)
            })?;
            let dir_met = stat(to.parent().unwrap()).inspect_err(|err| {
                tracing::error!(
                    "failed to stat target directory {}: {}",
                    to.parent().unwrap_or_else(|| Path::new("/")).display(),
                    err
                )
            })?;
            if file_meta.st_dev == dir_met.st_dev {
                match linkat(&file, "", CWD, &to, AtFlags::EMPTY_PATH) {
                    Ok(()) => {
                        futimens(&file, &EPOCH)?;
                    }
                    Err(_) => {
                        // linkat failed, switching back to copy
                    }
                }
                return Ok::<_, io::Error>(None);
            }
            let target = openat(
                CWD,
                &to,
                OFlags::CREATE | OFlags::WRONLY,
                Mode::from_raw_mode(file_meta.st_mode),
            )
            .inspect_err(|err| {
                tracing::error!("failed to open target file {}: {}", to.display(), err)
            })?;
            fchown(
                &target,
                Some(Uid::from_raw(file_meta.st_uid)),
                Some(Gid::from_raw(file_meta.st_gid)),
            )?;
            Ok(Some((file, target)))
        })
        .await
        .map_err(|err| {
            io::Error::other(format!(
                "failed to persist file {}: {}",
                name.as_ref().display(),
                err
            ))
        })? {
            None => Ok(()),
            Some((mut src, dst)) => {
                let mut dst: smol::fs::File = dst.into();
                src.seek(smol::io::SeekFrom::Start(0)).await?;
                smol::io::copy(&mut src, &mut dst).await?;
                dst.sync_data().await?;
                drop(src);
                blocking::unblock(move || {
                    futimens(&dst, &EPOCH)?;
                    Ok(())
                })
                .await
            }
        }
    }
}

const EPOCH: Timestamps = Timestamps {
    last_modification: Timespec {
        tv_sec: 0,
        tv_nsec: 0,
    },
    last_access: Timespec {
        tv_sec: 0,
        tv_nsec: UTIME_OMIT,
    },
};

fn mkdir(path: &std::path::Path, owner: Option<(u32, u32)>, mode: u32) -> io::Result<()> {
    rustix::fs::mkdirat(CWD, path, Mode::from_raw_mode(mode))?;
    if let Some((uid, gid)) = owner {
        chown(path, Some(Uid::from_raw(uid)), Some(Gid::from_raw(gid)))?;
    }
    utimensat(CWD, path, &EPOCH, AtFlags::empty())?;
    Ok(())
}

fn mkdir_rec(path: &std::path::Path, owner: Option<(u32, u32)>, mode: u32) -> io::Result<()> {
    if path.is_dir() {
        return Ok(());
    }
    match mkdir(path, owner, mode) {
        Ok(()) => Ok(()),
        Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
            let parent = path
                .parent()
                .ok_or_else(|| io::Error::other("failed to create tree: no parent"))?;
            mkdir_rec(parent, owner, mode)?;
            match mkdir(path, owner, mode) {
                Ok(()) => Ok(()),
                Err(_) if path.is_dir() => Ok(()),
                Err(e) => Err(e),
            }
        }
        Err(_) if path.is_dir() => Ok(()),
        Err(e) => Err(e),
    }
}

impl StagingFileSystem for HostFileSystem {
    type File = HostFile;
    fn create_dir<P: AsRef<Path>>(
        &self,
        path: P,
        uid: u32,
        gid: u32,
        mode: u32,
    ) -> impl Future<Output = io::Result<()>> {
        let target = self.target_path(path.as_ref());
        tracing::debug!(
            "creating directory {} at {} with mode {:o}",
            path.as_ref().display(),
            self.root.display(),
            mode
        );
        let (owner, mode) = if self.chown_allowed {
            (Some((uid, gid)), mode)
        } else {
            (
                None,
                mode & !(libc::S_ISUID | libc::S_ISGID | libc::S_ISVTX),
            )
        };
        blocking::unblock(move || {
            let target = target?;
            mkdir(target.as_ref(), owner, mode).map_err(|e| {
                io::Error::new(
                    e.kind(),
                    format!("failed to create directory {:?}: {}", target.as_os_str(), e),
                )
            })?;
            utimensat(CWD, target, &EPOCH, AtFlags::empty())?;
            Ok(())
        })
    }
    fn create_dir_all<P: AsRef<Path>>(
        &self,
        path: P,
        uid: u32,
        gid: u32,
        mode: u32,
    ) -> impl Future<Output = io::Result<()>> {
        let target = self.target_path(path.as_ref());
        tracing::debug!(
            "creating directory tree {} at {} with mode {:o}",
            path.as_ref().display(),
            self.root.display(),
            mode
        );
        let owner = if self.chown_allowed {
            Some((uid, gid))
        } else {
            None
        };
        blocking::unblock(move || {
            let target = target?;
            mkdir_rec(target.as_ref(), owner, mode).map_err(|e| {
                io::Error::new(
                    e.kind(),
                    format!(
                        "failed to create directory recursively {:?}: {}",
                        target.as_os_str(),
                        e
                    ),
                )
            })
        })
    }
    fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(
        &self,
        target: P,
        path: Q,
        uid: u32,
        gid: u32,
    ) -> impl Future<Output = io::Result<()>> {
        let link = self.target_path(path.as_ref());
        let target = target.as_ref().to_owned();
        let chown_allowed = self.chown_allowed;
        blocking::unblock(move || {
            let link = link?;
            symlinkat(target, CWD, &link).map_err(Into::<io::Error>::into)?;
            if chown_allowed {
                chownat(
                    CWD,
                    &link,
                    Some(Uid::from_raw(uid)),
                    Some(Gid::from_raw(gid)),
                    AtFlags::SYMLINK_NOFOLLOW,
                )
                .map_err(Into::<io::Error>::into)?;
            }
            utimensat(CWD, link, &EPOCH, AtFlags::SYMLINK_NOFOLLOW).map_err(Into::<io::Error>::into)
        })
    }
    fn hardlink<P: AsRef<Path>, Q: AsRef<Path>>(
        &self,
        from: P,
        to: Q,
    ) -> impl Future<Output = io::Result<()>> {
        let from = self.target_path(from.as_ref());
        let to = self.target_path(to.as_ref());
        blocking::unblock(move || {
            let from = from?;
            let to = to?;
            link(from, to).map_err(Into::into)
        })
    }
    fn create_file<'a, R: AsyncRead + Send + 'a>(
        &'a self,
        r: R,
        uid: u32,
        gid: u32,
        mode: u32,
        size: Option<usize>,
    ) -> impl Future<Output = io::Result<Self::File>> + 'a {
        tracing::debug!(
            "creating temporary file in {} with mode {:o}",
            self.root.display(),
            mode
        );
        let root = self.root.clone();
        async move {
            let chown_allowed = self.chown_allowed;
            let mode = if chown_allowed {
                mode
            } else {
                mode & !(libc::S_ISUID | libc::S_ISGID | libc::S_ISVTX)
            };
            let (file, path) = blocking::unblock(move || {
                let (file, path) = tempfile::Builder::new()
                    .permissions(smol::fs::Permissions::from_mode(mode))
                    .tempfile_in(&root)
                    .map(|f| f.into_parts())
                    .inspect_err(|err| {
                        tracing::error!(
                            "failed to create temporary file in {}: {}",
                            root.display(),
                            err
                        )
                    })?;
                if let Some(size) = size {
                    if size > 0 {
                        fallocate(&file, FallocateFlags::KEEP_SIZE, 0, size as u64)
                            .inspect_err(|err| {
                                tracing::warn!(
                                    "failed to preallocate file {}: {}",
                                    path.display(),
                                    err
                                )
                            })
                            .ok();
                    }
                }
                if chown_allowed {
                    fchown(&file, Some(Uid::from_raw(uid)), Some(Gid::from_raw(gid)))
                        .inspect_err(|err| {
                            tracing::error!(
                                "failed to set ownership of file {} to {}:{}: {}",
                                path.display(),
                                uid,
                                gid,
                                err
                            )
                        })
                        .ok();
                }
                Ok::<_, io::Error>((file, path))
            })
            .await?;
            let mut file: smol::fs::File = file.into();
            smol::io::copy(r, &mut file).await.inspect_err(|err| {
                tracing::error!(
                    "failed to write to temporary file {}: {}",
                    path.display(),
                    err
                )
            })?;
            file.sync_data().await.inspect_err(|err| {
                tracing::error!("failed to sync temporary file {}: {}", path.display(), err)
            })?;
            Ok(HostFile {
                base: Arc::clone(&self.root),
                file,
                path,
            })
        }
    }
    fn create_file_from_bytes<'a>(
        &'a self,
        r: &'a [u8],
        uid: u32,
        gid: u32,
        mode: u32,
    ) -> impl Future<Output = io::Result<Self::File>> + 'a {
        self.create_file(r, uid, gid, mode, Some(r.len()))
    }
    fn remove_file<P: AsRef<Path>>(&self, path: P) -> impl Future<Output = io::Result<()>> {
        let target = self.target_path(path.as_ref());
        blocking::unblock(move || unlink(target?).map_err(Into::into))
    }
    async fn stage<T>(
        &self,
        mut artifact: Box<dyn Stage<Target = Self, Output = T> + 'static>,
    ) -> io::Result<T>
    where
        T: Send + 'static,
    {
        artifact.as_mut().stage(self).await
    }
}

#[derive(Clone, Debug)]
/// File list for staged package contents.
pub struct FileList {
    out: std::sync::Arc<std::sync::Mutex<std::collections::HashSet<String>>>,
}

impl Default for FileList {
    fn default() -> Self {
        Self::new()
    }
}

impl FileList {
    pub fn new() -> Self {
        Self {
            out: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashSet::new())),
        }
    }
    pub async fn keep<P: AsRef<Path>>(self, path: P) -> io::Result<()> {
        let mut file = smol::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(path)
            .await?;
        let mut list = self.out.lock().unwrap().drain().collect::<Vec<_>>();
        list.sort();
        file.write_all(list.join("\n").as_bytes()).await?;
        file.flush().await?;
        file.sync_data().await?;
        Ok(())
    }
}

/// Entry in a staged file list.
pub struct FileListFile {
    uid: u32,
    gid: u32,
    mode: u32,
    size: u64,
    out: std::sync::Arc<std::sync::Mutex<std::collections::HashSet<String>>>,
}

impl StagingFile for FileListFile {
    async fn persist<P: AsRef<Path>>(self, path: P) -> io::Result<()> {
        self.out.lock().unwrap().insert(format!(
            "{} {:o} {} {} {}",
            path.as_ref().as_os_str().to_string_lossy(),
            self.mode,
            self.uid,
            self.gid,
            self.size
        ));
        Ok(())
    }
}

impl StagingFileSystem for FileList {
    type File = FileListFile;
    async fn create_dir<P: AsRef<Path>>(
        &self,
        path: P,
        uid: u32,
        gid: u32,
        mode: u32,
    ) -> io::Result<()> {
        self.out.lock().unwrap().insert(format!(
            "{} {:o} {} {}",
            path.as_ref().as_os_str().to_string_lossy(),
            mode,
            uid,
            gid,
        ));
        Ok(())
    }
    async fn create_dir_all<P: AsRef<Path>>(
        &self,
        path: P,
        uid: u32,
        gid: u32,
        mode: u32,
    ) -> io::Result<()> {
        self.out.lock().unwrap().insert(format!(
            "{} {:o} {} {}",
            path.as_ref().as_os_str().to_string_lossy(),
            mode,
            uid,
            gid,
        ));
        Ok(())
    }
    async fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(
        &self,
        target: P,
        path: Q,
        uid: u32,
        gid: u32,
    ) -> io::Result<()> {
        self.out.lock().unwrap().insert(format!(
            "{} -> {} {} {}",
            path.as_ref().as_os_str().to_string_lossy(),
            target.as_ref().as_os_str().to_string_lossy(),
            uid,
            gid,
        ));
        Ok(())
    }
    async fn hardlink<P: AsRef<Path>, Q: AsRef<Path>>(&self, from: P, to: Q) -> io::Result<()> {
        self.out.lock().unwrap().insert(format!(
            "{} -> {}",
            from.as_ref().as_os_str().to_string_lossy(),
            to.as_ref().as_os_str().to_string_lossy(),
        ));
        Ok(())
    }
    async fn create_file<'a, R: AsyncRead + Send + 'a>(
        &'a self,
        r: R,
        uid: u32,
        gid: u32,
        mode: u32,
        _size: Option<usize>,
    ) -> io::Result<Self::File> {
        let size = smol::io::copy(r, &mut smol::io::sink()).await?;
        Ok(FileListFile {
            mode,
            uid,
            gid,
            size,
            out: Arc::clone(&self.out),
        })
    }
    async fn remove_file<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
        self.out
            .lock()
            .unwrap()
            .insert(format!("!{}", path.as_ref().as_os_str().to_string_lossy(),));
        Ok(())
    }
    async fn stage<T>(
        &self,
        mut artifact: Box<dyn Stage<Target = Self, Output = T>>,
    ) -> io::Result<T>
    where
        T: Send + 'static,
    {
        artifact.as_mut().stage(self).await
    }
}

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

    #[allow(dead_code)]
    trait ThreadSafeStagingFS: StagingFileSystem + Send + Sync + Clone {}
    impl<T> ThreadSafeStagingFS for T
    where
        T: StagingFileSystem + Sync + Send + Clone,
        T::File: Send,
    {
    }

    use static_assertions::assert_impl_all;
    assert_impl_all!(HostFile: Send, Sync);
    assert_impl_all!(HostFileSystem: ThreadSafeStagingFS);

    #[test]
    fn mkdir_rec_creates_nested_directories() {
        let dir = tempfile::tempdir().expect("tempdir");
        let target = dir.path().join("a/b/c");

        mkdir_rec(&target, None, 0o755).expect("mkdir_rec nested");
        assert!(target.is_dir());

        // Already-exists early return
        mkdir_rec(&target, None, 0o755).expect("mkdir_rec existing");
    }

    #[test]
    fn mkdir_rec_handles_eexist_after_parent_creation() {
        let dir = tempfile::tempdir().expect("tempdir");
        let target = dir.path().join("x/y");

        // Create the target ahead of time so the second mkdir inside mkdir_rec hits EEXIST
        std::fs::create_dir_all(&target).expect("pre-create");
        // Remove the target but keep the parent so NotFound triggers parent creation,
        // then the target still exists via a race-like scenario.
        // Actually, just verify that mkdir_rec succeeds when the leaf already exists
        mkdir_rec(&target, None, 0o755).expect("mkdir_rec eexist");
    }

    #[test]
    fn clean_path_rejects_parent_traversal_and_strips_root() {
        let result = clean_path(Path::new("/foo/bar"));
        assert_eq!(result.expect("clean /foo/bar"), Path::new("foo/bar"));

        let result = clean_path(Path::new("foo/../etc/passwd"));
        assert!(result.is_err());

        let result = clean_path(Path::new("safe/path"));
        assert_eq!(result.expect("clean safe/path"), Path::new("safe/path"));
    }

    #[test]
    fn host_filesystem_target_path_and_clean_path_integration() {
        let fs = smol::block_on(HostFileSystem::new(
            tempfile::tempdir().expect("tempdir").path(),
            false,
        ))
        .expect("host fs");

        let result = fs.target_path(Path::new("/etc/config.txt"));
        assert!(result.is_ok());
        assert!(result.unwrap().ends_with("etc/config.txt"));

        let result = fs.target_path(Path::new("relative/path"));
        assert!(result.is_ok());

        let result = fs.target_path(Path::new("/foo/../etc/passwd"));
        assert!(result.is_err());
    }
}