use std::cell::OnceCell;
use std::ffi::OsStr;
use std::num::NonZeroU64;
use std::num::NonZeroUsize;
use std::path::Component;
use std::path::Path;
use crate::ArchiveError;
use crate::ConfigProblem;
use crate::ConfigSetting;
use crate::EntryPattern;
use crate::EntrySelection;
use crate::Limit;
use crate::MarkPropagation;
use crate::PathRewrite;
use crate::RatioLimit;
use crate::Result;
use crate::Violation;
use crate::closed_enum::closed_enum;
use crate::non_zero;
use crate::non_zero_u64;
use crate::security::fs_view::LinkKind;
use crate::security::fs_view::relative_below;
use crate::types::Extension;
use crate::types::ExtensionFilter;
use crate::types::PathComponentName;
#[derive(Debug, Clone, Copy)]
pub(crate) enum Landing<'a> {
Entry(&'a Path),
Link(LinkSite<'a>),
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct LinkSite<'a> {
pub(crate) link: &'a Path,
pub(crate) kind: LinkKind,
}
impl Landing<'_> {
fn escape(self) -> ArchiveError {
match self {
Self::Entry(path) => ArchiveError::PathTraversal {
path: path.to_path_buf(),
},
Self::Link(LinkSite { link, kind }) => {
let path = link.to_path_buf();
match kind {
LinkKind::Symlink => ArchiveError::SymlinkEscape { path },
LinkKind::Hardlink => ArchiveError::HardlinkEscape { path },
}
}
}
}
}
closed_enum! {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum Admit {
#[default]
Refuse => "refuse",
Allow => "allow",
}
}
impl Admit {
#[must_use]
pub const fn is_allowed(self) -> bool {
matches!(self, Self::Allow)
}
#[must_use]
pub const fn from_allowed(allowed: bool) -> Self {
if allowed { Self::Allow } else { Self::Refuse }
}
}
closed_enum! {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ExistingFiles {
#[default]
Skip => "skip",
Overwrite => "overwrite",
Refuse => "refuse",
}
}
closed_enum! {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Staging {
#[default]
InPlace => "in_place",
Atomic => "atomic",
AtomicReplace => "atomic_replace",
}
}
closed_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PermissionPolicy {
Normalize => "normalize",
Preserve => "preserve",
}
}
impl PermissionPolicy {
#[must_use]
pub const fn from_preserve(preserve: bool) -> Self {
if preserve {
Self::Preserve
} else {
Self::Normalize
}
}
#[must_use]
pub const fn preserves(self) -> bool {
matches!(self, Self::Preserve)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct AllowedFeatures {
pub symlinks: Admit,
pub hardlinks: Admit,
pub absolute_paths: Admit,
pub world_writable: Admit,
pub windows_reserved_names: Admit,
}
const DEFAULT_BANNED_PATH_COMPONENTS: [&str; 7] =
[".git", ".ssh", ".gnupg", ".aws", ".kube", ".docker", ".env"];
fn default_banned_path_components() -> Vec<PathComponentName> {
DEFAULT_BANNED_PATH_COMPONENTS
.iter()
.filter_map(|name| PathComponentName::try_from(*name).ok())
.collect()
}
closed_enum! {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ZipConsistencyPolicy {
#[default]
Enforce => "enforce",
Ignore => "ignore",
}
}
closed_enum! {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TarSparsePolicy {
#[default]
Refuse => "refuse",
Expand => "expand",
}
}
closed_enum! {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum RepeatedPaths {
#[default]
KeepFirst => "keep_first",
Refuse => "refuse",
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct SolidLimits {
pub max_block_memory: NonZeroU64,
pub max_ratio: RatioLimit,
}
impl SolidLimits {
pub const DEFAULT: Self = Self {
max_block_memory: non_zero!(512 * 1024 * 1024),
max_ratio: crate::ratio_limit!(1000.0),
};
pub const PERMISSIVE: Self = Self {
max_block_memory: non_zero!(1024 * 1024 * 1024),
max_ratio: crate::ratio_limit!(10_000.0),
};
#[must_use]
pub const fn new(max_block_memory: NonZeroU64, max_ratio: RatioLimit) -> Self {
Self {
max_block_memory,
max_ratio,
}
}
#[must_use]
pub const fn with_max_block_memory(mut self, max_block_memory: NonZeroU64) -> Self {
self.max_block_memory = max_block_memory;
self
}
#[must_use]
pub const fn with_max_ratio(mut self, max_ratio: RatioLimit) -> Self {
self.max_ratio = max_ratio;
self
}
}
impl Default for SolidLimits {
fn default() -> Self {
Self::DEFAULT
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
#[non_exhaustive]
pub enum SolidArchives {
#[default]
Refuse,
Allow(SolidLimits),
}
impl SolidArchives {
#[must_use]
pub const fn limits(self) -> Option<SolidLimits> {
match self {
Self::Refuse => None,
Self::Allow(limits) => Some(limits),
}
}
#[must_use]
pub const fn is_allowed(self) -> bool {
matches!(self, Self::Allow(_))
}
#[must_use]
pub const fn with_allowed(self, allow: bool) -> Self {
match (allow, self) {
(true, admitted @ Self::Allow(_)) => admitted,
(true, Self::Refuse) => Self::Allow(SolidLimits::DEFAULT),
(false, _) => Self::Refuse,
}
}
pub fn with_limits(self, limits: SolidLimits) -> crate::Result<Self> {
match self {
Self::Allow(_) => Ok(Self::Allow(limits)),
Self::Refuse => Err(crate::ArchiveError::InvalidConfiguration {
setting: ConfigSetting::MaxSolidBlockMemory,
problem: ConfigProblem::NotSupported,
}),
}
}
pub fn with_max_block_memory(self, max_block_memory: NonZeroU64) -> crate::Result<Self> {
match self {
Self::Allow(limits) => Ok(Self::Allow(limits.with_max_block_memory(max_block_memory))),
Self::Refuse => self.with_limits(SolidLimits::DEFAULT),
}
}
pub fn with_max_ratio(self, max_ratio: RatioLimit) -> crate::Result<Self> {
match self {
Self::Allow(limits) => Ok(Self::Allow(limits.with_max_ratio(max_ratio))),
Self::Refuse => Err(crate::ArchiveError::InvalidConfiguration {
setting: ConfigSetting::MaxSolidCompressionRatio,
problem: ConfigProblem::NotSupported,
}),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParallelDecode {
Sequential,
Bounded(NonZeroU64),
}
pub(crate) const DEFAULT_MEMBER_ALLOWANCE: NonZeroU64 = non_zero!(10_000);
impl ParallelDecode {
pub const DEFAULT_BYTES: NonZeroU64 = non_zero!(128 * 1024 * 1024);
#[must_use]
pub const fn lookahead(self) -> Option<NonZeroU64> {
match self {
Self::Sequential => None,
Self::Bounded(bytes) => Some(bytes),
}
}
}
impl ParallelDecode {
#[must_use]
pub const fn from_bytes(lookahead: Option<NonZeroU64>) -> Self {
match lookahead {
Some(bytes) => Self::Bounded(bytes),
None => Self::Sequential,
}
}
}
impl From<Option<NonZeroU64>> for ParallelDecode {
fn from(lookahead: Option<NonZeroU64>) -> Self {
Self::from_bytes(lookahead)
}
}
impl Default for ParallelDecode {
fn default() -> Self {
Self::Bounded(Self::DEFAULT_BYTES)
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SecurityConfig {
pub max_file_size: Limit<NonZeroU64>,
pub max_total_size: Limit<NonZeroU64>,
pub max_compression_ratio: RatioLimit,
pub max_file_count: Limit<NonZeroUsize>,
pub max_path_depth: NonZeroUsize,
pub allowed: AllowedFeatures,
pub permissions: PermissionPolicy,
pub allowed_extensions: ExtensionFilter,
pub selection: EntrySelection,
pub banned_path_components: Vec<PathComponentName>,
pub solid_archives: SolidArchives,
pub max_tar_metadata_bytes: NonZeroU64,
pub max_decoder_memory: NonZeroU64,
pub compressed_member_allowance: NonZeroU64,
pub parallel_decode: ParallelDecode,
pub zip_consistency: ZipConsistencyPolicy,
pub tar_sparse: TarSparsePolicy,
pub repeated_paths: RepeatedPaths,
pub max_kdf_work: NonZeroU64,
}
impl Default for SecurityConfig {
fn default() -> Self {
Self {
max_file_size: Limit::Bounded(non_zero!(50 * 1024 * 1024)), max_total_size: Limit::Bounded(non_zero!(500 * 1024 * 1024)), max_compression_ratio: crate::ratio_limit!(100.0),
max_file_count: Limit::Bounded(non_zero!(10_000)),
max_path_depth: non_zero!(32),
allowed: AllowedFeatures::default(), permissions: PermissionPolicy::Normalize,
allowed_extensions: ExtensionFilter::Any,
selection: EntrySelection::default(),
banned_path_components: default_banned_path_components(),
solid_archives: SolidArchives::Refuse,
max_tar_metadata_bytes: non_zero!(4 * 1024 * 1024), max_decoder_memory: non_zero!(256 * 1024 * 1024), compressed_member_allowance: DEFAULT_MEMBER_ALLOWANCE,
parallel_decode: ParallelDecode::Bounded(ParallelDecode::DEFAULT_BYTES),
zip_consistency: ZipConsistencyPolicy::Enforce,
tar_sparse: TarSparsePolicy::Refuse,
repeated_paths: RepeatedPaths::KeepFirst,
max_kdf_work: DEFAULT_MAX_KDF_WORK,
}
}
}
const DEFAULT_MAX_KDF_WORK: NonZeroU64 = non_zero!(1 << 27);
const PERMISSIVE_PARALLEL_DECODE: NonZeroU64 = non_zero!(1024 * 1024 * 1024);
impl SecurityConfig {
#[must_use]
pub fn permissive() -> Self {
Self {
allowed: AllowedFeatures {
symlinks: Admit::Allow,
hardlinks: Admit::Allow,
absolute_paths: Admit::Allow,
world_writable: Admit::Allow,
windows_reserved_names: Admit::Refuse,
},
permissions: PermissionPolicy::Preserve,
max_compression_ratio: crate::ratio_limit!(1000.0),
banned_path_components: Vec::new(),
solid_archives: SolidArchives::Allow(SolidLimits::PERMISSIVE),
max_tar_metadata_bytes: non_zero!(16 * 1024 * 1024), max_decoder_memory: non_zero!(1024 * 1024 * 1024), compressed_member_allowance: non_zero!(100_000),
parallel_decode: ParallelDecode::Bounded(PERMISSIVE_PARALLEL_DECODE),
..Self::default()
}
}
#[must_use]
#[inline]
pub fn with_max_file_size(mut self, size: impl Into<Limit<NonZeroU64>>) -> Self {
self.max_file_size = size.into();
self
}
#[must_use]
#[inline]
pub fn with_max_total_size(mut self, size: impl Into<Limit<NonZeroU64>>) -> Self {
self.max_total_size = size.into();
self
}
#[must_use]
#[inline]
pub fn with_max_compression_ratio(mut self, ratio: RatioLimit) -> Self {
self.max_compression_ratio = ratio;
self
}
#[must_use]
#[inline]
pub fn with_max_file_count(mut self, count: impl Into<Limit<NonZeroUsize>>) -> Self {
self.max_file_count = count.into();
self
}
#[must_use]
#[inline]
pub fn with_max_path_depth(mut self, depth: NonZeroUsize) -> Self {
self.max_path_depth = depth;
self
}
#[must_use]
#[inline]
pub fn with_allowed(mut self, allowed: AllowedFeatures) -> Self {
self.allowed = allowed;
self
}
#[must_use]
#[inline]
pub fn with_allow_symlinks(mut self, allow: bool) -> Self {
self.allowed.symlinks = Admit::from_allowed(allow);
self
}
#[must_use]
#[inline]
pub fn with_allow_hardlinks(mut self, allow: bool) -> Self {
self.allowed.hardlinks = Admit::from_allowed(allow);
self
}
#[must_use]
#[inline]
pub fn with_allow_absolute_paths(mut self, allow: bool) -> Self {
self.allowed.absolute_paths = Admit::from_allowed(allow);
self
}
#[must_use]
#[inline]
pub fn with_allow_world_writable(mut self, allow: bool) -> Self {
self.allowed.world_writable = Admit::from_allowed(allow);
self
}
#[must_use]
#[inline]
pub fn with_allow_windows_reserved_names(mut self, allow: bool) -> Self {
self.allowed.windows_reserved_names = Admit::from_allowed(allow);
self
}
#[must_use]
#[inline]
pub fn with_preserve_permissions(mut self, preserve: bool) -> Self {
self.permissions = PermissionPolicy::from_preserve(preserve);
self
}
#[must_use]
#[inline]
pub fn with_allowed_extensions(mut self, extensions: ExtensionFilter) -> Self {
self.allowed_extensions = extensions;
self
}
pub fn try_add_allowed_extension(mut self, extension: &str) -> crate::Result<Self> {
let extension = Extension::try_from(extension)?;
self.allowed_extensions =
std::mem::take(&mut self.allowed_extensions).with_added(extension);
Ok(self)
}
#[must_use]
pub fn with_selection(mut self, selection: EntrySelection) -> Self {
self.selection = selection;
self
}
pub fn try_add_include(mut self, pattern: &str) -> crate::Result<Self> {
let pattern = EntryPattern::parse_for(ConfigSetting::EntryInclude, pattern)?;
self.selection = self.selection.with_include(pattern);
Ok(self)
}
pub fn try_add_exclude(mut self, pattern: &str) -> crate::Result<Self> {
let pattern = EntryPattern::parse_for(ConfigSetting::EntryExclude, pattern)?;
self.selection = self.selection.with_exclude(pattern);
Ok(self)
}
#[must_use]
pub fn with_path_rewrite(mut self, rewrite: PathRewrite) -> Self {
self.selection = self.selection.with_rewrite(rewrite);
self
}
pub fn try_add_banned_path_component(mut self, component: &str) -> crate::Result<Self> {
self.banned_path_components
.push(PathComponentName::try_from(component)?);
Ok(self)
}
#[must_use]
#[inline]
pub fn with_banned_path_components(mut self, components: Vec<PathComponentName>) -> Self {
self.banned_path_components = components;
self
}
#[must_use]
#[inline]
pub fn with_solid_archives(mut self, solid: SolidArchives) -> Self {
self.solid_archives = solid;
self
}
#[must_use]
#[inline]
pub fn with_allow_solid_archives(mut self, allow: bool) -> Self {
self.solid_archives = self.solid_archives.with_allowed(allow);
self
}
pub fn with_solid_limits(mut self, limits: SolidLimits) -> crate::Result<Self> {
self.solid_archives = self.solid_archives.with_limits(limits)?;
Ok(self)
}
#[must_use]
#[inline]
pub fn with_max_tar_metadata_bytes(mut self, size: NonZeroU64) -> Self {
self.max_tar_metadata_bytes = size;
self
}
#[must_use]
#[inline]
pub fn with_max_decoder_memory(mut self, size: NonZeroU64) -> Self {
self.max_decoder_memory = size;
self
}
#[must_use]
#[inline]
pub fn with_compressed_member_allowance(mut self, base: NonZeroU64) -> Self {
self.compressed_member_allowance = base;
self
}
#[must_use]
#[inline]
pub fn with_parallel_decode(mut self, mode: ParallelDecode) -> Self {
self.parallel_decode = mode;
self
}
#[must_use]
#[inline]
pub fn with_zip_consistency(mut self, policy: ZipConsistencyPolicy) -> Self {
self.zip_consistency = policy;
self
}
#[must_use]
#[inline]
pub fn with_tar_sparse(mut self, policy: TarSparsePolicy) -> Self {
self.tar_sparse = policy;
self
}
#[must_use]
#[inline]
pub fn with_max_kdf_work(mut self, rounds: NonZeroU64) -> Self {
self.max_kdf_work = rounds;
self
}
#[must_use]
#[inline]
pub fn with_repeated_paths(mut self, policy: RepeatedPaths) -> Self {
self.repeated_paths = policy;
self
}
}
impl SecurityConfig {
#[must_use]
pub fn is_path_component_allowed(&self, component: &str) -> bool {
let fold = OnceCell::new();
!self
.banned_path_components
.iter()
.any(|banned| banned.matches_folding_once(component, &fold))
}
pub(crate) fn check_component(&self, comp: &OsStr, who: Landing<'_>) -> Result<()> {
let name = comp.to_string_lossy();
if self.is_path_component_allowed(&name) {
return Ok(());
}
let component = Box::from(name.as_ref());
Err(match who {
Landing::Entry(_) => Violation::BannedComponent { component },
Landing::Link(LinkSite { kind, .. }) => {
Violation::LinkTargetBannedComponent { kind, component }
}
}
.into())
}
pub(crate) fn check_banned_in(&self, relative: &Path, who: Landing<'_>) -> Result<()> {
relative
.components()
.try_for_each(|component| match component {
Component::Normal(name) => self.check_component(name, who),
_ => Ok(()),
})
}
pub(crate) fn check_landing(
&self,
canonical: &Path,
root: &Path,
who: Landing<'_>,
) -> Result<()> {
let relative = relative_below(canonical, root).ok_or_else(|| who.escape())?;
self.check_banned_in(relative, who)
}
#[must_use]
pub fn is_extension_allowed(&self, extension: Option<&str>) -> bool {
self.allowed_extensions.allows(extension)
}
pub(crate) fn for_listing(&self) -> Self {
let mut listing = self.clone();
listing.allowed.symlinks = Admit::Refuse;
listing.allowed.hardlinks = Admit::Refuse;
listing.allowed.world_writable = Admit::Refuse;
listing.permissions = PermissionPolicy::Normalize;
listing
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ExtractionOptions {
pub staging: Staging,
pub existing_files: ExistingFiles,
pub decode_reuse: DecodeReuse,
pub mark_propagation: MarkPropagation,
}
impl Default for ExtractionOptions {
fn default() -> Self {
Self {
staging: Staging::InPlace,
existing_files: ExistingFiles::Skip,
decode_reuse: DecodeReuse::default(),
mark_propagation: MarkPropagation::Never,
}
}
}
impl ExtractionOptions {
#[must_use]
#[inline]
pub const fn with_staging(mut self, staging: Staging) -> Self {
self.staging = staging;
self
}
#[must_use]
#[inline]
pub const fn with_existing_files(mut self, existing_files: ExistingFiles) -> Self {
self.existing_files = existing_files;
self
}
#[must_use]
#[inline]
pub const fn with_mark_propagation(mut self, mark_propagation: MarkPropagation) -> Self {
self.mark_propagation = mark_propagation;
self
}
#[must_use]
#[inline]
pub const fn with_decode_reuse(mut self, reuse: DecodeReuse) -> Self {
self.decode_reuse = reuse;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReuseLimit(NonZeroU64);
impl ReuseLimit {
pub const DEFAULT: Self = Self(non_zero!(32 * 1024 * 1024));
pub const MAX: Self = Self(non_zero!(256 * 1024 * 1024));
pub(crate) const MAX_BYTES: u64 = Self::MAX.0.get();
#[must_use]
pub const fn new(bytes: NonZeroU64) -> Self {
if bytes.get() > Self::MAX_BYTES {
Self::MAX
} else {
Self(bytes)
}
}
#[must_use]
pub const fn get(self) -> u64 {
self.0.get()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DecodeReuse {
Off,
Memory(ReuseLimit),
TempFile(ReuseLimit),
}
closed_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DecodeReuseKind {
Off => "off",
Memory => "memory",
TempFile => "temp_file",
}
}
impl DecodeReuse {
#[must_use]
pub const fn kind(self) -> DecodeReuseKind {
match self {
Self::Off => DecodeReuseKind::Off,
Self::Memory(_) => DecodeReuseKind::Memory,
Self::TempFile(_) => DecodeReuseKind::TempFile,
}
}
#[must_use]
pub const fn limit(self) -> Option<ReuseLimit> {
match self {
Self::Off => None,
Self::Memory(limit) | Self::TempFile(limit) => Some(limit),
}
}
pub fn from_parts(kind: DecodeReuseKind, limit: Option<ReuseLimit>) -> crate::Result<Self> {
match (kind, limit) {
(DecodeReuseKind::Off, None) => Ok(Self::Off),
(DecodeReuseKind::Off, Some(_)) => Err(crate::ArchiveError::InvalidConfiguration {
setting: ConfigSetting::DecodeReuseLimit,
problem: ConfigProblem::NotSupported,
}),
(DecodeReuseKind::Memory, limit) => {
Ok(Self::Memory(limit.unwrap_or(ReuseLimit::DEFAULT)))
}
(DecodeReuseKind::TempFile, limit) => {
Ok(Self::TempFile(limit.unwrap_or(ReuseLimit::DEFAULT)))
}
}
}
}
impl Default for DecodeReuse {
fn default() -> Self {
Self::Memory(ReuseLimit::DEFAULT)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DecompressionBudget(std::num::NonZeroU64);
impl DecompressionBudget {
pub const DEFAULT: Self = Self(non_zero!(500 * 1024 * 1024));
#[must_use]
pub const fn new(bytes: std::num::NonZeroU64) -> Self {
Self(bytes)
}
pub fn try_from_bytes(bytes: u64) -> crate::Result<Self> {
non_zero_u64(ConfigSetting::DecompressionBudget, bytes).map(Self)
}
#[must_use]
pub const fn get(self) -> u64 {
self.0.get()
}
}
impl Default for DecompressionBudget {
fn default() -> Self {
Self::DEFAULT
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum IntegrityCheck {
#[default]
Skip,
DecodeToEof(DecompressionBudget),
}
impl IntegrityCheck {
#[must_use]
pub const fn budget(self) -> Option<DecompressionBudget> {
match self {
Self::Skip => None,
Self::DecodeToEof(budget) => Some(budget),
}
}
}
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct VerificationOptions {
pub integrity: IntegrityCheck,
}
impl VerificationOptions {
#[must_use]
pub fn with_integrity(mut self, integrity: IntegrityCheck) -> Self {
self.integrity = integrity;
self
}
}
closed_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum StoredTargets {
#[default]
Skip => "skip",
Read => "read",
}
}
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct ListOptions {
pub stored_targets: StoredTargets,
}
impl ListOptions {
#[must_use]
pub fn with_stored_targets(mut self, stored_targets: StoredTargets) -> Self {
self.stored_targets = stored_targets;
self
}
}
#[cfg(test)]
#[allow(
clippy::field_reassign_with_default,
reason = "tests adjust a default value field by field"
)]
mod tests {
use std::assert_matches;
use super::*;
fn link(kind: LinkKind) -> Landing<'static> {
Landing::Link(LinkSite {
link: Path::new("dir/l"),
kind,
})
}
#[test]
fn check_component_picks_the_error_of_who_asks() {
let config = SecurityConfig::default();
let entry = Landing::Entry(Path::new("a/.git"));
assert!(config.check_component(OsStr::new("src"), entry).is_ok());
assert_matches!(
config.check_component(OsStr::new(".GIT"), entry),
Err(ArchiveError::SecurityViolation {
kind: Violation::BannedComponent { .. }
})
);
for kind in [LinkKind::Symlink, LinkKind::Hardlink] {
assert_matches!(
config.check_component(OsStr::new(".git"), link(kind)),
Err(ArchiveError::SecurityViolation {
kind: Violation::LinkTargetBannedComponent { kind: got, .. }
}) if got == kind
);
}
}
#[cfg(unix)]
#[test]
fn check_component_reports_the_lossy_text_of_a_non_utf8_name() {
use std::os::unix::ffi::OsStrExt as _;
let config = SecurityConfig::default()
.try_add_banned_path_component("\u{fffd}x")
.unwrap();
let name = OsStr::from_bytes(b"\xffx");
assert_matches!(
config.check_component(name, Landing::Entry(Path::new("p"))),
Err(ArchiveError::SecurityViolation {
kind: Violation::BannedComponent { component }
}) if &*component == "\u{fffd}x"
);
}
#[test]
fn check_banned_in_finds_the_first_normal_component_and_skips_the_rest() {
let config = SecurityConfig::default();
let who = Landing::Entry(Path::new("e"));
assert!(config.check_banned_in(Path::new(""), who).is_ok());
assert!(config.check_banned_in(Path::new("a/./b/c"), who).is_ok());
assert_matches!(
config.check_banned_in(Path::new("a/.ssh/.git"), who),
Err(ArchiveError::SecurityViolation {
kind: Violation::BannedComponent { component }
}) if &*component == ".ssh"
);
}
#[test]
fn check_landing_refuses_an_escape_with_the_error_of_who_asks() {
let config = SecurityConfig::default();
let root = Path::new("/dest");
let outside = Path::new("/elsewhere/x");
assert_matches!(
config.check_landing(outside, root, Landing::Entry(Path::new("a/b"))),
Err(ArchiveError::PathTraversal { path }) if path == Path::new("a/b")
);
assert_matches!(
config.check_landing(outside, root, link(LinkKind::Symlink)),
Err(ArchiveError::SymlinkEscape { path }) if path == Path::new("dir/l")
);
assert_matches!(
config.check_landing(outside, root, link(LinkKind::Hardlink)),
Err(ArchiveError::HardlinkEscape { path }) if path == Path::new("dir/l")
);
}
#[test]
fn check_landing_judges_the_part_below_the_root_only() {
let config = SecurityConfig::default();
let root = Path::new("/dest/.git");
assert!(
config
.check_landing(Path::new("/dest/.git/docs"), root, link(LinkKind::Symlink))
.is_ok(),
"a banned name in the root itself is not judged"
);
assert_matches!(
config.check_landing(
Path::new("/dest/.git/a/.ssh"),
root,
link(LinkKind::Hardlink)
),
Err(ArchiveError::SecurityViolation {
kind: Violation::LinkTargetBannedComponent {
kind: LinkKind::Hardlink,
..
}
})
);
assert_matches!(
config.check_landing(
Path::new("/dest/.git/.env"),
root,
Landing::Entry(Path::new("e"))
),
Err(ArchiveError::SecurityViolation {
kind: Violation::BannedComponent { .. }
})
);
}
#[test]
fn test_default_config() {
let config = SecurityConfig::default();
assert!(!config.allowed.symlinks.is_allowed());
assert!(!config.allowed.hardlinks.is_allowed());
assert!(!config.allowed.absolute_paths.is_allowed());
assert_eq!(config.max_file_size.ceiling(), 50 * 1024 * 1024);
}
#[test]
fn test_permissive_config() {
let config = SecurityConfig::permissive();
assert!(config.allowed.symlinks.is_allowed());
assert!(config.allowed.hardlinks.is_allowed());
assert!(config.allowed.absolute_paths.is_allowed());
}
#[test]
fn test_extension_allowed_empty_list() {
let config = SecurityConfig::default();
assert!(config.is_extension_allowed(Some("txt")));
assert!(config.is_extension_allowed(Some("pdf")));
}
#[test]
fn test_extension_allowed_with_list() {
let mut config = SecurityConfig::default();
config.allowed_extensions = ExtensionFilter::only(vec![
Extension::try_from("txt").unwrap(),
Extension::try_from("pdf").unwrap(),
])
.unwrap();
assert!(config.is_extension_allowed(Some("txt")));
assert!(config.is_extension_allowed(Some("TXT")));
assert!(!config.is_extension_allowed(Some("exe")));
}
#[test]
fn test_path_component_allowed() {
let config = SecurityConfig::default();
assert!(config.is_path_component_allowed("src"));
assert!(!config.is_path_component_allowed(".git"));
assert!(!config.is_path_component_allowed(".ssh"));
assert!(!config.is_path_component_allowed(".Git"));
assert!(!config.is_path_component_allowed(".GIT"));
assert!(!config.is_path_component_allowed(".SSH"));
assert!(!config.is_path_component_allowed(".Gnupg"));
}
#[test]
fn test_config_default_security_flags() {
let config = SecurityConfig::default();
assert!(
!config.allowed.symlinks.is_allowed(),
"symlinks should be denied by default"
);
assert!(
!config.allowed.hardlinks.is_allowed(),
"hardlinks should be denied by default"
);
assert!(
!config.allowed.absolute_paths.is_allowed(),
"absolute paths should be denied by default"
);
assert!(
!config.permissions.preserves(),
"permissions should not be preserved by default"
);
assert!(
!config.allowed.world_writable.is_allowed(),
"world-writable should be denied by default"
);
}
#[test]
fn test_config_permissive_security_flags() {
let config = SecurityConfig::permissive();
assert!(
config.allowed.symlinks.is_allowed(),
"permissive allows symlinks"
);
assert!(
config.allowed.hardlinks.is_allowed(),
"permissive allows hardlinks"
);
assert!(
config.allowed.absolute_paths.is_allowed(),
"permissive allows absolute paths"
);
assert!(
config.permissions.preserves(),
"permissive preserves permissions"
);
assert!(
config.allowed.world_writable.is_allowed(),
"permissive allows world-writable"
);
}
#[test]
fn test_config_quota_limits() {
let config = SecurityConfig::default();
assert_eq!(
config.max_file_size.ceiling(),
50 * 1024 * 1024,
"50 MB file limit"
);
assert_eq!(
config.max_total_size.ceiling(),
500 * 1024 * 1024,
"500 MB total limit"
);
assert_eq!(
config.max_file_count.ceiling(),
10_000,
"10k file count limit"
);
assert_eq!(config.max_path_depth.get(), 32, "32 level depth limit");
#[allow(clippy::float_cmp, reason = "tests assert exact float values")]
{
assert_eq!(
config.max_compression_ratio.get(),
100.0,
"100x compression ratio limit"
);
}
}
#[test]
fn test_config_banned_components_not_empty() {
let config = SecurityConfig::default();
assert!(
!config.banned_path_components.is_empty(),
"should have banned components by default"
);
assert!(
config
.banned_path_components
.contains(&PathComponentName::try_from(".git").unwrap()),
"should ban .git"
);
assert!(
config
.banned_path_components
.contains(&PathComponentName::try_from(".ssh").unwrap()),
"should ban .ssh"
);
}
#[test]
fn test_replaced_banned_components_match_non_ascii_spellings() {
let names = ["caf\u{e9}", ".s\u{17f}h"]
.into_iter()
.map(|raw| PathComponentName::try_from(raw).unwrap())
.collect();
let config = SecurityConfig::default().with_banned_path_components(names);
for banned in [
"caf\u{e9}",
"cafe\u{301}",
"CAF\u{c9}",
".ssh",
".SSH",
".\u{df}h",
] {
assert!(!config.is_path_component_allowed(banned), "{banned:?}");
}
for allowed in ["cafe", ".git", ".sshx"] {
assert!(config.is_path_component_allowed(allowed), "{allowed:?}");
}
}
#[test]
fn test_aliased_banned_names_coexist_without_changing_the_verdict() {
let spellings = [".ssh", ".\u{17f}sh"];
let list: Vec<_> = spellings
.into_iter()
.map(|raw| PathComponentName::try_from(raw).unwrap())
.collect();
assert_ne!(list[0], list[1]);
let config = SecurityConfig::default().with_banned_path_components(list);
for component in [".ssh", ".SSH", ".\u{17f}sh", ".\u{df}h"] {
assert!(
!config.is_path_component_allowed(component),
"{component:?}"
);
}
}
#[test]
fn test_config_solid_archives_default() {
let config = SecurityConfig::default();
assert_eq!(
config.solid_archives,
SolidArchives::Refuse,
"solid archives should be denied by default"
);
assert_eq!(
SolidLimits::DEFAULT.max_block_memory.get(),
512 * 1024 * 1024,
"max solid block memory should be 512 MB"
);
}
#[test]
fn test_config_permissive_solid_archives() {
let config = SecurityConfig::permissive();
assert_eq!(
config.solid_archives,
SolidArchives::Allow(SolidLimits::PERMISSIVE),
"permissive config should allow solid archives"
);
assert_eq!(
SolidLimits::PERMISSIVE.max_block_memory.get(),
1024 * 1024 * 1024,
"permissive should have 1 GB solid block limit"
);
}
#[test]
fn test_config_tar_metadata_bytes_default() {
let config = SecurityConfig::default();
assert_eq!(
config.max_tar_metadata_bytes.get(),
4 * 1024 * 1024,
"max TAR metadata bytes should be 4 MiB by default"
);
}
#[test]
fn test_config_permissive_tar_metadata_bytes() {
let config = SecurityConfig::permissive();
assert_eq!(
config.max_tar_metadata_bytes.get(),
16 * 1024 * 1024,
"permissive should have 16 MiB TAR metadata budget"
);
}
#[test]
fn test_with_max_tar_metadata_bytes_builder() {
let config = SecurityConfig::default().with_max_tar_metadata_bytes(crate::non_zero!(2048));
assert_eq!(config.max_tar_metadata_bytes.get(), 2048);
}
#[test]
fn test_solid_compression_ratio_defaults() {
assert_eq!(SolidLimits::DEFAULT.max_ratio.get(), 1000.0);
assert_eq!(SolidLimits::PERMISSIVE.max_ratio.get(), 10_000.0);
}
#[test]
fn allowing_solid_archives_keeps_admitted_limits_and_resets_a_refusal() {
let custom = SolidLimits::DEFAULT.with_max_block_memory(crate::non_zero!(4096));
let kept = SecurityConfig::default()
.with_solid_archives(SolidArchives::Allow(custom))
.with_allow_solid_archives(true);
assert_eq!(kept.solid_archives, SolidArchives::Allow(custom));
let reset = SecurityConfig::default().with_allow_solid_archives(true);
assert_eq!(
reset.solid_archives,
SolidArchives::Allow(SolidLimits::DEFAULT)
);
let refused = SecurityConfig::default()
.with_solid_archives(SolidArchives::Allow(custom))
.with_allow_solid_archives(false);
assert_eq!(refused.solid_archives, SolidArchives::Refuse);
}
#[test]
fn solid_limits_cannot_be_set_while_solid_archives_are_refused() {
let err = SecurityConfig::default()
.with_solid_limits(SolidLimits::DEFAULT)
.unwrap_err();
assert_matches!(
err,
crate::ArchiveError::InvalidConfiguration {
setting: ConfigSetting::MaxSolidBlockMemory,
problem: ConfigProblem::NotSupported,
}
);
let custom = SolidLimits::DEFAULT.with_max_block_memory(crate::non_zero!(4096));
let config = SecurityConfig::default()
.with_allow_solid_archives(true)
.with_solid_limits(custom)
.unwrap();
assert_eq!(config.solid_archives.limits(), Some(custom));
}
#[test]
fn every_integrity_check_has_a_budget_rule() {
for check in [
IntegrityCheck::Skip,
IntegrityCheck::DecodeToEof(DecompressionBudget::DEFAULT),
] {
let expected = match check {
IntegrityCheck::Skip => None,
IntegrityCheck::DecodeToEof(budget) => Some(budget),
};
assert_eq!(check.budget(), expected);
}
}
#[test]
fn admit_converts_to_and_from_a_bool() {
assert_eq!(Admit::from_allowed(true), Admit::Allow);
assert_eq!(Admit::from_allowed(false), Admit::Refuse);
assert!(Admit::Allow.is_allowed());
assert!(!Admit::Refuse.is_allowed());
assert_eq!(Admit::default(), Admit::Refuse);
}
#[test]
fn for_listing_resets_write_time_flags_only() {
let listing = SecurityConfig::permissive().for_listing();
assert_eq!(listing.allowed.symlinks, Admit::Refuse);
assert_eq!(listing.allowed.hardlinks, Admit::Refuse);
assert_eq!(listing.allowed.world_writable, Admit::Refuse);
assert!(!listing.permissions.preserves());
assert_eq!(listing.allowed.absolute_paths, Admit::Allow);
assert_eq!(
listing.solid_archives,
SecurityConfig::permissive().solid_archives
);
assert_eq!(
listing.max_decoder_memory,
SecurityConfig::permissive().max_decoder_memory
);
}
#[test]
fn test_compressed_member_allowance_defaults() {
assert_eq!(
SecurityConfig::default().compressed_member_allowance.get(),
10_000
);
assert_eq!(
SecurityConfig::permissive()
.compressed_member_allowance
.get(),
100_000
);
}
#[test]
fn test_parallel_decode_defaults() {
let bytes = |config: SecurityConfig| match config.parallel_decode {
ParallelDecode::Bounded(n) => n.get(),
ParallelDecode::Sequential => 0,
};
assert_eq!(bytes(SecurityConfig::default()), 128 * 1024 * 1024);
assert_eq!(bytes(SecurityConfig::permissive()), 1024 * 1024 * 1024);
}
#[test]
fn test_max_kdf_work_defaults_to_two_to_the_27th() {
assert_eq!(SecurityConfig::default().max_kdf_work.get(), 1 << 27);
assert_eq!(SecurityConfig::permissive().max_kdf_work.get(), 1 << 27);
}
#[test]
fn test_tar_sparse_defaults_to_refuse_and_the_setter_applies() {
assert_eq!(
SecurityConfig::default().tar_sparse,
TarSparsePolicy::Refuse
);
assert_eq!(
SecurityConfig::permissive().tar_sparse,
TarSparsePolicy::Refuse
);
let config = SecurityConfig::default().with_tar_sparse(TarSparsePolicy::Expand);
assert_eq!(config.tar_sparse, TarSparsePolicy::Expand);
}
#[test]
fn test_tar_sparse_policy_parses_its_string_forms() {
use crate::ClosedEnum as _;
assert_eq!(TarSparsePolicy::NAMES, &["refuse", "expand"]);
assert_eq!(
TarSparsePolicy::parse_for(ConfigSetting::TarSparse, "expand").unwrap(),
TarSparsePolicy::Expand
);
assert!(TarSparsePolicy::parse_for(ConfigSetting::TarSparse, "x").is_err());
assert_eq!(ConfigSetting::TarSparse.as_str(), "tar_sparse");
}
#[test]
fn test_repeated_paths_defaults_to_keep_first() {
assert_eq!(
SecurityConfig::default().repeated_paths,
RepeatedPaths::KeepFirst
);
assert_eq!(
SecurityConfig::permissive().repeated_paths,
RepeatedPaths::KeepFirst
);
}
#[test]
fn test_max_decoder_memory_defaults() {
assert_eq!(
SecurityConfig::default().max_decoder_memory.get(),
256 * 1024 * 1024
);
assert_eq!(
SecurityConfig::permissive().max_decoder_memory.get(),
1024 * 1024 * 1024
);
}
#[test]
fn test_try_add_refuses_unusable_entries() {
let long = "x".repeat(256);
for raw in ["", "bad\0ext", " gz", "tar.gz", "a/b", long.as_str()] {
assert!(
SecurityConfig::default()
.try_add_allowed_extension(raw)
.is_err(),
"{raw:?}"
);
}
for raw in ["", "bad\0", "a/b", "..", long.as_str()] {
assert!(
SecurityConfig::default()
.try_add_banned_path_component(raw)
.is_err(),
"{raw:?}"
);
}
}
#[test]
fn test_dotted_extension_is_normalized_and_matches_any_case() {
let cfg = SecurityConfig::default()
.try_add_allowed_extension(".txt")
.unwrap();
assert!(cfg.is_extension_allowed(Some("txt")));
assert!(crate::formats::common::is_extension_allowed(
std::path::Path::new("A.TXT"),
&cfg
));
assert!(cfg.is_extension_allowed(Some("TXT")));
assert!(!cfg.is_extension_allowed(Some("md")));
}
#[test]
fn default_banned_components_are_all_usable() {
assert_eq!(
default_banned_path_components().len(),
DEFAULT_BANNED_PATH_COMPONENTS.len()
);
}
}