← back to the page

crates/platform-storage/src/sealed.rs

the vault: how R2 objects are sealed · 181 lines · compiled into this Worker from the repository as it is

1//! Files sealed at rest in R2 (e.g. ytdl's downloads).
2//!
3//! R2 never sees a file, its name or what it was:
4//! - Objects are `f/<owner>/<id>` (the manifest) and `f/<owner>/<id>.<n>`
5//! (the chunks): the owner tag is a keyed hash ([`crate::owner_tag`]),
6//! the ID random.
7//! - Chunks are [`CHUNK`] bytes of AES-256-GCM, each bound by its AAD to the
8//! object name, so chunks can't be reordered or moved between files.
9//! - The manifest's body is the sealed [`FileMeta`] (name, type, length,
10//! chunk count), written last: a file without one is unfinished.
11//! - Records ([`Keys::seal_record`]): an owner's small named blobs, kept
12//! where the app likes (e.g. Durable Object storage).
13//!
14//! Keys: HKDF-SHA-512 of the app's `DATA_KEY`, then one key per owner, so
15//! one account's key opens no other account's files.
16
17use aes_gcm::aead::{Aead, KeyInit, Payload};
18use aes_gcm::{Aes256Gcm, Nonce};
19use hkdf::Hkdf;
20use hmac::{Hmac, Mac};
21use serde::{Deserialize, Serialize};
22use sha2::{Sha256, Sha512};
23
24/// Plaintext bytes per chunk.
25pub const CHUNK: usize = 4 * 1024 * 1024;
26/// Largest file kept.
27pub const MAX_FILE: u64 = 2 * 1024 * 1024 * 1024;
28
29/// Bytes of nonce before each sealed body, and of tag after it.
30pub const NONCE: usize = 12;
31pub const TAG: usize = 16;
32const SALT: &[u8] = b"platform-storage/sealed/v1";
33const AAD_META: &[u8] = b"platform-storage/sealed/v1/meta\0";
34const AAD_CHUNK: &[u8] = b"platform-storage/sealed/v1/chunk\0";
35const AAD_RECORD: &[u8] = b"platform-storage/sealed/v1/record\0";
36/// Largest sealed record.
37pub const MAX_RECORD: usize = 1024 * 1024;
38
39/// What a sealed file is, kept sealed in its manifest.
40#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
41pub struct FileMeta {
42 /// File name for the download (e.g. the video's title).
43 pub name: String,
44 /// Content type.
45 pub ct: String,
46 /// Length in bytes (before sealing).
47 pub len: u64,
48 /// Number of chunks.
49 pub chunks: u32,
50 /// When it was stored, ms since the epoch.
51 pub created_ms: u64,
52 /// Where it came from (e.g. the page URL).
53 #[serde(default)]
54 pub source: String,
55 /// The app's own JSON about the file (e.g. a video's title and channel).
56 #[serde(default, skip_serializing_if = "String::is_empty")]
57 pub info: String,
58}
59
60/// Chunks needed for `len` bytes (at least one, so empty files exist).
61pub fn chunk_count(len: u64) -> u32 {
62 len.div_ceil(CHUNK as u64).max(1) as u32
63}
64
65/// Every object of an owner's files starts with this.
66pub fn owner_prefix(owner: &str) -> String {
67 format!("f/{owner}/")
68}
69
70/// The manifest's object name.
71pub fn manifest_name(owner: &str, id: &str) -> String {
72 format!("f/{owner}/{id}")
73}
74
75/// Chunk `n`'s object name.
76pub fn chunk_name(owner: &str, id: &str, n: u32) -> String {
77 format!("f/{owner}/{id}.{n}")
78}
79
80/// The file ID of a manifest's object name (`None` for chunks and others).
81pub fn manifest_id<'a>(owner: &str, object: &'a str) -> Option<&'a str> {
82 let id = object.strip_prefix(&owner_prefix(owner))?;
83 crate::is_hex(id, 32).then_some(id)
84}
85
86/// A fresh random file ID (32 hex digits).
87pub fn new_id() -> String {
88 let mut b = [0u8; 16];
89 getrandom::getrandom(&mut b).expect("random id");
90 hex::encode(b)
91}
92
93/// The app's file keys, from its `DATA_KEY`.
94#[derive(Clone)]
95pub struct Keys {
96 root: [u8; 32],
97}
98
99impl Keys {
100 pub fn new(data_key: &[u8]) -> Self {
101 let mut root = [0u8; 32];
102 Hkdf::<Sha512>::new(Some(SALT), data_key).expand(b"files", &mut root).expect("32 bytes is a valid HKDF-SHA-512 length");
103 Self { root }
104 }
105
106 /// From a hex secret of at least 32 bytes (a `secret_text` binding).
107 pub fn from_hex(hex_secret: &str) -> Option<Self> {
108 let raw = hex::decode(hex_secret.trim()).ok()?;
109 (raw.len() >= 32).then(|| Self::new(&raw))
110 }
111
112 fn owner_key(&self, owner: &str) -> [u8; 32] {
113 let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(&self.root).expect("hmac accepts any key");
114 mac.update(b"owner\0");
115 mac.update(owner.as_bytes());
116 mac.finalize().into_bytes().into()
117 }
118
119 pub fn seal_meta(&self, owner: &str, id: &str, meta: &FileMeta) -> Vec<u8> {
120 let json = serde_json::to_vec(meta).expect("meta serializes");
121 seal(&self.owner_key(owner), &aad(AAD_META, &manifest_name(owner, id)), &json)
122 }
123
124 pub fn open_meta(&self, owner: &str, id: &str, sealed: &[u8]) -> Option<FileMeta> {
125 if sealed.len() > 64 * 1024 {
126 return None;
127 }
128 serde_json::from_slice(&open(&self.owner_key(owner), &aad(AAD_META, &manifest_name(owner, id)), sealed)?).ok()
129 }
130
131 pub fn seal_chunk(&self, owner: &str, id: &str, n: u32, body: &[u8]) -> Vec<u8> {
132 seal(&self.owner_key(owner), &aad(AAD_CHUNK, &chunk_name(owner, id, n)), body)
133 }
134
135 pub fn open_chunk(&self, owner: &str, id: &str, n: u32, sealed: &[u8]) -> Option<Vec<u8>> {
136 if sealed.len() > CHUNK + NONCE + TAG {
137 return None;
138 }
139 open(&self.owner_key(owner), &aad(AAD_CHUNK, &chunk_name(owner, id, n)), sealed)
140 }
141
142 /// An owner's small record `name` (e.g. a watch history), wherever the
143 /// app keeps it: bound to the owner and the name.
144 pub fn seal_record(&self, owner: &str, name: &str, plain: &[u8]) -> Vec<u8> {
145 seal(&self.owner_key(owner), &aad(AAD_RECORD, &format!("{owner}/{name}")), plain)
146 }
147
148 pub fn open_record(&self, owner: &str, name: &str, sealed: &[u8]) -> Option<Vec<u8>> {
149 if sealed.len() > MAX_RECORD + NONCE + TAG {
150 return None;
151 }
152 open(&self.owner_key(owner), &aad(AAD_RECORD, &format!("{owner}/{name}")), sealed)
153 }
154}
155
156fn aad(label: &[u8], name: &str) -> Vec<u8> {
157 let mut a = label.to_vec();
158 a.extend_from_slice(name.as_bytes());
159 a
160}
161
162fn seal(key: &[u8; 32], aad: &[u8], plain: &[u8]) -> Vec<u8> {
163 let mut nonce = [0u8; NONCE];
164 getrandom::getrandom(&mut nonce).expect("random nonce");
165 let ct = Aes256Gcm::new_from_slice(key)
166 .expect("32-byte key")
167 .encrypt(Nonce::from_slice(&nonce), Payload { msg: plain, aad })
168 .expect("aes-gcm encrypt");
169 let mut out = Vec::with_capacity(NONCE + ct.len());
170 out.extend_from_slice(&nonce);
171 out.extend_from_slice(&ct);
172 out
173}
174
175fn open(key: &[u8; 32], aad: &[u8], sealed: &[u8]) -> Option<Vec<u8>> {
176 if sealed.len() < NONCE + TAG {
177 return None;
178 }
179 let (iv, ct) = sealed.split_at(NONCE);
180 Aes256Gcm::new_from_slice(key).ok()?.decrypt(Nonce::from_slice(iv), Payload { msg: ct, aad }).ok()
181}