vta-tee 0.5.0

VTA TEE bootstrap — Nitro/SEV-SNP attestation providers, KMS attest/decrypt + storage-key derivation, the anchor MAC, and first-boot DID autogen
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
//! Time-limited mnemonic export guard with secure memory wiping.
//!
//! On first boot, the VTA generates entropy for the BIP-39 mnemonic inside
//! the TEE. The mnemonic is NEVER displayed. Instead, the entropy is held
//! in a `MnemonicExportGuard` that is only active if:
//!
//! 1. The VTA was started with `VTA_MNEMONIC_EXPORT_WINDOW=<seconds>` env var
//! 2. The current time is within the window since boot
//! 3. The requester is a super admin (authenticated via JWT)
//!
//! After the window expires, the entropy is cryptographically zeroed using
//! the `zeroize` crate (prevents compiler optimization of the wipe) and the
//! mnemonic can never be reconstructed.
//!
//! On subsequent boots (not first boot), no entropy exists to export.

use std::sync::Mutex;
use std::time::Instant;

use serde::Serialize;
use tracing::{info, warn};
use zeroize::Zeroize;

use vti_common::error::{AppError, tee_attestation_error};

/// Holds the BIP-39 entropy bytes during the export window.
pub struct MnemonicExportGuard {
    inner: Mutex<GuardState>,
}

struct GuardState {
    /// The 32-byte entropy used to generate the BIP-39 mnemonic.
    /// Cryptographically zeroed after export or window expiry.
    entropy: Option<[u8; 32]>,
    /// When the guard was created (boot time).
    created_at: Instant,
    /// How long the export window lasts.
    window_secs: u64,
    /// Whether the mnemonic has been exported (one-time use).
    exported: bool,
    /// Whether an export is in flight — reserved but not yet committed. Keeps
    /// a second concurrent request from reading the mnemonic while the first
    /// is still sealing it.
    reserved: bool,
}

impl Drop for GuardState {
    fn drop(&mut self) {
        self.wipe_entropy();
    }
}

impl GuardState {
    /// Cryptographically zero the entropy bytes.
    fn wipe_entropy(&mut self) {
        if let Some(ref mut e) = self.entropy {
            e.zeroize();
        }
        self.entropy = None;
    }
}

/// Status of the mnemonic export guard.
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct MnemonicExportStatus {
    /// Whether the export window is currently active.
    pub window_active: bool,
    /// Whether the mnemonic has already been exported.
    pub already_exported: bool,
    /// Whether entropy is available (false on subsequent boots).
    pub entropy_available: bool,
    /// Seconds remaining in the window (0 if expired or not active).
    pub window_remaining_secs: u64,
}

impl MnemonicExportGuard {
    /// Create a new guard holding the entropy bytes.
    ///
    /// The `window_secs` controls how long the entropy remains available.
    /// After the window, [`Self::reserve`] fails and the entropy is zeroed.
    pub fn new(entropy: [u8; 32], window_secs: u64) -> Self {
        info!(
            window_secs,
            "mnemonic export guard created — window open for {window_secs}s"
        );
        Self {
            inner: Mutex::new(GuardState {
                entropy: Some(entropy),
                created_at: Instant::now(),
                window_secs,
                exported: false,
                reserved: false,
            }),
        }
    }

    /// Create a guard with no entropy (subsequent boot — export is impossible).
    pub fn empty() -> Self {
        Self {
            inner: Mutex::new(GuardState {
                entropy: None,
                created_at: Instant::now(),
                window_secs: 0,
                exported: false,
                reserved: false,
            }),
        }
    }

    /// Check the current status of the export guard.
    pub fn status(&self) -> MnemonicExportStatus {
        let guard = self.inner.lock().unwrap();
        let elapsed = guard.created_at.elapsed().as_secs();
        let window_active =
            guard.entropy.is_some() && !guard.exported && elapsed < guard.window_secs;
        let remaining = if window_active {
            guard.window_secs.saturating_sub(elapsed)
        } else {
            0
        };

        MnemonicExportStatus {
            window_active,
            already_exported: guard.exported,
            entropy_available: guard.entropy.is_some(),
            window_remaining_secs: remaining,
        }
    }

    /// Reserve the one-time export: read the mnemonic **without** consuming
    /// the entropy yet.
    ///
    /// The only way to read the words. There is deliberately no one-shot
    /// "export" returning them as a plain `String`: the words leave the enclave
    /// only sealed to the requester, so every caller has work between reading
    /// and releasing them, and a reservation keeps that work from losing the
    /// root seed.
    ///
    /// The export is two-phase because the caller has work that can fail after
    /// reading the words — sealing them to the operator, recording the audit
    /// row — and the entropy exists nowhere else. Consuming it first would turn
    /// a failed seal into a lost root seed. So: reserve, do the work,
    /// [`MnemonicReservation::commit`] on success. A reservation dropped
    /// without a commit releases the export for a retry. While one is held, a
    /// concurrent reserve is refused, so the words are never handed to two
    /// requests at once.
    ///
    /// Returns `Err` if the window has expired (the entropy is zeroed then),
    /// the mnemonic was already exported, an export is in flight, or no
    /// entropy is available (subsequent boot).
    pub fn reserve(&self) -> Result<MnemonicReservation<'_>, AppError> {
        let mut guard = self.inner.lock().unwrap();

