keep_core/secret.rs
1// SPDX-FileCopyrightText: © 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3//! Arbitrary-secret records (passwords, API tokens, notes) stored in the vault
4//! alongside curve-key records.
5//!
6//! The vault below the record model is already secret-agnostic: the storage
7//! backend is a plain encrypted key-value store and [`crate::crypto`] encrypts
8//! arbitrary bytes, so storing generic secrets is an additive extension rather
9//! than a new subsystem. A [`SecretRecord`] is bincode-serialized as a whole --
10//! name, kind, AND the plaintext value -- then encrypted under the vault data
11//! key at rest (see [`crate::storage::Storage::store_secret`]), so entry titles
12//! are encrypted, not just the value. The plaintext `value` exists decrypted
13//! only in memory and is scrubbed on drop.
14
15use serde::{Deserialize, Serialize};
16use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
17
18use crate::crypto::{self, EncryptedData, SecretKey};
19use crate::entropy;
20use crate::error::Result;
21
22/// Category of a stored secret. Additive: only APPEND new variants, so a record
23/// written by an older build keeps decoding under bincode's integer tag.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25pub enum SecretKind {
26 /// A login password.
27 Password,
28 /// An API token or other bearer credential.
29 ApiToken,
30 /// A free-form secret note.
31 Note,
32 /// Any other secret material that does not fit the categories above.
33 Generic,
34}
35
36/// A stored arbitrary secret sitting alongside curve-key records in the vault.
37///
38/// Unlike [`crate::keys::KeyRecord`], whose `id` is derived from a public key
39/// (stable identity and dedup for free), a secret has no public key, so `id` is
40/// random. Importing the same secret twice therefore creates two distinct rows.
41/// This is intended for a password store, where two logins can legitimately
42/// share one value; callers that need dedup must do it themselves.
43///
44/// Every field except the identity/metadata is zeroized on drop. `id`, `kind`,
45/// and the timestamps are not secret and are skipped; `name` and `value` are
46/// scrubbed because an entry title reveals what the secret is for.
47#[derive(Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
48pub struct SecretRecord {
49 /// Random 32-byte identifier (a secret has no pubkey to derive one from),
50 /// used as the storage key.
51 #[zeroize(skip)]
52 pub id: [u8; 32],
53 /// Human-readable title (e.g. "GitHub login"). Sensitive: encrypted at rest
54 /// with the value, and scrubbed from memory on drop.
55 pub name: String,
56 /// Category of secret.
57 #[zeroize(skip)]
58 pub kind: SecretKind,
59 /// The plaintext secret bytes. Encrypted at rest via the record's outer
60 /// encryption; held decrypted only in memory and scrubbed on drop.
61 pub value: Vec<u8>,
62 /// Unix timestamp when the secret was created.
63 #[zeroize(skip)]
64 pub created_at: i64,
65 /// Unix timestamp of the last update.
66 #[zeroize(skip)]
67 pub updated_at: i64,
68}
69
70impl SecretRecord {
71 /// Create a new secret record with a fresh random id and `created_at ==
72 /// updated_at == now`. Returns `Err` (rather than panicking) if the CSPRNG
73 /// health check fails, so a broken RNG cannot crash the process here.
74 pub fn new(name: String, kind: SecretKind, value: Vec<u8>) -> Result<Self> {
75 let id: [u8; 32] = entropy::try_random_bytes()?;
76 let now = chrono::Utc::now().timestamp();
77 Ok(Self {
78 id,
79 name,
80 kind,
81 value,
82 created_at: now,
83 updated_at: now,
84 })
85 }
86}
87
88/// The threshold seal that gates a secret's VALUE behind a t-of-n OPRF quorum.
89///
90/// The value is encrypted under a fresh random per-secret data-encryption key
91/// (DEK); the DEK is itself encrypted ("wrapped") under the OPRF-quorum-derived
92/// key ([`crate::oprf::derive_luks_key`]). Recovering the plaintext therefore
93/// requires re-deriving the OPRF key, which needs a t-of-n quorum of devices --
94/// a single device that never assembles the quorum cannot decrypt the value even
95/// with the vault unlocked. Only the value is gated; a secret's name and kind
96/// stay readable with the vault data key so the store remains browsable.
97///
98/// `wrapped_dek` is ciphertext, so the seal is not itself secret, but it is
99/// stored encrypted under the vault data key at rest like every other record.
100#[derive(Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
101pub struct ThresholdSeal {
102 /// The per-secret DEK, encrypted under the OPRF-quorum-derived key
103 /// ([`EncryptedData::to_bytes`] output).
104 pub wrapped_dek: Vec<u8>,
105 /// OPRF domain-separation label fed to `derive_luks_key` (the secret id, hex),
106 /// so the quorum re-derives the same key for this secret.
107 #[zeroize(skip)]
108 pub oprf_id: String,
109 /// OPRF epoch: the rotation counter for the derived key, bumped to re-seal a
110 /// secret under a fresh key without changing the OPRF root.
111 #[zeroize(skip)]
112 pub epoch: u32,
113}
114
115impl std::fmt::Debug for ThresholdSeal {
116 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117 f.debug_struct("ThresholdSeal")
118 .field("oprf_id", &self.oprf_id)
119 .field("epoch", &self.epoch)
120 .field("wrapped_dek", &"[wrapped]")
121 .finish()
122 }
123}
124
125/// AAD binding the wrapped DEK to its secret id and OPRF epoch, so a wrapped DEK
126/// cannot be lifted onto a different secret or a tampered epoch: altering the
127/// stored `oprf_id`/`epoch` (which an attacker holding the vault data key could
128/// otherwise do to redirect the quorum query) makes the unwrap fail rather than
129/// silently succeed. Length-prefixed for injectivity, matching `derive_luks_key`.
130fn wrap_aad(oprf_id: &str, epoch: u32) -> Vec<u8> {
131 let mut aad = Vec::with_capacity(23 + 8 + oprf_id.len() + 4);
132 aad.extend_from_slice(b"keep/secret-seal/dek/v1");
133 aad.extend_from_slice(&(oprf_id.len() as u64).to_be_bytes());
134 aad.extend_from_slice(oprf_id.as_bytes());
135 aad.extend_from_slice(&epoch.to_be_bytes());
136 aad
137}
138
139/// AAD binding the value ciphertext to its secret id, so a value blob cannot be
140/// swapped between secrets.
141fn value_aad(oprf_id: &str) -> Vec<u8> {
142 let mut aad = Vec::with_capacity(25 + oprf_id.len());
143 aad.extend_from_slice(b"keep/secret-seal/value/v1");
144 aad.extend_from_slice(oprf_id.as_bytes());
145 aad
146}
147
148/// Seal `plaintext` under a fresh per-secret DEK and wrap that DEK under
149/// `oprf_key` (the t-of-n OPRF-quorum-derived key). Returns the value ciphertext
150/// (to store as the record's `value`) and the matching [`ThresholdSeal`] (to
151/// store alongside). `oprf_id`/`epoch` are recorded in the seal so the quorum can
152/// later re-derive the same key, and are bound into both ciphertexts as AAD.
153pub fn seal_value(
154 plaintext: &[u8],
155 oprf_key: &SecretKey,
156 oprf_id: String,
157 epoch: u32,
158) -> Result<(Vec<u8>, ThresholdSeal)> {
159 let dek = SecretKey::generate()?;
160 let value_ciphertext =
161 crypto::encrypt_with_aad(plaintext, &value_aad(&oprf_id), &dek)?.to_bytes();
162 // Wrap the raw DEK bytes under the OPRF key. `decrypt` returns an mlocked,
163 // zeroize-on-drop copy of the 32 DEK bytes.
164 let dek_raw = dek.decrypt()?;
165 let wrapped_dek =
166 crypto::encrypt_with_aad(&dek_raw[..], &wrap_aad(&oprf_id, epoch), oprf_key)?.to_bytes();
167 Ok((
168 value_ciphertext,
169 ThresholdSeal {
170 wrapped_dek,
171 oprf_id,
172 epoch,
173 },
174 ))
175}
176
177/// Recover a sealed secret's plaintext from `value_ciphertext` given its
178/// [`ThresholdSeal`] and the OPRF-quorum-derived key. Fails if `oprf_key` is
179/// wrong (a single-device caller that never assembled the quorum cannot derive
180/// it) or if the seal's bound `oprf_id`/`epoch` were tampered with: either way
181/// the AEAD tag check fails and the value stays sealed.
182pub fn unseal_value(
183 value_ciphertext: &[u8],
184 seal: &ThresholdSeal,
185 oprf_key: &SecretKey,
186) -> Result<Zeroizing<Vec<u8>>> {
187 let wrapped = EncryptedData::from_bytes(&seal.wrapped_dek)?;
188 let dek_bytes =
189 crypto::decrypt_with_aad(&wrapped, &wrap_aad(&seal.oprf_id, seal.epoch), oprf_key)?
190 .as_slice()?;
191 let dek = SecretKey::from_slice(&dek_bytes)?;
192 let value = EncryptedData::from_bytes(value_ciphertext)?;
193 crypto::decrypt_with_aad(&value, &value_aad(&seal.oprf_id), &dek)?.as_slice()
194}
195
196impl std::fmt::Debug for SecretRecord {
197 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198 // Never print `name` or `value`: both are secret. `name` leaks what the
199 // secret is for; `value` is the secret itself.
200 f.debug_struct("SecretRecord")
201 .field("id", &hex::encode(self.id))
202 .field("kind", &self.kind)
203 .field("name", &"[REDACTED]")
204 .field("value", &"[REDACTED]")
205 .field("created_at", &self.created_at)
206 .field("updated_at", &self.updated_at)
207 .finish()
208 }
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214
215 #[test]
216 fn new_mints_a_random_id_and_equal_timestamps() {
217 let a = SecretRecord::new("x".into(), SecretKind::Password, b"v".to_vec()).unwrap();
218 let b = SecretRecord::new("x".into(), SecretKind::Password, b"v".to_vec()).unwrap();
219 assert_ne!(a.id, b.id, "each secret gets a fresh random id");
220 assert_eq!(a.created_at, a.updated_at);
221 }
222
223 #[test]
224 fn seal_then_unseal_roundtrips_with_the_same_key() {
225 let oprf_key = SecretKey::generate().unwrap();
226 let (ct, seal) = seal_value(b"top-secret", &oprf_key, "abcd".into(), 0).unwrap();
227 assert_ne!(ct, b"top-secret", "value must be encrypted, not stored raw");
228 let plaintext = unseal_value(&ct, &seal, &oprf_key).unwrap();
229 assert_eq!(&plaintext[..], b"top-secret");
230 assert_eq!(seal.oprf_id, "abcd");
231 assert_eq!(seal.epoch, 0);
232 }
233
234 /// The core threshold property: without the quorum-derived key (a single
235 /// device that never assembled t-of-n), the wrapped DEK cannot be recovered,
236 /// so the value stays sealed.
237 #[test]
238 fn unseal_fails_with_a_different_oprf_key() {
239 let oprf_key = SecretKey::generate().unwrap();
240 let wrong_key = SecretKey::generate().unwrap();
241 let (ct, seal) = seal_value(b"top-secret", &oprf_key, "abcd".into(), 0).unwrap();
242 assert!(
243 unseal_value(&ct, &seal, &wrong_key).is_err(),
244 "unsealing with the wrong OPRF key must fail"
245 );
246 }
247
248 /// The seal's `oprf_id`/`epoch` are bound as AAD, so tampering with either
249 /// (an attacker with the vault data key redirecting the quorum query) makes
250 /// the unseal fail rather than silently proceed.
251 #[test]
252 fn unseal_fails_when_bound_oprf_params_are_tampered() {
253 let oprf_key = SecretKey::generate().unwrap();
254 let (ct, seal) = seal_value(b"v", &oprf_key, "abcd".into(), 0).unwrap();
255
256 let mut bad_epoch = seal.clone();
257 bad_epoch.epoch = 1;
258 assert!(
259 unseal_value(&ct, &bad_epoch, &oprf_key).is_err(),
260 "a tampered epoch must break the wrapped-DEK AAD"
261 );
262
263 let mut bad_id = seal.clone();
264 bad_id.oprf_id = "ffff".into();
265 assert!(
266 unseal_value(&ct, &bad_id, &oprf_key).is_err(),
267 "a tampered oprf_id must break the AAD"
268 );
269 }
270
271 #[test]
272 fn each_seal_uses_a_distinct_dek() {
273 let oprf_key = SecretKey::generate().unwrap();
274 let (_, seal_a) = seal_value(b"v", &oprf_key, "a".into(), 0).unwrap();
275 let (_, seal_b) = seal_value(b"v", &oprf_key, "b".into(), 0).unwrap();
276 assert_ne!(
277 seal_a.wrapped_dek, seal_b.wrapped_dek,
278 "each secret must get a fresh random DEK"
279 );
280 }
281
282 #[test]
283 fn threshold_seal_debug_never_leaks_wrapped_dek() {
284 let oprf_key = SecretKey::generate().unwrap();
285 let (_, seal) = seal_value(b"v", &oprf_key, "abcd".into(), 3).unwrap();
286 let s = format!("{seal:?}");
287 assert!(s.contains("abcd") && s.contains('3'));
288 assert!(!s.contains(&hex::encode(&seal.wrapped_dek)));
289 }
290
291 #[test]
292 fn debug_never_leaks_name_or_value() {
293 let rec = SecretRecord::new(
294 "GitHub login".into(),
295 SecretKind::Password,
296 b"hunter2".to_vec(),
297 )
298 .unwrap();
299 let s = format!("{rec:?}");
300 assert!(!s.contains("GitHub login"), "name must be redacted: {s}");
301 assert!(!s.contains("hunter2"), "value must be redacted: {s}");
302 assert!(s.contains("[REDACTED]"));
303 }
304}