use std::{fs, io::Read, path::Path};
use crate::{
error::ValidationError,
utils::{MAX_PDF_SIZE, MB, MIN_PDF_SIZE, PDF_MAGIC},
};
fn validate_exists(path: &Path) -> Result<(), ValidationError> {
if !path.exists() {
return Err(ValidationError::NotFound {
path: path.display().to_string(),
});
}
if !path.is_file() {
return Err(ValidationError::NotAFile {
path: path.display().to_string(),
});
}
Ok(())
}
fn validate_size(path: &Path) -> Result<(), ValidationError> {
let size = fs::metadata(path).map_err(ValidationError::Io)?.len();
match size {
s if s < MIN_PDF_SIZE => Err(ValidationError::TooSmall {
size: s,
min: MIN_PDF_SIZE,
}),
s if s > MAX_PDF_SIZE => Err(ValidationError::FileTooLarge {
size_mb: s,
max_mb: MAX_PDF_SIZE / MB,
}),
_ => Ok(()),
}
}
fn validate_magic_bytes(path: &Path) -> Result<(), ValidationError> {
let mut file = fs::File::open(path).map_err(ValidationError::Io)?;
let mut header = [0u8; PDF_MAGIC.len()];
file.read_exact(&mut header)
.map_err(|_| ValidationError::InvalidMagicBytes)?;
if header != *PDF_MAGIC {
return Err(ValidationError::InvalidMagicBytes);
}
Ok(())
}
pub fn validate_pdf(path: &Path) -> Result<(), ValidationError> {
validate_exists(path)?;
validate_size(path)?;
validate_magic_bytes(path)?;
Ok(())
}
#[cfg(test)]
mod tests {
use std::{fs, io::Write};
use rstest::{fixture, rstest};
use tempfile::{NamedTempFile, TempDir};
use super::*;
#[fixture]
fn valid_pdf() -> NamedTempFile {
let mut f = NamedTempFile::new().expect("tempfile");
f.write_all(PDF_MAGIC).expect("write magic");
let padding = vec![0u8; (MIN_PDF_SIZE as usize).saturating_sub(PDF_MAGIC.len())];
f.write_all(&padding).expect("write padding");
f
}
#[fixture]
fn non_pdf_file() -> NamedTempFile {
let mut f = NamedTempFile::new().expect("tempfile");
let size = MIN_PDF_SIZE as usize;
let mut content = vec![0u8; size];
let fake_magic = b"NOT_PDF!";
content[..fake_magic.len()].copy_from_slice(fake_magic);
f.write_all(&content).expect("write");
f
}
#[fixture]
fn too_small_pdf() -> NamedTempFile {
let mut f = NamedTempFile::new().expect("tempfile");
f.write_all(PDF_MAGIC).expect("write magic");
f
}
#[fixture]
fn too_large_pdf() -> NamedTempFile {
let mut f = NamedTempFile::new().expect("tempfile");
f.write_all(PDF_MAGIC).expect("write magic");
let overflow = vec![0u8; (MAX_PDF_SIZE as usize) + 1];
f.write_all(&overflow).expect("write overflow");
f
}
#[fixture]
fn temp_dir() -> TempDir {
tempfile::tempdir().expect("tempdir")
}
#[rstest]
fn test_exists_ok(valid_pdf: NamedTempFile) {
assert!(validate_exists(valid_pdf.path()).is_ok());
}
#[rstest]
fn test_exists_missing_path(temp_dir: TempDir) {
let ghost = temp_dir.path().join("does_not_exist.pdf");
let err = validate_exists(&ghost).unwrap_err();
assert!(
matches!(err, ValidationError::NotFound { .. }),
"expected NotFound, got {err:?}"
);
}
#[rstest]
fn test_exists_is_directory(temp_dir: TempDir) {
let err = validate_exists(temp_dir.path()).unwrap_err();
assert!(
matches!(err, ValidationError::NotAFile { .. }),
"expected NotAFile, got {err:?}"
);
}
#[rstest]
fn test_size_ok(valid_pdf: NamedTempFile) {
assert!(validate_size(valid_pdf.path()).is_ok());
}
#[rstest]
fn test_size_too_small(too_small_pdf: NamedTempFile) {
let err = validate_size(too_small_pdf.path()).unwrap_err();
assert!(
matches!(err, ValidationError::TooSmall { .. }),
"expected TooSmall, got {err:?}"
);
}
#[rstest]
fn test_size_too_large(too_large_pdf: NamedTempFile) {
let err = validate_size(too_large_pdf.path()).unwrap_err();
assert!(
matches!(
err,
ValidationError::FileTooLarge { size_mb, max_mb }
if size_mb > max_mb
),
"expected FileTooLarge, got {err:?}"
);
}
#[rstest]
fn test_magic_bytes_ok(valid_pdf: NamedTempFile) {
assert!(validate_magic_bytes(valid_pdf.path()).is_ok());
}
#[rstest]
fn test_magic_bytes_wrong(non_pdf_file: NamedTempFile) {
let err = validate_magic_bytes(non_pdf_file.path()).unwrap_err();
assert!(
matches!(err, ValidationError::InvalidMagicBytes),
"expected InvalidMagicBytes, got {err:?}"
);
}
#[rstest]
fn test_magic_bytes_empty_file(temp_dir: TempDir) {
let empty = temp_dir.path().join("empty.pdf");
fs::write(&empty, b"").expect("write empty");
let err = validate_magic_bytes(&empty).unwrap_err();
assert!(
matches!(err, ValidationError::InvalidMagicBytes),
"expected InvalidMagicBytes on empty file, got {err:?}"
);
}
#[rstest]
fn test_validate_pdf_happy_path(valid_pdf: NamedTempFile) {
assert!(validate_pdf(valid_pdf.path()).is_ok());
}
#[rstest]
fn test_validate_pdf_missing(temp_dir: TempDir) {
let ghost = temp_dir.path().join("ghost.pdf");
assert!(matches!(
validate_pdf(&ghost).unwrap_err(),
ValidationError::NotFound { .. }
));
}
#[rstest]
fn test_validate_pdf_too_small(too_small_pdf: NamedTempFile) {
assert!(matches!(
validate_pdf(too_small_pdf.path()).unwrap_err(),
ValidationError::TooSmall { .. }
));
}
#[rstest]
fn test_validate_pdf_too_large(too_large_pdf: NamedTempFile) {
assert!(matches!(
validate_pdf(too_large_pdf.path()).unwrap_err(),
ValidationError::FileTooLarge { .. }
));
}
#[rstest]
fn test_validate_pdf_wrong_magic(non_pdf_file: NamedTempFile) {
assert!(matches!(
validate_pdf(non_pdf_file.path()).unwrap_err(),
ValidationError::InvalidMagicBytes
));
}
#[rstest]
#[case(MIN_PDF_SIZE - 1, true)] #[case(MIN_PDF_SIZE, false)] #[case(MIN_PDF_SIZE + 1, false)] fn test_size_boundary(#[case] size: u64, #[case] expect_err: bool, temp_dir: TempDir) {
let path = temp_dir.path().join("boundary.pdf");
let mut content = PDF_MAGIC.to_vec();
let body_len = (size as usize).saturating_sub(PDF_MAGIC.len());
content.extend(vec![0u8; body_len]);
content.truncate(size as usize);
fs::write(&path, &content).expect("write boundary file");
let result = validate_size(&path);
assert_eq!(
result.is_err(),
expect_err,
"size={size}, expect_err={expect_err}"
);
}
}