#[cfg(test)]
mod tests {
use aex::crypto::zero_trust_session_key::SessionKey;
use chrono::Utc;
use x25519_dalek::PublicKey;
#[test]
fn test_full_handshake_and_communication() -> anyhow::Result<()> {
let mut alice = SessionKey::new();
let mut bob = SessionKey::new();
let _ = alice.created_at;
alice.establish(&bob.ephemeral_public)?;
bob.establish(&alice.ephemeral_public)?;
assert!(alice.key.is_some());
assert!(bob.key.is_some());
assert_eq!(alice.key, bob.key, "Shared secrets must match");
assert!(alice.ephemeral_secret.is_none());
assert!(bob.ephemeral_secret.is_none());
let message = b"Hello, Zero Trust P2P!";
let ciphertext = alice.encrypt(message)?;
assert_eq!(ciphertext.len(), 24 + 16 + message.len());
let decrypted = bob.decrypt(&ciphertext)?;
assert_eq!(decrypted, message);
let old_updated_at = alice.updated_at;
alice.touch();
assert!(alice.updated_at >= old_updated_at);
Ok(())
}
#[test]
fn test_decrypt_with_wrong_key() -> anyhow::Result<()> {
let mut alice = SessionKey::new();
let mut bob = SessionKey::new();
let eve = SessionKey::new();
alice.establish(&bob.ephemeral_public)?;
bob.establish(&alice.ephemeral_public)?;
let message = b"Secret Message";
let ciphertext = alice.encrypt(message)?;
let result = eve.decrypt(&ciphertext);
assert!(result.is_err());
assert_eq!(result.unwrap_err().to_string(), "session not established");
Ok(())
}
#[test]
fn test_tampered_data() -> anyhow::Result<()> {
let mut alice = SessionKey::new();
let mut bob = SessionKey::new();
alice.establish(&bob.ephemeral_public)?;
bob.establish(&alice.ephemeral_public)?;
let mut ciphertext = alice.encrypt(b"Original Data")?;
if let Some(last) = ciphertext.last_mut() {
*last ^= 0xFF;
}
let result = bob.decrypt(&ciphertext);
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("decrypt failed"));
Ok(())
}
#[test]
fn test_ciphertext_too_short() -> anyhow::Result<()> {
let alice = SessionKey {
key: Some([0u8; 32]),
ephemeral_secret: None,
ephemeral_public: PublicKey::from([0u8; 32]),
created_at: Utc::now(),
updated_at: Utc::now(),
};
let invalid_data = vec![0u8; 23]; let result = alice.decrypt(&invalid_data);
assert!(result.is_err());
assert_eq!(result.unwrap_err().to_string(), "ciphertext too short");
Ok(())
}
}