Skip to main content

moonproof_contracts/providers/
storage_encryption.rs

1//! Wire-compatible port of
2//! `@midnight-ntwrk/midnight-js-level-private-state-provider/src/storage-encryption.ts`.
3//!
4//! The TS package wraps every export/import payload in a base64-encoded
5//! AES-256-GCM ciphertext with a header that pins the version, the
6//! KDF salt, and the GCM IV/tag, so a payload encrypted on one runtime
7//! decrypts on the other. This module re-implements the TS encoder
8//! exactly:
9//!
10//! ```text
11//! base64( [ version u8 = 2 || salt[32] || iv[12] || tag[16] || ct ] )
12//! ```
13//!
14//! * `salt` is per-export random bytes (TS uses CSPRNG, we use the
15//!   caller-supplied [`rand::CryptoRng`]).
16//! * `iv` is per-encryption random bytes (12 bytes, GCM standard).
17//! * `tag` is the 16-byte GCM authentication tag.
18//! * `ct` is the AES-256-GCM ciphertext over the UTF-8 plaintext.
19//!
20//! ## Versioning
21//!
22//! `V1` (PBKDF2 100k iterations) is recognised on import for
23//! interop with old TS exports but never emitted. `V2` (PBKDF2 600k
24//! iterations) is the only encoder. Both numbers come from
25//! `storage-encryption.ts:31-32` (`PBKDF2_ITERATIONS_V1` /
26//! `_V2`) and must not drift — the tag is over the salt+iv+version
27//! prefix implicitly, but the iteration count is *not* in the header
28//! so a wrong count silently produces a tag-mismatch decryption error,
29//! which is the desired oracle-resistant behaviour (see TS `import`
30//! comment in `level-private-state-provider.ts:919`).
31//!
32//! ## Failure modes (matched to TS)
33//!
34//! | TS error                         | Rust variant                                           |
35//! |----------------------------------|--------------------------------------------------------|
36//! | `'Invalid encrypted data: too short'` | [`StorageEncryptionError::TooShort`]               |
37//! | `'Unsupported encryption version'`    | [`StorageEncryptionError::UnsupportedVersion`]     |
38//! | AES-GCM tag mismatch / corruption     | [`StorageEncryptionError::Decrypt`]                |
39//! | base64 decode failure                  | [`StorageEncryptionError::InvalidBase64`]          |
40//!
41//! The TS importer collapses every decryption failure into a single
42//! [`level-private-state-provider.ts:920`] `ExportDecryptionError` to
43//! avoid an oracle attack — callers of this module should do the same
44//! at their boundary (the Rust importer does; see
45//! [`crate::providers::in_memory_private_state`]).
46
47use aes_gcm::aead::{Aead, KeyInit, Payload};
48use aes_gcm::{Aes256Gcm, Key, Nonce};
49use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
50use base64::Engine as _;
51use hmac::Hmac;
52use sha2::Sha256;
53use thiserror::Error;
54
55/// AES-256-GCM key length (matches TS `KEY_LENGTH = 32`).
56pub const KEY_LENGTH: usize = 32;
57/// AES-GCM IV length, in bytes — TS `IV_LENGTH = 12`. Don't use a
58/// non-12-byte nonce here: GCM is unsafe with anything else, and the
59/// TS encoder is hard-coded to 12.
60pub const IV_LENGTH: usize = 12;
61/// AES-GCM authentication tag length — TS `AUTH_TAG_LENGTH = 16`.
62pub const AUTH_TAG_LENGTH: usize = 16;
63/// Salt length used by the KDF (PBKDF2-HMAC-SHA256). Matches TS
64/// `SALT_LENGTH = 32`.
65pub const SALT_LENGTH: usize = 32;
66
67/// PBKDF2 iteration count for `V1` — TS
68/// `PBKDF2_ITERATIONS_V1 = 100_000`. Imported-only; never emitted by
69/// this encoder.
70pub const PBKDF2_ITERATIONS_V1: u32 = 100_000;
71/// PBKDF2 iteration count for `V2` — TS `PBKDF2_ITERATIONS_V2 = 600_000`.
72/// Used by every fresh export.
73pub const PBKDF2_ITERATIONS_V2: u32 = 600_000;
74
75/// Magic byte for `V1` envelopes.
76pub const ENCRYPTION_VERSION_V1: u8 = 1;
77/// Magic byte for `V2` envelopes — the only version this module
78/// emits.
79pub const ENCRYPTION_VERSION_V2: u8 = 2;
80/// Header length: `[version u8 || salt[32] || iv[12] || tag[16]]` —
81/// matches TS `HEADER_LENGTH = 1 + 32 + 12 + 16 = 61`.
82pub const HEADER_LENGTH: usize = 1 + SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH;
83
84/// Errors that surface out of the storage-encryption envelope.
85///
86/// The library returns these typed variants so call sites can
87/// distinguish a structural error (e.g. truncated ciphertext) from a
88/// crypto failure. Callers that need TS-compatible behaviour
89/// (single generic `ExportDecryptionError` for oracle resistance)
90/// should collapse the variants at their boundary.
91#[derive(Debug, Error)]
92pub enum StorageEncryptionError {
93    /// Ciphertext was shorter than [`HEADER_LENGTH`] bytes; cannot
94    /// possibly contain a valid envelope.
95    #[error("invalid encrypted data: too short ({0} bytes, header is 61 bytes)")]
96    TooShort(usize),
97    /// The leading version byte is not [`ENCRYPTION_VERSION_V1`] or
98    /// [`ENCRYPTION_VERSION_V2`].
99    #[error("unsupported encryption version: {0}")]
100    UnsupportedVersion(u8),
101    /// `base64::decode` failed on the input.
102    #[error("invalid base64: {0}")]
103    InvalidBase64(#[source] base64::DecodeError),
104    /// AES-GCM authentication failed (wrong key, modified ciphertext,
105    /// truncated tag, etc.). Mapped to TS's generic
106    /// `ExportDecryptionError` at the importer boundary.
107    #[error("decryption failed (wrong password or corrupted ciphertext)")]
108    Decrypt,
109}
110
111/// Salt bound to a [`Cipher`] instance. Re-exposed on import so the
112/// caller can record it in the export wrapper alongside the
113/// base64-encoded ciphertext (the TS exporter does the same — the
114/// salt is *also* embedded in the encrypted blob, but exposing it
115/// separately makes round-trip APIs ergonomic and matches the TS
116/// `getSalt()` accessor).
117pub type Salt = [u8; SALT_LENGTH];
118
119/// One AES-256-GCM cipher bound to a derived key + the salt that
120/// produced it.
121///
122/// Construct with [`Cipher::derive`] (fresh random salt) or
123/// [`Cipher::derive_with_salt`] (importer reusing an existing salt).
124/// `encrypt` and `decrypt` operate on UTF-8 strings and return /
125/// expect base64 envelopes.
126#[derive(Clone)]
127pub struct Cipher {
128    aead: Aes256Gcm,
129    salt: Salt,
130}
131
132impl Cipher {
133    /// Derive an encryption key from `password` and a fresh random
134    /// `salt`. Matches TS `StorageEncryption.create(password)` (no
135    /// `existingSalt`).
136    pub fn derive<R: rand::CryptoRng + rand::RngCore>(rng: &mut R, password: &str) -> Self {
137        let mut salt = [0u8; SALT_LENGTH];
138        rng.fill_bytes(&mut salt);
139        Self::derive_with_salt(password, &salt, PBKDF2_ITERATIONS_V2)
140    }
141
142    /// Derive an encryption key from `password` and the supplied
143    /// `salt`. Always uses [`PBKDF2_ITERATIONS_V2`] — call
144    /// [`Cipher::derive_with_salt_iter`] if you're decrypting a `V1`
145    /// envelope.
146    #[allow(deprecated)]
147    pub fn derive_with_salt(password: &str, salt: &Salt, iterations: u32) -> Self {
148        let mut key = [0u8; KEY_LENGTH];
149        // pbkdf2 returns Result<(), Error> — failure is impossible
150        // for a fixed 32-byte output and any non-empty password
151        // (length is checked by upstream callers via
152        // validate_export_password). We propagate via expect because
153        // the signature constraint is what makes the call infallible.
154        pbkdf2::pbkdf2::<Hmac<Sha256>>(password.as_bytes(), salt, iterations, &mut key)
155            .expect("PBKDF2 with a 32-byte key length is infallible");
156        // Expand AES-256 key schedule + GHASH table once instead of on every
157        // encrypt/decrypt call.
158        let aead = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&key));
159        Self { aead, salt: *salt }
160    }
161
162    /// Helper for the importer path that reads the version byte off
163    /// an envelope before deriving the key. Selects the correct
164    /// iteration count based on `version`.
165    pub fn derive_for_version(
166        password: &str,
167        salt: &Salt,
168        version: u8,
169    ) -> Result<Self, StorageEncryptionError> {
170        let iterations = match version {
171            ENCRYPTION_VERSION_V1 => PBKDF2_ITERATIONS_V1,
172            ENCRYPTION_VERSION_V2 => PBKDF2_ITERATIONS_V2,
173            other => return Err(StorageEncryptionError::UnsupportedVersion(other)),
174        };
175        Ok(Self::derive_with_salt(password, salt, iterations))
176    }
177
178    /// Salt accessor — matches TS `getSalt()`.
179    #[must_use]
180    pub fn salt(&self) -> &Salt {
181        &self.salt
182    }
183
184    /// Encrypt `plaintext` (UTF-8) and return the base64-encoded
185    /// envelope. Matches TS `StorageEncryption.encrypt(data)`.
186    #[allow(deprecated)]
187    pub fn encrypt<R: rand::CryptoRng + rand::RngCore>(
188        &self,
189        rng: &mut R,
190        plaintext: &str,
191    ) -> String {
192        let mut iv = [0u8; IV_LENGTH];
193        rng.fill_bytes(&mut iv);
194        // GCM is safe with random 12-byte IVs up to ~2^32 invocations
195        // per key — well above any export workload.
196        let ct_with_tag = self
197            .aead
198            .encrypt(
199                Nonce::from_slice(&iv),
200                Payload {
201                    msg: plaintext.as_bytes(),
202                    aad: &[],
203                },
204            )
205            .expect(
206                "AES-256-GCM encryption with a 32-byte key, 12-byte nonce, \
207                 and well-formed plaintext is infallible",
208            );
209        // The aes_gcm crate returns ciphertext || tag concatenated.
210        // Split into ct and tag for the TS-compatible layout
211        // (TS appends auth_tag separately in the header before the
212        // ciphertext).
213        let (ct, tag) = ct_with_tag.split_at(ct_with_tag.len() - AUTH_TAG_LENGTH);
214        let mut envelope = Vec::with_capacity(HEADER_LENGTH + ct.len());
215        envelope.push(ENCRYPTION_VERSION_V2);
216        envelope.extend_from_slice(&self.salt);
217        envelope.extend_from_slice(&iv);
218        envelope.extend_from_slice(tag);
219        envelope.extend_from_slice(ct);
220        BASE64_STANDARD.encode(&envelope)
221    }
222
223    /// Decrypt a base64 envelope into the original UTF-8 string.
224    /// Matches TS `StorageEncryption.decrypt(encryptedData)`. The
225    /// `Cipher` instance MUST have been derived from the same salt
226    /// that's in the envelope; if it wasn't, the AES-GCM auth check
227    /// fails and we return [`StorageEncryptionError::Decrypt`].
228    pub fn decrypt(&self, base64_envelope: &str) -> Result<String, StorageEncryptionError> {
229        let parsed = parse_envelope(base64_envelope)?;
230        if parsed.salt != self.salt {
231            // Salt mismatch is a structural failure (the cipher was
232            // derived for a different salt), but treat it as a
233            // decrypt error to avoid leaking the salt-comparison
234            // result to a timing oracle. The TS code raises
235            // `'Salt mismatch'` here, but the `decryptValue` wrapper
236            // collapses it to `ExportDecryptionError` upstream. Same
237            // here: the caller will collapse all variants.
238            return Err(StorageEncryptionError::Decrypt);
239        }
240        decrypt_with_aead(&self.aead, &parsed)
241    }
242}
243
244/// Components of a parsed envelope, before the AES-GCM auth check.
245#[derive(Debug, Clone)]
246pub struct EnvelopeParts {
247    pub version: u8,
248    pub salt: Salt,
249    pub iv: [u8; IV_LENGTH],
250    pub tag: [u8; AUTH_TAG_LENGTH],
251    pub ciphertext: Vec<u8>,
252}
253
254/// Parse a base64 envelope into its raw header components — does
255/// not run the AES-GCM auth check. The importer reads the version
256/// byte first, then derives the key with the matching iteration
257/// count, then calls [`decrypt_with_key`]. Direct callers should
258/// prefer [`Cipher::decrypt`].
259pub fn parse_envelope(base64_envelope: &str) -> Result<EnvelopeParts, StorageEncryptionError> {
260    let bytes = BASE64_STANDARD
261        .decode(base64_envelope.trim())
262        .map_err(StorageEncryptionError::InvalidBase64)?;
263    if bytes.len() < HEADER_LENGTH {
264        return Err(StorageEncryptionError::TooShort(bytes.len()));
265    }
266    let version = bytes[0];
267    if version != ENCRYPTION_VERSION_V1 && version != ENCRYPTION_VERSION_V2 {
268        return Err(StorageEncryptionError::UnsupportedVersion(version));
269    }
270    let mut salt = [0u8; SALT_LENGTH];
271    salt.copy_from_slice(&bytes[1..=SALT_LENGTH]);
272    let mut iv = [0u8; IV_LENGTH];
273    iv.copy_from_slice(&bytes[1 + SALT_LENGTH..1 + SALT_LENGTH + IV_LENGTH]);
274    let mut tag = [0u8; AUTH_TAG_LENGTH];
275    tag.copy_from_slice(
276        &bytes[1 + SALT_LENGTH + IV_LENGTH..1 + SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH],
277    );
278    let ciphertext = bytes[HEADER_LENGTH..].to_vec();
279    Ok(EnvelopeParts {
280        version,
281        salt,
282        iv,
283        tag,
284        ciphertext,
285    })
286}
287
288/// Run AES-256-GCM decryption against the parsed envelope. Used by
289/// the importer to decrypt with a key derived for the envelope's
290/// version.
291#[allow(deprecated)]
292pub fn decrypt_with_key(
293    key: &[u8; KEY_LENGTH],
294    parts: &EnvelopeParts,
295) -> Result<String, StorageEncryptionError> {
296    let aead = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key));
297    decrypt_with_aead(&aead, parts)
298}
299
300#[allow(deprecated)]
301fn decrypt_with_aead(
302    aead: &Aes256Gcm,
303    parts: &EnvelopeParts,
304) -> Result<String, StorageEncryptionError> {
305    // The aes_gcm crate's decrypt API expects ciphertext || tag, so
306    // re-concatenate.
307    let mut combined = Vec::with_capacity(parts.ciphertext.len() + AUTH_TAG_LENGTH);
308    combined.extend_from_slice(&parts.ciphertext);
309    combined.extend_from_slice(&parts.tag);
310    let plaintext = aead
311        .decrypt(
312            Nonce::from_slice(&parts.iv),
313            Payload {
314                msg: &combined,
315                aad: &[],
316            },
317        )
318        .map_err(|_| StorageEncryptionError::Decrypt)?;
319    String::from_utf8(plaintext).map_err(|_| StorageEncryptionError::Decrypt)
320}
321
322/// `true` if `data` looks like a [`Cipher::encrypt`] envelope (passes
323/// length + magic-byte checks). Matches TS `StorageEncryption.isEncrypted`.
324#[must_use]
325pub fn is_encrypted(data: &str) -> bool {
326    let Ok(bytes) = BASE64_STANDARD.decode(data.trim()) else {
327        return false;
328    };
329    bytes.len() >= HEADER_LENGTH
330        && (bytes[0] == ENCRYPTION_VERSION_V1 || bytes[0] == ENCRYPTION_VERSION_V2)
331}
332
333/// Read the version byte from a base64 envelope. Matches TS
334/// `StorageEncryption.getVersion`.
335pub fn get_version(data: &str) -> Result<u8, StorageEncryptionError> {
336    let bytes = BASE64_STANDARD
337        .decode(data.trim())
338        .map_err(StorageEncryptionError::InvalidBase64)?;
339    if bytes.is_empty() {
340        return Err(StorageEncryptionError::TooShort(0));
341    }
342    Ok(bytes[0])
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348    use rand::rngs::StdRng;
349    use rand::SeedableRng;
350
351    fn rng(seed: u64) -> StdRng {
352        StdRng::seed_from_u64(seed)
353    }
354
355    #[test]
356    fn header_length_matches_ts_constant() {
357        // TS: VERSION_PREFIX_LENGTH(1) + SALT_LENGTH(32) + IV_LENGTH(12) + AUTH_TAG_LENGTH(16) = 61.
358        assert_eq!(HEADER_LENGTH, 61);
359    }
360
361    #[test]
362    fn pbkdf2_iteration_constants_match_ts() {
363        assert_eq!(PBKDF2_ITERATIONS_V1, 100_000);
364        assert_eq!(PBKDF2_ITERATIONS_V2, 600_000);
365    }
366
367    #[test]
368    fn round_trip_encrypt_then_decrypt_with_same_cipher() {
369        let mut r = rng(0x42);
370        let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
371        let plain = "this is the plaintext that should round-trip cleanly";
372        let envelope = cipher.encrypt(&mut r, plain);
373        assert!(is_encrypted(&envelope));
374        let recovered = cipher.decrypt(&envelope).expect("round-trip decrypt");
375        assert_eq!(recovered, plain);
376    }
377
378    #[test]
379    fn round_trip_via_importer_path_using_envelope_salt() {
380        // Importer flow: parse the envelope, derive the key with the
381        // header's salt + version, decrypt.
382        let mut r = rng(0x99);
383        let pw = "TheQuickBrownFox-12345!";
384        let cipher = Cipher::derive(&mut r, pw);
385        let plain = "import-path round-trip";
386        let envelope = cipher.encrypt(&mut r, plain);
387
388        let parts = parse_envelope(&envelope).unwrap();
389        let importer = Cipher::derive_for_version(pw, &parts.salt, parts.version).unwrap();
390        let recovered = importer.decrypt(&envelope).unwrap();
391        assert_eq!(recovered, plain);
392    }
393
394    #[test]
395    fn wrong_password_rejects_with_decrypt_error() {
396        let mut r = rng(1);
397        let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
398        let envelope = cipher.encrypt(&mut r, "some payload");
399        // Same salt — different password.
400        let parts = parse_envelope(&envelope).unwrap();
401        let wrong = Cipher::derive_for_version(
402            "DifferentPassword!12345",
403            &parts.salt,
404            ENCRYPTION_VERSION_V2,
405        )
406        .unwrap();
407        let err = wrong.decrypt(&envelope).unwrap_err();
408        assert!(matches!(err, StorageEncryptionError::Decrypt));
409    }
410
411    #[test]
412    fn truncated_envelope_rejects_with_too_short() {
413        // Envelope shorter than HEADER_LENGTH bytes.
414        let truncated = BASE64_STANDARD.encode([0u8; HEADER_LENGTH - 1]);
415        let err = parse_envelope(&truncated).unwrap_err();
416        assert!(matches!(err, StorageEncryptionError::TooShort(_)));
417    }
418
419    #[test]
420    fn unsupported_version_rejects() {
421        let mut bytes = vec![0xFFu8]; // version 255
422        bytes.extend(vec![0u8; HEADER_LENGTH - 1]);
423        let envelope = BASE64_STANDARD.encode(bytes);
424        let err = parse_envelope(&envelope).unwrap_err();
425        assert!(matches!(
426            err,
427            StorageEncryptionError::UnsupportedVersion(0xFF)
428        ));
429    }
430
431    #[test]
432    fn corrupted_ciphertext_rejects_with_decrypt_error() {
433        let mut r = rng(2);
434        let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
435        let envelope = cipher.encrypt(&mut r, "payload");
436
437        // Decode, flip the last ciphertext byte, re-encode.
438        let mut decoded = BASE64_STANDARD.decode(&envelope).unwrap();
439        let last = decoded.len() - 1;
440        decoded[last] ^= 0xff;
441        let tampered = BASE64_STANDARD.encode(&decoded);
442
443        let err = cipher.decrypt(&tampered).unwrap_err();
444        assert!(matches!(err, StorageEncryptionError::Decrypt));
445    }
446
447    #[test]
448    fn corrupted_tag_rejects_with_decrypt_error() {
449        let mut r = rng(3);
450        let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
451        let envelope = cipher.encrypt(&mut r, "payload");
452
453        // Flip a byte inside the auth tag region (bytes [1+32+12 ..
454        // 1+32+12+16]).
455        let mut decoded = BASE64_STANDARD.decode(&envelope).unwrap();
456        let tag_start = 1 + SALT_LENGTH + IV_LENGTH;
457        decoded[tag_start] ^= 0xff;
458        let tampered = BASE64_STANDARD.encode(&decoded);
459
460        let err = cipher.decrypt(&tampered).unwrap_err();
461        assert!(matches!(err, StorageEncryptionError::Decrypt));
462    }
463
464    #[test]
465    fn invalid_base64_rejects() {
466        let err = parse_envelope("@@@not-base64@@@").unwrap_err();
467        assert!(matches!(err, StorageEncryptionError::InvalidBase64(_)));
468    }
469
470    #[test]
471    fn is_encrypted_recognises_well_formed_envelope() {
472        let mut r = rng(4);
473        let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
474        let envelope = cipher.encrypt(&mut r, "x");
475        assert!(is_encrypted(&envelope));
476    }
477
478    #[test]
479    fn is_encrypted_rejects_random_string() {
480        // 64 valid base64 chars but doesn't pass the magic-byte check.
481        let bogus = BASE64_STANDARD.encode([0x99u8; HEADER_LENGTH + 4]);
482        assert!(!is_encrypted(&bogus));
483    }
484
485    #[test]
486    fn get_version_returns_emitted_version() {
487        let mut r = rng(5);
488        let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
489        let envelope = cipher.encrypt(&mut r, "x");
490        assert_eq!(get_version(&envelope).unwrap(), ENCRYPTION_VERSION_V2);
491    }
492
493    #[test]
494    fn distinct_salts_distinct_envelopes_for_same_plaintext() {
495        // Two derive() calls on the same password with different
496        // RNGs should produce different salts and therefore different
497        // envelopes (proves we're not deterministic across exports).
498        let mut r1 = rng(10);
499        let mut r2 = rng(11);
500        let c1 = Cipher::derive(&mut r1, "TheQuickBrownFox-12345!");
501        let c2 = Cipher::derive(&mut r2, "TheQuickBrownFox-12345!");
502        assert_ne!(c1.salt, c2.salt);
503        let e1 = c1.encrypt(&mut r1, "same plain");
504        let e2 = c2.encrypt(&mut r2, "same plain");
505        assert_ne!(e1, e2);
506    }
507
508    #[test]
509    fn pbkdf2_v2_known_answer_against_rfc6070_style_vector() {
510        // PBKDF2-HMAC-SHA256, password = "password", salt = "salt",
511        // iterations = 1, dkLen = 32. RFC 6070 doesn't cover SHA-256
512        // directly, but `cryptography.io` publishes the equivalent
513        // vector and `pbkdf2` crate documents it. Hard-coding a known
514        // answer here means a future cargo update that breaks the
515        // pbkdf2 dep surfaces immediately.
516        let mut out = [0u8; 32];
517        pbkdf2::pbkdf2::<Hmac<Sha256>>(b"password", b"salt", 1, &mut out).unwrap();
518        let expected =
519            hex::decode("120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b")
520                .unwrap();
521        assert_eq!(out.as_slice(), expected.as_slice());
522    }
523}