use std::num::NonZeroU64;
use std::num::NonZeroUsize;
use crate::ConfigProblem;
use crate::ConfigSetting;
use crate::Limit;
use crate::RatioLimit;
use crate::closed_enum::closed_enum;
use crate::non_zero;
use crate::non_zero_u64;
use crate::types::Extension;
use crate::types::PathComponentName;
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 }
}
}
#[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",
}
}
#[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),
}
}
}
#[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 preserve_permissions: bool,
pub allowed_extensions: Vec<Extension>,
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,
}
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(), preserve_permissions: false,
allowed_extensions: Vec::new(),
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,
}
}
}
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,
},
preserve_permissions: true,
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.preserve_permissions = preserve;
self
}
#[must_use]
#[inline]
pub fn with_allowed_extensions(mut self, extensions: Vec<Extension>) -> Self {
self.allowed_extensions = extensions;
self
}
pub fn try_add_allowed_extension(mut self, extension: &str) -> crate::Result<Self> {
self.allowed_extensions
.push(Extension::try_from(extension)?);
Ok(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
}
}
impl SecurityConfig {
#[must_use]
pub fn is_path_component_allowed(&self, component: &str) -> bool {
!self
.banned_path_components
.iter()
.any(|banned| banned.matches(component))
}
#[must_use]
pub fn is_extension_allowed(&self, extension: Option<&str>) -> bool {
self.allowed_extensions.is_empty()
|| extension.is_some_and(|ext| self.allowed_extensions.iter().any(|a| a.matches(ext)))
}
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.preserve_permissions = false;
listing
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ExtractionOptions {
pub atomic: bool,
pub skip_duplicates: bool,
pub decode_reuse: DecodeReuse,
}
impl Default for ExtractionOptions {
fn default() -> Self {
Self {
atomic: false,
skip_duplicates: true,
decode_reuse: DecodeReuse::default(),
}
}
}
impl ExtractionOptions {
#[must_use]
#[inline]
pub fn with_atomic(mut self, atomic: bool) -> Self {
self.atomic = atomic;
self
}
#[must_use]
#[inline]
pub fn with_skip_duplicates(mut self, skip: bool) -> Self {
self.skip_duplicates = skip;
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,
}
}
}
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
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum StoredTargets {
#[default]
Skip,
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::unwrap_used,
clippy::expect_used,
clippy::field_reassign_with_default
)]
mod tests {
use std::assert_matches;
use super::*;
#[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 = vec![
Extension::try_from("txt").unwrap(),
Extension::try_from("pdf").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.preserve_permissions,
"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.preserve_permissions,
"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)]
{
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_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.preserve_permissions);
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_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()
);
}
}