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

@@ -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));
}
}