capsule_core/crypto/encryption/rekey.rs
1//! Re-keying on rewrite — the writers that fold a fresh nonce into the key salt so a
2//! same-epoch rewrite re-rolls **both** the key and the nonce, and refuse to reuse the
3//! nonce of the record they supersede.
4//!
5//! A [`replace`] keeps a file's `file_id` and can land in the *same* AMK epoch as the bytes
6//! it supersedes; a `metadata-update` keeps a blob's `blob_id`. Because the fresh
7//! `nonce_prefix` / blob `nonce` is folded into the key salt
8//! ([`Amk::derive_file_key`] / [`Amk::derive_blob_key`]), re-encrypting byte-identical
9//! plaintext under the same id and epoch yields a different key, a different nonce, and
10//! different ciphertext — so AES-GCM nonce reuse is structurally impossible.
11//!
12//! These writers **couple the nonce draw to derivation** (the salt depends on the nonce, so
13//! the two cannot be separated) and add the defense-in-depth check that a freshly drawn
14//! nonce never equals the one being replaced (on top of the CSPRNG draw). A first write
15//! passes `replaces = None`; a rewrite passes the superseded nonce. SSoT: [Encryption §
16//! Re-keying on Rewrite].
17//!
18//! [`replace`]: https://docs/design/cryptography/encryption/#re-keying-on-rewrite
19//! [Encryption § Re-keying on Rewrite]: https://docs/design/cryptography/encryption/#re-keying-on-rewrite
20
21use std::io::{Read, Write};
22
23use thiserror::Error;
24use uuid::Uuid;
25
26use super::blob::{NONCE_LEN, seal_blob_with_nonce};
27use super::stream::{AssetEncryption, NONCE_PREFIX_LEN, StreamError, encrypt_asset_with_prefix};
28use crate::crypto::keys::Amk;
29use crate::crypto::{CryptoError, rng};
30
31/// Encrypt `plaintext` as a first or re-rolled asset write under `amk` scoped to `file_id`:
32/// draw a fresh `nonce_prefix`, fold it into the file-key salt, and STREAM-encrypt.
33///
34/// `replaces` is the `nonce_prefix` of the version being superseded (a same-epoch
35/// [`replace`]), if any; the writer refuses to emit that exact prefix again. Returns the
36/// [`AssetEncryption`] metadata, the ciphertext, and the derived file key.
37///
38/// [`replace`]: https://docs/design/cryptography/encryption/#re-keying-on-rewrite
39pub fn encrypt_asset_rekey(
40 amk: &Amk,
41 file_id: &Uuid,
42 plaintext: &[u8],
43 replaces: Option<[u8; NONCE_PREFIX_LEN]>,
44) -> Result<(AssetEncryption, Vec<u8>, [u8; 32]), CryptoError> {
45 encrypt_asset_rekey_with_prefix(
46 amk,
47 file_id,
48 plaintext,
49 rng::random_array::<NONCE_PREFIX_LEN>(),
50 replaces,
51 )
52}
53
54/// [`encrypt_asset_rekey`] with an explicit `nonce_prefix` — the deterministic, testable
55/// core of the fold and the reuse refusal.
56pub fn encrypt_asset_rekey_with_prefix(
57 amk: &Amk,
58 file_id: &Uuid,
59 plaintext: &[u8],
60 nonce_prefix: [u8; NONCE_PREFIX_LEN],
61 replaces: Option<[u8; NONCE_PREFIX_LEN]>,
62) -> Result<(AssetEncryption, Vec<u8>, [u8; 32]), CryptoError> {
63 let mut ciphertext = Vec::new();
64 match encrypt_asset_rekey_stream_with_prefix(
65 amk,
66 file_id,
67 plaintext,
68 &mut ciphertext,
69 nonce_prefix,
70 replaces,
71 ) {
72 Ok((enc, file_key)) => Ok((enc, ciphertext, file_key)),
73 Err(RekeyStreamError::Crypto(error)) => Err(error),
74 // A slice reader and a `Vec` writer cannot fail, and every chunk is under 64 KiB, so
75 // AES-GCM cannot refuse one either.
76 Err(RekeyStreamError::Stream(error)) => {
77 unreachable!("in-memory STREAM encryption is infallible: {error}")
78 }
79 }
80}
81
82/// Why a streaming re-keyed write failed: the reuse refusal, or the reader or writer.
83#[derive(Debug, Error)]
84pub enum RekeyStreamError {
85 /// The re-keying refusal ([`CryptoError::NonceReuse`]), raised before any byte is read.
86 #[error(transparent)]
87 Crypto(#[from] CryptoError),
88 /// The plaintext reader or the ciphertext writer failed part-way.
89 #[error(transparent)]
90 Stream(#[from] StreamError),
91}
92
93/// [`encrypt_asset_rekey`] from a reader to a writer, one STREAM chunk at a time: the same
94/// prefix draw, key fold and reuse refusal, without the plaintext or the ciphertext ever
95/// being whole in memory. Returns the [`AssetEncryption`] metadata (whose `ciphertext_hash` is
96/// computed as the chunks pass) and the derived file key.
97///
98/// This is how an original of any size is imported: the writer may be [`std::io::sink`],
99/// since the ciphertext is re-derivable from the plaintext and the recorded prefix.
100pub fn encrypt_asset_rekey_stream<R: Read, W: Write>(
101 amk: &Amk,
102 file_id: &Uuid,
103 reader: R,
104 writer: W,
105 replaces: Option<[u8; NONCE_PREFIX_LEN]>,
106) -> Result<(AssetEncryption, [u8; 32]), RekeyStreamError> {
107 encrypt_asset_rekey_stream_with_prefix(
108 amk,
109 file_id,
110 reader,
111 writer,
112 rng::random_array::<NONCE_PREFIX_LEN>(),
113 replaces,
114 )
115}
116
117/// [`encrypt_asset_rekey_stream`] with an explicit `nonce_prefix` — the one implementation of
118/// the fold and the reuse refusal, which [`encrypt_asset_rekey_with_prefix`] drives over a
119/// slice, so the two cannot produce different bytes.
120pub fn encrypt_asset_rekey_stream_with_prefix<R: Read, W: Write>(
121 amk: &Amk,
122 file_id: &Uuid,
123 reader: R,
124 writer: W,
125 nonce_prefix: [u8; NONCE_PREFIX_LEN],
126 replaces: Option<[u8; NONCE_PREFIX_LEN]>,
127) -> Result<(AssetEncryption, [u8; 32]), RekeyStreamError> {
128 if replaces == Some(nonce_prefix) {
129 return Err(CryptoError::NonceReuse.into());
130 }
131 let file_key = amk.derive_file_key(file_id, &nonce_prefix);
132 let enc = encrypt_asset_with_prefix(&file_key, nonce_prefix, reader, writer)?;
133 Ok((enc, file_key))
134}
135
136/// Seal `plaintext` (canonical CBOR sidecar) into a metadata blob under `amk` scoped to
137/// `blob_id`: draw a fresh blob `nonce`, fold it into the blob-key salt, and AEAD-seal.
138///
139/// `replaces` is the prior blob's `nonce` on a `metadata-update`, refused if drawn again.
140/// Returns the wire bytes and the derived blob key (for the immediate binding self-check).
141pub fn seal_metadata_blob(
142 amk: &Amk,
143 blob_id: &Uuid,
144 plaintext: &[u8],
145 replaces: Option<[u8; NONCE_LEN]>,
146) -> Result<(Vec<u8>, [u8; 32]), CryptoError> {
147 seal_metadata_blob_with_nonce(
148 amk,
149 blob_id,
150 plaintext,
151 rng::random_array::<NONCE_LEN>(),
152 replaces,
153 )
154}
155
156/// [`seal_metadata_blob`] with an explicit `nonce` — the deterministic, testable core.
157pub fn seal_metadata_blob_with_nonce(
158 amk: &Amk,
159 blob_id: &Uuid,
160 plaintext: &[u8],
161 nonce: [u8; NONCE_LEN],
162 replaces: Option<[u8; NONCE_LEN]>,
163) -> Result<(Vec<u8>, [u8; 32]), CryptoError> {
164 if replaces == Some(nonce) {
165 return Err(CryptoError::NonceReuse);
166 }
167 let blob_key = amk.derive_blob_key(blob_id, &nonce);
168 let wire = seal_blob_with_nonce(&blob_key, nonce, plaintext);
169 Ok((wire, blob_key))
170}
171
172#[cfg(test)]
173mod tests;