sekrit 1.0.0

Encrypt any file, decrypt anywhere. File encryption that doesn't suck.
Documentation
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct EncryptedFile {
    pub version: u8,
    pub salt: String,       // Base64 encoded
    pub nonce: String,      // Base64 encoded
    pub ciphertext: String, // Base64 encoded
    pub created_at: String, // ISO timestamp
}

impl EncryptedFile {
    pub fn new(salt: String, nonce: String, ciphertext: String) -> Self {
        Self {
            version: 1,
            salt,
            nonce,
            ciphertext,
            created_at: chrono::Utc::now().to_rfc3339(),
        }
    }

    pub fn from_json_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
        let encrypted_file: EncryptedFile = serde_json::from_slice(bytes)?;
        Ok(encrypted_file)
    }

    pub fn to_json_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
        let bytes = serde_json::to_vec(self)?;
        Ok(bytes)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_encrypted_file_new() {
        let salt = "dGVzdF9zYWx0".to_string();
        let nonce = "dGVzdF9ub25jZQ==".to_string();
        let ciphertext = "dGVzdF9jaXBoZXJ0ZXh0".to_string();

        let encrypted_file = EncryptedFile::new(salt.clone(), nonce.clone(), ciphertext.clone());

        assert_eq!(encrypted_file.version, 1);
        assert_eq!(encrypted_file.salt, salt);
        assert_eq!(encrypted_file.nonce, nonce);
        assert_eq!(encrypted_file.ciphertext, ciphertext);
        assert!(!encrypted_file.created_at.is_empty());

        // Verify created_at is a valid ISO timestamp
        chrono::DateTime::parse_from_rfc3339(&encrypted_file.created_at)
            .expect("created_at should be valid RFC3339 timestamp");
    }

    #[test]
    fn test_serialization_roundtrip() {
        let original = EncryptedFile::new(
            "c2FsdA==".to_string(),
            "bm9uY2U=".to_string(),
            "Y2lwaGVydGV4dA==".to_string(),
        );

        // Serialize to JSON bytes
        let json_bytes = original
            .to_json_bytes()
            .expect("Serialization should succeed");

        // Deserialize back from JSON bytes
        let deserialized =
            EncryptedFile::from_json_bytes(&json_bytes).expect("Deserialization should succeed");

        assert_eq!(original.version, deserialized.version);
        assert_eq!(original.salt, deserialized.salt);
        assert_eq!(original.nonce, deserialized.nonce);
        assert_eq!(original.ciphertext, deserialized.ciphertext);
        assert_eq!(original.created_at, deserialized.created_at);
    }

    #[test]
    fn test_json_structure() {
        let encrypted_file = EncryptedFile::new(
            "dGVzdF9zYWx0".to_string(),
            "dGVzdF9ub25jZQ==".to_string(),
            "dGVzdF9jaXBoZXJ0ZXh0".to_string(),
        );

        let json_bytes = encrypted_file
            .to_json_bytes()
            .expect("Serialization should succeed");

        let json_str = String::from_utf8(json_bytes).expect("JSON should be valid UTF-8");

        // Verify JSON contains expected fields
        assert!(json_str.contains("\"version\""));
        assert!(json_str.contains("\"salt\""));
        assert!(json_str.contains("\"nonce\""));
        assert!(json_str.contains("\"ciphertext\""));
        assert!(json_str.contains("\"created_at\""));

        // Verify specific values
        assert!(json_str.contains("\"version\":1"));
        assert!(json_str.contains("\"salt\":\"dGVzdF9zYWx0\""));
        assert!(json_str.contains("\"nonce\":\"dGVzdF9ub25jZQ==\""));
        assert!(json_str.contains("\"ciphertext\":\"dGVzdF9jaXBoZXJ0ZXh0\""));
    }

    #[test]
    fn test_empty_strings() {
        let encrypted_file = EncryptedFile::new(String::new(), String::new(), String::new());

        let json_bytes = encrypted_file
            .to_json_bytes()
            .expect("Should serialize empty strings");

        let deserialized =
            EncryptedFile::from_json_bytes(&json_bytes).expect("Should deserialize empty strings");

        assert_eq!(deserialized.salt, "");
        assert_eq!(deserialized.nonce, "");
        assert_eq!(deserialized.ciphertext, "");
        assert_eq!(deserialized.version, 1);
        assert!(!deserialized.created_at.is_empty());
    }

    #[test]
    fn test_large_base64_strings() {
        let large_salt = "a".repeat(1000);
        let large_nonce = "b".repeat(500);
        let large_ciphertext = "c".repeat(10000);

        let encrypted_file = EncryptedFile::new(
            large_salt.clone(),
            large_nonce.clone(),
            large_ciphertext.clone(),
        );

        let json_bytes = encrypted_file
            .to_json_bytes()
            .expect("Should serialize large strings");

        let deserialized =
            EncryptedFile::from_json_bytes(&json_bytes).expect("Should deserialize large strings");

        assert_eq!(deserialized.salt, large_salt);
        assert_eq!(deserialized.nonce, large_nonce);
        assert_eq!(deserialized.ciphertext, large_ciphertext);
    }

    #[test]
    fn test_unicode_in_base64() {
        // Base64 encoded unicode strings
        let salt = BASE64.encode("héllo wørld");
        let nonce = BASE64.encode("测试");
        let ciphertext = BASE64.encode("🔐🔑");

        let encrypted_file = EncryptedFile::new(salt.clone(), nonce.clone(), ciphertext.clone());

        let json_bytes = encrypted_file
            .to_json_bytes()
            .expect("Should serialize unicode Base64");

        let deserialized =
            EncryptedFile::from_json_bytes(&json_bytes).expect("Should deserialize unicode Base64");

        assert_eq!(deserialized.salt, salt);
        assert_eq!(deserialized.nonce, nonce);
        assert_eq!(deserialized.ciphertext, ciphertext);
    }

    #[test]
    fn test_invalid_json_fails() {
        let invalid_json = b"{\"version\":\"not_a_number\"}";

        let result = EncryptedFile::from_json_bytes(invalid_json);
        assert!(result.is_err(), "Invalid JSON should fail to deserialize");
    }

    #[test]
    fn test_incomplete_json_fails() {
        let incomplete_json = b"{\"version\":1}"; // Missing required fields

        let result = EncryptedFile::from_json_bytes(incomplete_json);
        assert!(
            result.is_err(),
            "Incomplete JSON should fail to deserialize"
        );
    }

    #[test]
    fn test_timestamp_format() {
        let encrypted_file = EncryptedFile::new(
            "salt".to_string(),
            "nonce".to_string(),
            "ciphertext".to_string(),
        );

        // Parse the timestamp to verify it's RFC3339 format
        let parsed_time = chrono::DateTime::parse_from_rfc3339(&encrypted_file.created_at)
            .expect("Timestamp should be valid RFC3339");

        // Verify it's recent (within last minute)
        let now = chrono::Utc::now();
        let diff = now.signed_duration_since(parsed_time);
        assert!(diff.num_seconds() < 60, "Timestamp should be recent");
    }

    #[test]
    fn test_multiple_instances_different_timestamps() {
        let file1 = EncryptedFile::new("a".to_string(), "b".to_string(), "c".to_string());

        // Small delay to ensure different timestamps
        std::thread::sleep(std::time::Duration::from_millis(1));

        let file2 = EncryptedFile::new("a".to_string(), "b".to_string(), "c".to_string());

        assert_ne!(
            file1.created_at, file2.created_at,
            "Different instances should have different timestamps"
        );
    }
}