Skip to main content

esh_crypto/
lib.rs

1//! Encryption / decryption adapters (FR-011).
2
3use async_trait::async_trait;
4use esh_core::{Error, Result, SecretBytes, SecretString};
5
6/// Decrypts ciphertext into plaintext secrets.
7#[async_trait]
8pub trait Decryptor: Send + Sync {
9    /// Decrypt opaque ciphertext.
10    async fn decrypt(&self, ciphertext: &[u8]) -> Result<SecretBytes>;
11}
12
13/// Encrypts plaintext (optional for libraries that only need decrypt-at-load).
14#[async_trait]
15pub trait Encryptor: Send + Sync {
16    /// Encrypt plaintext bytes.
17    async fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>>;
18}
19
20/// Cloud KMS decrypt interface (AWS KMS / Azure / GCP).
21#[async_trait]
22pub trait KmsClient: Send + Sync {
23    /// Decrypt a ciphertext blob produced by the KMS key.
24    async fn decrypt(&self, ciphertext: &[u8]) -> Result<SecretBytes>;
25}
26
27/// Adapter wrapping any [`KmsClient`] as a [`Decryptor`].
28pub struct KmsDecryptor {
29    client: std::sync::Arc<dyn KmsClient>,
30}
31
32impl KmsDecryptor {
33    /// Create from a KMS client.
34    #[must_use]
35    pub fn new(client: std::sync::Arc<dyn KmsClient>) -> Self {
36        Self { client }
37    }
38}
39
40#[async_trait]
41impl Decryptor for KmsDecryptor {
42    async fn decrypt(&self, ciphertext: &[u8]) -> Result<SecretBytes> {
43        self.client.decrypt(ciphertext).await
44    }
45}
46
47/// In-memory passthrough KMS fake for tests.
48#[derive(Debug, Default, Clone, Copy)]
49pub struct PassthroughKms;
50
51#[async_trait]
52impl KmsClient for PassthroughKms {
53    async fn decrypt(&self, ciphertext: &[u8]) -> Result<SecretBytes> {
54        Ok(SecretBytes::new(ciphertext.to_vec()))
55    }
56}
57
58#[cfg(feature = "age")]
59mod age_backend {
60    use super::*;
61    use age::x25519;
62    use age::{Decryptor as AgeDecryptorApi, Encryptor as AgeEncryptorApi};
63    use std::io::{Read, Write};
64
65    /// Age identity-based decryptor.
66    pub struct AgeIdentityDecryptor {
67        identity: x25519::Identity,
68    }
69
70    impl AgeIdentityDecryptor {
71        /// Parse an age secret identity string (`AGE-SECRET-KEY-...`).
72        pub fn from_secret_string(secret: &str) -> Result<Self> {
73            let identity: x25519::Identity = secret
74                .trim()
75                .parse()
76                .map_err(|e| Error::Crypto(format!("invalid age identity: {e}")))?;
77            Ok(Self { identity })
78        }
79
80        /// Generate a new identity (returns decryptor + public recipient string).
81        #[must_use]
82        pub fn generate() -> (Self, String) {
83            let identity = x25519::Identity::generate();
84            let recipient = identity.to_public().to_string();
85            (Self { identity }, recipient)
86        }
87    }
88
89    #[async_trait]
90    impl Decryptor for AgeIdentityDecryptor {
91        async fn decrypt(&self, ciphertext: &[u8]) -> Result<SecretBytes> {
92            let decryptor = AgeDecryptorApi::new(ciphertext)
93                .map_err(|e| Error::Crypto(format!("age decryptor: {e}")))?;
94            let mut reader = match decryptor {
95                AgeDecryptorApi::Recipients(d) => d
96                    .decrypt(std::iter::once(&self.identity as &dyn age::Identity))
97                    .map_err(|e| Error::Crypto(format!("age decrypt: {e}")))?,
98                AgeDecryptorApi::Passphrase(_) => {
99                    return Err(Error::Crypto(
100                        "passphrase-encrypted age files are not supported by AgeIdentityDecryptor"
101                            .into(),
102                    ));
103                }
104            };
105            let mut out = Vec::new();
106            reader
107                .read_to_end(&mut out)
108                .map_err(|e| Error::Crypto(e.to_string()))?;
109            Ok(SecretBytes::new(out))
110        }
111    }
112
113    /// Encrypt to an age recipient (public key).
114    pub fn age_encrypt(recipient: &str, plaintext: &[u8]) -> Result<Vec<u8>> {
115        let recipient: x25519::Recipient = recipient
116            .parse()
117            .map_err(|e| Error::Crypto(format!("invalid age recipient: {e}")))?;
118        let encryptor = AgeEncryptorApi::with_recipients(vec![Box::new(recipient) as Box<dyn age::Recipient + Send>])
119            .ok_or_else(|| Error::Crypto("age encryptor requires a recipient".into()))?;
120        let mut encrypted = vec![];
121        {
122            let mut writer = encryptor
123                .wrap_output(&mut encrypted)
124                .map_err(|e| Error::Crypto(e.to_string()))?;
125            writer
126                .write_all(plaintext)
127                .map_err(|e| Error::Crypto(e.to_string()))?;
128            writer
129                .finish()
130                .map_err(|e| Error::Crypto(e.to_string()))?;
131        }
132        Ok(encrypted)
133    }
134
135    /// Helper: decrypt age ciphertext to UTF-8 [`SecretString`].
136    pub async fn decrypt_age_string(
137        decryptor: &AgeIdentityDecryptor,
138        ciphertext: &[u8],
139    ) -> Result<SecretString> {
140        let bytes = decryptor.decrypt(ciphertext).await?;
141        let s = std::str::from_utf8(bytes.expose())
142            .map_err(|e| Error::Crypto(format!("utf-8: {e}")))?
143            .to_string();
144        Ok(SecretString::new(s))
145    }
146}
147
148#[cfg(feature = "age")]
149pub use age_backend::{age_encrypt, decrypt_age_string, AgeIdentityDecryptor};
150
151/// Marker / documentation helper for SOPS workflows.
152///
153/// SOPS files are typically decrypted out-of-band or via the `sops` CLI. This
154/// type documents the integration point: feed decrypted YAML/JSON into the
155/// hydrator defaults / dotenv path rather than embedding the SOPS binary.
156#[derive(Debug, Default, Clone, Copy)]
157pub struct SopsIntegration;
158
159impl SopsIntegration {
160    /// Reminder message for operators.
161    #[must_use]
162    pub fn guidance() -> &'static str {
163        "Decrypt SOPS files with the sops CLI or native library bindings, then load plaintext via dotenv/defaults. Use AgeIdentityDecryptor or KmsDecryptor for envelope payloads embedded in config."
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170    use std::sync::Arc;
171
172    #[tokio::test]
173    async fn kms_passthrough_roundtrip() {
174        let dec = KmsDecryptor::new(Arc::new(PassthroughKms));
175        let pt = dec.decrypt(b"kms-secret-needle").await.unwrap();
176        assert_eq!(pt.expose(), b"kms-secret-needle");
177        assert!(!format!("{pt:?}").contains("kms-secret"));
178    }
179
180    #[test]
181    fn sops_guidance_non_empty() {
182        assert!(!SopsIntegration::guidance().is_empty());
183    }
184
185    #[cfg(feature = "age")]
186    #[tokio::test]
187    async fn age_roundtrip() {
188        let (dec, recipient) = AgeIdentityDecryptor::generate();
189        let ct = age_encrypt(&recipient, b"hello-secret").unwrap();
190        let pt = dec.decrypt(&ct).await.unwrap();
191        assert_eq!(pt.expose(), b"hello-secret");
192        assert!(!format!("{pt:?}").contains("hello"));
193    }
194
195    #[cfg(feature = "age")]
196    #[tokio::test]
197    async fn age_decrypt_failure_on_garbage() {
198        let (dec, _) = AgeIdentityDecryptor::generate();
199        let err = dec.decrypt(b"not-age-ciphertext").await.unwrap_err();
200        assert!(matches!(err, Error::Crypto(_)));
201    }
202
203    #[cfg(feature = "age")]
204    #[test]
205    fn age_invalid_identity() {
206        match AgeIdentityDecryptor::from_secret_string("not-a-key") {
207            Err(Error::Crypto(_)) => {}
208            Ok(_) => panic!("expected crypto error"),
209            Err(e) => panic!("unexpected error: {e}"),
210        }
211    }
212}