pithos_lib 0.8.0

Library and components for encrypting / compressing pithos (.pith) files
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
use super::FsError;
use crate::archive::{Archive, EntryKind, ExternalBlockResolver};
use crate::format::file_entry::VALID_PERMISSION_BITS;
use crate::source::ArchiveSource;
use cap_std::fs::Dir;
use rustix::fs::{AtFlags, Mode, OFlags, fchmod, linkat, openat};
use std::cmp::Reverse;
use std::io::{self, Write};
use std::path::{Component, Path, PathBuf};

/// Options controlling filesystem extraction behavior.
#[derive(Clone, Copy, Debug, Default)]
pub struct ExtractionOptions {
    special_permissions: bool,
}

impl ExtractionOptions {
    /// Opt in to restoring setuid, setgid, and sticky permission bits.
    pub fn with_special_permissions(mut self) -> Self {
        self.special_permissions = true;
        self
    }
}

fn applied_mode(stored_permissions: u32, options: ExtractionOptions) -> Mode {
    let mask = if options.special_permissions {
        VALID_PERMISSION_BITS
    } else {
        0o0777
    };
    Mode::from(stored_permissions & mask)
}

fn open_dir_no_follow(parent: &Dir, component: &Path) -> io::Result<Dir> {
    rustix::fs::openat(
        parent,
        component,
        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
        Mode::empty(),
    )
    .map_err(io::Error::from)
    .map(|fd| Dir::from_std_file(std::fs::File::from(fd)))
}

/// Extract one validated archive entry through a capability-confined destination.
pub fn extract<S, E>(
    archive: &Archive<S, E>,
    archive_path: &str,
    destination: &Path,
) -> Result<(), FsError>
where
    S: ArchiveSource,
    E: ExternalBlockResolver,
{
    extract_with_options(
        archive,
        archive_path,
        destination,
        ExtractionOptions::default(),
    )
}

/// Extract one validated archive entry with explicit extraction options.
pub fn extract_with_options<S, E>(
    archive: &Archive<S, E>,
    archive_path: &str,
    destination: &Path,
    options: ExtractionOptions,
) -> Result<(), FsError>
where
    S: ArchiveSource,
    E: ExternalBlockResolver,
{
    let entry = archive
        .entry(archive_path)
        .map_err(|source| FsError::Archive {
            operation: "look up",
            archive_path: archive_path.to_owned(),
            destination: destination.to_path_buf(),
            source: Box::new(source),
        })?
        .ok_or_else(|| FsError::Archive {
            operation: "look up",
            archive_path: archive_path.to_owned(),
            destination: destination.to_path_buf(),
            source: Box::new(crate::error::PithosError::FileNotFound(
                archive_path.to_owned(),
            )),
        })?;
    let root = ExtractionRoot::open(destination, true, archive_path)?;
    let mode = applied_mode(entry.permissions, options);
    match entry.kind {
        EntryKind::File { .. } | EntryKind::Metadata { .. } => {
            let pending = root.pending_file(archive_path)?;
            let mut writer = pending.writer(archive_path)?;
            archive
                .copy_to(archive_path, &mut writer)
                .map_err(|source| root.archive_error("copy", archive_path, source))?;
            pending.commit(archive_path, mode)?;
        }
        EntryKind::Directory => root.create_dir(archive_path, mode)?,
        EntryKind::Symlink { target } => root.create_symlink(archive_path, &target)?,
    }
    Ok(())
}

/// Extract every archive entry in declaration order through one destination root.
pub fn extract_all<S, E>(archive: &Archive<S, E>, destination: &Path) -> Result<(), FsError>
where
    S: ArchiveSource,
    E: ExternalBlockResolver,
{
    extract_all_with_options(archive, destination, ExtractionOptions::default())
}

