#[cfg(any(unix, target_os = "wasi"))]
use crate::formats::pinned_dir::WalkerBacked;
use crate::security::fs_view::FsView;
use crate::security::fs_view::HostFs;
use crate::types::safe_path::ParentCheck;
use crate::types::safe_path::Resolved;
#[cfg(any(unix, target_os = "wasi"))]
use crate::types::safe_path::Walked;
use std::marker::PhantomData;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LeafSymlink {
Refuse,
Defer,
}
pub(crate) struct ValidationContext<'r, V: FsView = HostFs, P: ParentCheck = Resolved> {
symlink_seen: bool,
symlinks_allowed: bool,
leaf_symlink: LeafSymlink,
_proof: P::Proof<'r>,
view: PhantomData<fn() -> V>,
}
impl<V: FsView> ValidationContext<'_, V, Resolved> {
#[must_use]
pub(crate) fn new(symlinks_allowed: bool) -> Self {
Self {
symlink_seen: false,
symlinks_allowed,
leaf_symlink: LeafSymlink::Refuse,
_proof: (),
view: PhantomData,
}
}
#[must_use]
pub(crate) const fn deferring_leaf_symlink(mut self) -> Self {
self.leaf_symlink = LeafSymlink::Defer;
self
}
#[cfg(any(unix, target_os = "wasi"))]
#[must_use]
pub(crate) fn with_walker(self, proof: WalkerBacked<'_>) -> ValidationContext<'_, V, Walked> {
ValidationContext {
symlink_seen: self.symlink_seen,
symlinks_allowed: self.symlinks_allowed,
leaf_symlink: LeafSymlink::Defer,
_proof: proof,
view: PhantomData,
}
}
}
impl<V: FsView, P: ParentCheck> ValidationContext<'_, V, P> {
pub(crate) fn mark_symlink_seen(&mut self) {
self.symlink_seen = true;
}
#[inline]
pub(crate) const fn leaf_symlink(&self) -> LeafSymlink {
self.leaf_symlink
}
#[inline]
pub(crate) fn needs_full_canonicalize(&self) -> bool {
self.symlinks_allowed || self.symlink_seen
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::safe_path::ParentVetting;
use std::assert_matches;
#[cfg(unix)]
#[test]
#[allow(clippy::unwrap_used)]
fn test_walker_proof_keeps_the_symlink_state() {
let temp = tempfile::TempDir::new().unwrap();
let root = crate::formats::pinned_dir::PinnedRoot::open_for_test(temp.path()).unwrap();
let mut ctx = ValidationContext::<HostFs>::new(false);
ctx.mark_symlink_seen();
let walked = ctx.with_walker(root.backs_parent_probe());
assert!(walked.needs_full_canonicalize());
}
#[test]
fn test_parent_probe_is_a_property_of_the_state() {
assert_matches!(Resolved::VETTING, ParentVetting::Validator);
#[cfg(unix)]
assert_matches!(Walked::VETTING, ParentVetting::Walker);
}
#[test]
fn test_default_context_no_optimizations() {
let ctx = ValidationContext::<HostFs>::new(false);
assert!(!ctx.needs_full_canonicalize());
}
#[test]
fn test_context_with_symlinks_allowed() {
let ctx = ValidationContext::<HostFs>::new(true);
assert!(ctx.needs_full_canonicalize());
}
#[test]
fn test_context_symlink_seen_enables_canonicalize() {
let mut ctx = ValidationContext::<HostFs>::new(false);
assert!(!ctx.needs_full_canonicalize());
ctx.mark_symlink_seen();
assert!(ctx.needs_full_canonicalize());
}
}