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:
@@ -20,3 +20,5 @@ tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
uuid.workspace = true
|
||||
base64 = "0.22"
|
||||
rustls = { version = "=0.23.23", default-features = false, features = ["ring", "std"] }
|
||||
rustls-pemfile = "=2.2.0"
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
use anyhow::{Context, Result};
|
||||
use rustls::pki_types::ServerName;
|
||||
use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned};
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::fs::File;
|
||||
use std::io::{BufReader, Read, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)]) -> Result<String> {
|
||||
let payload = serde_json::to_string(body)?;
|
||||
@@ -15,8 +19,12 @@ fn request(
|
||||
content_type: Option<&str>,
|
||||
headers: &[(&str, &str)],
|
||||
) -> Result<String> {
|
||||
let (host, port, path) = parse_url(url)?;
|
||||
let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?;
|
||||
let (https, host, port, path) = parse_url(url)?;
|
||||
let mut stream: Box<dyn ReadWrite> = if https {
|
||||
Box::new(connect_mtls(&host, port)?)
|
||||
} else {
|
||||
Box::new(TcpStream::connect((host.as_str(), port)).context("connect")?)
|
||||
};
|
||||
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
|
||||
for (k, v) in headers {
|
||||
req.push_str(&format!("{k}: {v}\r\n"));
|
||||
@@ -38,20 +46,65 @@ fn request(
|
||||
Ok(buf[body_start..].trim().to_string())
|
||||
}
|
||||
|
||||
fn parse_url(url: &str) -> Result<(String, u16, String)> {
|
||||
let url = url.strip_prefix("http://").context("only http supported")?;
|
||||
let (host_port, path) = url.split_once('/').unwrap_or((url, ""));
|
||||
trait ReadWrite: Read + Write {}
|
||||
impl<T: Read + Write> ReadWrite for T {}
|
||||
|
||||
fn parse_url(url: &str) -> Result<(bool, String, u16, String)> {
|
||||
let (https, rest) = if let Some(rest) = url.strip_prefix("https://") {
|
||||
(true, rest)
|
||||
} else if let Some(rest) = url.strip_prefix("http://") {
|
||||
(false, rest)
|
||||
} else {
|
||||
anyhow::bail!("hub url must start with http:// or https://");
|
||||
};
|
||||
let (host_port, path) = rest.split_once('/').unwrap_or((rest, ""));
|
||||
let path = if path.is_empty() {
|
||||
"/".to_string()
|
||||
} else {
|
||||
format!("/{path}")
|
||||
};
|
||||
let (host, port) = if let Some((h, p)) = host_port.split_once(':') {
|
||||
(h.to_string(), p.parse()?)
|
||||
let (host, port) = if let Some((host, port)) = host_port.split_once(':') {
|
||||
(host.to_string(), port.parse()?)
|
||||
} else {
|
||||
(host_port.to_string(), 80)
|
||||
(host_port.to_string(), if https { 443 } else { 80 })
|
||||
};
|
||||
Ok((host, port, path))
|
||||
Ok((https, host, port, path))
|
||||
}
|
||||
|
||||
fn connect_mtls(host: &str, port: u16) -> Result<StreamOwned<ClientConnection, TcpStream>> {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
let ca = std::env::var("TESSERA_WORMHOLE_CA")
|
||||
.context("TESSERA_WORMHOLE_CA is required for an https hub")?;
|
||||
let cert = std::env::var("TESSERA_WORMHOLE_CLIENT_CERT")
|
||||
.context("TESSERA_WORMHOLE_CLIENT_CERT is required for an https hub")?;
|
||||
let key = std::env::var("TESSERA_WORMHOLE_CLIENT_KEY")
|
||||
.context("TESSERA_WORMHOLE_CLIENT_KEY is required for an https hub")?;
|
||||
let mut roots = RootCertStore::empty();
|
||||
for ca_cert in load_certs(&ca)? {
|
||||
roots.add(ca_cert).map_err(|error| anyhow::anyhow!("hub CA: {error}"))?;
|
||||
}
|
||||
let client = ClientConfig::builder()
|
||||
.with_root_certificates(roots)
|
||||
.with_client_auth_cert(load_certs(&cert)?, load_key(&key)?)
|
||||
.map_err(|error| anyhow::anyhow!("client certificate: {error}"))?;
|
||||
let name = ServerName::try_from(host.to_string()).context("hub hostname")?;
|
||||
let connection = ClientConnection::new(Arc::new(client), name)?;
|
||||
let tcp = TcpStream::connect((host, port)).context("connect")?;
|
||||
Ok(StreamOwned::new(connection, tcp))
|
||||
}
|
||||
|
||||
fn load_certs(path: &str) -> Result<Vec<rustls::pki_types::CertificateDer<'static>>> {
|
||||
let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {path}"))?);
|
||||
rustls_pemfile::certs(&mut reader)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.context("parse certificate")
|
||||
}
|
||||
|
||||
fn load_key(path: &str) -> Result<rustls::pki_types::PrivateKeyDer<'static>> {
|
||||
let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {path}"))?);
|
||||
rustls_pemfile::private_key(&mut reader)
|
||||
.context("parse private key")?
|
||||
.context("no private key in client key file")
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
|
||||
@@ -12,8 +12,9 @@ struct Cli {
|
||||
command: Commands,
|
||||
#[arg(long, env = "TESSERA_DATA_DIR", default_value = "./data")]
|
||||
data_dir: String,
|
||||
#[arg(long, env = "TESSERA_VAULT_PASSPHRASE", default_value = "dev-vault-key")]
|
||||
vault_pass: String,
|
||||
/// Required for vault commands. No default; the published example passphrase is rejected for new vaults.
|
||||
#[arg(long, env = "TESSERA_VAULT_PASSPHRASE")]
|
||||
vault_pass: Option<String>,
|
||||
#[arg(long, env = "TESSERA_HUB_URL", default_value = "http://127.0.0.1:8787")]
|
||||
hub_url: String,
|
||||
}
|
||||
@@ -98,14 +99,24 @@ fn main() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_passphrase(cli: &Cli) -> Result<&str> {
|
||||
match cli.vault_pass.as_deref() {
|
||||
Some(pass) if !pass.is_empty() => Ok(pass),
|
||||
_ => anyhow::bail!(
|
||||
"Set TESSERA_VAULT_PASSPHRASE or pass --vault-pass. Tessera does not ship a default passphrase."
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn cmd_seed_demo(cli: &Cli, force: bool, reset: bool) -> Result<()> {
|
||||
let data = std::path::Path::new(&cli.data_dir);
|
||||
let vault_pass = require_passphrase(cli)?;
|
||||
if reset {
|
||||
tessera_demo::clear_demo(data, &cli.vault_pass)?;
|
||||
tessera_demo::clear_demo(data, vault_pass)?;
|
||||
println!("Demo seed cleared.");
|
||||
return Ok(());
|
||||
}
|
||||
let report = tessera_demo::apply(data, &cli.vault_pass, force)?;
|
||||
let report = tessera_demo::apply(data, vault_pass, force)?;
|
||||
if report.skipped {
|
||||
println!(
|
||||
"Demo seed already applied ({} orbits, {} snapshots). Use --force to re-seed.",
|
||||
@@ -130,7 +141,7 @@ fn cmd_init(cli: &Cli) -> Result<()> {
|
||||
println!("Vault already initialized.");
|
||||
return Ok(());
|
||||
}
|
||||
Vault::init(&vp, &cli.vault_pass).context("init vault")?;
|
||||
Vault::init(&vp, require_passphrase(cli)?).context("init vault")?;
|
||||
println!("Vault initialized at {}", vp.display());
|
||||
Ok(())
|
||||
}
|
||||
@@ -142,7 +153,7 @@ fn cmd_status(cli: &Cli) -> Result<()> {
|
||||
}
|
||||
let vp = vault_path(&cli.data_dir);
|
||||
if vp.join("config").exists() {
|
||||
let vault = Vault::open(&vp, &cli.vault_pass)?;
|
||||
let vault = Vault::open(&vp, require_passphrase(cli)?)?;
|
||||
let n = vault.list_snapshots()?.len();
|
||||
println!("Vault: online — {n} snapshots");
|
||||
} else {
|
||||
@@ -197,7 +208,7 @@ fn cmd_snap(cli: &Cli, orbit_name: Option<String>) -> Result<()> {
|
||||
}
|
||||
|
||||
fn cmd_list(cli: &Cli) -> Result<()> {
|
||||
let vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?;
|
||||
let vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?;
|
||||
for s in vault.list_snapshots()? {
|
||||
println!(
|
||||
"{} {} {} bytes orbit={}",
|
||||
@@ -211,14 +222,14 @@ fn cmd_list(cli: &Cli) -> Result<()> {
|
||||
}
|
||||
|
||||
fn cmd_reconstitute(cli: &Cli, snapshot_id: Uuid, target: String) -> Result<()> {
|
||||
let vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?;
|
||||
let vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?;
|
||||
let n = vault.restore_snapshot(snapshot_id, std::path::Path::new(&target))?;
|
||||
println!("Reconstituted {n} bytes to {target}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cmd_decay(cli: &Cli, preset: &str) -> Result<()> {
|
||||
let mut vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?;
|
||||
let mut vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?;
|
||||
let pruned = vault.prune_with_decay(preset)?;
|
||||
println!("{} snapshots decayed.", pruned.len());
|
||||
Ok(())
|
||||
|
||||
@@ -18,7 +18,7 @@ pub struct HubConfig {
|
||||
impl Default for HubConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
listen: "0.0.0.0:8787".into(),
|
||||
listen: "127.0.0.1:8787".into(),
|
||||
data_dir: "./data".into(),
|
||||
admin_password_hash: None,
|
||||
}
|
||||
|
||||
@@ -31,3 +31,14 @@ uuid.workspace = true
|
||||
hex.workspace = true
|
||||
base64 = "0.22"
|
||||
indexmap = "=2.2.6"
|
||||
hyper = { version = "=1.12.0", features = ["server", "http1"] }
|
||||
hyper-util = { version = "=0.1.21", features = ["tokio"] }
|
||||
rustls = { version = "=0.23.23", default-features = false, features = ["ring", "std"] }
|
||||
rustls-pemfile = "=2.2.0"
|
||||
tokio-rustls = "=0.26.2"
|
||||
tower = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
rcgen = "=0.13.2"
|
||||
tempfile.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
135
crates/tessera-hub/src/admin.rs
Normal file
135
crates/tessera-hub/src/admin.rs
Normal file
@@ -0,0 +1,135 @@
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use std::net::SocketAddr;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AdminGate {
|
||||
pub token: Option<String>,
|
||||
}
|
||||
|
||||
impl AdminGate {
|
||||
pub fn from_env() -> Self {
|
||||
let token = std::env::var("TESSERA_ADMIN_TOKEN")
|
||||
.ok()
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty());
|
||||
Self { token }
|
||||
}
|
||||
|
||||
pub fn log_policy(&self) {
|
||||
if self.token.is_none() {
|
||||
tracing::warn!(
|
||||
"TESSERA_ADMIN_TOKEN is unset; snapshot, orbit, reconstitute, and pairing APIs are open to loopback clients only"
|
||||
);
|
||||
} else {
|
||||
tracing::info!(
|
||||
"TESSERA_ADMIN_TOKEN is set; backup APIs require that token from every client"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn authorize(&self, peer: SocketAddr, headers: &HeaderMap) -> Result<(), StatusCode> {
|
||||
let presented = presented_token(headers);
|
||||
match &self.token {
|
||||
Some(expected) => {
|
||||
if presented.is_some_and(|value| tokens_match(expected, value)) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StatusCode::UNAUTHORIZED)
|
||||
}
|
||||
}
|
||||
None if peer.ip().is_loopback() => Ok(()),
|
||||
None => Err(StatusCode::UNAUTHORIZED),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn presented_token(headers: &HeaderMap) -> Option<&str> {
|
||||
if let Some(value) = headers
|
||||
.get("x-tessera-admin-token")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
{
|
||||
let value = value.trim();
|
||||
if !value.is_empty() {
|
||||
return Some(value);
|
||||
}
|
||||
}
|
||||
let header = headers.get("authorization")?.to_str().ok()?;
|
||||
let token = header
|
||||
.strip_prefix("Bearer ")
|
||||
.or_else(|| header.strip_prefix("bearer "))?
|
||||
.trim();
|
||||
if token.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(token)
|
||||
}
|
||||
}
|
||||
|
||||
fn tokens_match(expected: &str, presented: &str) -> bool {
|
||||
let expected = expected.as_bytes();
|
||||
let presented = presented.as_bytes();
|
||||
let mut diff = expected.len() ^ presented.len();
|
||||
for (left, right) in expected.iter().zip(presented.iter()) {
|
||||
diff |= (*left ^ *right) as usize;
|
||||
}
|
||||
diff == 0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::http::HeaderValue;
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
|
||||
fn peer(ip: IpAddr) -> SocketAddr {
|
||||
SocketAddr::new(ip, 9)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loopback_without_a_token_is_the_only_open_path() {
|
||||
let gate = AdminGate { token: None };
|
||||
let headers = HeaderMap::new();
|
||||
assert!(gate
|
||||
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
|
||||
.is_ok());
|
||||
assert!(gate
|
||||
.authorize(peer(IpAddr::V6(Ipv6Addr::LOCALHOST)), &headers)
|
||||
.is_ok());
|
||||
assert!(gate
|
||||
.authorize(peer(IpAddr::V4(Ipv4Addr::new(10, 1, 0, 4))), &headers)
|
||||
.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_token_is_required_on_loopback() {
|
||||
let gate = AdminGate {
|
||||
token: Some("secret-token".into()),
|
||||
};
|
||||
let mut headers = HeaderMap::new();
|
||||
assert!(gate
|
||||
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
|
||||
.is_err());
|
||||
headers.insert(
|
||||
"authorization",
|
||||
HeaderValue::from_static("Bearer secret-token"),
|
||||
);
|
||||
assert!(gate
|
||||
.authorize(peer(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 8))), &headers)
|
||||
.is_ok());
|
||||
headers.remove("authorization");
|
||||
headers.insert(
|
||||
"x-tessera-admin-token",
|
||||
HeaderValue::from_static("secret-token"),
|
||||
);
|
||||
assert!(gate
|
||||
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
|
||||
.is_ok());
|
||||
headers.insert(
|
||||
"x-tessera-admin-token",
|
||||
HeaderValue::from_static("secret-tokem"),
|
||||
);
|
||||
assert!(gate
|
||||
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
|
||||
.is_err());
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,8 @@ async fn run_orbit_row(state: &HubState, orbit: OrbitRow) -> Result<Option<Uuid>
|
||||
let provider_kind = match orbit.provider.as_str() {
|
||||
"filesystem" => ProviderKind::Filesystem,
|
||||
"postgres" => ProviderKind::Postgres,
|
||||
_ => ProviderKind::Command,
|
||||
"command" => ProviderKind::Command,
|
||||
other => anyhow::bail!("unknown provider '{other}'"),
|
||||
};
|
||||
let config: serde_json::Value = serde_json::from_str(&orbit.provider_config)?;
|
||||
let provider = provider_from_config(&provider_kind, &config)?;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use crate::db::OrbitRow;
|
||||
use crate::state::{HubState, PairingEntry};
|
||||
use crate::state::HubState;
|
||||
use crate::upload::write_at;
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
extract::{ConnectInfo, Path, State},
|
||||
http::{header, HeaderMap, HeaderValue, StatusCode, Uri},
|
||||
response::IntoResponse,
|
||||
routing::{get, post},
|
||||
@@ -9,8 +10,11 @@ use axum::{
|
||||
};
|
||||
use base64::Engine;
|
||||
use include_dir::{include_dir, Dir};
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
use std::net::SocketAddr;
|
||||
use tessera_core::manifest::SnapshotManifest;
|
||||
use tessera_core::reconstitute::{ReconstituteSession, ReconstituteState, RECONSTITUTE_GRACE_SECS};
|
||||
use tessera_core::wormhole::PairingState;
|
||||
use tower_http::trace::TraceLayer;
|
||||
use utoipa::OpenApi;
|
||||
use uuid::Uuid;
|
||||
@@ -109,6 +113,14 @@ struct ReconstituteStartResponse {
|
||||
session: ReconstituteSession,
|
||||
}
|
||||
|
||||
fn require_admin(
|
||||
state: &HubState,
|
||||
peer: SocketAddr,
|
||||
headers: &HeaderMap,
|
||||
) -> Result<(), StatusCode> {
|
||||
state.admin.authorize(peer, headers)
|
||||
}
|
||||
|
||||
pub fn router(state: HubState) -> Router {
|
||||
let api = Router::new()
|
||||
.route("/health", get(health))
|
||||
@@ -141,7 +153,12 @@ async fn health() -> &'static str {
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/snapshots", responses((status = 200, body = [SnapshotSummary])))]
|
||||
async fn list_snapshots(State(state): State<HubState>) -> Result<Json<Vec<SnapshotSummary>>, StatusCode> {
|
||||
async fn list_snapshots(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<Vec<SnapshotSummary>>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
let vault = state.vault.read().await;
|
||||
let snaps = vault.list_snapshots().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let out = snaps
|
||||
@@ -158,7 +175,12 @@ async fn list_snapshots(State(state): State<HubState>) -> Result<Json<Vec<Snapsh
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/orbits", responses((status = 200, body = [OrbitRow])))]
|
||||
async fn list_orbits(State(state): State<HubState>) -> Result<Json<Vec<OrbitRow>>, StatusCode> {
|
||||
async fn list_orbits(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<Vec<OrbitRow>>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
state
|
||||
.db
|
||||
.list_orbits()
|
||||
@@ -169,9 +191,12 @@ async fn list_orbits(State(state): State<HubState>) -> Result<Json<Vec<OrbitRow>
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/orbits", request_body = CreateOrbitRequest, responses((status = 200, body = OrbitRow)))]
|
||||
async fn create_orbit(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(req): Json<CreateOrbitRequest>,
|
||||
) -> Result<Json<OrbitRow>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
let row = OrbitRow {
|
||||
id: Uuid::new_v4(),
|
||||
name: req.name,
|
||||
@@ -190,19 +215,26 @@ async fn create_orbit(
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/orbits/{id}/run", params(("id" = Uuid, Path, description = "orbit id")), responses((status = 204, headers(("X-Tessera-Snapshot-Id" = Uuid, description = "New retained snapshot ID when a capture writes to the vault")))))]
|
||||
async fn trigger_orbit(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<(StatusCode, HeaderMap), StatusCode> {
|
||||
) -> Result<(StatusCode, HeaderMap), (StatusCode, String)> {
|
||||
require_admin(&state, peer, &headers).map_err(|status| (status, "unauthorized".into()))?;
|
||||
let snapshot_id = crate::api::run_orbit_internal(state, id)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
tracing::warn!(orbit_id = %id, %error, "capture did not complete");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, error.to_string())
|
||||
})?;
|
||||
let mut headers = HeaderMap::new();
|
||||
if let Some(snapshot_id) = snapshot_id {
|
||||
let value = HeaderValue::from_str(&snapshot_id.to_string())
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let value = HeaderValue::from_str(&snapshot_id.to_string()).map_err(|_| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"snapshot id header".into(),
|
||||
)
|
||||
})?;
|
||||
headers.insert("x-tessera-snapshot-id", value);
|
||||
}
|
||||
Ok((StatusCode::NO_CONTENT, headers))
|
||||
@@ -210,9 +242,12 @@ async fn trigger_orbit(
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/reconstitute", request_body = ReconstituteRequest, responses((status = 200, body = ReconstituteStartResponse)))]
|
||||
async fn start_reconstitute(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(req): Json<ReconstituteRequest>,
|
||||
) -> Result<Json<ReconstituteStartResponse>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
let session_id = Uuid::new_v4();
|
||||
let session = ReconstituteSession {
|
||||
snapshot_id: req.snapshot_id,
|
||||
@@ -273,17 +308,23 @@ async fn start_reconstitute(
|
||||
}
|
||||
|
||||
async fn reconstitute_status(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<ReconstituteSession>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
let map = state.reconstitute_sessions.read().await;
|
||||
map.get(&id).cloned().map(Json).ok_or(StatusCode::NOT_FOUND)
|
||||
}
|
||||
|
||||
async fn abort_reconstitute(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
let mut map = state.reconstitute_sessions.write().await;
|
||||
if let Some(s) = map.get_mut(&id) {
|
||||
if matches!(
|
||||
@@ -298,7 +339,12 @@ async fn abort_reconstitute(
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/wormhole/pairing", responses((status = 200, body = PairingResponse)))]
|
||||
async fn pairing_start(State(state): State<HubState>) -> Json<PairingResponse> {
|
||||
async fn pairing_start(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<PairingResponse>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
let code: String = (0..6)
|
||||
.map(|_| {
|
||||
let n = rand::random::<u8>() % 36;
|
||||
@@ -312,14 +358,16 @@ async fn pairing_start(State(state): State<HubState>) -> Json<PairingResponse> {
|
||||
let expires = chrono::Utc::now() + chrono::Duration::minutes(10);
|
||||
let outpost_id = Uuid::new_v4();
|
||||
let upload_token = hex::encode(Uuid::new_v4().as_bytes());
|
||||
state.pairing_codes.write().await.push(PairingEntry {
|
||||
code: code.clone(),
|
||||
expires_at: expires,
|
||||
state: PairingState::CodeShown,
|
||||
outpost_id,
|
||||
upload_token: upload_token.clone(),
|
||||
});
|
||||
Json(PairingResponse { code, expires_at: expires })
|
||||
state
|
||||
.db
|
||||
.insert_wormhole_token(
|
||||
&upload_token,
|
||||
&outpost_id.to_string(),
|
||||
&code,
|
||||
&expires.to_rfc3339(),
|
||||
)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(Json(PairingResponse { code, expires_at: expires }))
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/wormhole/claim", request_body = ClaimRequest, responses((status = 200, body = ClaimResponse)))]
|
||||
@@ -327,23 +375,28 @@ async fn pairing_claim(
|
||||
State(state): State<HubState>,
|
||||
Json(req): Json<ClaimRequest>,
|
||||
) -> Result<Json<ClaimResponse>, StatusCode> {
|
||||
let mut codes = state.pairing_codes.write().await;
|
||||
let now = chrono::Utc::now();
|
||||
let entry = codes
|
||||
.iter_mut()
|
||||
.find(|c| c.code == req.code && c.expires_at > now)
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
let claimed = state
|
||||
.db
|
||||
.claim_wormhole_code(&req.code, &req.outpost_name, &now)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::GONE)?;
|
||||
entry.state = PairingState::Active;
|
||||
let hub_url =
|
||||
std::env::var("TESSERA_PUBLIC_URL").unwrap_or_else(|_| "http://127.0.0.1:8787".into());
|
||||
let hub_url = std::env::var("TESSERA_PUBLIC_URL").unwrap_or_else(|_| {
|
||||
if state.wormhole_mtls {
|
||||
"https://127.0.0.1:8788".into()
|
||||
} else {
|
||||
"http://127.0.0.1:8787".into()
|
||||
}
|
||||
});
|
||||
state
|
||||
.db
|
||||
.audit("wormhole.paired", &req.outpost_name)
|
||||
.await
|
||||
.ok();
|
||||
let outpost_id = Uuid::parse_str(&claimed.1).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(Json(ClaimResponse {
|
||||
outpost_id: entry.outpost_id,
|
||||
upload_token: entry.upload_token.clone(),
|
||||
outpost_id,
|
||||
upload_token: claimed.0,
|
||||
hub_url,
|
||||
}))
|
||||
}
|
||||
@@ -354,16 +407,26 @@ async fn wormhole_upload_init(
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<UploadInit>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
verify_upload_token(&state, &headers).await?;
|
||||
verify_upload_token(&state, &headers)?;
|
||||
let total = body.total_bytes.ok_or(StatusCode::BAD_REQUEST)?;
|
||||
let session_id = Uuid::new_v4();
|
||||
state
|
||||
.db
|
||||
.insert_upload_session(
|
||||
&session_id.to_string(),
|
||||
&body.orbit_id.to_string(),
|
||||
body.total_bytes.map(|t| t as i64),
|
||||
Some(i64::try_from(total).map_err(|_| StatusCode::BAD_REQUEST)?),
|
||||
)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
if total == 0 {
|
||||
let seal = state
|
||||
.db
|
||||
.record_range(&session_id.to_string(), 0, 0, 0)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
if seal {
|
||||
seal_upload(&state, session_id, body.orbit_id, Vec::new()).await?;
|
||||
}
|
||||
}
|
||||
Ok(Json(serde_json::json!({ "session_id": session_id })))
|
||||
}
|
||||
|
||||
@@ -373,39 +436,141 @@ async fn wormhole_upload_chunk(
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<UploadChunk>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
verify_upload_token(&state, &headers).await?;
|
||||
verify_upload_token(&state, &headers)?;
|
||||
let session = state
|
||||
.db
|
||||
.upload_session(&body.session_id.to_string())
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
if session.sealed {
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
let data = base64::engine::general_purpose::STANDARD
|
||||
.decode(&body.data_b64)
|
||||
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let tmp = state.data_dir.join("wormhole").join(format!("{}.part", body.session_id));
|
||||
if let Some(parent) = tmp.parent() {
|
||||
std::fs::create_dir_all(parent).ok();
|
||||
let path = upload_part_path(&state, body.session_id);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
}
|
||||
use std::io::Write;
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
let mut file = OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&tmp)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
file.write_all(&data).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
restrict_part(&path);
|
||||
let range = write_at(&mut file, body.offset, &data, session.total).map_err(|error| {
|
||||
if error.kind() == std::io::ErrorKind::InvalidInput {
|
||||
StatusCode::BAD_REQUEST
|
||||
} else {
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
})?;
|
||||
let seal = state
|
||||
.db
|
||||
.record_range(
|
||||
&body.session_id.to_string(),
|
||||
range.start,
|
||||
range.end,
|
||||
session.total,
|
||||
)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
if seal {
|
||||
let mut bytes = Vec::new();
|
||||
file.seek(SeekFrom::Start(0))
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
file.read_to_end(&mut bytes)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
if (bytes.len() as u64) < session.total {
|
||||
let _ = state.db.mark_upload_unsealed(&body.session_id.to_string());
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
bytes.truncate(session.total as usize);
|
||||
if let Err(status) = seal_upload(&state, body.session_id, session.orbit_id, bytes).await {
|
||||
let _ = state.db.mark_upload_unsealed(&body.session_id.to_string());
|
||||
return Err(status);
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn verify_upload_token(
|
||||
state: &HubState,
|
||||
headers: &axum::http::HeaderMap,
|
||||
) -> Result<(), StatusCode> {
|
||||
fn upload_part_path(state: &HubState, session_id: Uuid) -> std::path::PathBuf {
|
||||
state
|
||||
.data_dir
|
||||
.join("wormhole")
|
||||
.join(format!("{session_id}.part"))
|
||||
}
|
||||
|
||||
fn restrict_part(path: &std::path::Path) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = path;
|
||||
}
|
||||
|
||||
fn verify_upload_token(state: &HubState, headers: &HeaderMap) -> Result<(), StatusCode> {
|
||||
if !state.accept_plain_upload {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
let token = headers
|
||||
.get("x-tessera-upload-token")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
if state.upload_token_valid(token).await {
|
||||
if state.upload_token_valid(token) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StatusCode::UNAUTHORIZED)
|
||||
}
|
||||
}
|
||||
|
||||
async fn seal_upload(
|
||||
state: &HubState,
|
||||
session_id: Uuid,
|
||||
orbit_id: Uuid,
|
||||
bytes: Vec<u8>,
|
||||
) -> Result<(), StatusCode> {
|
||||
let orbits = state
|
||||
.db
|
||||
.list_orbits()
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let orbit = orbits.into_iter().find(|orbit| orbit.id == orbit_id);
|
||||
let orbit_name = orbit
|
||||
.as_ref()
|
||||
.map(|orbit| orbit.name.clone())
|
||||
.unwrap_or_else(|| orbit_id.to_string());
|
||||
let decay = orbit
|
||||
.as_ref()
|
||||
.map(|orbit| orbit.decay_preset.clone())
|
||||
.unwrap_or_else(|| "week-of-dailies".into());
|
||||
let manifest = SnapshotManifest {
|
||||
snapshot_id: Uuid::new_v4(),
|
||||
orbit_id,
|
||||
orbit_name,
|
||||
labels: vec!["wormhole".into()],
|
||||
provider: "wormhole".into(),
|
||||
paths: vec![],
|
||||
restore_hints: serde_json::json!({ "session_id": session_id }),
|
||||
};
|
||||
let snap_id = {
|
||||
let mut vault = state.vault.write().await;
|
||||
let snap = vault
|
||||
.snapshot(manifest, &bytes, false)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let _ = vault.prune_orbit_with_decay(orbit_id, &decay);
|
||||
snap.id
|
||||
};
|
||||
let _ = state
|
||||
.db
|
||||
.audit("wormhole.sealed", &format!("snapshot={snap_id}"))
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn spa_fallback(uri: Uri) -> impl IntoResponse {
|
||||
let mut path = uri.path().trim_start_matches('/').to_string();
|
||||
if path.is_empty() {
|
||||
|
||||
@@ -66,8 +66,22 @@ impl Db {
|
||||
total INTEGER,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS wormhole_tokens (
|
||||
token TEXT PRIMARY KEY,
|
||||
outpost_id TEXT NOT NULL,
|
||||
code TEXT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL,
|
||||
outpost_name TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS upload_ranges (
|
||||
session_id TEXT NOT NULL,
|
||||
start_off INTEGER NOT NULL,
|
||||
end_off INTEGER NOT NULL
|
||||
);
|
||||
"#,
|
||||
)?;
|
||||
ensure_column(&conn, "upload_sessions", "sealed", "INTEGER NOT NULL DEFAULT 0")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -137,9 +151,156 @@ impl Db {
|
||||
) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO upload_sessions (id, orbit_id, offset, total, created_at) VALUES (?1, ?2, 0, ?3, datetime('now'))",
|
||||
"INSERT INTO upload_sessions (id, orbit_id, offset, total, sealed, created_at) VALUES (?1, ?2, 0, ?3, 0, datetime('now'))",
|
||||
params![id, orbit_id, total],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn insert_wormhole_token(
|
||||
&self,
|
||||
token: &str,
|
||||
outpost_id: &str,
|
||||
code: &str,
|
||||
expires_at: &str,
|
||||
) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO wormhole_tokens (token, outpost_id, code, state, expires_at) VALUES (?1, ?2, ?3, 'code_shown', ?4)",
|
||||
params![token, outpost_id, code, expires_at],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn claim_wormhole_code(
|
||||
&self,
|
||||
code: &str,
|
||||
outpost_name: &str,
|
||||
now: &str,
|
||||
) -> Result<Option<(String, String)>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let changed = conn.execute(
|
||||
"UPDATE wormhole_tokens SET state = 'active', outpost_name = ?2 WHERE code = ?1 AND state = 'code_shown' AND expires_at > ?3",
|
||||
params![code, outpost_name, now],
|
||||
)?;
|
||||
if changed != 1 {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT token, outpost_id FROM wormhole_tokens WHERE code = ?1 AND state = 'active'",
|
||||
)?;
|
||||
let mut rows = stmt.query(params![code])?;
|
||||
let Some(row) = rows.next()? else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some((row.get(0)?, row.get(1)?)))
|
||||
}
|
||||
|
||||
pub fn upload_token_active(&self, token: &str) -> Result<bool> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT 1 FROM wormhole_tokens WHERE token = ?1 AND state = 'active' LIMIT 1",
|
||||
)?;
|
||||
Ok(stmt.query_row(params![token], |_| Ok(())).is_ok())
|
||||
}
|
||||
|
||||
pub fn upload_session(&self, id: &str) -> Result<Option<UploadSession>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT orbit_id, total, sealed FROM upload_sessions WHERE id = ?1",
|
||||
)?;
|
||||
let mut rows = stmt.query(params![id])?;
|
||||
let Some(row) = rows.next()? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let orbit_id: String = row.get(0)?;
|
||||
let total: Option<i64> = row.get(1)?;
|
||||
let sealed: i64 = row.get(2)?;
|
||||
Ok(Some(UploadSession {
|
||||
orbit_id: Uuid::parse_str(&orbit_id).map_err(|e| anyhow::anyhow!(e))?,
|
||||
total: total.unwrap_or(0).max(0) as u64,
|
||||
sealed: sealed != 0,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Records a received range. Returns whether this call won the right to seal.
|
||||
pub fn record_range(&self, session_id: &str, start: u64, end: u64, total: u64) -> Result<bool> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute_batch("BEGIN IMMEDIATE")?;
|
||||
let outcome = (|| -> Result<bool> {
|
||||
let sealed: i64 = conn.query_row(
|
||||
"SELECT sealed FROM upload_sessions WHERE id = ?1",
|
||||
params![session_id],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
if sealed != 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
conn.execute(
|
||||
"INSERT INTO upload_ranges (session_id, start_off, end_off) VALUES (?1, ?2, ?3)",
|
||||
params![session_id, start as i64, end as i64],
|
||||
)?;
|
||||
let mut stmt =
|
||||
conn.prepare("SELECT start_off, end_off FROM upload_ranges WHERE session_id = ?1")?;
|
||||
let ranges = stmt
|
||||
.query_map(params![session_id], |row| {
|
||||
Ok(crate::upload::ByteRange {
|
||||
start: row.get::<_, i64>(0)? as u64,
|
||||
end: row.get::<_, i64>(1)? as u64,
|
||||
})
|
||||
})?
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let covered = crate::upload::contiguous_from_zero(&ranges);
|
||||
conn.execute(
|
||||
"UPDATE upload_sessions SET offset = ?2 WHERE id = ?1",
|
||||
params![session_id, covered as i64],
|
||||
)?;
|
||||
if covered >= total {
|
||||
conn.execute(
|
||||
"UPDATE upload_sessions SET sealed = 1 WHERE id = ?1 AND sealed = 0",
|
||||
params![session_id],
|
||||
)?;
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
})();
|
||||
match outcome {
|
||||
Ok(value) => {
|
||||
conn.execute_batch("COMMIT")?;
|
||||
Ok(value)
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = conn.execute_batch("ROLLBACK");
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mark_upload_unsealed(&self, session_id: &str) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute(
|
||||
"UPDATE upload_sessions SET sealed = 0 WHERE id = ?1",
|
||||
params![session_id],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct UploadSession {
|
||||
pub orbit_id: Uuid,
|
||||
pub total: u64,
|
||||
pub sealed: bool,
|
||||
}
|
||||
|
||||
fn ensure_column(conn: &Connection, table: &str, column: &str, decl: &str) -> Result<()> {
|
||||
let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
|
||||
let names = stmt.query_map([], |row| row.get::<_, String>(1))?;
|
||||
for name in names {
|
||||
if name? == column {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column} {decl}"), [])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
mod admin;
|
||||
mod api;
|
||||
mod db;
|
||||
mod mtls;
|
||||
mod scheduler;
|
||||
mod state;
|
||||
mod upload;
|
||||
|
||||
use anyhow::Result;
|
||||
use state::HubState;
|
||||
@@ -15,10 +18,22 @@ async fn main() -> Result<()> {
|
||||
.init();
|
||||
|
||||
let data_dir = std::env::var("TESSERA_DATA_DIR").unwrap_or_else(|_| "./data".into());
|
||||
let listen = std::env::var("TESSERA_LISTEN").unwrap_or_else(|_| "0.0.0.0:8787".into());
|
||||
let vault_pass = std::env::var("TESSERA_VAULT_PASSPHRASE").unwrap_or_else(|_| "dev-vault-key".into());
|
||||
let listen = std::env::var("TESSERA_LISTEN").unwrap_or_else(|_| "127.0.0.1:8787".into());
|
||||
let vault_pass = std::env::var("TESSERA_VAULT_PASSPHRASE")
|
||||
.ok()
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"TESSERA_VAULT_PASSPHRASE is required and must be non-empty. Tessera does not ship a default passphrase."
|
||||
)
|
||||
})?;
|
||||
if vault_pass == "dev-vault-key" {
|
||||
tracing::warn!(
|
||||
"TESSERA_VAULT_PASSPHRASE is the old published example. New vaults refuse it; set a private passphrase."
|
||||
);
|
||||
}
|
||||
|
||||
let state = HubState::bootstrap(&data_dir, &vault_pass).await?;
|
||||
let mut state = HubState::bootstrap(&data_dir, &vault_pass).await?;
|
||||
|
||||
if std::env::var("TESSERA_SEED_DEMO")
|
||||
.map(|v| v == "1" || v == "true")
|
||||
@@ -26,8 +41,9 @@ async fn main() -> Result<()> {
|
||||
{
|
||||
match tessera_demo::apply(std::path::Path::new(&data_dir), &vault_pass, false) {
|
||||
Ok(r) if !r.skipped => {
|
||||
tracing::info!(
|
||||
"demo seed: {} orbits, {} snapshots",
|
||||
tracing::warn!(
|
||||
"TESSERA_SEED_DEMO wrote demo backup history into {}: {} orbits, {} snapshots",
|
||||
data_dir,
|
||||
r.orbits,
|
||||
r.snapshots
|
||||
);
|
||||
@@ -41,11 +57,37 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
|
||||
scheduler::start_orbit_scheduler(state.clone()).await?;
|
||||
state.admin.log_policy();
|
||||
|
||||
if let Some(wormhole) = mtls::from_env()? {
|
||||
state.wormhole_mtls = true;
|
||||
state.accept_plain_upload = false;
|
||||
let mut tls_state = state.clone();
|
||||
tls_state.accept_plain_upload = true;
|
||||
let listen_addr = wormhole.listen;
|
||||
let tls_app = api::router(tls_state);
|
||||
tokio::spawn(async move {
|
||||
if let Err(error) = mtls::serve(wormhole, tls_app).await {
|
||||
tracing::error!("wormhole mTLS stopped: {error:#}");
|
||||
}
|
||||
});
|
||||
tracing::info!("plain HTTP uploads are closed; wormhole clients use {listen_addr}");
|
||||
}
|
||||
|
||||
let admin_token_unset = state.admin.token.is_none();
|
||||
let app = api::router(state);
|
||||
let addr: SocketAddr = listen.parse()?;
|
||||
if addr.ip().is_unspecified() && admin_token_unset {
|
||||
tracing::warn!(
|
||||
"listening on {addr}; backup APIs reject non-loopback clients until TESSERA_ADMIN_TOKEN is set"
|
||||
);
|
||||
}
|
||||
tracing::info!("Tessera hub listening on {addr}");
|
||||
let listener = tokio::net::TcpListener::bind(addr).await?;
|
||||
axum::serve(listener, app).await?;
|
||||
axum::serve(
|
||||
listener,
|
||||
app.into_make_service_with_connect_info::<SocketAddr>(),
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
145
crates/tessera-hub/src/mtls.rs
Normal file
145
crates/tessera-hub/src/mtls.rs
Normal file
@@ -0,0 +1,145 @@
|
||||
use anyhow::{Context, Result};
|
||||
use axum::body::Body;
|
||||
use axum::extract::Request;
|
||||
use axum::response::Response;
|
||||
use axum::Router;
|
||||
use hyper::body::Incoming;
|
||||
use hyper_util::rt::TokioIo;
|
||||
use hyper_util::service::TowerToHyperService;
|
||||
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
|
||||
use rustls::server::WebPkiClientVerifier;
|
||||
use rustls::RootCertStore;
|
||||
use rustls::ServerConfig;
|
||||
use std::convert::Infallible;
|
||||
use std::fs::File;
|
||||
use std::future::Future;
|
||||
use std::io::BufReader;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::Path;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context as TaskContext, Poll};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_rustls::TlsAcceptor;
|
||||
use tower::{Service, ServiceExt};
|
||||
|
||||
pub struct WormholeMtls {
|
||||
pub listen: SocketAddr,
|
||||
cert: Vec<CertificateDer<'static>>,
|
||||
key: PrivateKeyDer<'static>,
|
||||
client_ca: RootCertStore,
|
||||
}
|
||||
|
||||
pub fn from_env() -> Result<Option<WormholeMtls>> {
|
||||
let raw = std::env::var("TESSERA_WORMHOLE_MTLS").unwrap_or_default();
|
||||
let enabled = raw == "1" || raw.eq_ignore_ascii_case("true");
|
||||
if !enabled {
|
||||
return Ok(None);
|
||||
}
|
||||
let cert = std::env::var("TESSERA_WORMHOLE_CERT").context(
|
||||
"TESSERA_WORMHOLE_CERT is required when TESSERA_WORMHOLE_MTLS is enabled",
|
||||
)?;
|
||||
let key = std::env::var("TESSERA_WORMHOLE_KEY").context(
|
||||
"TESSERA_WORMHOLE_KEY is required when TESSERA_WORMHOLE_MTLS is enabled",
|
||||
)?;
|
||||
let ca = std::env::var("TESSERA_WORMHOLE_CLIENT_CA").context(
|
||||
"TESSERA_WORMHOLE_CLIENT_CA is required when TESSERA_WORMHOLE_MTLS is enabled",
|
||||
)?;
|
||||
let listen = std::env::var("TESSERA_WORMHOLE_LISTEN")
|
||||
.unwrap_or_else(|_| "127.0.0.1:8788".into())
|
||||
.parse()
|
||||
.context("TESSERA_WORMHOLE_LISTEN")?;
|
||||
install_provider();
|
||||
Ok(Some(WormholeMtls {
|
||||
listen,
|
||||
cert: load_certs(Path::new(&cert))?,
|
||||
key: load_key(Path::new(&key))?,
|
||||
client_ca: load_ca(Path::new(&ca))?,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn install_provider() {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
}
|
||||
|
||||
pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> {
|
||||
install_provider();
|
||||
let verifier = WebPkiClientVerifier::builder(Arc::new(mtls.client_ca))
|
||||
.build()
|
||||
.map_err(|error| anyhow::anyhow!("wormhole client CA: {error}"))?;
|
||||
let server = ServerConfig::builder()
|
||||
.with_client_cert_verifier(verifier)
|
||||
.with_single_cert(mtls.cert, mtls.key)
|
||||
.map_err(|error| anyhow::anyhow!("wormhole certificate: {error}"))?;
|
||||
let acceptor = TlsAcceptor::from(Arc::new(server));
|
||||
let listener = TcpListener::bind(mtls.listen)
|
||||
.await
|
||||
.with_context(|| format!("bind wormhole mTLS {}", mtls.listen))?;
|
||||
tracing::info!(
|
||||
"wormhole mTLS listening on {}; a client certificate is required",
|
||||
mtls.listen
|
||||
);
|
||||
loop {
|
||||
let (tcp, _) = listener.accept().await.context("accept wormhole mTLS")?;
|
||||
let acceptor = acceptor.clone();
|
||||
let app = app.clone();
|
||||
tokio::spawn(async move {
|
||||
let Ok(tls) = acceptor.accept(tcp).await else {
|
||||
return;
|
||||
};
|
||||
let io = TokioIo::new(tls);
|
||||
let service = TowerToHyperService::new(HyperApp(app));
|
||||
let _ = hyper::server::conn::http1::Builder::new()
|
||||
.serve_connection(io, service)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct HyperApp(Router);
|
||||
|
||||
impl Service<Request<Incoming>> for HyperApp {
|
||||
type Response = Response;
|
||||
type Error = Infallible;
|
||||
type Future = Pin<Box<dyn Future<Output = Result<Response, Infallible>> + Send>>;
|
||||
|
||||
fn poll_ready(&mut self, _cx: &mut TaskContext<'_>) -> Poll<Result<(), Infallible>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, request: Request<Incoming>) -> Self::Future {
|
||||
let app = self.0.clone();
|
||||
Box::pin(async move {
|
||||
Ok(app
|
||||
.oneshot(request.map(Body::new))
|
||||
.await
|
||||
.unwrap_or_else(|error| match error {}))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load_certs(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
|
||||
let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?);
|
||||
rustls_pemfile::certs(&mut reader)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.context("parse certificate")
|
||||
}
|
||||
|
||||
pub fn load_key(path: &Path) -> Result<PrivateKeyDer<'static>> {
|
||||
let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?);
|
||||
rustls_pemfile::private_key(&mut reader)
|
||||
.context("parse private key")?
|
||||
.context("certificate file has no private key")
|
||||
}
|
||||
|
||||
pub fn load_ca(path: &Path) -> Result<RootCertStore> {
|
||||
let mut roots = RootCertStore::empty();
|
||||
for cert in load_certs(path)? {
|
||||
roots.add(cert).map_err(|error| anyhow::anyhow!("client CA: {error}"))?;
|
||||
}
|
||||
if roots.is_empty() {
|
||||
anyhow::bail!("client CA file contained no certificates");
|
||||
}
|
||||
Ok(roots)
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
use crate::admin::AdminGate;
|
||||
use crate::db::Db;
|
||||
use anyhow::Result;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tessera_core::reconstitute::ReconstituteSession;
|
||||
use tessera_core::wormhole::PairingState;
|
||||
use tessera_store::Vault;
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
use uuid::Uuid;
|
||||
@@ -15,18 +15,13 @@ pub struct HubState {
|
||||
pub data_dir: PathBuf,
|
||||
pub vault_passphrase: String,
|
||||
pub vault: Arc<RwLock<Vault>>,
|
||||
pub pairing_codes: Arc<RwLock<Vec<PairingEntry>>>,
|
||||
pub reconstitute_sessions: Arc<RwLock<HashMap<Uuid, ReconstituteSession>>>,
|
||||
pub active_orbits: Arc<Mutex<HashSet<Uuid>>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PairingEntry {
|
||||
pub code: String,
|
||||
pub expires_at: chrono::DateTime<chrono::Utc>,
|
||||
pub state: PairingState,
|
||||
pub outpost_id: Uuid,
|
||||
pub upload_token: String,
|
||||
pub admin: AdminGate,
|
||||
pub wormhole_mtls: bool,
|
||||
/// Token uploads are accepted on this listener. Plain HTTP turns this off
|
||||
/// when wormhole mTLS is required, so those routes are not a bypass.
|
||||
pub accept_plain_upload: bool,
|
||||
}
|
||||
|
||||
impl HubState {
|
||||
@@ -49,14 +44,15 @@ impl HubState {
|
||||
data_dir,
|
||||
vault_passphrase: vault_pass.to_string(),
|
||||
vault: Arc::new(RwLock::new(vault)),
|
||||
pairing_codes: Arc::new(RwLock::new(Vec::new())),
|
||||
reconstitute_sessions: Arc::new(RwLock::new(HashMap::new())),
|
||||
active_orbits: Arc::new(Mutex::new(HashSet::new())),
|
||||
admin: AdminGate::from_env(),
|
||||
wormhole_mtls: false,
|
||||
accept_plain_upload: true,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn upload_token_valid(&self, token: &str) -> bool {
|
||||
let codes = self.pairing_codes.read().await;
|
||||
codes.iter().any(|c| c.upload_token == token && c.state == PairingState::Active)
|
||||
pub fn upload_token_valid(&self, token: &str) -> bool {
|
||||
self.db.upload_token_active(token).unwrap_or(false)
|
||||
}
|
||||
}
|
||||
|
||||
79
crates/tessera-hub/src/upload.rs
Normal file
79
crates/tessera-hub/src/upload.rs
Normal file
@@ -0,0 +1,79 @@
|
||||
use std::fs::File;
|
||||
use std::io::{self, Seek, SeekFrom, Write};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ByteRange {
|
||||
pub start: u64,
|
||||
pub end: u64,
|
||||
}
|
||||
|
||||
/// Bytes covered from offset 0 with no gap. Overlaps are merged.
|
||||
pub fn contiguous_from_zero(ranges: &[ByteRange]) -> u64 {
|
||||
let mut ordered: Vec<ByteRange> = ranges
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|range| range.end > range.start)
|
||||
.collect();
|
||||
ordered.sort_by_key(|range| (range.start, range.end));
|
||||
let mut covered = 0u64;
|
||||
for range in ordered {
|
||||
if range.start > covered {
|
||||
break;
|
||||
}
|
||||
covered = covered.max(range.end);
|
||||
}
|
||||
covered
|
||||
}
|
||||
|
||||
pub fn write_at(file: &mut File, offset: u64, data: &[u8], total: u64) -> io::Result<ByteRange> {
|
||||
let end = offset.checked_add(data.len() as u64).ok_or_else(|| {
|
||||
io::Error::new(io::ErrorKind::InvalidInput, "chunk offset overflows")
|
||||
})?;
|
||||
if end > total {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"chunk exceeds the declared upload size",
|
||||
));
|
||||
}
|
||||
file.seek(SeekFrom::Start(offset))?;
|
||||
file.write_all(data)?;
|
||||
Ok(ByteRange { start: offset, end })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
#[test]
|
||||
fn out_of_order_chunks_cover_the_object() {
|
||||
assert_eq!(
|
||||
contiguous_from_zero(&[ByteRange { start: 4, end: 8 }]),
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
contiguous_from_zero(&[
|
||||
ByteRange { start: 4, end: 8 },
|
||||
ByteRange { start: 0, end: 4 },
|
||||
]),
|
||||
8
|
||||
);
|
||||
assert_eq!(
|
||||
contiguous_from_zero(&[
|
||||
ByteRange { start: 0, end: 3 },
|
||||
ByteRange { start: 2, end: 5 },
|
||||
]),
|
||||
5
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_honor_offset() {
|
||||
let mut file = NamedTempFile::new().unwrap();
|
||||
write_at(file.as_file_mut(), 3, b"def", 6).unwrap();
|
||||
write_at(file.as_file_mut(), 0, b"abc", 6).unwrap();
|
||||
assert!(write_at(file.as_file_mut(), 4, b"xyz", 6).is_err());
|
||||
let bytes = std::fs::read(file.path()).unwrap();
|
||||
assert_eq!(&bytes[..6], b"abcdef");
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ pub fn provider_from_config(kind: &ProviderKind, config: &Value) -> Result<Box<d
|
||||
match kind {
|
||||
ProviderKind::Filesystem => Ok(Box::new(FilesystemProvider::from_config(config)?)),
|
||||
ProviderKind::Postgres => Ok(Box::new(PostgresProvider::from_config(config)?)),
|
||||
ProviderKind::Command => anyhow::bail!("command provider not implemented in v1"),
|
||||
ProviderKind::Command => anyhow::bail!(
|
||||
"command provider is outside this release; use filesystem or postgres"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,9 @@ use anyhow::{Context, Result};
|
||||
use async_trait::async_trait;
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
use tessera_core::config::ProviderKind;
|
||||
use tokio::process::Command;
|
||||
@@ -22,6 +25,25 @@ pub struct PostgresProvider {
|
||||
config: PostgresConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PgTarget {
|
||||
host: String,
|
||||
port: String,
|
||||
user: String,
|
||||
password: String,
|
||||
dbname: String,
|
||||
}
|
||||
|
||||
struct PgpassFile {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Drop for PgpassFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_file(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
impl PostgresProvider {
|
||||
pub fn from_config(config: &serde_json::Value) -> Result<Self> {
|
||||
let config: PostgresConfig = serde_json::from_value(config.clone())?;
|
||||
@@ -29,6 +51,110 @@ impl PostgresProvider {
|
||||
}
|
||||
}
|
||||
|
||||
fn percent_decode(input: &str) -> Result<String> {
|
||||
let bytes = input.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut index = 0;
|
||||
while index < bytes.len() {
|
||||
if bytes[index] == b'%' && index + 2 < bytes.len() {
|
||||
let hex = std::str::from_utf8(&bytes[index + 1..index + 3]).ok();
|
||||
if let Some(hex) = hex {
|
||||
if let Ok(value) = u8::from_str_radix(hex, 16) {
|
||||
out.push(value);
|
||||
index += 3;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(bytes[index]);
|
||||
index += 1;
|
||||
}
|
||||
String::from_utf8(out).context("connection url is not utf-8")
|
||||
}
|
||||
|
||||
fn parse_postgres_url(url: &str) -> Result<PgTarget> {
|
||||
let rest = url
|
||||
.strip_prefix("postgres://")
|
||||
.or_else(|| url.strip_prefix("postgresql://"))
|
||||
.context("postgres connection_url must start with postgres:// or postgresql://")?;
|
||||
let (userinfo, hostpart) = rest.split_once('@').context("connection url is missing userinfo")?;
|
||||
let (user, password) = userinfo
|
||||
.split_once(':')
|
||||
.context("connection url is missing a password")?;
|
||||
let (hostport, dbpath) = hostpart.split_once('/').context("connection url is missing a database")?;
|
||||
let dbname = dbpath.split('?').next().unwrap_or(dbpath);
|
||||
let (host, port) = if let Some(host) = hostport.strip_prefix('[') {
|
||||
let (host, port) = host
|
||||
.split_once("]:")
|
||||
.context("ipv6 connection url is missing a port")?;
|
||||
(host.to_string(), port.to_string())
|
||||
} else if let Some((host, port)) = hostport.split_once(':') {
|
||||
(host.to_string(), port.to_string())
|
||||
} else {
|
||||
(hostport.to_string(), "5432".into())
|
||||
};
|
||||
if host.is_empty() || dbname.is_empty() {
|
||||
anyhow::bail!("connection url is missing a host or database");
|
||||
}
|
||||
Ok(PgTarget {
|
||||
host,
|
||||
port,
|
||||
user: percent_decode(user)?,
|
||||
password: percent_decode(password)?,
|
||||
dbname: percent_decode(dbname)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn escape_pgpass(value: &str) -> String {
|
||||
value.replace('\\', "\\\\").replace(':', "\\:")
|
||||
}
|
||||
|
||||
fn write_pgpass(target: &PgTarget) -> Result<PgpassFile> {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"tessera-pgpass-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0)
|
||||
));
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&path)
|
||||
.context("create pgpass file")?;
|
||||
restrict_secret_file(&path)?;
|
||||
let line = format!(
|
||||
"{}:{}:{}:{}:{}\n",
|
||||
escape_pgpass(&target.host),
|
||||
escape_pgpass(&target.port),
|
||||
escape_pgpass(&target.dbname),
|
||||
escape_pgpass(&target.user),
|
||||
escape_pgpass(&target.password)
|
||||
);
|
||||
file.write_all(line.as_bytes())?;
|
||||
Ok(PgpassFile { path })
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
|
||||
fn dump_args(format: &str) -> Result<Vec<String>> {
|
||||
match format {
|
||||
"custom" => Ok(vec!["-Fc".into(), "-w".into()]),
|
||||
"plain" => Ok(vec!["-w".into()]),
|
||||
other => anyhow::bail!("unknown pg format: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BackupProvider for PostgresProvider {
|
||||
fn kind(&self) -> ProviderKind {
|
||||
@@ -36,17 +162,20 @@ impl BackupProvider for PostgresProvider {
|
||||
}
|
||||
|
||||
async fn capture(&self) -> Result<CaptureResult> {
|
||||
let target = parse_postgres_url(&self.config.connection_url)?;
|
||||
let args = dump_args(&self.config.format)?;
|
||||
let pgpass = write_pgpass(&target)?;
|
||||
let mut cmd = Command::new("pg_dump");
|
||||
cmd.arg(&self.config.connection_url);
|
||||
match self.config.format.as_str() {
|
||||
"custom" => {
|
||||
cmd.arg("-Fc");
|
||||
}
|
||||
"plain" => {}
|
||||
other => anyhow::bail!("unknown pg format: {other}"),
|
||||
}
|
||||
cmd.args(&args);
|
||||
cmd.env("PGPASSFILE", &pgpass.path);
|
||||
cmd.env("PGHOST", &target.host);
|
||||
cmd.env("PGPORT", &target.port);
|
||||
cmd.env("PGUSER", &target.user);
|
||||
cmd.env("PGDATABASE", &target.dbname);
|
||||
cmd.env_remove("PGPASSWORD");
|
||||
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
let output = cmd.output().await.context("pg_dump failed to start")?;
|
||||
drop(pgpass);
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
anyhow::bail!("pg_dump failed: {stderr}");
|
||||
@@ -56,8 +185,30 @@ impl BackupProvider for PostgresProvider {
|
||||
labels: vec!["postgres".into()],
|
||||
restore_hints: json!({
|
||||
"format": self.config.format,
|
||||
"restore_command_hint": "pg_restore -d $DATABASE_URL dump.file"
|
||||
"restore_command_hint": "pg_restore -d \"$DATABASE_URL\" dump.file"
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
#[test]
|
||||
fn pg_dump_keeps_the_url_out_of_argv() {
|
||||
let target = parse_postgres_url("postgres://migrator:s%3Acret@db.internal:5433/billing").unwrap();
|
||||
assert_eq!(target.password, "s:cret");
|
||||
let args = dump_args("custom").unwrap();
|
||||
let pgpass = write_pgpass(&target).unwrap();
|
||||
let rendered = fs::read_to_string(&pgpass.path).unwrap();
|
||||
assert!(rendered.contains("s\\:cret"));
|
||||
assert!(!args.iter().any(|arg| arg.contains("s:cret") || arg.contains("postgres://")));
|
||||
let mode = fs::metadata(&pgpass.path).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o600);
|
||||
let joined = args.join(" ");
|
||||
assert!(!joined.contains(&target.password));
|
||||
assert!(!joined.contains(&target.user));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ license.workspace = true
|
||||
tessera-core = { path = "../tessera-core" }
|
||||
anyhow.workspace = true
|
||||
aes-gcm.workspace = true
|
||||
pbkdf2.workspace = true
|
||||
argon2.workspace = true
|
||||
hmac.workspace = true
|
||||
sha2.workspace = true
|
||||
chrono.workspace = true
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user