use std::fmt;
use bytes::Bytes;
use sha2::{Digest, Sha256};
use crate::{Error, Result};
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct Checksum(String);
impl Checksum {
pub fn new(value: impl Into<String>) -> Result<Self> {
let value = value.into();
if value.is_empty() || value.chars().any(char::is_control) {
return Err(Error::invalid_input(
"checksum",
"expected a non-empty value without control characters",
));
}
if let Some(hex) = value.strip_prefix("SHA-256=")
&& !is_sha256_hex(hex)
{
return Err(Error::invalid_input(
"checksum",
"a declared SHA-256 checksum requires exactly 64 hexadecimal digits",
));
}
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn declared_algorithm(&self) -> Option<ChecksumAlgorithm> {
self.0
.strip_prefix("SHA-256=")
.filter(|hex| is_sha256_hex(hex))
.map(|_| ChecksumAlgorithm::Sha256)
}
pub fn verify(&self, content: &[u8]) -> Result<IntegrityStatus> {
match self.declared_algorithm() {
Some(ChecksumAlgorithm::Sha256) => self.verify_sha256(content),
None => Ok(IntegrityStatus::Unverified),
}
}
pub fn verify_sha256(&self, content: &[u8]) -> Result<IntegrityStatus> {
let expected = self.0.strip_prefix("SHA-256=").unwrap_or(self.0.as_str());
if !is_sha256_hex(expected) {
return Err(Error::invalid_input(
"checksum",
"explicit SHA-256 verification requires SHA-256= followed by 64 hexadecimal digits, or a bare 64-digit value",
));
}
let actual_hex = Sha256::digest(content)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
if actual_hex.eq_ignore_ascii_case(expected) {
Ok(IntegrityStatus::Verified)
} else {
Err(Error::IntegrityMismatch)
}
}
}
impl fmt::Debug for Checksum {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Checksum")
.field("algorithm", &self.declared_algorithm())
.finish_non_exhaustive()
}
}
impl fmt::Display for Checksum {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
fn is_sha256_hex(value: &str) -> bool {
value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit())
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ChecksumAlgorithm {
Sha256,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum IntegrityStatus {
Verified,
Unverified,
}
#[derive(Clone, Eq, PartialEq)]
#[non_exhaustive]
pub struct FileMetadata {
pub name: String,
pub size: u64,
pub checksum: Checksum,
pub character_set: Option<String>,
}
impl fmt::Debug for FileMetadata {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("FileMetadata")
.field("name", &"[REDACTED]")
.field("size", &self.size)
.field("checksum", &self.checksum)
.field("character_set", &self.character_set)
.finish()
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct FilePayload {
pub metadata: FileMetadata,
bytes: Bytes,
}
impl FilePayload {
pub(crate) fn new(metadata: FileMetadata, bytes: Bytes) -> Result<Self> {
if bytes.len() as u64 != metadata.size {
return Err(Error::IntegrityMismatch);
}
metadata.checksum.verify(&bytes)?;
Ok(Self { metadata, bytes })
}
pub fn bytes(&self) -> &Bytes {
&self.bytes
}
pub fn into_bytes(self) -> Bytes {
self.bytes
}
pub fn verify_sha256(&self) -> Result<IntegrityStatus> {
self.metadata.checksum.verify_sha256(&self.bytes)
}
}
impl fmt::Debug for FilePayload {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("FilePayload")
.field("metadata", &self.metadata)
.field("byte_len", &self.bytes.len())
.finish()
}
}
fn validate_file_name(name: &str) -> Result<()> {
if name.is_empty()
|| name.len() >= 128
|| name.starts_with('.')
|| !name.is_ascii()
|| name.contains(['/', '\\', '<', '>', ':', '"', '|', '?', '*', '~'])
|| name.chars().any(char::is_control)
{
return Err(Error::invalid_input(
"file.name",
"expected an ASCII file name shorter than 128 bytes without a leading dot or DMVS-forbidden characters",
));
}
Ok(())
}
#[derive(Clone, Eq, PartialEq)]
pub struct InputFile {
name: String,
pub content: Bytes,
pub character_set: Option<String>,
pub checksum: Option<Checksum>,
}
impl InputFile {
pub fn new(name: impl Into<String>, content: impl Into<Bytes>) -> Result<Self> {
let name = name.into();
validate_file_name(&name)?;
Ok(Self {
name,
content: content.into(),
character_set: None,
checksum: None,
})
}
pub fn as_str(&self) -> &str {
&self.name
}
pub(crate) fn validate(&self) -> Result<()> {
validate_file_name(&self.name)
}
pub fn with_character_set(mut self, character_set: impl Into<String>) -> Self {
self.character_set = Some(character_set.into());
self
}
pub fn with_checksum(mut self, checksum: Checksum) -> Self {
self.checksum = Some(checksum);
self
}
pub(crate) fn checksum(&self) -> Checksum {
self.checksum.clone().unwrap_or_else(|| {
let digest = Sha256::digest(&self.content);
let hex = digest
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
Checksum(format!("SHA-256={hex}"))
})
}
}
impl fmt::Debug for InputFile {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("InputFile")
.field("name", &"[REDACTED]")
.field("content_bytes", &self.content.len())
.field("character_set", &self.character_set)
.field("checksum", &self.checksum)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prefixed_checksum_is_verified_and_bare_hex_is_not_inferred() {
let bytes = b"synthetic file";
let digest = Sha256::digest(bytes);
let hex = digest
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
let prefixed = Checksum::new(format!("SHA-256={hex}")).unwrap();
assert_eq!(prefixed.verify(bytes).unwrap(), IntegrityStatus::Verified);
let bare = Checksum::new(hex).unwrap();
assert_eq!(bare.declared_algorithm(), None);
assert_eq!(bare.verify(bytes).unwrap(), IntegrityStatus::Unverified);
assert_eq!(
bare.verify_sha256(bytes).unwrap(),
IntegrityStatus::Verified
);
assert!(bare.verify(b"other").is_ok());
assert!(bare.verify_sha256(b"other").is_err());
assert!(Checksum::new("SHA-256=not-hex").is_err());
assert_eq!(
Checksum::new("SHA-512=unknown-but-preserved")
.unwrap()
.verify(bytes)
.unwrap(),
IntegrityStatus::Unverified
);
}
#[test]
fn input_file_name_is_revalidated_after_internal_mutation() {
let mut input = InputFile::new("synthetic.txt", b"first".as_slice()).unwrap();
input.content = Bytes::from_static(b"second");
input.checksum = Some(Checksum::new("unknown=synthetic").unwrap());
assert_eq!(input.as_str(), "synthetic.txt");
input.validate().unwrap();
input.name = "../synthetic.txt".into();
assert!(input.validate().is_err());
}
#[test]
fn file_names_and_integrity_are_checked() {
assert!(InputFile::new("../secret", b"x".as_slice()).is_err());
assert!(InputFile::new("folder/secret", b"x".as_slice()).is_err());
let input = InputFile::new("evidence.txt", b"abc".as_slice()).unwrap();
assert_eq!(input.as_str(), "evidence.txt");
assert!(input.checksum().as_str().starts_with("SHA-256="));
let payload = FilePayload::new(
FileMetadata {
name: "a.txt".into(),
size: 3,
checksum: Checksum::new("unknown=value").unwrap(),
character_set: Some("UTF-8".into()),
},
Bytes::from_static(b"abc"),
)
.unwrap();
assert!(!format!("{payload:?}").contains("abc"));
let input = InputFile::new("sensitive-name.txt", b"sensitive-content".as_slice()).unwrap();
let debug = format!("{input:?}");
assert!(!debug.contains("sensitive-name"));
assert!(!debug.contains("sensitive-content"));
let payload = FilePayload::new(
FileMetadata {
name: "sensitive-output.pdf".into(),
size: 3,
checksum: Checksum::new("unknown=value").unwrap(),
character_set: None,
},
Bytes::from_static(b"abc"),
)
.unwrap();
assert!(!format!("{payload:?}").contains("sensitive-output"));
}
}