tanzim-testing 0.3.0

Sandboxed temporary environment for tanzim tests and examples
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
//! A sandboxed temporary [`Environment`] for tests and examples.
//!
//! [`Environment::run`] executes a closure inside a freshly created temporary directory. On entry it
//! changes the working directory into that sandbox and snapshots the whole process environment; on
//! exit (whether the closure returns or panics) it restores the environment and working directory and
//! deletes the sandbox. Every run is serialized behind a process-global lock, so parallel tests do not
//! race on the shared working directory / environment — with the caveat that `Environment`-based tests
//! effectively run one at a time.
//!
//! ```
//! use tanzim_testing::environment::run;
//!
//! let read_back = run(|env| {
//!     env.write_file("hello.txt", b"world")?;
//!     Ok(std::fs::read_to_string("hello.txt")?)
//! })
//! .unwrap();
//! assert_eq!(read_back, "world");
//! ```

use cfg_if::cfg_if;
use std::error::Error as StdError;
use std::ffi::{OsStr, OsString};
use std::fmt::{self, Display, Formatter};
use std::path::{Component, Path, PathBuf};
use std::sync::{Mutex, MutexGuard};
use std::time::Instant;

/// Process-global lock. Serializes every [`Environment::run`] so concurrent test threads cannot stomp
/// on the shared working directory / environment. A `std` `Mutex` with a `const` initializer keeps the
/// crate dependency-free.
static ENV_LOCK: Mutex<()> = Mutex::new(());

/// Errors returned by [`Environment`] operations.
///
/// [`Display`] is one line by default; the alternate form (`{error:#}`) appends the underlying cause
/// chain, so wrapped [`std::io::Error`]s surface their real reason.
#[derive(Debug)]
pub enum Error {
    /// A method that requires an active sandbox was called outside of [`Environment::run`].
    Inactive,
    /// A filesystem or environment operation failed. `action` describes what was attempted and `path`
    /// names the target when there is one.
    Io {
        /// What was being attempted, e.g. `"create the file"`.
        action: String,
        /// The target path, when the failing operation had one.
        path: Option<PathBuf>,
        /// The underlying cause.
        source: std::io::Error,
    },
    /// A `create_*` / `write_file` path was absolute; sandbox paths must be relative.
    NotRelative {
        /// The offending path.
        path: PathBuf,
    },
    /// A path resolved outside the sandbox directory (e.g. it contained a `..` component).
    Escapes {
        /// The offending path.
        path: PathBuf,
    },
    /// A user error `?`-converted from inside a `run` closure.
    Other(Box<dyn StdError + Send + Sync>),
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Error::Inactive => write!(
                f,
                "the sandbox environment is not active; call this inside `Environment::run`"
            )?,
            Error::Io {
                action,
                path,
                source: _,
            } => match path {
                Some(path) => write!(f, "could not {action} `{}`", path.display())?,
                None => write!(f, "could not {action}")?,
            },
            Error::NotRelative { path } => write!(
                f,
                "path `{}` must be relative to the sandbox",
                path.display()
            )?,
            Error::Escapes { path } => {
                write!(f, "path `{}` escapes the sandbox directory", path.display())?
            }
            Error::Other(source) => write!(f, "{source}")?,
        }
        if f.alternate() {
            let mut cause = StdError::source(self);
            while let Some(error) = cause {
                write!(f, ": {error}")?;
                cause = error.source();
            }
        }
        Ok(())
    }
}

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Error::Io { source, .. } => Some(source),
            Error::Other(source) => source.source(),
            Error::Inactive | Error::NotRelative { .. } | Error::Escapes { .. } => None,
        }
    }
}

impl From<Box<dyn StdError + Send + Sync>> for Error {
    fn from(source: Box<dyn StdError + Send + Sync>) -> Self {
        Error::Other(source)
    }
}

impl From<std::io::Error> for Error {
    fn from(source: std::io::Error) -> Self {
        Error::Other(Box::new(source))
    }
}

/// A sandboxed temporary environment. Build one with [`Environment::temporary`] and enter it with
/// [`Environment::run`], or use the free [`run`] function to do both at once.
pub struct Environment {
    entered: Option<Entered>,
}

/// State captured while a sandbox is active. Restored and torn down in [`Environment`]'s `Drop`.
struct Entered {
    directory: PathBuf,
    saved_cwd: PathBuf,
    saved_env: Vec<(OsString, OsString)>,
    started: Instant,
    // Held for the whole run; released only after `Drop` finishes cleaning up. Declared last so it is
    // dropped last.
    _guard: MutexGuard<'static, ()>,
}

/// Run `f` inside a fresh sandbox. Shorthand for [`Environment::temporary`] followed by
/// [`Environment::run`].
pub fn run<T>(f: impl FnOnce(&mut Environment) -> Result<T, Error>) -> Result<T, Error> {
    Environment::temporary().run(f)
}

