fix: harden the vault before release

Require a private passphrase and loopback-or-token admin auth. New vaults use Argon2id; existing PBKDF2 vaults still open, and new snapshot metadata is encrypted. Wormhole tokens survive restart, offset uploads seal into the vault, and client-certificate uploads are real. Reject the command provider and keep Postgres passwords off the process arguments. Keep the interruptible canvas motion.
This commit is contained in:
2026-11-10 09:53:06 +07:00
parent 60ba8fed88
commit 95778d54e4
46 changed files with 2311 additions and 415 deletions

View File

@@ -1,10 +1,11 @@
use aes_gcm::aead::generic_array::GenericArray;
use aes_gcm::aead::{Aead, NewAead};
use aes_gcm::Aes256Gcm;
use aes_gcm::aead::Aead;
use aes_gcm::{Aes256Gcm, KeyInit};
use anyhow::{anyhow, Result};
use hmac::Hmac;
use pbkdf2::pbkdf2;
use argon2::{Algorithm, Argon2, Params, Version};
use hmac::{Hmac, Mac};
use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use std::fs;
use std::path::Path;
@@ -17,25 +18,37 @@ pub struct VaultKey {
}
impl VaultKey {
/// Opens an existing key or creates one. A salt with no `kdf.json` stays
/// PBKDF2 so vaults created before Argon2id still open. A missing salt is a
/// new vault and uses Argon2id.
pub fn derive_from_passphrase(passphrase: &str, salt_path: &Path) -> Result<Self> {
let salt = if salt_path.exists() {
fs::read(salt_path)?
} else {
let mut salt = [0u8; SALT_LEN];
rand::thread_rng().fill_bytes(&mut salt);
if let Some(parent) = salt_path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(salt_path, &salt)?;
salt.to_vec()
};
if passphrase.is_empty() {
anyhow::bail!("vault passphrase is required");
}
let marker = salt_path.with_file_name("kdf.json");
if marker.exists() {
let spec: KdfSpec = serde_json::from_slice(&fs::read(&marker)?)?;
let salt = fs::read(salt_path)?;
restrict_secret_file(salt_path)?;
return derive_marked(passphrase, &salt, &spec);
}
if salt_path.exists() {
restrict_secret_file(salt_path)?;
let salt = fs::read(salt_path)?;
return cipher_from_key(&pbkdf2_key(passphrase, &salt));
}
let mut key = [0u8; 32];
pbkdf2::<Hmac<Sha256>>(passphrase.as_bytes(), &salt, 100_000, &mut key);
let cipher =
Aes256Gcm::new_from_slice(&key).map_err(|e| anyhow!("cipher key: {e}"))?;
Ok(Self { cipher })
let mut salt = [0u8; SALT_LEN];
rand::thread_rng().fill_bytes(&mut salt);
if let Some(parent) = salt_path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(salt_path, &salt)?;
restrict_secret_file(salt_path)?;
let spec = KdfSpec::argon2id();
fs::write(&marker, serde_json::to_vec_pretty(&spec)?)?;
restrict_secret_file(&marker)?;
derive_marked(passphrase, &salt, &spec)
}
pub fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
@@ -63,6 +76,100 @@ impl VaultKey {
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
struct KdfSpec {
kdf: String,
#[serde(default = "default_m_kib")]
m_kib: u32,
#[serde(default = "default_t")]
t: u32,
#[serde(default = "default_p")]
p: u32,
}
fn default_m_kib() -> u32 {
19_456
}
fn default_t() -> u32 {
2
}
fn default_p() -> u32 {
1
}
impl KdfSpec {
fn argon2id() -> Self {
Self {
kdf: "argon2id".into(),
m_kib: default_m_kib(),
t: default_t(),
p: default_p(),
}
}
}
fn pbkdf2_key(passphrase: &str, salt: &[u8]) -> [u8; 32] {
pbkdf2_hmac_sha256(passphrase.as_bytes(), salt, 100_000)
}
fn pbkdf2_hmac_sha256(password: &[u8], salt: &[u8], iterations: u32) -> [u8; 32] {
// RFC 8018 PBKDF2-HMAC-SHA256, one block (dkLen = 32). This is the historical
// vault KDF, so existing salt files still open.
type HmacSha256 = Hmac<Sha256>;
let mut block = {
let mut mac =
<HmacSha256 as Mac>::new_from_slice(password).expect("hmac accepts any key length");
mac.update(salt);
mac.update(&1u32.to_be_bytes());
mac.finalize().into_bytes()
};
let mut derived = block;
for _ in 1..iterations {
let mut mac =
<HmacSha256 as Mac>::new_from_slice(password).expect("hmac accepts any key length");
mac.update(&block);
block = mac.finalize().into_bytes();
for (slot, byte) in derived.iter_mut().zip(block.iter()) {
*slot ^= *byte;
}
}
derived.into()
}
fn derive_marked(passphrase: &str, salt: &[u8], spec: &KdfSpec) -> Result<VaultKey> {
let key = match spec.kdf.as_str() {
"argon2id" => {
let params = Params::new(spec.m_kib, spec.t, spec.p, Some(32))
.map_err(|e| anyhow!("argon2 params: {e}"))?;
let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
let mut key = [0u8; 32];
argon
.hash_password_into(passphrase.as_bytes(), salt, &mut key)
.map_err(|e| anyhow!("argon2id: {e}"))?;
key
}
"pbkdf2" => pbkdf2_key(passphrase, salt),
other => anyhow::bail!("unknown vault kdf: {other}"),
};
cipher_from_key(&key)
}
fn cipher_from_key(key: &[u8; 32]) -> Result<VaultKey> {
let cipher = Aes256Gcm::new_from_slice(key).map_err(|e| anyhow!("cipher key: {e}"))?;
Ok(VaultKey { cipher })
}
fn restrict_secret_file(path: &Path) -> Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
}
#[cfg(not(unix))]
let _ = path;
Ok(())
}
pub fn content_id(data: &[u8]) -> String {
use sha2::Digest;
hex::encode(Sha256::digest(data))
@@ -76,6 +183,9 @@ pub fn pack_path(data_dir: &Path, id: &str) -> std::path::PathBuf {
#[cfg(test)]
mod tests {
use super::*;
use aes_gcm::aead::generic_array::GenericArray;
use aes_gcm::aead::Aead;
use aes_gcm::{Aes256Gcm, KeyInit};
use tempfile::tempdir;
#[test]
@@ -87,4 +197,63 @@ mod tests {
let plain = key.decrypt(&enc).unwrap();
assert_eq!(plain, b"stardust");
}
#[test]
fn rejects_empty_passphrase() {
let dir = tempdir().unwrap();
let err = VaultKey::derive_from_passphrase("", &dir.path().join("salt"));
assert!(err.is_err());
}
#[cfg(unix)]
#[test]
fn salt_file_is_owner_only() {
use std::os::unix::fs::PermissionsExt;
let dir = tempdir().unwrap();
let salt = dir.path().join("salt");
VaultKey::derive_from_passphrase("test-vault", &salt).unwrap();
let mode = fs::metadata(&salt).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
}
#[test]
fn new_vault_uses_argon2id() {
let dir = tempdir().unwrap();
let salt = dir.path().join("tessera.salt");
let key = VaultKey::derive_from_passphrase("test-vault", &salt).unwrap();
let marker: serde_json::Value =
serde_json::from_slice(&fs::read(dir.path().join("kdf.json")).unwrap()).unwrap();
assert_eq!(marker["kdf"], "argon2id");
let enc = key.encrypt(b"stardust").unwrap();
let raw_salt = fs::read(&salt).unwrap();
let legacy = pbkdf2_key("test-vault", &raw_salt);
let legacy_cipher = Aes256Gcm::new_from_slice(&legacy).unwrap();
let nonce = GenericArray::from_slice(&enc[..NONCE_LEN]);
assert!(legacy_cipher.decrypt(nonce, &enc[NONCE_LEN..]).is_err());
assert_eq!(key.decrypt(&enc).unwrap(), b"stardust");
}
#[test]
fn pbkdf2_matches_the_rfc_vector() {
let key = super::pbkdf2_hmac_sha256(b"password", b"salt", 4096);
assert_eq!(
hex::encode(key),
"c5e478d59288c841aa530db6845c4c8d962893a001ce4e11a4963873aa98134a"
);
}
#[test]
fn existing_pbkdf2_salt_still_opens() {
let dir = tempdir().unwrap();
let salt = dir.path().join("tessera.salt");
fs::write(&salt, b"0123456789abcdef").unwrap();
let key = VaultKey::derive_from_passphrase("test-vault", &salt).unwrap();
assert!(!dir.path().join("kdf.json").exists());
let enc = key.encrypt(b"legacy").unwrap();
let legacy = pbkdf2_key("test-vault", b"0123456789abcdef");
let legacy_cipher = Aes256Gcm::new_from_slice(&legacy).unwrap();
let nonce = GenericArray::from_slice(&enc[..NONCE_LEN]);
let plain = legacy_cipher.decrypt(nonce, &enc[NONCE_LEN..]).unwrap();
assert_eq!(plain, b"legacy");
}
}

View File

@@ -28,11 +28,17 @@ pub struct Vault {
impl Vault {
pub fn init(root: impl AsRef<Path>, passphrase: &str) -> Result<Self> {
if passphrase == "dev-vault-key" {
anyhow::bail!(
"refusing to initialize a vault with the published dev passphrase; choose a private passphrase"
);
}
let root = root.as_ref().to_path_buf();
fs::create_dir_all(root.join("data"))?;
fs::create_dir_all(root.join("snapshots"))?;
fs::create_dir_all(root.join("index"))?;
fs::create_dir_all(root.join("keys"))?;
restrict_dir(&root.join("keys"))?;
let config_path = root.join("config");
if !config_path.exists() {
@@ -56,6 +62,7 @@ impl Vault {
if !root.join("config").exists() {
anyhow::bail!("vault not initialized");
}
restrict_dir(&root.join("keys"))?;
let salt = root.join("keys/tessera.salt");
let key = VaultKey::derive_from_passphrase(passphrase, &salt)?;
let index = Self::load_index(&root)?;
@@ -150,14 +157,28 @@ impl Vault {
tree_root: chunk_id,
};
let plain = serde_json::to_vec(&snap)?;
let enc = self.key.encrypt(&plain)?;
let path = self
.root
.join("snapshots")
.join(format!("{}.json", snap.id));
fs::write(&path, serde_json::to_string_pretty(&snap)?)?;
.join(format!("{}.json.enc", snap.id));
fs::write(&path, &enc)?;
Ok(snap)
}
fn read_snapshot_file(&self, path: &Path) -> Result<StoredSnapshot> {
let name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
if name.ends_with(".json.enc") {
let plain = self.key.decrypt(&fs::read(path)?)?;
Ok(serde_json::from_slice(&plain)?)
} else if name.ends_with(".json") {
Ok(serde_json::from_str(&fs::read_to_string(path)?)?)
} else {
anyhow::bail!("not a snapshot file");
}
}
pub fn list_snapshots(&self) -> Result<Vec<StoredSnapshot>> {
let dir = self.root.join("snapshots");
if !dir.exists() {
@@ -166,21 +187,21 @@ impl Vault {
let mut out = Vec::new();
for entry in fs::read_dir(&dir)? {
let path = entry?.path();
if path.extension().and_then(|e| e.to_str()) != Some("json") {
let name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
if !(name.ends_with(".json") || name.ends_with(".json.enc")) {
continue;
}
let data = fs::read_to_string(&path)?;
let snap: StoredSnapshot = serde_json::from_str(&data)?;
out.push(snap);
out.push(self.read_snapshot_file(&path)?);
}
out.sort_by(|a, b| b.taken_at.cmp(&a.taken_at));
Ok(out)
}
pub fn restore_snapshot(&self, id: Uuid, dest: &Path) -> Result<u64> {
let path = self.root.join("snapshots").join(format!("{id}.json"));
let data = fs::read_to_string(&path).context("snapshot metadata")?;
let snap: StoredSnapshot = serde_json::from_str(&data)?;
let enc = self.root.join("snapshots").join(format!("{id}.json.enc"));
let plain = self.root.join("snapshots").join(format!("{id}.json"));
let path = if enc.exists() { enc } else { plain };
let snap = self.read_snapshot_file(&path).context("snapshot metadata")?;
let bytes = self.read_chunk(&snap.tree_root)?;
if let Some(parent) = dest.parent() {
fs::create_dir_all(parent)?;
@@ -192,9 +213,15 @@ impl Vault {
pub fn forget(&mut self, ids: &[Uuid]) -> Result<usize> {
let mut removed = 0;
for id in ids {
let path = self.root.join("snapshots").join(format!("{id}.json"));
if path.exists() {
fs::remove_file(&path)?;
let mut gone = false;
for suffix in [".json.enc", ".json"] {
let path = self.root.join("snapshots").join(format!("{id}{suffix}"));
if path.exists() {
fs::remove_file(&path)?;
gone = true;
}
}
if gone {
removed += 1;
}
}
@@ -236,6 +263,19 @@ impl Vault {
}
}
fn restrict_dir(path: &Path) -> Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if path.exists() {
fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
}
}
#[cfg(not(unix))]
let _ = path;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -315,4 +355,69 @@ mod tests {
.iter()
.any(|s| s.manifest.orbit_id == other_id));
}
#[test]
fn new_snapshots_are_encrypted_and_legacy_json_still_reads() {
let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret").unwrap();
let legacy_id = Uuid::new_v4();
let legacy = StoredSnapshot {
id: legacy_id,
taken_at: DateTime::from_timestamp(1_700_000_000, 0).unwrap(),
manifest: SnapshotManifest {
snapshot_id: legacy_id,
orbit_id: Uuid::new_v4(),
orbit_name: "legacy".into(),
labels: vec![],
provider: "filesystem".into(),
paths: vec![],
restore_hints: serde_json::json!({}),
},
size_bytes: 4,
tree_root: "missing".into(),
};
fs::write(
dir.path().join("snapshots").join(format!("{legacy_id}.json")),
serde_json::to_string(&legacy).unwrap(),
)
.unwrap();
let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(),
orbit_name: "new".into(),
labels: vec![],
provider: "filesystem".into(),
paths: vec![],
restore_hints: serde_json::json!({}),
};
let snap = vault.snapshot(manifest, b"cipher", false).unwrap();
assert!(dir
.path()
.join("snapshots")
.join(format!("{}.json.enc", snap.id))
.exists());
assert!(!dir
.path()
.join("snapshots")
.join(format!("{}.json", snap.id))
.exists());
let names: Vec<_> = vault
.list_snapshots()
.unwrap()
.into_iter()
.map(|s| s.manifest.orbit_name)
.collect();
assert!(names.contains(&"legacy".to_string()));
assert!(names.contains(&"new".to_string()));
let out = dir.path().join("restored.bin");
assert_eq!(vault.restore_snapshot(snap.id, &out).unwrap(), 6);
}
#[test]
fn init_rejects_published_dev_passphrase() {
let dir = tempdir().unwrap();
assert!(Vault::init(dir.path(), "dev-vault-key").is_err());
assert!(Vault::init(dir.path(), "").is_err());
}
}