Skip to main content

aft_base/secret/
vault.rs

1//! Request-addressed vault access. Every outgoing use names its real target;
2//! material is zeroized after that request and is never cached between uses.
3
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::time::{SystemTime, UNIX_EPOCH};
6
7use secret_rules::audit::AuditRecordV1;
8
9use super::wire::{
10    self, ApiKeyTarget, ApprovalRequest, ReleasedApiKey, SecretUseAnswer, SecretUseReply,
11    SecretUseRequest,
12};
13
14/// Key bytes for one request or fetch hop.
15///
16/// Held in a buffer that is wiped when it drops and never reused across
17/// requests (a grant may release different bytes after a rotation). `Debug`
18/// prints the length only.
19pub struct Material(Vec<u8>);
20
21impl Material {
22    /// Take ownership of key bytes.
23    pub fn new(bytes: Vec<u8>) -> Self {
24        Self(bytes)
25    }
26
27    /// The key bytes.
28    pub fn expose(&self) -> &[u8] {
29        &self.0
30    }
31
32    /// The key's length in bytes.
33    pub fn len(&self) -> usize {
34        self.0.len()
35    }
36
37    /// Whether the material is empty, which no admissible key is.
38    pub fn is_empty(&self) -> bool {
39        self.0.is_empty()
40    }
41}
42
43impl Drop for Material {
44    fn drop(&mut self) {
45        zeroize(&mut self.0);
46    }
47}
48
49impl std::fmt::Debug for Material {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        f.debug_struct("Material")
52            .field("len", &self.0.len())
53            .finish()
54    }
55}
56
57/// Overwrite a byte buffer with zeros, in a way the compiler may not drop as
58/// dead. AFT reaches this through material buffers, whose contents must not
59/// outlive their one request.
60pub fn zeroize(bytes: &mut [u8]) {
61    for byte in bytes.iter_mut() {
62        // SAFETY: `byte` is a valid, aligned pointer to one initialized `u8`,
63        // and a volatile store is the only way to keep the wipe from being
64        // optimized away for a buffer that is about to be freed.
65        unsafe { std::ptr::write_volatile(byte, 0) };
66    }
67    std::sync::atomic::compiler_fence(Ordering::SeqCst);
68}
69
70/// What the vault says about one concrete outgoing request.
71#[derive(Debug)]
72pub enum UseAnswer {
73    /// Key and location for this request only.
74    Released(ReleasedApiKey),
75    /// The vault is waiting for the user's answer.
76    ApprovalRequired(ApprovalRequest),
77    /// Uniform refusal: forwarding the literal placeholder reveals no key.
78    NotFound,
79    /// Transport, grammar, setup, and store failures never permit substitution.
80    Unavailable,
81}
82
83/// Why `audit` did not take a record.
84#[derive(Clone, PartialEq, Eq, Debug)]
85pub enum AuditError {
86    /// The record failed its key or scope check; the detail names the field,
87    /// never a value.
88    Invalid {
89        /// Which check failed, in plain text.
90        detail: String,
91    },
92    /// The sink could not be reached.
93    Unavailable {
94        /// Plain-text detail.
95        detail: String,
96    },
97}
98
99/// Request-addressed release and local audit reporting.
100///
101/// Both scopes are [`crate::secret::SecretScope`] values the daemon stamped,
102/// never tool arguments or session ids.
103pub trait SecretVault: Send + Sync {
104    /// Ask once for every outgoing request, including repeated requests after
105    /// approval. The vault audits uses and may rotate material between calls.
106    fn use_secret(
107        &self,
108        scope: &crate::secret::SecretScope,
109        label: &str,
110        target: &ApiKeyTarget,
111    ) -> UseAnswer;
112
113    /// Hand one record to the vault's audit sink.
114    fn audit(&self, record: &AuditRecordV1) -> Result<(), AuditError>;
115
116    /// Whether this vault can ever hand key bytes to AFT. A launch hardens the
117    /// process (no core dumps; non-dumpable on Linux) before talking to a vault
118    /// that can. The hardening is irreversible and on Linux costs the daemon
119    /// its own /proc counters, so a vault that never releases material skips it.
120    fn can_release_material(&self) -> bool {
121        true
122    }
123}
124
125/// Standalone processes have no attested AFT identity and cannot ask the vault.
126#[derive(Debug, Default, Clone, Copy)]
127pub struct UnavailableVault;
128
129impl SecretVault for UnavailableVault {
130    fn use_secret(
131        &self,
132        _scope: &crate::secret::SecretScope,
133        _label: &str,
134        _target: &ApiKeyTarget,
135    ) -> UseAnswer {
136        UseAnswer::Unavailable
137    }
138
139    fn audit(&self, _record: &AuditRecordV1) -> Result<(), AuditError> {
140        // The record's own checks already ran; there is simply nowhere to send
141        // it until the vault's shape is live. Count it rather than drop it.
142        UNRECORDED_AUDIT_RECORDS.fetch_add(1, Ordering::Relaxed);
143        Ok(())
144    }
145
146    fn can_release_material(&self) -> bool {
147        false
148    }
149}
150
151static UNRECORDED_AUDIT_RECORDS: AtomicU64 = AtomicU64::new(0);
152
153/// How many audit records the production vault accepted with no sink to write
154/// them to, so a future sink can report the gap instead of losing it.
155pub fn unrecorded_audit_records() -> u64 {
156    UNRECORDED_AUDIT_RECORDS.load(Ordering::Relaxed)
157}
158
159/// Milliseconds since the Unix epoch, for a record's `timestamp_ms`.
160pub fn now_ms() -> u64 {
161    SystemTime::now()
162        .duration_since(UNIX_EPOCH)
163        .map(|elapsed| elapsed.as_millis().min(u128::from(u64::MAX)) as u64)
164        .unwrap_or(0)
165}
166
167/// The transport one `secret.use` call travels on.
168///
169/// Production opens a scoped management-surface route to the vault module and
170/// carries the request envelope; tests install a fake. The request is the
171/// contract's `params`, so a transport never has to know the grammar.
172pub trait SecretUseTransport: Send + Sync {
173    /// Send `params` as a `secret.use` call and return the reply body: either
174    /// `{"result": …}` or an error object (§15, §1a).
175    fn secret_use(&self, params: serde_json::Value) -> Result<zeroize::Zeroizing<Vec<u8>>, String>;
176}
177
178/// The real client: `secret.use` over the daemon's transport (§15).
179///
180/// AFT is one of only two senders the vault admits, and it receives only API
181/// keys. Each reply belongs to the real target supplied with that call.
182pub struct SubcSecretVault {
183    transport: std::sync::Arc<dyn SecretUseTransport>,
184}
185
186impl std::fmt::Debug for SubcSecretVault {
187    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
188        f.debug_struct("SubcSecretVault").finish_non_exhaustive()
189    }
190}
191
192impl SubcSecretVault {
193    /// Build the client over `transport`.
194    pub fn new(transport: std::sync::Arc<dyn SecretUseTransport>) -> Self {
195        Self { transport }
196    }
197
198    /// Send one `secret.use` call for `label` and read the answer.
199    fn call(
200        &self,
201        scope: &crate::secret::SecretScope,
202        label: &str,
203        target: wire::Target,
204    ) -> Result<SecretUseAnswer, wire::ReplyError> {
205        let request = SecretUseRequest::new(label, scope.stamp(), target);
206        let body = self
207            .transport
208            .secret_use(request.to_params())
209            .map_err(|detail| wire::ReplyError::Malformed { detail })?;
210        super::wire_owned::parse(&body)
211    }
212}
213
214impl SecretVault for SubcSecretVault {
215    fn use_secret(
216        &self,
217        scope: &crate::secret::SecretScope,
218        label: &str,
219        target: &ApiKeyTarget,
220    ) -> UseAnswer {
221        match self.call(scope, label, wire::Target::ApiKey(target.clone())) {
222            Ok(SecretUseAnswer::Reply(SecretUseReply::ReleasedApiKey(key))) => {
223                UseAnswer::Released(key)
224            }
225            Ok(SecretUseAnswer::Reply(SecretUseReply::ApprovalRequired(request))) => {
226                UseAnswer::ApprovalRequired(request)
227            }
228            Ok(SecretUseAnswer::Refused(error)) if error.code == "not_found" => UseAnswer::NotFound,
229            _ => UseAnswer::Unavailable,
230        }
231    }
232
233    fn audit(&self, _record: &AuditRecordV1) -> Result<(), AuditError> {
234        // The contract has no AFT-facing sink yet; the production stand-in's
235        // counter is the honest record until one lands.
236        UNRECORDED_AUDIT_RECORDS.fetch_add(1, Ordering::Relaxed);
237        Ok(())
238    }
239}
240
241/// The fake vault, compiled only for tests or an explicitly feature-enabled
242/// build.
243#[cfg(any(any(test, feature = "test-support"), feature = "secret-test-fake"))]
244pub mod fake;