Skip to main content

agent_hub_runtime/core/
crypto.rs

1use aes_gcm::{
2    aead::{Aead, KeyInit},
3    Aes256Gcm, Key, Nonce,
4};
5use anyhow::{Context, Result};
6use std::path::Path;
7
8pub const ENC_PREFIX: &str = "enc:v1:";
9
10/// Load an existing 32-byte key from `path`, or generate and persist a new one.
11///
12/// If the file exists but has an unexpected size, returns an error instead of
13/// silently regenerating — regenerating would make all previously encrypted
14/// values permanently undecryptable.
15pub fn load_or_create_key(path: &Path) -> Result<[u8; 32]> {
16    if path.exists() {
17        let bytes = std::fs::read(path).context("Failed to read secret key file")?;
18        anyhow::ensure!(
19            bytes.len() == 32,
20            "Secret key file '{}' is corrupted ({} bytes, expected 32). \
21             Delete it manually to regenerate, but note that existing encrypted values will be lost.",
22            path.display(),
23            bytes.len()
24        );
25        let mut key = [0u8; 32];
26        key.copy_from_slice(&bytes);
27        return Ok(key);
28    }
29
30    let mut key = [0u8; 32];
31    use rand::RngCore;
32    rand::thread_rng().fill_bytes(&mut key);
33    std::fs::write(path, key).context("Failed to write secret key file")?;
34    set_owner_readonly(path);
35    Ok(key)
36}
37
38/// On Unix, restrict the key file to owner-only access (0600).
39#[cfg(unix)]
40fn set_owner_readonly(path: &Path) {
41    use std::os::unix::fs::PermissionsExt;
42    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
43}
44
45#[cfg(not(unix))]
46fn set_owner_readonly(_path: &Path) {}
47
48/// Encrypt `plaintext` with AES-256-GCM and return an `enc:v1:<hex>` string.
49pub fn encrypt(key: &[u8; 32], plaintext: &str) -> Result<String> {
50    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key));
51
52    let mut nonce_bytes = [0u8; 12];
53    use rand::RngCore;
54    rand::thread_rng().fill_bytes(&mut nonce_bytes);
55    let nonce = Nonce::from_slice(&nonce_bytes);
56
57    let ciphertext = cipher
58        .encrypt(nonce, plaintext.as_bytes())
59        .map_err(|_| anyhow::anyhow!("Encryption failed"))?;
60
61    // Store as hex(nonce || ciphertext) so the result is printable ASCII.
62    let mut combined = nonce_bytes.to_vec();
63    combined.extend_from_slice(&ciphertext);
64    Ok(format!("{}{}", ENC_PREFIX, hex::encode(&combined)))
65}
66
67/// Decrypt an `enc:v1:<hex>` string.  Returns an error if the value is not
68/// a recognised encrypted blob (callers can detect plaintext via `is_encrypted`).
69pub fn decrypt(key: &[u8; 32], value: &str) -> Result<String> {
70    let hex_str = value
71        .strip_prefix(ENC_PREFIX)
72        .ok_or_else(|| anyhow::anyhow!("Value is not an encrypted blob"))?;
73
74    let combined = hex::decode(hex_str).context("Invalid hex in encrypted value")?;
75    if combined.len() < 12 {
76        anyhow::bail!("Encrypted value is too short to contain a nonce");
77    }
78
79    let (nonce_bytes, ciphertext) = combined.split_at(12);
80    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key));
81    let nonce = Nonce::from_slice(nonce_bytes);
82
83    let plaintext = cipher
84        .decrypt(nonce, ciphertext)
85        .map_err(|_| anyhow::anyhow!("Decryption failed — key mismatch or data corrupted"))?;
86
87    String::from_utf8(plaintext).context("Decrypted bytes are not valid UTF-8")
88}
89
90/// Returns true if `value` looks like it was produced by `encrypt()`.
91pub fn is_encrypted(value: &str) -> bool {
92    value.starts_with(ENC_PREFIX)
93}
94
95#[cfg(test)]
96mod tests;