use crate::error::{SecretScanError, SecretScanErrorCode};
pub const DEFAULT_MAX_INPUT_BYTES: usize = 64 * 1024 * 1024;
pub const DEFAULT_MAX_FINDINGS: usize = 50_000;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct WholeInputLimits {
max_input_bytes: usize,
max_findings: usize,
}
impl WholeInputLimits {
pub fn new(max_input_bytes: usize, max_findings: usize) -> Result<Self, SecretScanError> {
if max_input_bytes == 0 || max_findings == 0 {
return Err(SecretScanErrorCode::InvalidLimits.into());
}
Ok(Self {
max_input_bytes,
max_findings,
})
}
#[must_use]
pub const fn max_input_bytes(self) -> usize {
self.max_input_bytes
}
#[must_use]
pub const fn max_findings(self) -> usize {
self.max_findings
}
pub fn check_input(&self, input: &str) -> Result<(), SecretScanError> {
if input.len() > self.max_input_bytes {
return Err(SecretScanErrorCode::InputLimitExceeded.into());
}
Ok(())
}
pub fn check_findings(&self, count: usize) -> Result<(), SecretScanError> {
if count > self.max_findings {
return Err(SecretScanErrorCode::FindingLimitExceeded.into());
}
Ok(())
}
}
impl Default for WholeInputLimits {
fn default() -> Self {
Self {
max_input_bytes: DEFAULT_MAX_INPUT_BYTES,
max_findings: DEFAULT_MAX_FINDINGS,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_matches_declared_constants() {
let limits = WholeInputLimits::default();
assert_eq!(limits.max_input_bytes(), DEFAULT_MAX_INPUT_BYTES);
assert_eq!(limits.max_findings(), DEFAULT_MAX_FINDINGS);
}
#[test]
fn new_rejects_a_zero_input_bound() {
assert_eq!(
WholeInputLimits::new(0, 10).unwrap_err().code(),
SecretScanErrorCode::InvalidLimits
);
}
#[test]
fn new_rejects_a_zero_finding_bound() {
assert_eq!(
WholeInputLimits::new(10, 0).unwrap_err().code(),
SecretScanErrorCode::InvalidLimits
);
}
#[test]
fn check_input_accepts_exactly_at_bound() {
let limits = WholeInputLimits::new(5, 10).unwrap();
assert!(limits.check_input("abcde").is_ok());
}
#[test]
fn check_input_rejects_one_over_bound() {
let limits = WholeInputLimits::new(5, 10).unwrap();
assert_eq!(
limits.check_input("abcdef").unwrap_err().code(),
SecretScanErrorCode::InputLimitExceeded
);
}
#[test]
fn check_findings_accepts_exactly_at_bound() {
let limits = WholeInputLimits::new(5, 10).unwrap();
assert!(limits.check_findings(10).is_ok());
}
#[test]
fn check_findings_rejects_one_over_bound() {
let limits = WholeInputLimits::new(5, 10).unwrap();
assert_eq!(
limits.check_findings(11).unwrap_err().code(),
SecretScanErrorCode::FindingLimitExceeded
);
}
}