Skip to main content

capsule_core/crypto/keys/
album.rs

1//! Album Master Keys (AMKs) and per-file/blob key derivation.
2//!
3//! Each album is an MLS group; its content key is a **random 32-byte AMK minted per
4//! epoch** (`AMK_v{n}`) — never derived from MLS ratchet state. Per-file and per-blob
5//! keys are derived from the AMK via HKDF-SHA512 with a scope-unique salt (the file/blob
6//! UUID with the write's fresh nonce folded in, so a same-id rewrite re-rolls the key) and
7//! a versioned label (SSoT: [Cryptography — Keys § Album Master Keys] and
8//! [Encryption § Asset Key Derivation]).
9//!
10//! [Cryptography — Keys § Album Master Keys]: https://docs/design/cryptography/keys/#album-master-keys-amks
11//! [Encryption § Asset Key Derivation]: https://docs/design/cryptography/encryption/#asset-key-derivation
12
13use serde::{Deserialize, Serialize};
14use uuid::Uuid;
15
16use crate::crypto::primitives::info;
17use crate::crypto::{kdf, rng};
18
19/// The monotonic epoch identifier for an AMK (`amk_version`).
20#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
21pub struct AmkVersion(pub u32);
22
23impl AmkVersion {
24    /// The first epoch minted at album creation.
25    pub const FIRST: AmkVersion = AmkVersion(1);
26
27    /// The next epoch after this one.
28    pub fn next(self) -> AmkVersion {
29        AmkVersion(self.0 + 1)
30    }
31}
32
33/// A random 32-byte album content key for one epoch. Holding it lets you decrypt; not
34/// holding it means you cannot (secrecy is enforced by encryption, authorization by
35/// signatures — see [`HybridSigningKey`](super::HybridSigningKey) write-tier keys).
36#[derive(Clone)]
37pub struct Amk([u8; 32]);
38
39impl Amk {
40    /// Mint a fresh random AMK for a new epoch.
41    pub fn generate() -> Self {
42        Self(rng::random_array::<32>())
43    }
44
45    /// Wrap raw AMK bytes (e.g. from the escrowed ledger).
46    pub fn from_bytes(bytes: [u8; 32]) -> Self {
47        Self(bytes)
48    }
49
50    /// Borrow the raw bytes (for escrow into the backup AMK ledger).
51    pub fn as_bytes(&self) -> &[u8; 32] {
52        &self.0
53    }
54
55    /// Derive the per-file AES-256 key:
56    /// `HKDF(ikm=AMK, salt=file_id || nonce_prefix, info="asset-file/v1")`.
57    ///
58    /// The fresh `nonce_prefix` drawn for *this* encryption is folded into the salt, so a
59    /// same-epoch [`replace`] (constant `file_id`) re-rolls the **key**, not merely the
60    /// nonce — no `(file_key, nonce_prefix)` pair is ever reused, which is what lets the
61    /// STREAM counter safely start at zero. The re-keying writers in
62    /// `crypto::encryption`'s re-keying writers draw the nonce and derive together (the salt
63    /// depends on the nonce). SSoT: [Encryption § Asset Key Derivation].
64    ///
65    /// [`replace`]: https://docs/design/cryptography/encryption/#re-keying-on-rewrite
66    /// [Encryption § Asset Key Derivation]: https://docs/design/cryptography/encryption/#asset-key-derivation
67    pub fn derive_file_key(&self, file_id: &Uuid, nonce_prefix: &[u8]) -> [u8; 32] {
68        derive_scoped(&self.0, file_id, nonce_prefix, info::ASSET_FILE_V1)
69    }
70
71    /// Derive the per-metadata-blob AES-256 key:
72    /// `HKDF(ikm=AMK, salt=blob_id || nonce, info="metadata-blob/v1")`.
73    ///
74    /// The blob's fresh 12-byte `nonce` is folded into the salt, so the key is re-derived
75    /// per write even though `blob_id` (the asset id) is constant across a `metadata-update`.
76    pub fn derive_blob_key(&self, blob_id: &Uuid, nonce: &[u8]) -> [u8; 32] {
77        derive_scoped(&self.0, blob_id, nonce, info::METADATA_BLOB_V1)
78    }
79
80    /// Derive the AES-256 key that wraps an externally-chosen file key `K` for an adopted
81    /// [web-upload drop](https://docs/design/web-upload/) (`key_mode = wrapped`):
82    /// `HKDF(ikm=AMK, salt=file_id || wrap_nonce, info="asset-keywrap/v1")`.
83    ///
84    /// The fresh `wrap_nonce` is folded into the salt exactly as `nonce_prefix` is for a
85    /// derived file key, so no `(wrap_key, wrap_nonce)` pair repeats even under a constant
86    /// `file_id`. Used only by the keywrap seal/unseal path
87    /// ([`crate::crypto::encryption::seal_file_key`]).
88    pub fn derive_wrap_key(&self, file_id: &Uuid, wrap_nonce: &[u8]) -> [u8; 32] {
89        derive_scoped(&self.0, file_id, wrap_nonce, info::ASSET_KEYWRAP_V1)
90    }
91}
92
93/// Derive a 32-byte key salted on `id || fold`, the shared shape of every per-scope key
94/// (file, blob, wrap): the scope UUID gives domain separation and the folded fresh nonce
95/// makes the salt unique per write, so no `(key, nonce)` pair repeats.
96fn derive_scoped(ikm: &[u8; 32], id: &Uuid, fold: &[u8], info: &[u8]) -> [u8; 32] {
97    let mut salt = Vec::with_capacity(id.as_bytes().len() + fold.len());
98    salt.extend_from_slice(id.as_bytes());
99    salt.extend_from_slice(fold);
100    kdf::derive_key32(ikm, &salt, info)
101}
102
103impl std::fmt::Debug for Amk {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        f.write_str("Amk(****)")
106    }
107}
108
109#[cfg(test)]
110mod tests;