hardware-enclave 0.2.8

Hardware-backed key management — macOS Secure Enclave, Windows TPM 2.0, Linux TPM/keyring — plus in-process memory protection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
// Copyright 2026 Jay Gowdy
// SPDX-License-Identifier: MIT

//! Mock encryption storage for testing without hardware.
//!
//! Uses AES-256-GCM with a random in-memory key. Provides no hardware
//! backing; suitable only for tests and development.

// aes-gcm 0.10 still uses generic-array 0.14 internally and emits a
// deprecation notice on `Nonce::from_slice` — the 1.x migration is
// upstream work, silence here so `-D warnings` doesn't trip.
#![allow(
    dead_code,
    unused_imports,
    unused_qualifications,
    unreachable_patterns,
    deprecated
)]

use aes_gcm::aead::Aead;
use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
use rand::RngCore;
use sha2::{Digest, Sha256};

use super::encryption::EncryptionStorage;
use super::error::{Result, StorageError};
use super::platform::BackendKind;

/// Nonce size for AES-256-GCM (96 bits).
const NONCE_SIZE: usize = 12;

/// Mock secure storage for testing.
///
/// Uses AES-256-GCM with a random in-memory key.
/// Encrypts/decrypts in a format compatible with test assertions
/// but does not provide hardware-backed security.
pub struct MockEncryptionStorage {
    cipher: Aes256Gcm,
}

impl std::fmt::Debug for MockEncryptionStorage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MockEncryptionStorage")
            .field("cipher", &"<Aes256Gcm>")
            .finish()
    }
}

impl MockEncryptionStorage {
    /// Create a new mock storage with a randomly generated AES-256 key.
    pub fn new() -> Self {
        let mut key_bytes = [0_u8; 32];
        rand::thread_rng().fill_bytes(&mut key_bytes);
        Self::from_key_bytes(key_bytes)
    }

    /// Create a mock storage with a key deterministically derived from
    /// the application name.
    ///
    /// This is how [`create_encryption_storage`](crate::internal::app_storage::create_encryption_storage)
    /// instantiates the mock when [`MOCK_STORAGE_ENV`](crate::internal::app_storage::MOCK_STORAGE_ENV)
    /// is set. The deterministic key makes the mock viable across
    /// process boundaries — parent and child `cargo test` processes
    /// that both construct storage for the same app will land on the
    /// same AES key and can decrypt each other's ciphertexts. A
    /// random-keyed [`new`] would fail cross-process tests with
    /// `aead::Error` because each process would have its own key.
    ///
    /// The derivation is `SHA-256("enclaveapp-app-storage mock v1\0" || app_name)`.
    /// It is explicitly *not* cryptographically secret — anyone with
    /// the app name can recompute it. That is the point: this is a
    /// test-only backend.
    pub fn for_app(app_name: &str) -> Self {
        let mut hasher = Sha256::new();
        hasher.update(b"enclaveapp-app-storage mock v1\0");
        hasher.update(app_name.as_bytes());
        let key_bytes: [u8; 32] = hasher.finalize().into();
        Self::from_key_bytes(key_bytes)
    }

    fn from_key_bytes(key_bytes: [u8; 32]) -> Self {
        let cipher = Aes256Gcm::new_from_slice(&key_bytes)
            .expect("32-byte key is always valid for AES-256-GCM");
        Self { cipher }
    }
}

impl Default for MockEncryptionStorage {
    fn default() -> Self {
        Self::new()
    }
}

impl EncryptionStorage for MockEncryptionStorage {
    fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
        let mut nonce_bytes = [0_u8; NONCE_SIZE];
        rand::thread_rng().fill_bytes(&mut nonce_bytes);
        let nonce = Nonce::from_slice(&nonce_bytes);

        let ciphertext = self
            .cipher
            .encrypt(nonce, plaintext)
            .map_err(|e| StorageError::EncryptionFailed(e.to_string()))?;

