dmvs 0.1.1

Async high-level client for selected Czech ČÚZK DMVS SOAP services
Documentation
use std::fmt;

use bytes::Bytes;
use sha2::{Digest, Sha256};

use crate::{Error, Result};

/// A checksum value exactly as declared by DMVS.
///
/// A bare hexadecimal string is algorithm-unspecified. In particular, a
/// 64-character value is not automatically interpreted as SHA-256.
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct Checksum(String);

impl Checksum {
    /// Retains a checksum without inferring an algorithm from its length.
    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))
    }

    /// Returns the untouched protocol value.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns the explicitly declared algorithm, if this crate recognizes it.
    pub fn declared_algorithm(&self) -> Option<ChecksumAlgorithm> {
        self.0
            .strip_prefix("SHA-256=")
            .filter(|hex| is_sha256_hex(hex))
            .map(|_| ChecksumAlgorithm::Sha256)
    }

    /// Verifies an explicitly declared supported algorithm.
    ///
    /// Unknown or algorithm-unspecified values return
    /// [`IntegrityStatus::Unverified`]. A declared SHA-256 mismatch is an error.
    pub fn verify(&self, content: &[u8]) -> Result<IntegrityStatus> {
        match self.declared_algorithm() {
            Some(ChecksumAlgorithm::Sha256) => self.verify_sha256(content),
            None => Ok(IntegrityStatus::Unverified),
        }
    }

    /// Explicitly verifies SHA-256, including for an algorithm-unspecified value.
    ///
    /// This never changes the checksum's declared-algorithm metadata.
    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())
}

/// A checksum algorithm explicitly declared by a protocol value.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ChecksumAlgorithm {
    /// SHA-256 declared with the `SHA-256=` prefix.
    Sha256,
}

/// Result of a requested integrity check.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum IntegrityStatus {
    /// Content matched a declared or caller-selected algorithm.
    Verified,
    /// No supported algorithm was declared, so no verification was claimed.
    Unverified,
}

/// File metadata returned by DMVS, independent of its payload bytes.
#[derive(Clone, Eq, PartialEq)]
#[non_exhaustive]
pub struct FileMetadata {
    /// Server-provided file name. It is metadata, not a safe local path.
    pub name: String,
    /// Declared byte size.
    pub size: u64,
    /// Raw-preserving checksum declaration.
    pub checksum: Checksum,
    /// Optional character-set declaration for text files.
    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()
    }
}

/// A bounded output file with original bytes and all protocol metadata.
#[derive(Clone, Eq, PartialEq)]
pub struct FilePayload {
    /// File metadata.
    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 })
    }

    /// Returns the original decoded bytes.
    pub fn bytes(&self) -> &Bytes {
        &self.bytes
    }

    /// Consumes the payload and returns its bytes.
    pub fn into_bytes(self) -> Bytes {
        self.bytes
    }

    /// Verifies an algorithm-unspecified checksum as caller-selected SHA-256.
    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(())
}

/// Metadata for a caller-supplied supporting document.
#[derive(Clone, Eq, PartialEq)]
pub struct InputFile {
    name: String,
    /// Original content bytes.
    pub content: Bytes,
    /// Optional declared character set.
    pub character_set: Option<String>,
    /// Optional caller-supplied checksum. SHA-256 is computed when omitted.
    pub checksum: Option<Checksum>,
}

impl InputFile {
    /// Creates a bounded supporting-file input with a checked single file name.
    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,
        })
    }

    /// Returns the validated single file name, never a path.
    pub fn as_str(&self) -> &str {
        &self.name
    }

    pub(crate) fn validate(&self) -> Result<()> {
        validate_file_name(&self.name)
    }

    /// Sets an optional text character-set declaration.
    pub fn with_character_set(mut self, character_set: impl Into<String>) -> Self {
        self.character_set = Some(character_set.into());
        self
    }

    /// Sets an explicit raw checksum declaration instead of computed SHA-256.
    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"));
    }
}