impl Environment {
    /// Create a fresh, not-yet-entered environment. The temporary directory is created later, inside
    /// [`run`](Environment::run), while the global lock is held.
    pub fn temporary() -> Self {
        Self { entered: None }
    }

    /// The active sandbox directory (the canonicalized temporary directory), or `None` before
    /// [`run`](Environment::run) has entered.
    pub fn directory(&self) -> Option<&Path> {
        match &self.entered {
            Some(entered) => Some(&entered.directory),
            None => None,
        }
    }

    /// Enter the sandbox and run `f` inside it.
    ///
    /// Acquires the global lock, creates a temporary directory (falling back to the current directory
    /// if the system temporary directory is not writable), snapshots the environment and working
    /// directory, and `chdir`s into the sandbox. When `f` returns — or panics — the environment and
    /// working directory are restored and the sandbox is deleted before the lock is released.
    ///
    /// User errors convert into [`Error::Other`], so `?` works inside the closure for any
    /// `Box<dyn Error + Send + Sync>` or [`std::io::Error`].
    pub fn run<T>(
        mut self,
        f: impl FnOnce(&mut Environment) -> Result<T, Error>,
    ) -> Result<T, Error> {
        let guard = match ENV_LOCK.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        let started = Instant::now();

        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::debug!(msg = "Entering sandbox environment");
            } else if #[cfg(feature = "logging")] {
                log::debug!("msg=\"Entering sandbox environment\"");
            }
        }

        let saved_cwd = match std::env::current_dir() {
            Ok(cwd) => cwd,
            Err(source) => {
                return Err(Error::Io {
                    action: String::from("read the current directory"),
                    path: None,
                    source,
                });
            }
        };
        let saved_env = std::env::vars_os().collect();

        let nanos = match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
            Ok(elapsed) => elapsed.as_nanos(),
            Err(_) => 0,
        };
        let name = format!("tanzim-testing-{}-{}", std::process::id(), nanos);

        let target = std::env::temp_dir().join(&name);
        let created = match std::fs::create_dir(&target) {
            Ok(()) => target,
            Err(source) => {
                if source.kind() != std::io::ErrorKind::PermissionDenied {
                    return Err(Error::Io {
                        action: String::from("create the sandbox directory"),
                        path: Some(target),
                        source,
                    });
                }
                let fallback = saved_cwd.join(&name);
                match std::fs::create_dir(&fallback) {
                    Ok(()) => fallback,
                    Err(source) => {
                        return Err(Error::Io {
                            action: String::from("create the sandbox directory"),
                            path: Some(fallback),
                            source,
                        });
                    }
                }
            }
        };
        let directory = match std::fs::canonicalize(&created) {
            Ok(directory) => directory,
            Err(source) => {
                let _ = std::fs::remove_dir_all(&created);
                return Err(Error::Io {
                    action: String::from("resolve the sandbox directory"),
                    path: Some(created),
                    source,
                });
            }
        };

        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::info!(msg = "Created sandbox directory", path = ?directory);
            } else if #[cfg(feature = "logging")] {
                log::info!("msg=\"Created sandbox directory\" path={directory:?}");
            }
        }

        let cwd_target = directory.clone();
        self.entered = Some(Entered {
            directory,
            saved_cwd,
            saved_env,
            started,
            _guard: guard,
        });

        match std::env::set_current_dir(&cwd_target) {
            Ok(()) => {}
            Err(source) => {
                return Err(Error::Io {
                    action: String::from("enter the sandbox directory"),
                    path: Some(cwd_target),
                    source,
                });
            }
        }

        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::trace!(msg = "Changed working directory into sandbox", path = ?cwd_target);
            } else if #[cfg(feature = "logging")] {
                log::trace!("msg=\"Changed working directory into sandbox\" path={cwd_target:?}");
            }
        }

        f(&mut self)
    }

    /// Remove every environment variable from the process. The full environment was snapshotted on
    /// entry, so it is restored when the sandbox is dropped. A no-op if called outside of
    /// [`run`](Environment::run).
    pub fn clear_env(&mut self) {
        if self.entered.is_none() {
            return;
        }

        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::debug!(msg = "Clearing environment variables");
            } else if #[cfg(feature = "logging")] {
                log::debug!("msg=\"Clearing environment variables\"");
            }
        }

        for (key, _) in std::env::vars_os() {
            // SAFETY: guarded by ENV_LOCK; single-threaded within the sandbox.
            unsafe { std::env::remove_var(&key) };
        }
    }

    /// Set the environment variable `key` to `value` for the duration of the sandbox. The full
    /// environment was snapshotted on entry, so this is undone when the sandbox is dropped — use it
    /// instead of a hand-rolled `unsafe { std::env::set_var(..) }` so tests stay self-contained.
    /// Returns [`Error::Inactive`] when called outside of [`run`](Environment::run).
    pub fn set_env(
        &mut self,
        key: impl AsRef<OsStr>,
        value: impl AsRef<OsStr>,
    ) -> Result<(), Error> {
        if self.entered.is_none() {
            return Err(Error::Inactive);
        }
        let key = key.as_ref();
        let value = value.as_ref();

        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::debug!(msg = "Setting environment variable", key = ?key);
            } else if #[cfg(feature = "logging")] {
                log::debug!("msg=\"Setting environment variable\" key={key:?}");
            }
        }

        // SAFETY: guarded by ENV_LOCK; single-threaded within the sandbox.
        unsafe { std::env::set_var(key, value) };

        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::trace!(msg = "Set environment variable value", key = ?key, value = ?value);
            } else if #[cfg(feature = "logging")] {
                log::trace!("msg=\"Set environment variable value\" key={key:?} value={value:?}");
            }
        }
        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::info!(msg = "Set environment variable", key = ?key);
            } else if #[cfg(feature = "logging")] {
                log::info!("msg=\"Set environment variable\" key={key:?}");
            }
        }
        Ok(())
    }

    /// Create an empty file at `path` (relative to the sandbox), truncating any existing file. The
    /// sandbox is the current directory during [`run`](Environment::run), so read it back with the
    /// same relative path.
    pub fn create_file(&mut self, path: impl AsRef<Path>) -> Result<(), Error> {
        let directory = match &self.entered {
            Some(entered) => entered.directory.clone(),
            None => return Err(Error::Inactive),
        };
        let full = resolve(&directory, path.as_ref())?;
        let _existed = full.exists();

        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::debug!(msg = "Creating file", path = ?full);
            } else if #[cfg(feature = "logging")] {
                log::debug!("msg=\"Creating file\" path={full:?}");
            }
        }

        create_parents(&full)?;
        match std::fs::File::create(&full) {
            Ok(_) => {}
            Err(source) => {
                return Err(Error::Io {
                    action: String::from("create the file"),
                    path: Some(full),
                    source,
                });
            }
        }
        confirm_within(&directory, &full)?;

        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::info!(msg = "Created file", path = ?full, recreated = _existed);
            } else if #[cfg(feature = "logging")] {
                log::info!("msg=\"Created file\" path={full:?} recreated={_existed}");
            }
        }
        Ok(())
    }

    /// Create a fresh file at `path` (relative to the sandbox), truncating any existing file, and write
    /// `contents` to it.
    pub fn write_file(
        &mut self,
        path: impl AsRef<Path>,
        contents: impl AsRef<[u8]>,
    ) -> Result<(), Error> {
        let directory = match &self.entered {
            Some(entered) => entered.directory.clone(),
            None => return Err(Error::Inactive),
        };
        let full = resolve(&directory, path.as_ref())?;
        let bytes = contents.as_ref();
        let _existed = full.exists();

        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::debug!(msg = "Writing file", path = ?full, bytes = bytes.len());
            } else if #[cfg(feature = "logging")] {
                log::debug!("msg=\"Writing file\" path={full:?} bytes={}", bytes.len());
            }
        }

        create_parents(&full)?;
        match std::fs::write(&full, bytes) {
            Ok(()) => {}
            Err(source) => {
                return Err(Error::Io {
                    action: String::from("write the file"),
                    path: Some(full),
                    source,
                });
            }
        }
        confirm_within(&directory, &full)?;

        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::trace!(
                    msg = "Wrote file contents",
                    path = ?full,
                    contents = %String::from_utf8_lossy(bytes),
                );
            } else if #[cfg(feature = "logging")] {
                log::trace!(
                    "msg=\"Wrote file contents\" path={full:?} contents={}",
                    String::from_utf8_lossy(bytes),
                );
            }
        }
        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::info!(
                    msg = "Wrote file",
                    path = ?full,
                    bytes = bytes.len(),
                    recreated = _existed,
                );
            } else if #[cfg(feature = "logging")] {
                log::info!(
                    "msg=\"Wrote file\" path={full:?} bytes={} recreated={_existed}",
                    bytes.len(),
                );
            }
        }
        Ok(())
    }

    /// Create a directory (and any missing parents) at `path`, relative to the sandbox.
    pub fn create_directory(&mut self, path: impl AsRef<Path>) -> Result<(), Error> {
        let directory = match &self.entered {
            Some(entered) => entered.directory.clone(),
            None => return Err(Error::Inactive),
        };
        let full = resolve(&directory, path.as_ref())?;
        let _existed = full.exists();

        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::debug!(msg = "Creating directory", path = ?full);
            } else if #[cfg(feature = "logging")] {
                log::debug!("msg=\"Creating directory\" path={full:?}");
            }
        }

        match std::fs::create_dir_all(&full) {
            Ok(()) => {}
            Err(source) => {
                return Err(Error::Io {
                    action: String::from("create the directory"),
                    path: Some(full),
                    source,
                });
            }
        }
        confirm_within(&directory, &full)?;

        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::info!(msg = "Created directory", path = ?full, recreated = _existed);
            } else if #[cfg(feature = "logging")] {
                log::info!("msg=\"Created directory\" path={full:?} recreated={_existed}");
            }
        }
        Ok(())
    }
}