        let mut output = Vec::with_capacity(NONCE_SIZE + ciphertext.len());
        output.extend_from_slice(&nonce_bytes);
        output.extend_from_slice(&ciphertext);
        Ok(output)
    }

    fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>> {
        if ciphertext.len() < NONCE_SIZE {
            return Err(StorageError::DecryptionFailed(
                "ciphertext too short to contain nonce".into(),
            ));
        }

        let (nonce_bytes, encrypted) = ciphertext.split_at(NONCE_SIZE);
        let nonce = Nonce::from_slice(nonce_bytes);

        self.cipher
            .decrypt(nonce, encrypted)
            .map_err(|e| StorageError::DecryptionFailed(e.to_string()))
    }

    fn destroy(&self) -> Result<()> {
        Ok(())
    }

    fn is_available(&self) -> bool {
        true
    }

    fn backend_name(&self) -> &'static str {
        "Mock (AES-GCM)"
    }

    fn backend_kind(&self) -> BackendKind {
        BackendKind::Keyring
    }
}

// ── MockSigner ────────────────────────────────────────────────────────────────

use crate::internal::core::{
    traits::{EnclaveKeyManager, EnclaveSigner},
    types::{AccessPolicy, KeyType},
    Error as CoreError, Result as CoreResult,
};
use elliptic_curve::sec1::ToEncodedPoint;
use p256::{
    ecdsa::{signature::Signer, DerSignature, SigningKey},
    SecretKey,
};
use std::path::{Path, PathBuf};
use zeroize::Zeroizing;

/// Cross-platform mock signer for testing without hardware.
///
/// Stores P-256 private keys as raw-bytes files in a temporary directory.
/// Disk-backed so that multiple processes using the same app_name and
/// `ENCLAVEAPP_MOCK_STORAGE` env share the same key store — critical for
/// the sshenc architecture where the CLI and agent are separate processes.
pub struct MockSigner {
    keys_dir: PathBuf,
}

impl std::fmt::Debug for MockSigner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MockSigner")
            .field("keys_dir", &self.keys_dir)
            .finish()
    }
}

impl MockSigner {
    /// Create a mock signer that stores keys under `keys_dir`.
    /// All MockSigner instances with the same `keys_dir` share the same keys.
    pub fn with_keys_dir(keys_dir: PathBuf) -> Self {
        drop(std::fs::create_dir_all(&keys_dir));
        Self { keys_dir }
    }

    fn key_path(&self, label: &str) -> PathBuf {
        self.keys_dir.join(format!("{label}.mock-key"))
    }

    fn pub_path(&self, label: &str) -> PathBuf {
        self.keys_dir.join(format!("{label}.pub"))
    }
}

impl Default for MockSigner {
    fn default() -> Self {
        Self::with_keys_dir(std::env::temp_dir().join("hardware-enclave-mock-signer"))
    }
}

// Safety: MockSigner only accesses files via std::fs which is Send+Sync.
#[allow(unsafe_code)]
unsafe impl Send for MockSigner {}
#[allow(unsafe_code)]
unsafe impl Sync for MockSigner {}

fn load_secret(path: &Path) -> CoreResult<SecretKey> {
    if !path.exists() {
        let label = path
            .file_stem()
            .unwrap_or_default()
            .to_string_lossy()
            .to_string();
        return Err(CoreError::KeyNotFound { label });
    }
    let bytes = Zeroizing::new(std::fs::read(path).map_err(|e| CoreError::KeyOperation {
        operation: "mock_load".into(),
        detail: e.to_string(),
    })?);
    SecretKey::from_slice(&bytes).map_err(|e| CoreError::KeyOperation {
        operation: "mock_parse".into(),
        detail: e.to_string(),
    })
}