/// Extract every archive entry in declaration order with explicit options.
pub fn extract_all_with_options<S, E>(
    archive: &Archive<S, E>,
    destination: &Path,
    options: ExtractionOptions,
) -> Result<(), FsError>
where
    S: ArchiveSource,
    E: ExternalBlockResolver,
{
    let root = ExtractionRoot::open(destination, true, "<all>")?;
    let mut directories = Vec::new();

    for entry in archive.entries() {
        let path = entry.path;
        let mode = applied_mode(entry.permissions, options);
        match entry.kind {
            EntryKind::File { .. } | EntryKind::Metadata { .. } => {
                let pending = root.pending_file(&path)?;
                let mut writer = pending.writer(&path)?;
                archive
                    .copy_to(&path, &mut writer)
                    .map_err(|source| root.archive_error("copy", &path, source))?;
                pending.commit(&path, mode)?;
            }
            EntryKind::Directory => {
                let directory = root.create_dir_open(&path)?;
                fchmod(&directory, Mode::RWXU).map_err(|source| {
                    root.operation("set temporary directory permissions", &path, source.into())
                })?;
                directories.push(PendingDirectory {
                    path,
                    directory,
                    mode,
                });
            }
            EntryKind::Symlink { target } => root.create_symlink(&path, &target)?,
        }
    }

    directories.sort_by_key(|directory| Reverse(directory.path.split('/').count()));
    for directory in directories {
        fchmod(&directory.directory, directory.mode).map_err(|source| {
            root.operation("set directory permissions", &directory.path, source.into())
        })?;
    }
    Ok(())
}

pub(crate) struct ExtractionRoot {
    root: Dir,
    destination: PathBuf,
}

impl ExtractionRoot {
    pub(crate) fn open(path: &Path, create: bool, archive_path: &str) -> Result<Self, FsError> {
        let base = if path.is_absolute() {
            Path::new("/")
        } else {
            Path::new(".")
        };
        let mut root = rustix::fs::open(
            base,
            OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
            Mode::empty(),
        )
        .map_err(io::Error::from)
        .map(|fd| Dir::from_std_file(std::fs::File::from(fd)))
        .map_err(|source| FsError::Operation {
            operation: "open destination",
            archive_path: archive_path.to_owned(),
            destination: path.to_path_buf(),
            source,
        })?;
        for component in path.components() {
            let Component::Normal(component) = component else {
                if matches!(component, Component::ParentDir) {
                    return Err(FsError::Operation {
                        operation: "open destination",
                        archive_path: archive_path.to_owned(),
                        destination: path.to_path_buf(),
                        source: io::Error::new(
                            io::ErrorKind::InvalidInput,
                            "destination path contains parent traversal",
                        ),
                    });
                }
                continue;
            };
            let component = Path::new(component);
            root = match open_dir_no_follow(&root, component) {
                Ok(directory) => directory,
                Err(error) if create && error.kind() == io::ErrorKind::NotFound => {
                    match root.create_dir(component) {
                        Ok(()) => {}
                        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
                        Err(source) => {
                            return Err(FsError::Operation {
                                operation: "create destination",
                                archive_path: archive_path.to_owned(),
                                destination: path.to_path_buf(),
                                source,
                            });
                        }
                    }
                    open_dir_no_follow(&root, component).map_err(|source| FsError::Operation {
                        operation: "open destination",
                        archive_path: archive_path.to_owned(),
                        destination: path.to_path_buf(),
                        source,
                    })?
                }
                Err(source) => {
                    return Err(FsError::Operation {
                        operation: "open destination",
                        archive_path: archive_path.to_owned(),
                        destination: path.to_path_buf(),
                        source,
                    });
                }
            };
        }
        Ok(Self {
            root,
            destination: path.to_path_buf(),
        })
    }

    fn operation(&self, operation: &'static str, archive_path: &str, source: io::Error) -> FsError {
        FsError::Operation {
            operation,
            archive_path: archive_path.to_owned(),
            destination: self.destination.clone(),
            source,
        }
    }

    fn archive_error(
        &self,
        operation: &'static str,
        archive_path: &str,
        source: crate::error::PithosError,
    ) -> FsError {
        FsError::Archive {
            operation,
            archive_path: archive_path.to_owned(),
            destination: self.destination.clone(),
            source: Box::new(source),
        }
    }

    fn collision(&self, archive_path: &str, reason: &'static str) -> FsError {
        FsError::ExtractionCollision {
            archive_path: archive_path.to_owned(),
            destination: self.destination.clone(),
            reason,
        }
    }