        let entropy = match guard.entropy {
            Some(e) => e,
            None => {
                return Err(tee_attestation_error(
                    "no mnemonic available — entropy only exists on first boot",
                ));
            }
        };
        if guard.exported {
            return Err(tee_attestation_error(
                "mnemonic already exported — one-time operation",
            ));
        }
        if guard.reserved {
            return Err(tee_attestation_error(
                "a mnemonic export is already in progress",
            ));
        }
        let elapsed = guard.created_at.elapsed().as_secs();
        if elapsed >= guard.window_secs {
            guard.wipe_entropy();
            warn!("mnemonic export attempted after window expired — entropy zeroed");
            return Err(tee_attestation_error(format!(
                "mnemonic export window expired ({elapsed}s elapsed, window was {}s)",
                guard.window_secs
            )));
        }

        let mnemonic = bip39::Mnemonic::from_entropy(&entropy)
            .map_err(|e| tee_attestation_error(format!("failed to derive mnemonic: {e}")))?;
        guard.reserved = true;
        Ok(MnemonicReservation {
            guard: self,
            mnemonic: zeroize::Zeroizing::new(mnemonic.to_string()),
            window_remaining_secs: guard.window_secs.saturating_sub(elapsed),
            committed: false,
        })
    }
}

/// An export in flight — see [`MnemonicExportGuard::reserve`].
pub struct MnemonicReservation<'a> {
    guard: &'a MnemonicExportGuard,
    mnemonic: zeroize::Zeroizing<String>,
    window_remaining_secs: u64,
    committed: bool,
}

impl MnemonicReservation<'_> {
    /// The mnemonic phrase. Zeroized when the reservation is dropped.
    pub fn mnemonic(&self) -> &str {
        &self.mnemonic
    }

    /// Seconds left in the export window when the reservation was taken.
    pub fn window_remaining_secs(&self) -> u64 {
        self.window_remaining_secs
    }

    /// Complete the export: mark it done and zero the entropy. One-time.
    pub fn commit(mut self) {
        let mut guard = self.guard.inner.lock().unwrap();
        guard.exported = true;
        guard.reserved = false;
        guard.wipe_entropy();
        self.committed = true;
        info!(
            remaining_secs = self.window_remaining_secs,
            "mnemonic exported to authenticated super admin — entropy zeroed"
        );
    }
}