impl EnclaveKeyManager for MockSigner {
    fn generate(
        &self,
        label: &str,
        _key_type: KeyType,
        _policy: AccessPolicy,
    ) -> CoreResult<Vec<u8>> {
        // Reject duplicates atomically: use OpenOptions::create_new so the
        // first writer wins and concurrent callers get DuplicateLabel.
        let key_path = self.key_path(label);
        let secret = SecretKey::random(&mut elliptic_curve::rand_core::OsRng);
        let pub_bytes = secret
            .public_key()
            .to_encoded_point(false)
            .as_bytes()
            .to_vec();
        let key_bytes = Zeroizing::new(secret.to_bytes().to_vec());
        use std::io::Write;
        let result = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&key_path)
            .and_then(|mut f| f.write_all(&key_bytes));
        match result {
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                return Err(CoreError::DuplicateLabel {
                    label: label.to_string(),
                });
            }
            Err(e) => {
                return Err(CoreError::KeyOperation {
                    operation: "mock_save".into(),
                    detail: e.to_string(),
                });
            }
            Ok(()) => {}
        }
        // Write SEC1 public key cache so list_labels() (which scans .pub files) finds it.
        std::fs::write(self.pub_path(label), &pub_bytes).map_err(|e| CoreError::KeyOperation {
            operation: "mock_save_pub".into(),
            detail: e.to_string(),
        })?;
        Ok(pub_bytes)
    }

    fn public_key(&self, label: &str) -> CoreResult<Vec<u8>> {
        let secret = load_secret(&self.key_path(label))?;
        Ok(secret
            .public_key()
            .to_encoded_point(false)
            .as_bytes()
            .to_vec())
    }

    fn list_keys(&self) -> CoreResult<Vec<String>> {
        // Scan .pub files — consistent with compat::list_labels so sshenc list works.
        let mut labels = Vec::new();
        if let Ok(entries) = std::fs::read_dir(&self.keys_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().map(|e| e == "pub").unwrap_or(false) {
                    if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                        labels.push(stem.to_string());
                    }
                }
            }
        }
        Ok(labels)
    }

    fn delete_key(&self, label: &str) -> CoreResult<()> {
        let path = self.key_path(label);
        if !path.exists() {
            return Err(CoreError::KeyNotFound {
                label: label.to_string(),
            });
        }
        std::fs::remove_file(&path).map_err(|e| CoreError::KeyOperation {
            operation: "mock_delete".into(),
            detail: e.to_string(),
        })?;
        // Best-effort .pub cleanup.
        drop(std::fs::remove_file(self.pub_path(label)));
        Ok(())
    }

    fn is_available(&self) -> bool {
        true
    }

    fn rename_key(&self, old_label: &str, new_label: &str) -> CoreResult<()> {
        let old_key = self.key_path(old_label);
        let old_pub = self.pub_path(old_label);
        if !old_key.exists() {
            return Err(CoreError::KeyNotFound {
                label: old_label.to_string(),
            });
        }
        std::fs::rename(&old_key, self.key_path(new_label)).map_err(|e| {
            CoreError::KeyOperation {
                operation: "mock_rename_key".into(),
                detail: e.to_string(),
            }
        })?;
        if old_pub.exists() {
            drop(std::fs::rename(&old_pub, self.pub_path(new_label)));
        }
        Ok(())
    }
}