impl Drop for Environment {
    fn drop(&mut self) {
        let entered = match self.entered.take() {
            Some(entered) => entered,
            None => return,
        };

        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::trace!(msg = "Restoring environment and removing sandbox");
            } else if #[cfg(feature = "logging")] {
                log::trace!("msg=\"Restoring environment and removing sandbox\"");
            }
        }

        for (key, _) in std::env::vars_os() {
            // SAFETY: guarded by ENV_LOCK; single-threaded within the sandbox.
            unsafe { std::env::remove_var(&key) };
        }
        for (key, value) in &entered.saved_env {
            // SAFETY: guarded by ENV_LOCK; single-threaded within the sandbox.
            unsafe { std::env::set_var(key, value) };
        }

        match std::env::set_current_dir(&entered.saved_cwd) {
            Ok(()) => {}
            Err(_source) => {
                cfg_if! {
                    if #[cfg(feature = "tracing")] {
                        tracing::warn!(
                            msg = "Could not restore working directory",
                            path = ?entered.saved_cwd,
                            error = ?_source,
                        );
                    } else if #[cfg(feature = "logging")] {
                        log::warn!(
                            "msg=\"Could not restore working directory\" path={:?} error={_source:?}",
                            entered.saved_cwd,
                        );
                    }
                }
            }
        }

        match std::fs::remove_dir_all(&entered.directory) {
            Ok(()) => {
                cfg_if! {
                    if #[cfg(feature = "tracing")] {
                        tracing::info!(msg = "Removed sandbox directory", path = ?entered.directory);
                    } else if #[cfg(feature = "logging")] {
                        log::info!(
                            "msg=\"Removed sandbox directory\" path={:?}",
                            entered.directory,
                        );
                    }
                }
            }
            Err(_source) => {
                cfg_if! {
                    if #[cfg(feature = "tracing")] {
                        tracing::warn!(
                            msg = "Could not remove sandbox directory",
                            path = ?entered.directory,
                            error = ?_source,
                        );
                    } else if #[cfg(feature = "logging")] {
                        log::warn!(
                            "msg=\"Could not remove sandbox directory\" path={:?} error={_source:?}",
                            entered.directory,
                        );
                    }
                }
            }
        }

        let _held = entered.started.elapsed();
        cfg_if! {
            if #[cfg(feature = "tracing")] {
                tracing::info!(msg = "Released sandbox lock", held_seconds = _held.as_secs_f64());
            } else if #[cfg(feature = "logging")] {
                log::info!("msg=\"Released sandbox lock\" held_seconds={}", _held.as_secs_f64());
            }
        }
    }
}

