feat: add managed database capture and operator restore
PostgreSQL and MySQL backups run through paired outposts, with operator sign-in, off-site copies, and legacy import. Retention stays on each orbit, so the unused retention console is removed. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,13 +1,13 @@
|
||||
use super::{BackupProvider, CaptureResult};
|
||||
use super::{ssh::loopback_listener, BackupProvider, CaptureResult, SshEndpoint};
|
||||
use anyhow::{Context, Result};
|
||||
use async_trait::async_trait;
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::PathBuf;
|
||||
use std::process::Stdio;
|
||||
use tessera_core::config::ProviderKind;
|
||||
use tessera_core::{config::ProviderKind, restore::DatabaseIdentity};
|
||||
use tokio::process::Command;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
@@ -25,7 +25,6 @@ pub struct PostgresProvider {
|
||||
config: PostgresConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PgTarget {
|
||||
host: String,
|
||||
port: String,
|
||||
@@ -34,19 +33,118 @@ struct PgTarget {
|
||||
dbname: String,
|
||||
}
|
||||
|
||||
struct PgpassFile {
|
||||
path: PathBuf,
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PostgresSource {
|
||||
pub host: String,
|
||||
#[serde(default = "default_port")]
|
||||
pub port: u16,
|
||||
pub database: String,
|
||||
pub user: String,
|
||||
pub password_file: PathBuf,
|
||||
#[serde(default)]
|
||||
pub tls: PostgresTls,
|
||||
pub bastion: Option<SshEndpoint>,
|
||||
}
|
||||
|
||||
impl Drop for PgpassFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_file(&self.path);
|
||||
fn default_port() -> u16 {
|
||||
5432
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum PostgresTls {
|
||||
#[default]
|
||||
VerifyFull,
|
||||
VerifyFullWithCa {
|
||||
ca_file: PathBuf,
|
||||
},
|
||||
Require,
|
||||
Disable,
|
||||
}
|
||||
|
||||
impl PostgresSource {
|
||||
pub async fn dump_to(&self, file: fs::File, format: &str) -> Result<()> {
|
||||
self.dump_archive(file, format, false).await
|
||||
}
|
||||
|
||||
pub async fn safety_dump_to(&self, file: fs::File) -> Result<()> {
|
||||
self.dump_archive(file, "custom", true).await
|
||||
}
|
||||
|
||||
async fn dump_archive(&self, file: fs::File, format: &str, preserve_permissions: bool) -> Result<()> {
|
||||
let mut args = dump_args(format)?;
|
||||
if !preserve_permissions {
|
||||
args.extend(["--no-owner".into(), "--no-acl".into()]);
|
||||
}
|
||||
self.run(
|
||||
"pg_dump",
|
||||
&args,
|
||||
None,
|
||||
Stdio::null(),
|
||||
Stdio::from(file.try_clone()?),
|
||||
)
|
||||
.await?;
|
||||
anyhow::ensure!(file.metadata()?.len() > 0, "pg_dump produced an empty file");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn identity(&self) -> Result<DatabaseIdentity> {
|
||||
let args = ["-X", "-w", "-At", "-v", "ON_ERROR_STOP=1", "-c",
|
||||
"SELECT json_build_object('instance', system_identifier::text, 'database', pg_catalog.current_database()) FROM pg_catalog.pg_control_system()"];
|
||||
let args = args.map(String::from);
|
||||
let output = self
|
||||
.run("psql", &args, None, Stdio::null(), Stdio::piped())
|
||||
.await?;
|
||||
serde_json::from_slice(&output.stdout).context("invalid PostgreSQL identity")
|
||||
}
|
||||
|
||||
pub(crate) async fn run(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
database: Option<&str>,
|
||||
stdin: Stdio,
|
||||
stdout: Stdio,
|
||||
) -> Result<std::process::Output> {
|
||||
let password =
|
||||
fs::read_to_string(&self.password_file).context("read PostgreSQL password file")?;
|
||||
let mut target = PgTarget {
|
||||
host: self.host.clone(),
|
||||
port: self.port.to_string(),
|
||||
dbname: database.unwrap_or(&self.database).to_owned(),
|
||||
user: self.user.clone(),
|
||||
password: password.trim_end_matches(['\r', '\n']).to_owned(),
|
||||
};
|
||||
anyhow::ensure!(
|
||||
!target.host.contains(',') && self.port != 0,
|
||||
"invalid PostgreSQL endpoint"
|
||||
);
|
||||
let spec = PgProcess {
|
||||
program,
|
||||
args,
|
||||
stdin,
|
||||
stdout,
|
||||
};
|
||||
if let Some(bastion) = &self.bastion {
|
||||
let listener = loopback_listener().await?;
|
||||
target.port = listener.local_addr()?.port().to_string();
|
||||
let forwarding = bastion.forward(listener, &self.host, self.port);
|
||||
tokio::select! {
|
||||
result = run_pg(&target, spec, Some((&self.tls, true))) => result,
|
||||
result = forwarding => { result?; anyhow::bail!("SSH forwarding stopped"); }
|
||||
}
|
||||
} else {
|
||||
run_pg(&target, spec, Some((&self.tls, false))).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PostgresProvider {
|
||||
pub fn from_config(config: &serde_json::Value) -> Result<Self> {
|
||||
let config: PostgresConfig = serde_json::from_value(config.clone())?;
|
||||
parse_postgres_url(&config.connection_url)?;
|
||||
dump_args(&config.format)?;
|
||||
Ok(Self { config })
|
||||
}
|
||||
|
||||
@@ -59,30 +157,17 @@ impl PostgresProvider {
|
||||
async fn dump(&self, stdout: Stdio) -> Result<std::process::Output> {
|
||||
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");
|
||||
let output = cmd
|
||||
.args(args)
|
||||
.env("PGPASSFILE", &pgpass.path)
|
||||
.env("PGHOST", &target.host)
|
||||
.env("PGPORT", &target.port)
|
||||
.env("PGUSER", &target.user)
|
||||
.env("PGDATABASE", &target.dbname)
|
||||
.env_remove("PGPASSWORD")
|
||||
.stdout(stdout)
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.context("pg_dump failed to start")?
|
||||
.wait_with_output()
|
||||
.await
|
||||
.context("waiting for pg_dump")?;
|
||||
anyhow::ensure!(
|
||||
output.status.success(),
|
||||
"pg_dump failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
Ok(output)
|
||||
run_pg(
|
||||
&target,
|
||||
PgProcess {
|
||||
program: "pg_dump",
|
||||
args: &args,
|
||||
stdin: Stdio::null(),
|
||||
stdout,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn restore_hints(&self) -> serde_json::Value {
|
||||
@@ -121,11 +206,15 @@ fn parse_postgres_url(url: &str) -> Result<PgTarget> {
|
||||
.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 (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 (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
|
||||
@@ -153,42 +242,89 @@ 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 })
|
||||
struct PgProcess<'a> {
|
||||
program: &'a str,
|
||||
args: &'a [String],
|
||||
stdin: Stdio,
|
||||
stdout: Stdio,
|
||||
}
|
||||
|
||||
fn restrict_secret_file(path: &Path) -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
|
||||
async fn run_pg(
|
||||
target: &PgTarget,
|
||||
process: PgProcess<'_>,
|
||||
tls: Option<(&PostgresTls, bool)>,
|
||||
) -> Result<std::process::Output> {
|
||||
let pgpass = write_pgpass(target, tls.is_some())?;
|
||||
let mut cmd = Command::new(process.program);
|
||||
if let Some((tls, forwarded)) = tls {
|
||||
// Local profiles explicitly control the libpq endpoint and TLS policy.
|
||||
for (name, _) in std::env::vars_os() {
|
||||
if name.to_string_lossy().starts_with("PG") {
|
||||
cmd.env_remove(name);
|
||||
}
|
||||
}
|
||||
if forwarded {
|
||||
cmd.env("PGHOSTADDR", "127.0.0.1");
|
||||
}
|
||||
let mode = match tls {
|
||||
PostgresTls::VerifyFull => "verify-full",
|
||||
PostgresTls::VerifyFullWithCa { ca_file } => {
|
||||
cmd.env("PGSSLROOTCERT", ca_file);
|
||||
"verify-full"
|
||||
}
|
||||
PostgresTls::Require => "require",
|
||||
PostgresTls::Disable => "disable",
|
||||
};
|
||||
cmd.env("PGSSLMODE", mode).env("PGGSSENCMODE", "disable");
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = path;
|
||||
Ok(())
|
||||
let output = cmd
|
||||
.args(process.args)
|
||||
.env("PGPASSFILE", pgpass.path())
|
||||
.env("PGHOST", &target.host)
|
||||
.env("PGPORT", &target.port)
|
||||
.env("PGUSER", &target.user)
|
||||
.env("PGDATABASE", &target.dbname)
|
||||
.env_remove("PGPASSWORD")
|
||||
.stdin(process.stdin)
|
||||
.stdout(process.stdout)
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.context("starting PostgreSQL client")?
|
||||
.wait_with_output()
|
||||
.await
|
||||
.context("waiting for PostgreSQL client")?;
|
||||
anyhow::ensure!(
|
||||
output.status.success(),
|
||||
"{} failed ({})",
|
||||
process.program,
|
||||
output.status
|
||||
);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn write_pgpass(target: &PgTarget, any_database: bool) -> Result<tempfile::NamedTempFile> {
|
||||
let fields = [
|
||||
&target.host,
|
||||
&target.port,
|
||||
&target.dbname,
|
||||
&target.user,
|
||||
&target.password,
|
||||
];
|
||||
anyhow::ensure!(
|
||||
fields
|
||||
.iter()
|
||||
.all(|field| !field.is_empty() && !field.contains(['\n', '\r', '\0'])),
|
||||
"invalid PostgreSQL connection field"
|
||||
);
|
||||
let mut file = tempfile::NamedTempFile::new().context("create pgpass file")?;
|
||||
let mut fields = fields.map(|value| escape_pgpass(value));
|
||||
if any_database {
|
||||
fields[2] = "*".into();
|
||||
}
|
||||
let line = fields.join(":");
|
||||
writeln!(file, "{line}")?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
fn dump_args(format: &str) -> Result<Vec<String>> {
|
||||
@@ -222,14 +358,17 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn pg_dump_keeps_the_url_out_of_argv() {
|
||||
let target = parse_postgres_url("postgres://migrator:s%3Acret@db.internal:5433/billing").unwrap();
|
||||
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();
|
||||
let pgpass = write_pgpass(&target, false).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!(!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));
|
||||
|
||||
Reference in New Issue
Block a user