impl EnclaveSigner for MockSigner {
    fn sign(&self, label: &str, data: &[u8]) -> CoreResult<Vec<u8>> {
        let secret = load_secret(&self.key_path(label))?;
        let signing_key = SigningKey::from(&secret);
        let sig: DerSignature = signing_key.sign(data);
        Ok(sig.to_bytes().to_vec())
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn encrypt_decrypt_roundtrip() {
        let storage = MockEncryptionStorage::new();
        let plaintext = b"hello, secure world!";

        let ciphertext = storage.encrypt(plaintext).unwrap();
        assert_ne!(ciphertext, plaintext);
        assert!(ciphertext.len() > plaintext.len());

        let decrypted = storage.decrypt(&ciphertext).unwrap();
        assert_eq!(decrypted, plaintext);
    }

    #[test]
    fn encrypt_produces_different_ciphertexts() {
        let storage = MockEncryptionStorage::new();
        let plaintext = b"same input";

        let ct1 = storage.encrypt(plaintext).unwrap();
        let ct2 = storage.encrypt(plaintext).unwrap();
        assert_ne!(ct1, ct2);
    }

    #[test]
    fn decrypt_empty_input_fails() {
        let storage = MockEncryptionStorage::new();
        assert!(storage.decrypt(&[]).is_err());
    }

    #[test]
    fn decrypt_short_input_fails() {
        let storage = MockEncryptionStorage::new();
        assert!(storage.decrypt(&[0_u8; 5]).is_err());
    }

    #[test]
    fn decrypt_tampered_ciphertext_fails() {
        let storage = MockEncryptionStorage::new();
        let mut ciphertext = storage.encrypt(b"sensitive data").unwrap();
        if let Some(byte) = ciphertext.get_mut(NONCE_SIZE + 1) {
            *byte ^= 0xff;
        }
        assert!(storage.decrypt(&ciphertext).is_err());
    }

    #[test]
    fn decrypt_wrong_key_fails() {
        let s1 = MockEncryptionStorage::new();
        let s2 = MockEncryptionStorage::new();

        let ciphertext = s1.encrypt(b"key-specific").unwrap();
        assert!(s2.decrypt(&ciphertext).is_err());
    }

    #[test]
    fn decrypt_truncated_by_one_byte_fails() {
        // A ciphertext that is longer than the nonce but missing the last
        // byte of the GCM authentication tag must be rejected cleanly.
        let storage = MockEncryptionStorage::new();
        let mut ciphertext = storage.encrypt(b"truncation test").unwrap();
        assert!(
            ciphertext.len() > NONCE_SIZE,
            "ciphertext must exceed nonce"
        );
        ciphertext.pop(); // remove last byte
        let result = storage.decrypt(&ciphertext);
        assert!(
            result.is_err(),
            "truncated ciphertext must return Err, not panic"
        );
    }

    #[test]
    fn encrypt_empty_plaintext() {
        let storage = MockEncryptionStorage::new();
        let ciphertext = storage.encrypt(b"").unwrap();
        let decrypted = storage.decrypt(&ciphertext).unwrap();
        assert!(decrypted.is_empty());
    }

    #[test]
    fn encrypt_large_plaintext() {
        let storage = MockEncryptionStorage::new();
        let plaintext = vec![0xAB_u8; 100_000];
        let ciphertext = storage.encrypt(&plaintext).unwrap();
        let decrypted = storage.decrypt(&ciphertext).unwrap();
        assert_eq!(decrypted, plaintext);
    }

    #[test]
    fn trait_methods() {
        let storage = MockEncryptionStorage::new();
        assert!(storage.is_available());
        assert_eq!(storage.backend_name(), "Mock (AES-GCM)");
        assert_eq!(storage.backend_kind(), BackendKind::Keyring);
        assert!(storage.destroy().is_ok());
    }

    #[test]
    fn default_impl_works() {
        let storage = MockEncryptionStorage::default();
        let ciphertext = storage.encrypt(b"default test").unwrap();
        let decrypted = storage.decrypt(&ciphertext).unwrap();
        assert_eq!(decrypted, b"default test");
    }

    #[test]
    fn encrypt_decrypt_various_sizes() {
        let storage = MockEncryptionStorage::new();
        for size in [0, 1, 100, 10_000] {
            let plaintext = vec![0xAA_u8; size];
            let ciphertext = storage.encrypt(&plaintext).unwrap();
            let decrypted = storage.decrypt(&ciphertext).unwrap();
            assert_eq!(decrypted, plaintext, "roundtrip failed for size {size}");
        }
    }
}