    fn parents(&self, path: &str) -> Result<(Dir, String), FsError> {
        let mut components = path.split('/').peekable();
        let final_name = components
            .next_back()
            .ok_or_else(|| self.collision(path, "empty final component"))?;
        let mut dir = self
            .root
            .try_clone()
            .map_err(|source| self.operation("open destination parent", path, source))?;
        for component in components {
            if component.is_empty() || component == "." || component == ".." {
                return Err(self.collision(path, "invalid component"));
            }
            match open_dir_no_follow(&dir, Path::new(component)) {
                Ok(child) => dir = child,
                Err(error) if error.kind() == io::ErrorKind::NotFound => {
                    match dir.create_dir(component) {
                        Ok(()) => {}
                        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
                        Err(source) => {
                            return Err(self.operation("create destination parent", path, source));
                        }
                    }
                    dir = open_dir_no_follow(&dir, Path::new(component)).map_err(|source| {
                        self.operation("open destination parent", path, source)
                    })?;
                }
                Err(source) if source.raw_os_error() == Some(libc::ELOOP) => {
                    return Err(self.collision(path, "parent is a symlink"));
                }
                Err(source) if source.kind() == io::ErrorKind::NotADirectory => {
                    return Err(self.collision(path, "parent is not a directory"));
                }
                Err(source) => return Err(self.operation("open destination parent", path, source)),
            }
        }
        Ok((dir, final_name.to_string()))
    }

    fn create_dir_open(&self, path: &str) -> Result<Dir, FsError> {
        let (parent, name) = self.parents(path)?;
        match parent.symlink_metadata(&name) {
            Ok(_) => Err(self.collision(path, "final entry already exists")),
            Err(error) if error.kind() == io::ErrorKind::NotFound => {
                parent
                    .create_dir(&name)
                    .map_err(|source| self.operation("create directory", path, source))?;
                open_dir_no_follow(&parent, Path::new(&name))
                    .map_err(|source| self.operation("open directory", path, source))
            }
            Err(source) => Err(self.operation("inspect destination entry", path, source)),
        }
    }

    fn create_dir(&self, path: &str, mode: Mode) -> Result<(), FsError> {
        let directory = self.create_dir_open(path)?;
        fchmod(&directory, mode)
            .map_err(|source| self.operation("set directory permissions", path, source.into()))
    }

    pub(crate) fn create_symlink(&self, path: &str, target: &str) -> Result<(), FsError> {
        let (parent, name) = self.parents(path)?;
        match parent.symlink_metadata(&name) {
            Ok(_) => return Err(self.collision(path, "final entry already exists")),
            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
            Err(source) => return Err(self.operation("inspect destination entry", path, source)),
        }
        parent
            .symlink(target, &name)
            .map_err(|source| self.operation("create symlink", path, source))
    }

    pub(crate) fn pending_file(&self, path: &str) -> Result<PendingFile, FsError> {
        let (parent, name) = self.parents(path)?;
        match parent.symlink_metadata(&name) {
            Ok(_) => return Err(self.collision(path, "final entry already exists")),
            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
            Err(source) => return Err(self.operation("inspect destination entry", path, source)),
        }
        let file = openat(
            &parent,
            ".",
            OFlags::WRONLY | OFlags::TMPFILE | OFlags::CLOEXEC,
            Mode::RUSR | Mode::WUSR | Mode::RGRP | Mode::WGRP | Mode::ROTH | Mode::WOTH,
        )
        .map_err(io::Error::from)
        .map(std::fs::File::from)
        .map(cap_std::fs::File::from_std)
        .map_err(|source| self.operation("stage file", path, source))?;
        Ok(PendingFile {
            parent,
            final_name: name,
            file,
            destination: self.destination.clone(),
        })
    }
}

pub(crate) struct PendingFile {
    parent: Dir,
    final_name: String,
    file: cap_std::fs::File,
    destination: PathBuf,
}

impl PendingFile {
    pub(crate) fn writer(&self, archive_path: &str) -> Result<cap_std::fs::File, FsError> {
        self.file.try_clone().map_err(|source| FsError::Operation {
            operation: "open staged file",
            archive_path: archive_path.to_owned(),
            destination: self.destination.clone(),
            source,
        })
    }

