use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
use aes_gcm::aead::{Aead, Payload};
use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use rand::RngCore;
use crate::encryption_key::EncryptionKey;
pub const ENVELOPE_PREFIX: &str = "adk-enc:v1:";
pub const NONCE_LEN: usize = 12;
pub fn is_envelope(text: &str) -> bool {
text.starts_with(ENVELOPE_PREFIX)
}
pub fn associated_data(domain: &[u8], parts: &[&str]) -> Vec<u8> {
let mut aad = domain.to_vec();
for part in parts {
aad.extend_from_slice(&(part.len() as u64).to_be_bytes());
aad.extend_from_slice(part.as_bytes());
}
aad
}
pub fn seal(key: &EncryptionKey, plaintext: &[u8], aad: &[u8]) -> Result<String> {
let cipher = Aes256Gcm::new_from_slice(key.as_bytes())
.map_err(|e| encrypt_error(format!("invalid key: {e}")))?;
let mut nonce = [0u8; NONCE_LEN];
rand::rng().fill_bytes(&mut nonce);
let ciphertext = cipher
.encrypt(Nonce::from_slice(&nonce), Payload { msg: plaintext, aad })
.map_err(|_| encrypt_error("AES-256-GCM encryption failed"))?;
let mut bytes = Vec::with_capacity(NONCE_LEN + ciphertext.len());
bytes.extend_from_slice(&nonce);
bytes.extend_from_slice(&ciphertext);
Ok(format!("{ENVELOPE_PREFIX}{}", BASE64.encode(bytes)))
}
pub fn open<'a>(
keys: impl IntoIterator<Item = &'a EncryptionKey>,
envelope: &str,
aad: &[u8],
) -> Option<(Vec<u8>, usize)> {
let encoded = envelope.strip_prefix(ENVELOPE_PREFIX)?;
let bytes = BASE64.decode(encoded).ok()?;
if bytes.len() < NONCE_LEN {
return None;
}
let (nonce, ciphertext) = bytes.split_at(NONCE_LEN);
keys.into_iter().enumerate().find_map(|(index, key)| {
Aes256Gcm::new_from_slice(key.as_bytes())
.ok()?
.decrypt(Nonce::from_slice(nonce), Payload { msg: ciphertext, aad })
.ok()
.map(|plaintext| (plaintext, index))
})
}
fn encrypt_error(message: impl Into<String>) -> AdkError {
AdkError::new(
ErrorComponent::Session,
ErrorCategory::Internal,
"session.encryption.encrypt_failed",
message,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_second_key_opens_what_the_first_sealed_and_reports_its_index() {
let old = EncryptionKey::generate();
let new = EncryptionKey::generate();
let aad = associated_data(b"t/v1", &["a"]);
let sealed = seal(&old, b"x", &aad).unwrap();
assert_eq!(open([&new, &old], &sealed, &aad), Some((b"x".to_vec(), 1)));
assert_eq!(open([&new], &sealed, &aad), None);
assert_eq!(open([&old], "not an envelope", &aad), None);
assert_eq!(open([&old], &format!("{ENVELOPE_PREFIX}!!"), &aad), None);
}
#[test]
fn associated_data_is_length_prefixed_so_parts_never_slide() {
assert_ne!(associated_data(b"d", &["ab", "c"]), associated_data(b"d", &["a", "bc"]));
assert_ne!(associated_data(b"d", &["a"]), associated_data(b"e", &["a"]));
}
}