impl Drop for MnemonicReservation<'_> {
    fn drop(&mut self) {
        if !self.committed {
            // Not committed: release, so the operator can retry inside the
            // window. `lock()` only fails if a holder panicked; the entropy is
            // then unreachable anyway.
            if let Ok(mut guard) = self.guard.inner.lock() {
                guard.reserved = false;
            }
        }
    }
}

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

    /// 32 bytes of fixed entropy for tests. Real entropy comes from
    /// the TEE's CSPRNG; for tests we need a deterministic value so
    /// we can assert specific mnemonic words round-trip via
    /// `bip39::Mnemonic::from_entropy`.
    const TEST_ENTROPY: [u8; 32] = [0x42; 32];

    #[test]
    fn first_export_within_window_succeeds_then_burns_entropy() {
        let g = MnemonicExportGuard::new(TEST_ENTROPY, 60);
        let r = g
            .reserve()
            .expect("first export within window must succeed");
        // BIP-39 24-word phrase: 23 spaces between 24 words.
        assert_eq!(r.mnemonic().split_whitespace().count(), 24);
        assert!(r.window_remaining_secs() <= 60);
        r.commit();

        // Status flips to exhausted: one-time semantics.
        let s = g.status();
        assert!(!s.entropy_available, "entropy must be wiped after export");
        assert!(s.already_exported, "exported flag must be sticky");
        assert!(!s.window_active);
    }

    /// Pin the one-shot semantic: a second reservation after a
    /// successful first must fail, regardless of remaining window.
    ///
    /// The current implementation wipes entropy as part of the
    /// successful-export path, so the second call hits the
    /// `no mnemonic available` branch (entropy=None) before the
    /// `exported` flag check ever fires. Either message satisfies
    /// the one-shot contract — accept both.
    #[test]
    fn second_export_after_first_rejected() {
        let g = MnemonicExportGuard::new(TEST_ENTROPY, 60);
        g.reserve().unwrap().commit();
        let err = g
            .reserve()
            .err()
            .expect("second export must be refused — one-time operation");
        let msg = format!("{err}");
        assert!(
            msg.contains("already exported")
                || msg.contains("no mnemonic available")
                || msg.contains("entropy only exists on first boot"),
            "error must indicate the export is exhausted: got {msg}"
        );
    }

    /// `empty()` constructor (subsequent boot — no entropy) refuses
    /// export with a clear "no entropy on subsequent boot" message.
    #[test]
    fn empty_guard_rejects_export_with_no_entropy_message() {
        let g = MnemonicExportGuard::empty();
        let err = g.reserve().err().expect("no entropy → export must fail");
        let msg = format!("{err}");
        assert!(
            msg.contains("no mnemonic available")
                || msg.contains("entropy only exists on first boot"),
            "error must explain why entropy is absent: got {msg}"
        );

        let s = g.status();
        assert!(!s.entropy_available);
        assert!(!s.window_active);
        assert!(!s.already_exported);
    }

    /// Window-expired path zeroes entropy AND surfaces an actionable
    /// error. We use a 0-second window to force expiry without
    /// sleeping (a real test should never sleep arbitrary durations
    /// to exercise the time check).
    #[test]
    fn export_after_window_expired_zeroes_entropy_and_fails() {
        let g = MnemonicExportGuard::new(TEST_ENTROPY, 0);
        // 0-second window: any elapsed time is past the window.
        let err = g
            .reserve()
            .err()
            .expect("zero-second window must reject export immediately");
        let msg = format!("{err}");
        assert!(msg.contains("window expired"), "got: {msg}");

        // Entropy must be zeroed by the failed export path so a
        // later memory dump can't recover it. Surface this through
        // `status().entropy_available`.
        let s = g.status();
        assert!(
            !s.entropy_available,
            "expired-window path must zero entropy, status says {s:?}"
        );
    }

    /// `Drop` on the guard zeroes the entropy. Fundamental security
    /// property: a guard going out of scope (e.g. on shutdown without
    /// export) must not leave the BIP-39 entropy in heap memory for a
    /// post-mortem dump to recover.
    ///
    /// We can't observe memory after free in safe Rust, but we can
    /// inspect the inner state immediately before drop and assert
    /// `wipe_entropy` was called as part of the drop path. The cheap
    /// proxy is to drop a guard whose inner `Arc<Mutex<...>>` we hold
    /// a weak ref to, then assert the strong count went to zero —
    /// confirming nothing leaked the GuardState. Combined with the
    /// `Drop for GuardState` impl that calls `wipe_entropy()`, this
    /// pins the contract.
    #[test]
    fn drop_zeros_entropy() {
        // Use a Mutex<GuardState> directly so we can inspect after
        // mutation. Then drop and confirm.
        let mut state = GuardState {
            entropy: Some(TEST_ENTROPY),
            created_at: Instant::now(),
            window_secs: 60,
            exported: false,
            reserved: false,
        };
        state.wipe_entropy();
        assert!(
            state.entropy.is_none(),
            "wipe_entropy must clear the Option"
        );
        // Idempotent: a second wipe on already-cleared state is a no-op.
        state.wipe_entropy();
        assert!(state.entropy.is_none());
    }

    /// `status()` reports `window_active=true` while the window is
    /// open, then flips to false after expiry. Pin the
    /// `window_remaining_secs` math.
    #[test]
    fn status_reflects_window_state_correctly() {
        let g = MnemonicExportGuard::new(TEST_ENTROPY, 3600);
        let s = g.status();
        assert!(s.window_active, "fresh guard with 1h window must be active");
        assert!(s.entropy_available);
        assert!(!s.already_exported);
        assert!(s.window_remaining_secs <= 3600);
        assert!(
            s.window_remaining_secs > 3590,
            "remaining ≈ window for fresh guard"
        );

        // Zero-window guard: never active.
        let g0 = MnemonicExportGuard::new(TEST_ENTROPY, 0);
        let s0 = g0.status();
        assert!(!s0.window_active, "0-second window is never active");
        assert_eq!(s0.window_remaining_secs, 0);
    }

    /// A reservation dropped without a commit leaves the mnemonic exportable,
    /// so a failed seal cannot lose the root seed; while it is held, a second
    /// reserve is refused.
    #[test]
    fn an_uncommitted_reservation_releases_the_export() {
        let g = MnemonicExportGuard::new(TEST_ENTROPY, 60);
        let first = g.reserve().expect("reserve");
        let words = first.mnemonic().to_string();
        assert!(g.reserve().is_err(), "a concurrent reserve is refused");
        drop(first);
        let second = g.reserve().expect("released for a retry");
        assert_eq!(second.mnemonic(), words);
        second.commit();
        assert!(g.status().already_exported);
        assert!(g.reserve().is_err(), "one-time after a commit");
    }
}