//! Sealing a secret's payload under the vault master key (spec §2.2).//!//! ```text//! seal(vmk, secret_id, vmk_version, payload)//! nonce = 12 random bytes//! ct = AES-256-GCM(vmk, nonce, payload, aad = secret_id || ":" || vmk_version)//! → "v2:" + base64url_nopad(nonce || ct)//! ```//!//! **The aad is the row's identity and the key's version**, and both halves//! earn their place. Binding to `secret_id` means a sealed value copied from one//! row into another does not open — a `cotton_secrets` row cannot be made to//! answer with somebody else's password by an edit to the `id` column. Binding//! to `vmk_version` means a value left behind by a rotation fails LOUDLY at the//! open rather than quietly decrypting under a key that was supposed to have//! been retired.//!//! **A legacy value is anything without the `v2:` prefix** — today's//! `base64:base64:base64` triple, written by the server under//! `COTTON_KEYS_SECRET`. [`is_legacy`] is the one classifier, and the server's//! one-time sweep is the one thing that reads one.use aes_gcm::aead::{Aead, Payload};use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engineas _;use rand::RngCore;use zeroize::{Zeroize, ZeroizeOnDrop};/// The prefix a sealed value carries.pubconst SEAL_PREFIX: &str = "v2:";const NONCE_LEN: usize = 12;const TAG_LEN: usize = 16;/// The vault master key, held in memory and wiped when it is dropped.////// Not `Clone`, not `Debug`, not `Serialize`: every one of those is a way for/// 32 bytes that are never supposed to be written down to end up in a log line/// or a second allocation nobody zeroises.#[derive(ZeroizeOnDrop)]pubstructVmk([u8; 32]);implVmk {/// A fresh vault master key, from the OS. This is minted ONCE per workspace/// and once more per rotation.pubfn mint() -> Vmk {letmut bytes = [0u8; 32]; rand::rngs::OsRng.fill_bytes(&mut bytes);Vmk(bytes) }/// The key as it came back out of a wrap.pubfn from_bytes(bytes: [u8; 32]) -> Vmk {Vmk(bytes) }/// The key as it goes INTO a wrap, and nowhere else. The slice borrows the/// key rather than copying it.pubfn expose(&self) -> &[u8; 32] { &self.0 }}impl std::fmt::DebugforVmk {/// Never the bytes. A `{:?}` on a struct holding one of these is how a key/// ends up in a crash report.fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("Vmk(…)") }}/// Seal one payload for one row, under one version of the key.////// The nonce comes from the OS; [`seal_with`] takes it, which is what the/// vectors use.pubfn seal(vmk: &Vmk, secret_id: &str, vmk_version: u32, payload: &[u8]) -> Option<String> {letmut nonce = [0u8; NONCE_LEN]; rand::rngs::OsRng.fill_bytes(&mut nonce); seal_with(&nonce, vmk, secret_id, vmk_version, payload)}/// [`seal`] with the nonce supplied.pubfn seal_with( nonce: &[u8; NONCE_LEN], vmk: &Vmk, secret_id: &str, vmk_version: u32, payload: &[u8],) -> Option<String> {let aad = associated_data(secret_id, vmk_version);let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(vmk.expose()));let ciphertext = cipher .encrypt(Nonce::from_slice(nonce),Payload { msg: payload, aad: aad.as_bytes(), }, ) .ok()?;letmut body = Vec::with_capacity(NONCE_LEN + ciphertext.len()); body.extend_from_slice(nonce); body.extend_from_slice(&ciphertext);Some(format!("{SEAL_PREFIX}{}", URL_SAFE_NO_PAD.encode(body)))}/// Open a sealed value. `None` for a wrong key, a wrong row, a wrong version, a/// tampered body or a value that is not sealed at all — the caller does the/// same thing in every case, and telling them apart would be an oracle.pubfn open(vmk: &Vmk, secret_id: &str, vmk_version: u32, sealed: &str) -> Option<Vec<u8>> {let body = URL_SAFE_NO_PAD .decode(sealed.strip_prefix(SEAL_PREFIX)?) .ok()?;if body.len() < NONCE_LEN + TAG_LEN {returnNone; }let aad = associated_data(secret_id, vmk_version);let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(vmk.expose())); cipher .decrypt(Nonce::from_slice(&body[..NONCE_LEN]),Payload { msg: &body[NONCE_LEN..], aad: aad.as_bytes(), }, ) .ok()}/// Is this value one the OLD scheme wrote?////// The ONE classifier, so "which scheme is this row under" is asked in one/// place. A row whose `value_enc` answers true is what the server's one-time/// re-seal sweep looks for, and what the page shows as *sealed under the old/// key*. An absent value is not legacy: there is nothing to re-seal.pubfn is_legacy(value_enc: &str) -> bool { !value_enc.is_empty() && !value_enc.starts_with(SEAL_PREFIX)}fn associated_data(secret_id: &str, vmk_version: u32) -> String { format!("{secret_id}:{vmk_version}")}/// Wipe a payload a caller is done with — the plaintext JSON of a secret, on/// its way out of memory.pubfn wipe(mut payload: Vec<u8>) { payload.zeroize();}#[cfg(test)]#[path = "seal_tests.rs"]mod tests;