/// Join `relative` onto the sandbox `directory`, rejecting absolute paths and any `..` component that
/// could escape the sandbox.
fn resolve(directory: &Path, relative: &Path) -> Result<PathBuf, Error> {
    if relative.is_absolute() {
        return Err(Error::NotRelative {
            path: relative.to_path_buf(),
        });
    }
    for component in relative.components() {
        if matches!(component, Component::ParentDir) {
            return Err(Error::Escapes {
                path: relative.to_path_buf(),
            });
        }
    }
    Ok(directory.join(relative))
}

/// Create any missing parent directories for `full`.
fn create_parents(full: &Path) -> Result<(), Error> {
    match full.parent() {
        Some(parent) => match std::fs::create_dir_all(parent) {
            Ok(()) => Ok(()),
            Err(source) => Err(Error::Io {
                action: String::from("create parent directories"),
                path: Some(parent.to_path_buf()),
                source,
            }),
        },
        None => Ok(()),
    }
}

/// Defense in depth: confirm the just-created `full` canonicalizes to somewhere inside `directory`.
fn confirm_within(directory: &Path, full: &Path) -> Result<(), Error> {
    let canonical = match std::fs::canonicalize(full) {
        Ok(canonical) => canonical,
        Err(source) => {
            return Err(Error::Io {
                action: String::from("resolve the created path"),
                path: Some(full.to_path_buf()),
                source,
            });
        }
    };
    if canonical.starts_with(directory) {
        Ok(())
    } else {
        Err(Error::Escapes {
            path: full.to_path_buf(),
        })
    }
}