    pub(crate) fn commit(self, archive_path: &str, mode: Mode) -> Result<(), FsError> {
        fchmod(&self.file, mode).map_err(|source| FsError::Operation {
            operation: "set staged file permissions",
            archive_path: archive_path.to_owned(),
            destination: self.destination.clone(),
            source: source.into(),
        })?;
        self.file.sync_all().map_err(|source| FsError::Operation {
            operation: "sync staged file",
            archive_path: archive_path.to_owned(),
            destination: self.destination.clone(),
            source,
        })?;
        match linkat(
            &self.file,
            "",
            &self.parent,
            &self.final_name,
            AtFlags::EMPTY_PATH,
        ) {
            Ok(()) => Ok(()),
            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
                Err(FsError::ExtractionCollision {
                    archive_path: archive_path.to_owned(),
                    destination: self.destination.clone(),
                    reason: "final entry already exists",
                })
            }
            Err(source) => Err(FsError::Operation {
                operation: "publish staged file",
                archive_path: archive_path.to_owned(),
                destination: self.destination.clone(),
                source: source.into(),
            }),
        }
    }
}

struct PendingDirectory {
    path: String,
    directory: Dir,
    mode: Mode,
}

impl Write for PendingFile {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.file.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.file.flush()
    }
}

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

    #[test]
    fn staged_file_is_removed_after_sink_failure() {
        let temporary = tempfile::tempdir().unwrap();
        let root = ExtractionRoot::open(temporary.path(), false, "data").unwrap();
        let mut pending = root.pending_file("data").unwrap();
        pending.file = cap_std::fs::File::from_std(std::fs::File::open("/dev/null").unwrap());

        assert!(
            pending
                .writer("data")
                .unwrap()
                .write_all(b"content")
                .is_err()
        );
        drop(pending);

        assert!(!temporary.path().join("data").exists());
        assert_eq!(std::fs::read_dir(temporary.path()).unwrap().count(), 0);
    }

    #[test]
    fn staged_file_is_removed_after_commit_collision() {
        let temporary = tempfile::tempdir().unwrap();
        let root = ExtractionRoot::open(temporary.path(), false, "data").unwrap();
        let pending = root.pending_file("data").unwrap();
        pending
            .writer("data")
            .unwrap()
            .write_all(b"content")
            .unwrap();
        std::fs::write(temporary.path().join("data"), b"sentinel").unwrap();

        assert!(matches!(
            pending.commit("data", Mode::RUSR | Mode::WUSR),
            Err(FsError::ExtractionCollision { .. })
        ));

        assert_eq!(
            std::fs::read(temporary.path().join("data")).unwrap(),
            b"sentinel"
        );
        assert_eq!(std::fs::read_dir(temporary.path()).unwrap().count(), 1);
    }

    #[test]
    fn staged_file_publication_uses_the_retained_anonymous_file() {
        let temporary = tempfile::tempdir().unwrap();
        let root = ExtractionRoot::open(temporary.path(), false, "data").unwrap();
        let pending = root.pending_file("data").unwrap();
        pending
            .writer("data")
            .unwrap()
            .write_all(b"verified")
            .unwrap();
        assert_eq!(std::fs::read_dir(temporary.path()).unwrap().count(), 0);

        pending.commit("data", Mode::RUSR | Mode::WUSR).unwrap();

        assert_eq!(
            std::fs::read(temporary.path().join("data")).unwrap(),
            b"verified"
        );
    }

    #[test]
    fn extraction_modes_strip_special_bits_unless_explicitly_enabled() {
        assert_eq!(
            applied_mode(0o7777, ExtractionOptions::default()).bits(),
            0o0777
        );
        assert_eq!(
            applied_mode(
                0o7777,
                ExtractionOptions::default().with_special_permissions(),
            )
            .bits(),
            0o7777
        );
    }

    #[test]
    fn staged_file_mode_failure_prevents_publication() {
        let temporary = tempfile::tempdir().unwrap();
        let root = ExtractionRoot::open(temporary.path(), false, "data").unwrap();
        let mut pending = root.pending_file("data").unwrap();
        pending.file = cap_std::fs::File::from_std(std::fs::File::open("/dev/null").unwrap());

        assert!(matches!(
            pending.commit("data", Mode::RUSR),
            Err(FsError::Operation {
                operation: "set staged file permissions",
                ..
            })
        ));
        assert!(!temporary.path().join("data").exists());
    }

    #[test]
    fn destination_root_rejects_parent_traversal() {
        let Err(error) = ExtractionRoot::open(Path::new(".."), true, "data") else {
            panic!("parent traversal unexpectedly opened as a destination root");
        };

        assert!(matches!(
            error,
            FsError::Operation {
                operation: "open destination",
                ..
            }
        ));
    }
}