Skip to main content

strypt_core/
io.rs

1//! Bounded reading and atomic writing.
2//!
3//! This module holds the two file operations that can hurt a user independently of any
4//! parser bug: reading an input large enough to exhaust memory, and writing an output in a
5//! way that can leave a half-sanitised file where the original was.
6//!
7//! # Where temporary files go, and why it matters
8//!
9//! The temporary file is created **in the destination's own directory**, never in `TMPDIR`.
10//! Two reasons, and the second is the important one:
11//!
12//! 1. `rename` is only atomic within a filesystem. A temp file on a different mount turns the
13//!    final step into a copy, which is precisely the non-atomic behaviour being avoided.
14//! 2. `TMPDIR` is somewhere else on the disk. Writing a copy of a sensitive document to
15//!    somewhere the user did not choose — and did not know to clean up — is a leak in its own
16//!    right, and on an amnesic system such as Tails it may be the one location that is not
17//!    what the user assumed it was (`docs/ARCHITECTURE.md` §8).
18//!
19//! The temporary file is removed on every failure path.
20
21use std::fs::File;
22use std::io::{Read, Write};
23use std::path::{Path, PathBuf};
24use std::sync::atomic::{AtomicU64, Ordering};
25
26use crate::error::{IoAction, Result, StryptError};
27
28/// Resource ceilings applied before and during parsing.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30#[non_exhaustive]
31pub struct Limits {
32    /// Largest input strypt will read, in bytes.
33    pub max_input_bytes: u64,
34}
35
36impl Limits {
37    /// The default input ceiling: 512 MiB.
38    ///
39    /// Chosen to clear the largest files the Phase 1 formats plausibly produce — a
40    /// high-resolution scanned PDF runs to a few hundred megabytes — while still refusing a
41    /// file whose only purpose is to exhaust memory. It is a ceiling on the *input*; a PDF
42    /// rewrite holds the parsed document as well, so peak usage is a multiple of this. That
43    /// matters on the constrained, RAM-only systems this tool is aimed at, which is why the
44    /// number is deliberately not "as much as will fit".
45    ///
46    /// Provisional: revisit with measured figures once the handlers exist (`docs/PRD.md` §9
47    /// still carries estimates rather than measurements).
48    pub const DEFAULT_MAX_INPUT_BYTES: u64 = 512 * 1024 * 1024;
49}
50
51impl Limits {
52    /// Limits with a caller-chosen input ceiling.
53    ///
54    /// A constructor rather than a struct literal because this type is `#[non_exhaustive]`:
55    /// new ceilings will be added, and a front-end built against an older version must keep
56    /// compiling rather than silently missing one.
57    #[must_use]
58    pub const fn with_max_input_bytes(max_input_bytes: u64) -> Self {
59        Self { max_input_bytes }
60    }
61}
62
63impl Default for Limits {
64    fn default() -> Self {
65        Self {
66            max_input_bytes: Self::DEFAULT_MAX_INPUT_BYTES,
67        }
68    }
69}
70
71/// Read `path` into memory, refusing anything above `limits.max_input_bytes`.
72///
73/// The size is checked twice: once against the directory entry, so an oversized file is
74/// refused without reading a byte of it, and again while reading, because the first answer
75/// came from metadata that a hostile or merely unusual source can misreport — a growing file,
76/// a named pipe, a synthetic filesystem. Trusting the first check alone would make the limit
77/// advisory.
78///
79/// # Errors
80///
81/// [`StryptError::InputTooLarge`] if the file exceeds the limit; [`StryptError::Io`] if it
82/// cannot be measured or read.
83pub fn read_bounded(path: &Path, limits: Limits) -> Result<Vec<u8>> {
84    let file = File::open(path).map_err(|source| StryptError::Io {
85        action: IoAction::ReadingInput,
86        source,
87    })?;
88    let declared = file
89        .metadata()
90        .map_err(|source| StryptError::Io {
91            action: IoAction::MeasuringInput,
92            source,
93        })?
94        .len();
95    if declared > limits.max_input_bytes {
96        return Err(StryptError::InputTooLarge {
97            limit: limits.max_input_bytes,
98            actual: Some(declared),
99        });
100    }
101    read_bounded_from(file, limits, Some(declared))
102}
103
104/// Read a stream into memory under the same ceiling as [`read_bounded`].
105///
106/// `hint` pre-allocates when a trustworthy size is known. It is only ever a hint: the read
107/// itself is what enforces the limit.
108fn read_bounded_from<R: Read>(source: R, limits: Limits, hint: Option<u64>) -> Result<Vec<u8>> {
109    // Read one byte past the ceiling. If that byte arrives, the source lied about its size
110    // and the input is over the limit — a `take(limit)` alone would silently truncate, which
111    // would hand a partial file to a handler and produce a report about content that was
112    // never there.
113    let probe = limits.max_input_bytes.saturating_add(1);
114    let mut buffer = Vec::new();
115    if let Some(hint) = hint {
116        // Reserve only what the ceiling permits: `Vec::with_capacity(n_from_file)` driven by
117        // an attacker-controlled number is itself the memory-exhaustion bug.
118        let reserve = hint.min(limits.max_input_bytes);
119        if let Ok(reserve) = usize::try_from(reserve) {
120            buffer
121                .try_reserve_exact(reserve)
122                .map_err(|_| StryptError::InputTooLarge {
123                    limit: limits.max_input_bytes,
124                    actual: Some(hint),
125                })?;
126        }
127    }
128    let read = source
129        .take(probe)
130        .read_to_end(&mut buffer)
131        .map_err(|source| StryptError::Io {
132            action: IoAction::ReadingInput,
133            source,
134        })?;
135    if u64::try_from(read).unwrap_or(u64::MAX) > limits.max_input_bytes {
136        return Err(StryptError::InputTooLarge {
137            limit: limits.max_input_bytes,
138            actual: None,
139        });
140    }
141    Ok(buffer)
142}
143
144/// What to do when the destination already exists.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub enum Overwrite {
147    /// Refuse. The default everywhere: overwriting the user's file is a decision only the
148    /// user gets to make.
149    Refuse,
150    /// Replace it. Requires `--force` at the CLI.
151    Replace,
152}
153
154/// Whether output permissions are tightened.
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156pub enum Permissions {
157    /// Owner read/write only (`0600` on Unix; a no-op on Windows, ADR-0047).
158    ///
159    /// The default, and the decision recorded in ADR-0019. A stripped file is the *more*
160    /// sensitive artefact of the pair, not the less: the user is about to publish it, and a
161    /// world-readable copy sitting in a shared directory in the meantime is an avoidable
162    /// exposure. Source timestamps and permissions are never copied onto the output —
163    /// modification time is itself metadata, and preserving it would hand back a fact the
164    /// user believed they had just removed.
165    OwnerOnly,
166    /// Whatever the platform's default for a new file is (the process umask on Unix).
167    Inherit,
168}
169
170/// A file being written through a temporary alongside its destination, replaced by an atomic
171/// rename only once the content is complete and durable.
172///
173/// Nothing partial ever appears at the destination path. If the process dies mid-write, the
174/// destination is untouched and a `.strypt-*.tmp` file is left behind — visible, obviously
175/// incomplete, and adjacent to where it belongs, rather than a silently truncated file the
176/// user might publish.
177#[derive(Debug)]
178pub struct AtomicWrite {
179    destination: PathBuf,
180    temporary: PathBuf,
181    file: Option<File>,
182    permissions: Permissions,
183}
184
185impl AtomicWrite {
186    /// Begin writing to `destination`.
187    ///
188    /// # Errors
189    ///
190    /// [`StryptError::OutputExists`] if the destination exists and `overwrite` is
191    /// [`Overwrite::Refuse`]; [`StryptError::Io`] if the temporary file cannot be created.
192    pub fn begin(
193        destination: &Path,
194        overwrite: Overwrite,
195        permissions: Permissions,
196    ) -> Result<Self> {
197        // A pre-check, not a guarantee: another process can create the file between here and
198        // the rename. Closing that race needs a link/rename dance that behaves differently on
199        // every platform, and the realistic failure it would prevent — a user racing
200        // themselves in two terminals — is not the threat this tool is defending against. The
201        // honest position is that this is a courtesy check; the atomicity that matters is
202        // that the destination is never *partially* written.
203        if overwrite == Overwrite::Refuse && destination.exists() {
204            return Err(StryptError::OutputExists);
205        }
206
207        let temporary = temporary_path_for(destination);
208        let file = create_private(&temporary, permissions)?;
209        Ok(Self {
210            destination: destination.to_path_buf(),
211            temporary,
212            file: Some(file),
213            permissions,
214        })
215    }
216
217    /// Write bytes into the temporary file.
218    ///
219    /// # Errors
220    ///
221    /// [`StryptError::Io`] if the write fails.
222    pub fn write_all(&mut self, bytes: &[u8]) -> Result<()> {
223        let Some(file) = self.file.as_mut() else {
224            return Err(StryptError::Io {
225                action: IoAction::WritingOutput,
226                source: std::io::Error::other("write after the file was finished"),
227            });
228        };
229        file.write_all(bytes).map_err(|source| StryptError::Io {
230            action: IoAction::WritingOutput,
231            source,
232        })
233    }
234
235    /// Flush, synchronise, and atomically move the temporary into place.
236    ///
237    /// The `sync_all` is not ceremony. Without it the rename can be durable while the
238    /// content behind it is not, so a crash at the wrong moment leaves a file that exists,
239    /// has the right name, and contains nothing — which for this tool means a user with a
240    /// file they believe is a stripped copy of their document.
241    ///
242    /// # Errors
243    ///
244    /// [`StryptError::Io`] if syncing or renaming fails. The temporary is removed either way.
245    pub fn commit(mut self) -> Result<()> {
246        let Some(file) = self.file.take() else {
247            return Err(StryptError::Io {
248                action: IoAction::SyncingOutput,
249                source: std::io::Error::other("already finished"),
250            });
251        };
252        if let Err(source) = file.sync_all() {
253            self.discard_temporary();
254            return Err(StryptError::Io {
255                action: IoAction::SyncingOutput,
256                source,
257            });
258        }
259        drop(file);
260
261        if let Err(source) = std::fs::rename(&self.temporary, &self.destination) {
262            self.discard_temporary();
263            return Err(StryptError::Io {
264                action: IoAction::ReplacingDestination,
265                source,
266            });
267        }
268        // Re-assert permissions after the rename. On Unix the mode travels with the inode so
269        // this is a no-op, but stating it here keeps the guarantee in one place rather than
270        // resting on a platform detail.
271        apply_permissions(&self.destination, self.permissions)?;
272        Ok(())
273    }
274
275    /// Abandon the write, leaving the destination untouched.
276    pub fn abort(mut self) {
277        self.file = None;
278        self.discard_temporary();
279    }
280
281    fn discard_temporary(&mut self) {
282        self.file = None;
283        // A failure to clean up is not worth failing the operation over — the caller already
284        // has a real error to report, and a leftover `.tmp` is visible rather than dangerous.
285        let _ = std::fs::remove_file(&self.temporary);
286    }
287}
288
289impl Drop for AtomicWrite {
290    /// Removes the temporary if the writer was neither committed nor aborted.
291    ///
292    /// This is the path taken when a handler returns `Err` mid-write, which is the normal way
293    /// a fail-closed handler gives up. Without it, every failed strip would litter a partial
294    /// file next to the user's document.
295    fn drop(&mut self) {
296        if self.file.is_some() {
297            self.discard_temporary();
298        }
299    }
300}
301
302/// Build a temporary path alongside `destination`.
303///
304/// Uniqueness comes from the process id, a monotonic counter, and the clock. This does not
305/// need to be unpredictable — the file is created with `create_new`, so a collision is a
306/// failed creation rather than a clobbered file — it only needs to avoid colliding with
307/// strypt's own concurrent writes. That is also why no random-number dependency is pulled in
308/// for it (ADR-0008).
309fn temporary_path_for(destination: &Path) -> PathBuf {
310    static COUNTER: AtomicU64 = AtomicU64::new(0);
311    let nonce = COUNTER.fetch_add(1, Ordering::Relaxed);
312    let clock: u32 = std::time::SystemTime::now()
313        .duration_since(std::time::UNIX_EPOCH)
314        .map_or(0, |d| d.subsec_nanos());
315    let name = format!(".strypt-{}-{clock}-{nonce}.tmp", std::process::id());
316    destination.parent().unwrap_or(Path::new(".")).join(name)
317}
318
319/// Create a new file, applying restrictive permissions at creation time on Unix.
320///
321/// Setting the mode in the open call rather than afterwards closes the window in which the
322/// file exists with the umask's permissions — a window another local process can read
323/// through, and one that is entirely avoidable.
324fn create_private(path: &Path, permissions: Permissions) -> Result<File> {
325    let mut options = std::fs::OpenOptions::new();
326    options.write(true).create_new(true);
327
328    #[cfg(unix)]
329    if permissions == Permissions::OwnerOnly {
330        use std::os::unix::fs::OpenOptionsExt as _;
331        options.mode(0o600);
332    }
333
334    let file = options.open(path).map_err(|source| StryptError::Io {
335        action: IoAction::CreatingTemporary,
336        source,
337    })?;
338
339    // On Windows the file inherits the parent directory's ACL and `OwnerOnly` is a no-op:
340    // std takes no security descriptor, and narrowing would need `unsafe` (ADR-0047).
341    let _ = permissions;
342    Ok(file)
343}
344
345/// Apply permissions to an existing path. A no-op off Unix.
346fn apply_permissions(path: &Path, permissions: Permissions) -> Result<()> {
347    #[cfg(unix)]
348    if permissions == Permissions::OwnerOnly {
349        use std::os::unix::fs::PermissionsExt as _;
350        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(
351            |source| StryptError::Io {
352                action: IoAction::SettingPermissions,
353                source,
354            },
355        )?;
356    }
357    let _ = (path, permissions);
358    Ok(())
359}
360
361#[cfg(test)]
362mod tests {
363    #![allow(clippy::unwrap_used)]
364
365    use super::*;
366
367    /// A scratch directory that removes itself, so tests never depend on an external crate
368    /// or leave files behind.
369    struct Scratch(PathBuf);
370
371    impl Scratch {
372        fn new(tag: &str) -> Self {
373            let path = std::env::temp_dir().join(format!(
374                "strypt-test-{tag}-{}-{:?}",
375                std::process::id(),
376                std::thread::current().id()
377            ));
378            std::fs::create_dir_all(&path).unwrap();
379            Self(path)
380        }
381        fn join(&self, name: &str) -> PathBuf {
382            self.0.join(name)
383        }
384    }
385
386    impl Drop for Scratch {
387        fn drop(&mut self) {
388            let _ = std::fs::remove_dir_all(&self.0);
389        }
390    }
391
392    #[test]
393    fn a_file_over_the_limit_is_refused_not_truncated() {
394        let dir = Scratch::new("limit");
395        let path = dir.join("big.bin");
396        std::fs::write(&path, vec![0u8; 4096]).unwrap();
397
398        let err = read_bounded(
399            &path,
400            Limits {
401                max_input_bytes: 1024,
402            },
403        )
404        .unwrap_err();
405        assert!(
406            matches!(
407                err,
408                StryptError::InputTooLarge {
409                    limit: 1024,
410                    actual: Some(4096)
411                }
412            ),
413            "got {err:?}"
414        );
415    }
416
417    #[test]
418    fn a_lying_size_hint_cannot_get_past_the_ceiling() {
419        // Models a source whose metadata understates its real length. Truncating silently
420        // here would hand a partial file to a handler, which would then report confidently on
421        // content that was never examined.
422        let data = vec![0u8; 4096];
423        let err = read_bounded_from(
424            data.as_slice(),
425            Limits {
426                max_input_bytes: 1024,
427            },
428            Some(16),
429        )
430        .unwrap_err();
431        assert!(
432            matches!(err, StryptError::InputTooLarge { .. }),
433            "got {err:?}"
434        );
435    }
436
437    #[test]
438    fn a_file_exactly_at_the_limit_is_accepted() {
439        let dir = Scratch::new("exact");
440        let path = dir.join("exact.bin");
441        std::fs::write(&path, vec![7u8; 1024]).unwrap();
442        let got = read_bounded(
443            &path,
444            Limits {
445                max_input_bytes: 1024,
446            },
447        )
448        .unwrap();
449        assert_eq!(got.len(), 1024);
450    }
451
452    #[test]
453    fn nothing_appears_at_the_destination_until_commit() {
454        let dir = Scratch::new("atomic");
455        let dest = dir.join("out.bin");
456
457        let mut w = AtomicWrite::begin(&dest, Overwrite::Refuse, Permissions::OwnerOnly).unwrap();
458        w.write_all(b"partial").unwrap();
459        assert!(
460            !dest.exists(),
461            "a half-written file must never be visible at the destination path"
462        );
463        w.commit().unwrap();
464        assert_eq!(std::fs::read(&dest).unwrap(), b"partial");
465    }
466
467    #[test]
468    fn an_abandoned_write_leaves_no_temporary_behind() {
469        let dir = Scratch::new("abort");
470        let dest = dir.join("out.bin");
471
472        let mut w = AtomicWrite::begin(&dest, Overwrite::Refuse, Permissions::OwnerOnly).unwrap();
473        w.write_all(b"doomed").unwrap();
474        w.abort();
475
476        assert!(!dest.exists());
477        let leftovers: Vec<_> = std::fs::read_dir(&dir.0)
478            .unwrap()
479            .filter_map(std::result::Result::ok)
480            .filter(|e| e.file_name().to_string_lossy().starts_with(".strypt-"))
481            .collect();
482        assert!(leftovers.is_empty(), "temporary files were left behind");
483    }
484
485    #[test]
486    fn dropping_a_writer_mid_failure_cleans_up() {
487        // The path a fail-closed handler takes when it gives up part-way through.
488        let dir = Scratch::new("drop");
489        let dest = dir.join("out.bin");
490        {
491            let mut w =
492                AtomicWrite::begin(&dest, Overwrite::Refuse, Permissions::OwnerOnly).unwrap();
493            w.write_all(b"incomplete").unwrap();
494        }
495        assert!(!dest.exists());
496        let count = std::fs::read_dir(&dir.0).unwrap().count();
497        assert_eq!(
498            count, 0,
499            "the temporary should have been dropped with the writer"
500        );
501    }
502
503    #[test]
504    fn an_existing_destination_is_refused_by_default() {
505        let dir = Scratch::new("refuse");
506        let dest = dir.join("out.bin");
507        std::fs::write(&dest, b"the user's file").unwrap();
508
509        let err = AtomicWrite::begin(&dest, Overwrite::Refuse, Permissions::OwnerOnly).unwrap_err();
510        assert!(matches!(err, StryptError::OutputExists));
511        assert_eq!(
512            std::fs::read(&dest).unwrap(),
513            b"the user's file",
514            "the existing file must be untouched"
515        );
516    }
517
518    #[test]
519    fn replace_is_available_when_the_caller_asks_for_it() {
520        let dir = Scratch::new("replace");
521        let dest = dir.join("out.bin");
522        std::fs::write(&dest, b"old").unwrap();
523
524        let mut w = AtomicWrite::begin(&dest, Overwrite::Replace, Permissions::OwnerOnly).unwrap();
525        w.write_all(b"new").unwrap();
526        w.commit().unwrap();
527        assert_eq!(std::fs::read(&dest).unwrap(), b"new");
528    }
529
530    #[cfg(unix)]
531    #[test]
532    fn output_is_not_readable_by_anyone_else() {
533        use std::os::unix::fs::PermissionsExt as _;
534
535        let dir = Scratch::new("perms");
536        let dest = dir.join("out.bin");
537        let mut w = AtomicWrite::begin(&dest, Overwrite::Refuse, Permissions::OwnerOnly).unwrap();
538        w.write_all(b"sensitive").unwrap();
539        w.commit().unwrap();
540
541        let mode = std::fs::metadata(&dest).unwrap().permissions().mode() & 0o777;
542        assert_eq!(mode, 0o600, "ADR-0019: stripped output is owner-only");
543    }
544
545    #[cfg(unix)]
546    #[test]
547    fn the_temporary_is_private_while_it_is_being_written() {
548        // The window that matters: the file is at its most exposed before it is finished,
549        // because that is when the user is not yet watching it.
550        use std::os::unix::fs::PermissionsExt as _;
551
552        let dir = Scratch::new("temp-perms");
553        let dest = dir.join("out.bin");
554        let w = AtomicWrite::begin(&dest, Overwrite::Refuse, Permissions::OwnerOnly).unwrap();
555        let mode = std::fs::metadata(&w.temporary)
556            .unwrap()
557            .permissions()
558            .mode()
559            & 0o777;
560        assert_eq!(mode, 0o600);
561        w.abort();
562    }
563
564    #[test]
565    fn the_temporary_sits_beside_the_destination_not_in_tmpdir() {
566        // Writing a copy of a sensitive document somewhere the user did not choose is a leak
567        // in its own right (docs/ARCHITECTURE.md §8).
568        let dir = Scratch::new("location");
569        let dest = dir.join("out.bin");
570        let w = AtomicWrite::begin(&dest, Overwrite::Refuse, Permissions::OwnerOnly).unwrap();
571        assert_eq!(w.temporary.parent(), dest.parent());
572        w.abort();
573    }
574}