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,8 +1,16 @@
|
||||
mod filesystem;
|
||||
mod mysql;
|
||||
mod mysql_restore;
|
||||
mod postgres;
|
||||
mod postgres_restore;
|
||||
mod ssh;
|
||||
|
||||
pub use filesystem::*;
|
||||
pub use mysql::MysqlSource;
|
||||
pub use mysql_restore::MysqlRestore;
|
||||
pub use postgres::*;
|
||||
pub use postgres_restore::{PostgresReset, PostgresRestore};
|
||||
pub use ssh::SshEndpoint;
|
||||
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
|
||||
238
crates/tessera-providers/src/mysql.rs
Normal file
238
crates/tessera-providers/src/mysql.rs
Normal file
@@ -0,0 +1,238 @@
|
||||
use crate::SshEndpoint;
|
||||
use anyhow::{Context, Result};
|
||||
use serde::Deserialize;
|
||||
use std::{fs, io::Write, path::PathBuf, process::Stdio};
|
||||
use tessera_core::restore::DatabaseIdentity;
|
||||
use tokio::process::Command;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "transport", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum MysqlSource {
|
||||
Direct {
|
||||
host: String,
|
||||
#[serde(default = "default_port")]
|
||||
port: u16,
|
||||
database: String,
|
||||
user: String,
|
||||
password_file: PathBuf,
|
||||
#[serde(default)]
|
||||
tls: MysqlTls,
|
||||
},
|
||||
Ssh {
|
||||
bastion: SshEndpoint,
|
||||
database: String,
|
||||
defaults_file: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn default_port() -> u16 {
|
||||
3306
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum MysqlTls {
|
||||
#[default]
|
||||
VerifyIdentity,
|
||||
VerifyIdentityWithCa {
|
||||
ca_file: PathBuf,
|
||||
},
|
||||
Required,
|
||||
Disabled,
|
||||
}
|
||||
|
||||
const FLAGS: &[&str] = &[
|
||||
"--single-transaction",
|
||||
"--skip-dump-date",
|
||||
"--skip-lock-tables",
|
||||
"--no-tablespaces",
|
||||
"--set-gtid-purged=OFF",
|
||||
"--default-character-set=utf8mb4",
|
||||
"--routines",
|
||||
"--events",
|
||||
"--triggers",
|
||||
];
|
||||
|
||||
impl MysqlSource {
|
||||
pub async fn dump_to(&self, file: fs::File) -> Result<()> {
|
||||
self.run(
|
||||
"mysqldump",
|
||||
FLAGS,
|
||||
Stdio::null(),
|
||||
Stdio::from(file.try_clone()?),
|
||||
)
|
||||
.await?;
|
||||
anyhow::ensure!(
|
||||
file.metadata()?.len() > 0,
|
||||
"MySQL dump produced an empty file"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn database(&self) -> &str {
|
||||
match self {
|
||||
Self::Direct { database, .. } | Self::Ssh { database, .. } => database,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn identity(&self) -> Result<DatabaseIdentity> {
|
||||
let output = self
|
||||
.run(
|
||||
"mysql",
|
||||
&[
|
||||
"--batch",
|
||||
"--raw",
|
||||
"--skip-column-names",
|
||||
"--default-character-set=utf8mb4",
|
||||
"--execute",
|
||||
"SELECT JSON_OBJECT('instance', LOWER(@@server_uuid), 'database', DATABASE())",
|
||||
],
|
||||
Stdio::null(),
|
||||
Stdio::piped(),
|
||||
)
|
||||
.await?;
|
||||
serde_json::from_slice(&output.stdout).context("invalid MySQL identity")
|
||||
}
|
||||
|
||||
pub(crate) async fn run(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[&str],
|
||||
stdin: Stdio,
|
||||
stdout: Stdio,
|
||||
) -> Result<std::process::Output> {
|
||||
let config;
|
||||
let mut cmd = match self {
|
||||
Self::Direct {
|
||||
host,
|
||||
port,
|
||||
database,
|
||||
user,
|
||||
password_file,
|
||||
tls,
|
||||
} => {
|
||||
validate_database(database)?;
|
||||
anyhow::ensure!(
|
||||
!host.is_empty() && *port != 0 && !user.is_empty(),
|
||||
"invalid MySQL endpoint"
|
||||
);
|
||||
let password =
|
||||
fs::read_to_string(password_file).context("read MySQL password file")?;
|
||||
let mut defaults =
|
||||
tempfile::NamedTempFile::new().context("create private MySQL options file")?;
|
||||
writeln!(
|
||||
defaults,
|
||||
"[client]\npassword={}",
|
||||
option_value(password.trim_end_matches(['\r', '\n']))?
|
||||
)?;
|
||||
let mut cmd = Command::new(program);
|
||||
cmd.arg(format!("--defaults-file={}", defaults.path().display()))
|
||||
.arg("--protocol=TCP")
|
||||
.arg("--host")
|
||||
.arg(host)
|
||||
.arg("--port")
|
||||
.arg(port.to_string())
|
||||
.arg("--user")
|
||||
.arg(user);
|
||||
let mode = match tls {
|
||||
MysqlTls::VerifyIdentity => "VERIFY_IDENTITY",
|
||||
MysqlTls::VerifyIdentityWithCa { ca_file } => {
|
||||
cmd.arg("--ssl-ca").arg(ca_file);
|
||||
"VERIFY_IDENTITY"
|
||||
}
|
||||
MysqlTls::Required => "REQUIRED",
|
||||
MysqlTls::Disabled => "DISABLED",
|
||||
};
|
||||
cmd.arg(format!("--ssl-mode={mode}"))
|
||||
.args(args)
|
||||
.args(["--", database]);
|
||||
config = Some(defaults);
|
||||
cmd
|
||||
}
|
||||
Self::Ssh {
|
||||
bastion,
|
||||
database,
|
||||
defaults_file,
|
||||
} => {
|
||||
validate_database(database)?;
|
||||
anyhow::ensure!(
|
||||
defaults_file.starts_with('/') && !defaults_file.contains(['\0', '\r', '\n']),
|
||||
"invalid remote options path"
|
||||
);
|
||||
let mut cmd = bastion.command()?;
|
||||
let options = shell_arg(&format!("--defaults-file={defaults_file}"));
|
||||
let database = shell_arg(database);
|
||||
let args = args
|
||||
.iter()
|
||||
.map(|arg| shell_arg(arg))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let command = format!("env -u MYSQL_PWD MYSQL_TEST_LOGIN_FILE=/dev/null {program} {options} {args} -- {database}");
|
||||
cmd.args(["--", &bastion.host, &command]);
|
||||
config = None;
|
||||
cmd
|
||||
}
|
||||
};
|
||||
let output = cmd
|
||||
.env_remove("MYSQL_PWD")
|
||||
.env("MYSQL_TEST_LOGIN_FILE", "/dev/null")
|
||||
.stdin(stdin)
|
||||
.stderr(Stdio::null())
|
||||
.stdout(stdout)
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.context("start MySQL client")?
|
||||
.wait_with_output()
|
||||
.await
|
||||
.context("wait for MySQL client")?;
|
||||
drop(config);
|
||||
anyhow::ensure!(
|
||||
output.status.success(),
|
||||
"{program} failed ({})",
|
||||
output.status
|
||||
);
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_database(database: &str) -> Result<()> {
|
||||
anyhow::ensure!(
|
||||
!database.is_empty() && !database.contains(['\0', '\r', '\n']),
|
||||
"invalid MySQL database name"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn option_value(value: &str) -> Result<String> {
|
||||
anyhow::ensure!(
|
||||
!value.is_empty() && !value.contains(['\0', '\r', '\n']),
|
||||
"invalid MySQL password"
|
||||
);
|
||||
Ok(format!(
|
||||
"\"{}\"",
|
||||
value.replace('\\', "\\\\").replace('"', "\\\"")
|
||||
))
|
||||
}
|
||||
|
||||
fn shell_arg(value: &str) -> String {
|
||||
format!("'{}'", value.replace('\'', "'\\''"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn remote_database_and_options_are_literal_shell_arguments() {
|
||||
let value = "space 'quote' $(exit 23)";
|
||||
let script = format!("printf '%s' {}", shell_arg(value));
|
||||
let result = std::process::Command::new("sh")
|
||||
.args(["-c", &script])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(result.status.success());
|
||||
assert_eq!(result.stdout, value.as_bytes());
|
||||
assert!(option_value("secret\n[client]").is_err());
|
||||
assert_eq!(option_value("a\\b\"#c").unwrap(), "\"a\\\\b\\\"#c\"");
|
||||
}
|
||||
}
|
||||
94
crates/tessera-providers/src/mysql_restore.rs
Normal file
94
crates/tessera-providers/src/mysql_restore.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
use crate::MysqlSource;
|
||||
use anyhow::{ensure, Result};
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{BufRead, BufReader, Seek, SeekFrom, Write},
|
||||
process::Stdio,
|
||||
};
|
||||
use tessera_core::restore::{DatabaseIdentity, Engine};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct MysqlRestore {
|
||||
pub connection: MysqlSource,
|
||||
#[serde(default)]
|
||||
pub recreate_database: bool,
|
||||
#[serde(default)]
|
||||
pub use_target_definer: bool,
|
||||
}
|
||||
|
||||
impl MysqlRestore {
|
||||
pub async fn prepare(&self, mut dump: File, expected: &DatabaseIdentity) -> Result<File> {
|
||||
ensure!(
|
||||
expected.valid(Engine::Mysql) && expected.database == self.connection.database(),
|
||||
"MySQL target identity does not match the local profile"
|
||||
);
|
||||
ensure!(
|
||||
!matches!(
|
||||
expected.database.to_ascii_lowercase().as_str(),
|
||||
"mysql" | "information_schema" | "performance_schema" | "sys"
|
||||
),
|
||||
"system database restore is forbidden"
|
||||
);
|
||||
dump.seek(SeekFrom::Start(0))?;
|
||||
let mut script = tempfile::tempfile()?;
|
||||
let database = mysql_hex(&expected.database);
|
||||
let instance = mysql_hex(&expected.instance);
|
||||
// PREPARE fails before any DDL if this connection resolves to the wrong target.
|
||||
writeln!(script, "SET @tessera_guard = IF(BINARY LOWER(@@server_uuid) = {instance} AND BINARY DATABASE() = {database}, 'DO 0', 'TESSERA_RESTORE_TARGET_MISMATCH');")?;
|
||||
writeln!(script, "PREPARE tessera_guard FROM @tessera_guard;\nEXECUTE tessera_guard;\nDEALLOCATE PREPARE tessera_guard;")?;
|
||||
if self.recreate_database {
|
||||
let name = format!("`{}`", expected.database.replace('`', "``"));
|
||||
writeln!(
|
||||
script,
|
||||
"DROP DATABASE {name};\nCREATE DATABASE {name} CHARACTER SET utf8mb4;\nUSE {name};"
|
||||
)?;
|
||||
}
|
||||
let use_target_definer = self.use_target_definer;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
if use_target_definer {
|
||||
let definer = regex::bytes::Regex::new(
|
||||
r"^(CREATE |/\*![0-9]{5} )DEFINER=`(?:[^`]|``)*`@`(?:[^`]|``)*`",
|
||||
)?;
|
||||
let mut reader = BufReader::new(dump);
|
||||
let mut line = Vec::new();
|
||||
while reader.read_until(b'\n', &mut line)? > 0 {
|
||||
script.write_all(&definer.replace(&line, &b"${1}DEFINER=CURRENT_USER"[..]))?;
|
||||
line.clear();
|
||||
}
|
||||
} else {
|
||||
std::io::copy(&mut dump, &mut script)?;
|
||||
}
|
||||
script.seek(SeekFrom::Start(0))?;
|
||||
Ok(script)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
pub async fn apply(&self, script: File) -> Result<()> {
|
||||
self.connection
|
||||
.run(
|
||||
"mysql",
|
||||
&[
|
||||
"--binary-mode",
|
||||
"--skip-reconnect",
|
||||
"--skip-force",
|
||||
"--default-character-set=utf8mb4",
|
||||
],
|
||||
Stdio::from(script),
|
||||
Stdio::null(),
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn mysql_hex(value: &str) -> String {
|
||||
use std::fmt::Write;
|
||||
let mut literal = String::from("0x");
|
||||
for byte in value.bytes() {
|
||||
write!(literal, "{byte:02x}").expect("writing to String cannot fail");
|
||||
}
|
||||
literal
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
265
crates/tessera-providers/src/postgres_restore.rs
Normal file
265
crates/tessera-providers/src/postgres_restore.rs
Normal file
@@ -0,0 +1,265 @@
|
||||
use crate::PostgresSource;
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
fs::{self, File},
|
||||
io::{self, BufRead, BufReader, Read, Seek, SeekFrom, Write},
|
||||
path::PathBuf,
|
||||
process::Stdio,
|
||||
};
|
||||
use tessera_core::{
|
||||
job::CaptureFormat,
|
||||
restore::{DatabaseIdentity, Engine},
|
||||
};
|
||||
use tokio::process::Command;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "reset", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum PostgresReset {
|
||||
Schema {
|
||||
#[serde(default = "public")]
|
||||
schema: String,
|
||||
},
|
||||
RecreateDatabase,
|
||||
}
|
||||
|
||||
fn public() -> String {
|
||||
"public".into()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PostgresRestore {
|
||||
pub connection: PostgresSource,
|
||||
pub mode: PostgresReset,
|
||||
pub post_restore_sql: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
pub omit_transaction_timeout: bool,
|
||||
#[serde(default)]
|
||||
pub omit_pg_stat_statements: bool,
|
||||
}
|
||||
|
||||
impl PostgresRestore {
|
||||
pub async fn prepare(
|
||||
&self,
|
||||
mut dump: File,
|
||||
format: CaptureFormat,
|
||||
expected: &DatabaseIdentity,
|
||||
) -> Result<File> {
|
||||
ensure!(
|
||||
expected.valid(Engine::Postgres) && expected.database == self.connection.database,
|
||||
"PostgreSQL target identity does not match the local profile"
|
||||
);
|
||||
ensure!(
|
||||
!matches!(
|
||||
expected.database.as_str(),
|
||||
"postgres" | "template0" | "template1"
|
||||
),
|
||||
"system database restore is forbidden"
|
||||
);
|
||||
let help = Command::new("psql")
|
||||
.arg("--help=commands")
|
||||
.kill_on_drop(true)
|
||||
.output()
|
||||
.await?;
|
||||
ensure!(
|
||||
help.status.success()
|
||||
&& help
|
||||
.stdout
|
||||
.windows(b"\\restrict".len())
|
||||
.any(|word| word == b"\\restrict"),
|
||||
"PostgreSQL restore requires a psql client with restricted mode"
|
||||
);
|
||||
dump.seek(SeekFrom::Start(0))?;
|
||||
let mut data = match format {
|
||||
CaptureFormat::PostgresCustom => {
|
||||
convert(
|
||||
dump,
|
||||
"pg_restore",
|
||||
&["--no-owner", "--no-privileges", "--file=-"],
|
||||
)
|
||||
.await?
|
||||
}
|
||||
CaptureFormat::PostgresSql => {
|
||||
let mut signature = [0; 2];
|
||||
dump.read_exact(&mut signature)?;
|
||||
dump.seek(SeekFrom::Start(0))?;
|
||||
if signature == [0x1f, 0x8b] {
|
||||
convert(dump, "gzip", &["-dc"]).await?
|
||||
} else {
|
||||
dump
|
||||
}
|
||||
}
|
||||
_ => anyhow::bail!("invalid PostgreSQL dump format"),
|
||||
};
|
||||
data.seek(SeekFrom::Start(0))?;
|
||||
let mut script = tempfile::tempfile()?;
|
||||
writeln!(script, "SET standard_conforming_strings = on;")?;
|
||||
let instance = literal(&expected.instance);
|
||||
let database = literal(&expected.database);
|
||||
match &self.mode {
|
||||
PostgresReset::Schema { schema } => {
|
||||
ensure!(
|
||||
!schema.is_empty()
|
||||
&& schema.len() <= 63
|
||||
&& !schema.chars().any(char::is_control)
|
||||
&& schema != "information_schema"
|
||||
&& !schema.starts_with("pg_"),
|
||||
"invalid target schema"
|
||||
);
|
||||
writeln!(script, "BEGIN;")?;
|
||||
writeln!(script, "SELECT 1 / ((system_identifier::text = {instance} AND pg_catalog.current_database() = {database})::int) FROM pg_catalog.pg_control_system();")?;
|
||||
writeln!(
|
||||
script,
|
||||
"DROP SCHEMA IF EXISTS {} CASCADE;",
|
||||
identifier(schema)
|
||||
)?;
|
||||
if schema == "public" {
|
||||
writeln!(script, "CREATE SCHEMA public;")?;
|
||||
}
|
||||
}
|
||||
PostgresReset::RecreateDatabase => {
|
||||
ensure!(
|
||||
expected
|
||||
.database
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_'),
|
||||
"recreate mode requires an alphanumeric database identifier"
|
||||
);
|
||||
writeln!(script, "SELECT 1 / ((system_identifier::text = {instance} AND EXISTS (SELECT 1 FROM pg_catalog.pg_database WHERE datname = {database}))::int) FROM pg_catalog.pg_control_system();")?;
|
||||
let name = identifier(&expected.database);
|
||||
writeln!(
|
||||
script,
|
||||
"DROP DATABASE {name};\nCREATE DATABASE {name};\n\\connect {}",
|
||||
expected.database
|
||||
)?;
|
||||
writeln!(script, "SELECT 1 / ((system_identifier::text = {instance} AND pg_catalog.current_database() = {database})::int) FROM pg_catalog.pg_control_system();")?;
|
||||
writeln!(script, "BEGIN;")?;
|
||||
}
|
||||
}
|
||||
let key = uuid::Uuid::new_v4().simple();
|
||||
writeln!(script, "\\restrict {key}")?;
|
||||
let skip_timeout = self.omit_transaction_timeout;
|
||||
let skip_extension = self.omit_pg_stat_statements;
|
||||
let create_public =
|
||||
matches!(&self.mode, PostgresReset::Schema { schema } if schema == "public");
|
||||
let post_sql = self.post_restore_sql.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
append_dump(
|
||||
data,
|
||||
&mut script,
|
||||
skip_timeout,
|
||||
skip_extension,
|
||||
create_public,
|
||||
)?;
|
||||
if let Some(path) = post_sql {
|
||||
io::copy(
|
||||
&mut fs::File::open(path).context("read local post-restore SQL")?,
|
||||
&mut script,
|
||||
)?;
|
||||
}
|
||||
writeln!(script, "\nCOMMIT;\n\\unrestrict {key}")?;
|
||||
script.seek(SeekFrom::Start(0))?;
|
||||
Ok(script)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
pub async fn apply(&self, script: File) -> Result<()> {
|
||||
let database = match self.mode {
|
||||
PostgresReset::RecreateDatabase => Some("postgres"),
|
||||
PostgresReset::Schema { .. } => None,
|
||||
};
|
||||
let args = ["-X", "-w", "-q", "-v", "ON_ERROR_STOP=1", "-f", "-"].map(String::from);
|
||||
self.connection
|
||||
.run("psql", &args, database, Stdio::from(script), Stdio::null())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn literal(value: &str) -> String {
|
||||
format!("'{}'", value.replace('\'', "''"))
|
||||
}
|
||||
|
||||
fn identifier(value: &str) -> String {
|
||||
format!("\"{}\"", value.replace('"', "\"\""))
|
||||
}
|
||||
|
||||
async fn convert(input: File, executable: &str, args: &[&str]) -> Result<File> {
|
||||
let file = tempfile::tempfile()?;
|
||||
let status = Command::new(executable)
|
||||
.args(args)
|
||||
.stdin(Stdio::from(input))
|
||||
.stdout(Stdio::from(file.try_clone()?))
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.status()
|
||||
.await
|
||||
.context("prepare PostgreSQL restore script")?;
|
||||
ensure!(
|
||||
status.success(),
|
||||
"{executable} rejected the restore archive"
|
||||
);
|
||||
ensure!(
|
||||
file.metadata()?.len() > 0,
|
||||
"empty PostgreSQL restore script"
|
||||
);
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
fn append_dump(
|
||||
data: File,
|
||||
script: &mut File,
|
||||
skip_timeout: bool,
|
||||
skip_extension: bool,
|
||||
create_public: bool,
|
||||
) -> Result<()> {
|
||||
let mut input = BufReader::new(data);
|
||||
let mut header = true;
|
||||
let mut extension_statement = false;
|
||||
let mut copy_data = false;
|
||||
let mut line = Vec::new();
|
||||
while input.read_until(b'\n', &mut line)? > 0 {
|
||||
let text = line.strip_suffix(b"\n").unwrap_or(&line);
|
||||
if copy_data {
|
||||
script.write_all(&line)?;
|
||||
copy_data = text != b"\\.";
|
||||
line.clear();
|
||||
continue;
|
||||
}
|
||||
if text.starts_with(b"-- Name: ") {
|
||||
extension_statement = skip_extension
|
||||
&& (text.starts_with(b"-- Name: pg_stat_statements; Type: EXTENSION;")
|
||||
|| text.starts_with(b"-- Name: EXTENSION pg_stat_statements; Type: COMMENT;"));
|
||||
header = false;
|
||||
}
|
||||
// Tessera installs its own restricted-mode key. Archive-generated keys are redundant.
|
||||
let own_restriction = [b"\\restrict ".as_slice(), b"\\unrestrict ".as_slice()]
|
||||
.iter()
|
||||
.any(|prefix| {
|
||||
text.strip_prefix(*prefix)
|
||||
.is_some_and(|key| !key.is_empty() && key.iter().all(u8::is_ascii_alphanumeric))
|
||||
});
|
||||
let extension = extension_statement
|
||||
&& (text
|
||||
.starts_with(b"CREATE EXTENSION IF NOT EXISTS pg_stat_statements WITH SCHEMA ")
|
||||
|| text.starts_with(b"COMMENT ON EXTENSION pg_stat_statements IS "));
|
||||
if !text.is_empty() && !text.starts_with(b"--") {
|
||||
extension_statement = false;
|
||||
}
|
||||
if !(own_restriction
|
||||
|| extension
|
||||
|| header && skip_timeout && text == b"SET transaction_timeout = 0;")
|
||||
{
|
||||
if create_public && text == b"CREATE SCHEMA public;" {
|
||||
writeln!(script, "CREATE SCHEMA IF NOT EXISTS public;")?;
|
||||
} else {
|
||||
script.write_all(&line)?;
|
||||
}
|
||||
}
|
||||
copy_data = text.starts_with(b"COPY ") && text.ends_with(b" FROM stdin;");
|
||||
line.clear();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
148
crates/tessera-providers/src/ssh.rs
Normal file
148
crates/tessera-providers/src/ssh.rs
Normal file
@@ -0,0 +1,148 @@
|
||||
use anyhow::{Context, Result};
|
||||
use serde::Deserialize;
|
||||
use std::{net::Ipv4Addr, path::PathBuf, process::Stdio};
|
||||
use tokio::{
|
||||
io,
|
||||
net::{TcpListener, TcpStream},
|
||||
process::Command,
|
||||
};
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SshEndpoint {
|
||||
pub host: String,
|
||||
#[serde(default = "default_port")]
|
||||
pub port: u16,
|
||||
pub user: String,
|
||||
pub identity_file: PathBuf,
|
||||
pub known_hosts_file: PathBuf,
|
||||
}
|
||||
|
||||
fn default_port() -> u16 {
|
||||
22
|
||||
}
|
||||
|
||||
fn valid_host(host: &str) -> bool {
|
||||
!host.is_empty()
|
||||
&& host
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b".-_:".contains(&b))
|
||||
}
|
||||
|
||||
impl SshEndpoint {
|
||||
pub(crate) fn command(&self) -> Result<Command> {
|
||||
anyhow::ensure!(
|
||||
valid_host(&self.host) && self.port != 0,
|
||||
"invalid SSH endpoint"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
!self.user.is_empty()
|
||||
&& self
|
||||
.user
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)),
|
||||
"invalid SSH user"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
self.known_hosts_file.is_absolute() && self.identity_file.is_absolute(),
|
||||
"SSH files require absolute paths"
|
||||
);
|
||||
// OpenSSH treats these options as config values and expands tokens in paths.
|
||||
anyhow::ensure!(
|
||||
self.known_hosts_file
|
||||
.to_str()
|
||||
.is_some_and(|s| !s.contains(['"', '\\', '\n', '\r', '%', '$'])),
|
||||
"invalid SSH known_hosts path"
|
||||
);
|
||||
let mut cmd = Command::new("ssh");
|
||||
cmd.args([
|
||||
"-F",
|
||||
"/dev/null",
|
||||
"-T",
|
||||
"-o",
|
||||
"BatchMode=yes",
|
||||
"-o",
|
||||
"IdentitiesOnly=yes",
|
||||
"-o",
|
||||
"IdentityAgent=none",
|
||||
"-o",
|
||||
"StrictHostKeyChecking=yes",
|
||||
"-o",
|
||||
"GlobalKnownHostsFile=/dev/null",
|
||||
"-o",
|
||||
"UpdateHostKeys=no",
|
||||
"-o",
|
||||
"ConnectTimeout=10",
|
||||
"-o",
|
||||
"ServerAliveInterval=10",
|
||||
"-o",
|
||||
"ServerAliveCountMax=2",
|
||||
"-o",
|
||||
"ForwardAgent=no",
|
||||
"-o",
|
||||
"PasswordAuthentication=no",
|
||||
])
|
||||
.arg("-o")
|
||||
.arg(format!(
|
||||
"UserKnownHostsFile=\"{}\"",
|
||||
self.known_hosts_file.display()
|
||||
))
|
||||
.arg("-i")
|
||||
.arg(&self.identity_file)
|
||||
.arg("-p")
|
||||
.arg(self.port.to_string())
|
||||
.arg("-l")
|
||||
.arg(&self.user)
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true);
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
pub(crate) async fn forward(&self, listener: TcpListener, host: &str, port: u16) -> Result<()> {
|
||||
anyhow::ensure!(valid_host(host), "invalid forwarded host");
|
||||
let destination = if host.contains(':') {
|
||||
format!("[{host}]:{port}")
|
||||
} else {
|
||||
format!("{host}:{port}")
|
||||
};
|
||||
let mut connections = tokio::task::JoinSet::new();
|
||||
loop {
|
||||
tokio::select! {
|
||||
socket = listener.accept(), if connections.len() < 4 => {
|
||||
let (socket, _) = socket?;
|
||||
let endpoint = self.clone();
|
||||
let destination = destination.clone();
|
||||
connections.spawn(async move { endpoint.forward_connection(socket, &destination).await });
|
||||
}
|
||||
completed = connections.join_next(), if !connections.is_empty() => {
|
||||
// Closing one client connection must not interrupt its replacement.
|
||||
if let Err(error) = completed.context("missing SSH forwarding task")?? {
|
||||
tracing::debug!(%error, "SSH forwarding connection closed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn forward_connection(&self, socket: TcpStream, destination: &str) -> Result<()> {
|
||||
let mut child = self
|
||||
.command()?
|
||||
.args(["-W", destination, "--", &self.host])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.context("start SSH forward")?;
|
||||
let (mut reader, mut writer) = socket.into_split();
|
||||
let mut stdin = child.stdin.take().context("SSH stdin missing")?;
|
||||
let mut stdout = child.stdout.take().context("SSH stdout missing")?;
|
||||
let send = async move { io::copy(&mut reader, &mut stdin).await };
|
||||
let receive = async move { io::copy(&mut stdout, &mut writer).await };
|
||||
tokio::try_join!(send, receive).context("forward database connection")?;
|
||||
anyhow::ensure!(child.wait().await?.success(), "SSH forwarding failed");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn loopback_listener() -> Result<TcpListener> {
|
||||
Ok(TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?)
|
||||
}
|
||||
Reference in New Issue
Block a user