use age::secrecy::{ExposeSecret, SecretString};
use oxabl_cache_format::{CacheId, PublicKey, TenantId};
use serde_json::{Value, json};
use zeroize::Zeroizing;
use crate::error::{Error, Result};
use crate::identity::Identity;
use crate::identity_file::WORK_FACTOR;
use crate::random;
pub const MAX_VAULT_BYTES: usize = 64 * 1024;
pub const PASSPHRASE_WORDS: usize = 6;
const MAX_OWNER_KEYS: usize = 16;
pub const MAX_CLIENT_ID_BYTES: usize = 256;
const FORMAT_VERSION: u64 = 2;
const FIRST_FORMAT_VERSION: u64 = 1;
const WORDS_COUNT: u16 = 7776;
const WORDS: &str = include_str!("eff_large_wordlist.txt");
pub struct VaultContents {
pub identity: Identity,
pub tenant: TenantId,
pub cache: CacheId,
pub owner_keys: Vec<PublicKey>,
pub high_water: u64,
pub issuer: Option<String>,
pub client_id: String,
}
pub fn default_client_id(tenant: &TenantId) -> String {
format!("oxabl-cache:{}", tenant.to_text())
}
pub fn client_id_valid(client_id: &str) -> bool {
!client_id.is_empty()
&& client_id.len() <= MAX_CLIENT_ID_BYTES
&& client_id.bytes().all(|b| b.is_ascii_graphic())
}
impl std::fmt::Debug for VaultContents {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VaultContents")
.field("cache", &self.cache.to_text())
.field("high_water", &self.high_water)
.finish_non_exhaustive()
}
}
pub fn generate_passphrase() -> Result<SecretString> {
let words: Vec<&str> = WORDS.lines().collect();
assert_eq!(words.len(), usize::from(WORDS_COUNT));
let limit = u16::MAX - (u16::MAX % WORDS_COUNT);
let mut text = String::with_capacity(PASSPHRASE_WORDS * 10);
let mut chosen: usize = 0;
let mut draws: u32 = 0;
while chosen < PASSPHRASE_WORDS {
draws += 1;
if draws > 1000 {
return Err(Error::Random);
}
let value = u16::from_le_bytes(random::array::<2>()?);
if value < limit {
if chosen > 0 {
text.push('-');
}
text.push_str(words[usize::from(value % WORDS_COUNT)]);
chosen += 1;
}
}
Ok(SecretString::from(text))
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
fn unhex_key(text: &str) -> Option<PublicKey> {
if text.len() != 64 || !text.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let mut key = [0u8; 32];
for (index, byte) in key.iter_mut().enumerate() {
*byte = u8::from_str_radix(text.get(index * 2..index * 2 + 2)?, 16).ok()?;
}
Some(key)
}
pub fn seal_vault(contents: &VaultContents, passphrase: &SecretString) -> Result<Vec<u8>> {
if contents.owner_keys.is_empty() || contents.owner_keys.len() > MAX_OWNER_KEYS {
return Err(Error::Limit("a vault pins 1 to 16 owner keys"));
}
if !client_id_valid(&contents.client_id) {
return Err(Error::Identity("not a client id"));
}
let identity = contents.identity.to_secret_string()?;
let secret = identity.expose_secret();
if !secret
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-')
{
return Err(Error::Identity("not an identity"));
}
let public = json!({
"version": FORMAT_VERSION,
"tenant": contents.tenant.to_text(),
"cache": contents.cache.to_text(),
"owner_keys": contents.owner_keys.iter().map(|key| hex(key)).collect::<Vec<_>>(),
"high_water": contents.high_water,
"issuer": contents.issuer,
"client_id": contents.client_id,
})
.to_string();
let rest = public
.strip_prefix('{')
.ok_or(Error::Identity("encoding failed"))?;
let document = Zeroizing::new(format!("{{\"identity\":\"{secret}\",{rest}"));
let mut recipient = age::scrypt::Recipient::new(passphrase.clone());
recipient.set_work_factor(WORK_FACTOR);
let sealed = age::encrypt(&recipient, document.as_bytes())
.map_err(|_| Error::Identity("encryption failed"))?;
if sealed.len() > MAX_VAULT_BYTES {
return Err(Error::Limit("vault size"));
}
Ok(sealed)
}
pub fn open_vault(bytes: &[u8], passphrase: &SecretString) -> Result<VaultContents> {
if bytes.len() > MAX_VAULT_BYTES {
return Err(Error::Limit("vault size"));
}
let mut unlock = age::scrypt::Identity::new(passphrase.clone());
unlock.set_max_work_factor(WORK_FACTOR);
let plain = Zeroizing::new(
age::decrypt(&unlock, bytes).map_err(|_| Error::Identity("cannot unlock the vault"))?,
);
let invalid = Error::Identity("the vault document is not valid");
let mut document: Value = serde_json::from_slice(&plain).map_err(|_| invalid.clone())?;
let identity_text = match document.get_mut("identity").map(Value::take) {
Some(Value::String(text)) => Zeroizing::new(text),
_ => return Err(invalid),
};
let version = document.get("version").and_then(Value::as_u64);
if !matches!(version, Some(FIRST_FORMAT_VERSION | FORMAT_VERSION)) {
return Err(invalid);
}
let text = |name: &str| document.get(name).and_then(Value::as_str);
let identity = Identity::parse(&identity_text)?;
let tenant = TenantId::from_text(text("tenant").ok_or(invalid.clone())?)?;
let cache = CacheId::from_text(text("cache").ok_or(invalid.clone())?)?;
let keys = document
.get("owner_keys")
.and_then(Value::as_array)
.ok_or(invalid.clone())?;
if keys.is_empty() || keys.len() > MAX_OWNER_KEYS {
return Err(invalid);
}
let owner_keys = keys
.iter()
.map(|key| key.as_str().and_then(unhex_key))
.collect::<Option<Vec<_>>>()
.ok_or(invalid.clone())?;
let high_water = document
.get("high_water")
.and_then(Value::as_u64)
.ok_or(invalid.clone())?;
let issuer = match document.get("issuer") {
None | Some(Value::Null) => None,
Some(Value::String(issuer)) if issuer.starts_with("https://") => Some(issuer.clone()),
Some(_) => return Err(invalid),
};
let client_id = match (version, document.get("client_id")) {
(Some(FIRST_FORMAT_VERSION), None) => default_client_id(&tenant),
(Some(FORMAT_VERSION), Some(Value::String(id))) if client_id_valid(id) => id.clone(),
_ => return Err(invalid),
};
Ok(VaultContents {
identity,
tenant,
cache,
owner_keys,
high_water,
issuer,
client_id,
})
}