oxabl_cache_crypto/
vault.rs1use age::secrecy::{ExposeSecret, SecretString};
9use oxabl_cache_format::{CacheId, PublicKey, TenantId};
10use serde_json::{Value, json};
11use zeroize::Zeroizing;
12
13use crate::error::{Error, Result};
14use crate::identity::Identity;
15use crate::identity_file::WORK_FACTOR;
16use crate::random;
17
18pub const MAX_VAULT_BYTES: usize = 64 * 1024;
20pub const PASSPHRASE_WORDS: usize = 6;
22const MAX_OWNER_KEYS: usize = 16;
23pub const MAX_CLIENT_ID_BYTES: usize = 256;
25const FORMAT_VERSION: u64 = 2;
26const FIRST_FORMAT_VERSION: u64 = 1;
27const WORDS_COUNT: u16 = 7776;
28const WORDS: &str = include_str!("eff_large_wordlist.txt");
29
30pub struct VaultContents {
32 pub identity: Identity,
33 pub tenant: TenantId,
34 pub cache: CacheId,
35 pub owner_keys: Vec<PublicKey>,
37 pub high_water: u64,
39 pub issuer: Option<String>,
41 pub client_id: String,
44}
45
46pub fn default_client_id(tenant: &TenantId) -> String {
48 format!("oxabl-cache:{}", tenant.to_text())
49}
50
51pub fn client_id_valid(client_id: &str) -> bool {
53 !client_id.is_empty()
54 && client_id.len() <= MAX_CLIENT_ID_BYTES
55 && client_id.bytes().all(|b| b.is_ascii_graphic())
56}
57
58impl std::fmt::Debug for VaultContents {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 f.debug_struct("VaultContents")
61 .field("cache", &self.cache.to_text())
62 .field("high_water", &self.high_water)
63 .finish_non_exhaustive()
64 }
65}
66
67pub fn generate_passphrase() -> Result<SecretString> {
70 let words: Vec<&str> = WORDS.lines().collect();
71 assert_eq!(words.len(), usize::from(WORDS_COUNT));
72 let limit = u16::MAX - (u16::MAX % WORDS_COUNT);
73 let mut text = String::with_capacity(PASSPHRASE_WORDS * 10);
74 let mut chosen: usize = 0;
75 let mut draws: u32 = 0;
76 while chosen < PASSPHRASE_WORDS {
77 draws += 1;
78 if draws > 1000 {
79 return Err(Error::Random);
80 }
81 let value = u16::from_le_bytes(random::array::<2>()?);
82 if value < limit {
83 if chosen > 0 {
84 text.push('-');
85 }
86 text.push_str(words[usize::from(value % WORDS_COUNT)]);
87 chosen += 1;
88 }
89 }
90 Ok(SecretString::from(text))
91}
92
93fn hex(bytes: &[u8]) -> String {
94 bytes.iter().map(|b| format!("{b:02x}")).collect()
95}
96
97fn unhex_key(text: &str) -> Option<PublicKey> {
98 if text.len() != 64 || !text.bytes().all(|b| b.is_ascii_hexdigit()) {
99 return None;
100 }
101 let mut key = [0u8; 32];
102 for (index, byte) in key.iter_mut().enumerate() {
103 *byte = u8::from_str_radix(text.get(index * 2..index * 2 + 2)?, 16).ok()?;
104 }
105 Some(key)
106}
107
108pub fn seal_vault(contents: &VaultContents, passphrase: &SecretString) -> Result<Vec<u8>> {
110 if contents.owner_keys.is_empty() || contents.owner_keys.len() > MAX_OWNER_KEYS {
111 return Err(Error::Limit("a vault pins 1 to 16 owner keys"));
112 }
113 if !client_id_valid(&contents.client_id) {
114 return Err(Error::Identity("not a client id"));
115 }
116 let identity = contents.identity.to_secret_string()?;
117 let secret = identity.expose_secret();
118 if !secret
119 .bytes()
120 .all(|b| b.is_ascii_alphanumeric() || b == b'-')
121 {
122 return Err(Error::Identity("not an identity"));
123 }
124 let public = json!({
125 "version": FORMAT_VERSION,
126 "tenant": contents.tenant.to_text(),
127 "cache": contents.cache.to_text(),
128 "owner_keys": contents.owner_keys.iter().map(|key| hex(key)).collect::<Vec<_>>(),
129 "high_water": contents.high_water,
130 "issuer": contents.issuer,
131 "client_id": contents.client_id,
132 })
133 .to_string();
134 let rest = public
135 .strip_prefix('{')
136 .ok_or(Error::Identity("encoding failed"))?;
137 let document = Zeroizing::new(format!("{{\"identity\":\"{secret}\",{rest}"));
138 let mut recipient = age::scrypt::Recipient::new(passphrase.clone());
139 recipient.set_work_factor(WORK_FACTOR);
140 let sealed = age::encrypt(&recipient, document.as_bytes())
141 .map_err(|_| Error::Identity("encryption failed"))?;
142 if sealed.len() > MAX_VAULT_BYTES {
143 return Err(Error::Limit("vault size"));
144 }
145 Ok(sealed)
146}
147
148pub fn open_vault(bytes: &[u8], passphrase: &SecretString) -> Result<VaultContents> {
151 if bytes.len() > MAX_VAULT_BYTES {
152 return Err(Error::Limit("vault size"));
153 }
154 let mut unlock = age::scrypt::Identity::new(passphrase.clone());
155 unlock.set_max_work_factor(WORK_FACTOR);
156 let plain = Zeroizing::new(
157 age::decrypt(&unlock, bytes).map_err(|_| Error::Identity("cannot unlock the vault"))?,
158 );
159 let invalid = Error::Identity("the vault document is not valid");
160 let mut document: Value = serde_json::from_slice(&plain).map_err(|_| invalid.clone())?;
161 let identity_text = match document.get_mut("identity").map(Value::take) {
162 Some(Value::String(text)) => Zeroizing::new(text),
163 _ => return Err(invalid),
164 };
165 let version = document.get("version").and_then(Value::as_u64);
166 if !matches!(version, Some(FIRST_FORMAT_VERSION | FORMAT_VERSION)) {
167 return Err(invalid);
168 }
169 let text = |name: &str| document.get(name).and_then(Value::as_str);
170 let identity = Identity::parse(&identity_text)?;
171 let tenant = TenantId::from_text(text("tenant").ok_or(invalid.clone())?)?;
172 let cache = CacheId::from_text(text("cache").ok_or(invalid.clone())?)?;
173 let keys = document
174 .get("owner_keys")
175 .and_then(Value::as_array)
176 .ok_or(invalid.clone())?;
177 if keys.is_empty() || keys.len() > MAX_OWNER_KEYS {
178 return Err(invalid);
179 }
180 let owner_keys = keys
181 .iter()
182 .map(|key| key.as_str().and_then(unhex_key))
183 .collect::<Option<Vec<_>>>()
184 .ok_or(invalid.clone())?;
185 let high_water = document
186 .get("high_water")
187 .and_then(Value::as_u64)
188 .ok_or(invalid.clone())?;
189 let issuer = match document.get("issuer") {
190 None | Some(Value::Null) => None,
191 Some(Value::String(issuer)) if issuer.starts_with("https://") => Some(issuer.clone()),
192 Some(_) => return Err(invalid),
193 };
194 let client_id = match (version, document.get("client_id")) {
195 (Some(FIRST_FORMAT_VERSION), None) => default_client_id(&tenant),
196 (Some(FORMAT_VERSION), Some(Value::String(id))) if client_id_valid(id) => id.clone(),
197 _ => return Err(invalid),
198 };
199 Ok(VaultContents {
200 identity,
201 tenant,
202 cache,
203 owner_keys,
204 high_water,
205 issuer,
206 client_id,
207 })
208}