Files
tessera/crates/tessera-providers/src/postgres.rs
Adnan Zahir 43709aeeab feat: say why a restore failed, and add the user_schemas reset mode
- the agent reports the client's primary ERROR/FATAL line with a failed restore step; the hub keeps it
  as failure_reason (administrators only), logs it and audits restore.failed. psql runs with
  VERBOSITY=terse and DETAIL/CONTEXT/statement text is dropped so row data never travels
- reset mode user_schemas empties every non-system schema in the restore transaction, so multi-schema
  databases restore without DROP DATABASE; proven against a real PostgreSQL server

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 12:29:48 +07:00

428 lines
14 KiB
Rust

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;
use std::io::Write;
use std::path::PathBuf;
use std::process::Stdio;
use tessera_core::{config::ProviderKind, restore::DatabaseIdentity};
use tokio::process::Command;
#[derive(Debug, Clone, Deserialize)]
pub struct PostgresConfig {
pub connection_url: String,
#[serde(default = "default_format")]
pub format: String,
}
fn default_format() -> String {
"custom".into()
}
pub struct PostgresProvider {
config: PostgresConfig,
}
struct PgTarget {
host: String,
port: String,
user: String,
password: String,
dbname: String,
}
#[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>,
}
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 })
}
pub async fn dump_to(&self, file: fs::File) -> Result<serde_json::Value> {
self.dump(Stdio::from(file.try_clone()?)).await?;
anyhow::ensure!(file.metadata()?.len() > 0, "pg_dump produced an empty file");
Ok(self.restore_hints())
}
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)?;
run_pg(
&target,
PgProcess {
program: "pg_dump",
args: &args,
stdin: Stdio::null(),
stdout,
},
None,
)
.await
}
fn restore_hints(&self) -> serde_json::Value {
let command = if self.config.format == "plain" {
"psql -d \"$DATABASE_URL\" -f dump.file"
} else {
"pg_restore -d \"$DATABASE_URL\" dump.file"
};
json!({ "format": self.config.format, "restore_command_hint": command })
}
}
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(':', "\\:")
}
struct PgProcess<'a> {
program: &'a str,
args: &'a [String],
stdin: Stdio,
stdout: Stdio,
}
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");
}
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::piped())
.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,
client_reason(&output.stderr)
);
Ok(output)
}
/// The reason a PostgreSQL client gave for failing, reduced to what is safe to report: only the primary
/// `ERROR:`/`FATAL:` lines. `DETAIL`, `CONTEXT`, `LINE`, `STATEMENT` and `HINT` are left out because they
/// quote rows and statements, and the location prefix (`psql:-:1234:`) is not needed. At most two lines.
pub(crate) fn client_reason(stderr: &[u8]) -> String {
let text = String::from_utf8_lossy(stderr);
let lines: Vec<String> = text
.lines()
.filter_map(|line| {
let line = line.trim();
let line = match line.find(": ").filter(|_| line.starts_with("psql:")) {
Some(_) => line.splitn(4, ':').nth(3).unwrap_or(line).trim(),
None => line,
};
let primary = ["ERROR:", "FATAL:", "pg_dump: error:", "pg_restore: error:"]
.iter()
.any(|prefix| line.starts_with(prefix));
primary.then(|| line.to_string())
})
.take(2)
.collect();
if lines.is_empty() {
String::new()
} else {
format!(": {}", lines.join(" | "))
}
}
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>> {
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 {
ProviderKind::Postgres
}
async fn capture(&self) -> Result<CaptureResult> {
let output = self.dump(Stdio::piped()).await?;
Ok(CaptureResult {
payload: output.stdout,
labels: vec!["postgres".into()],
restore_hints: self.restore_hints(),
})
}
}
#[cfg(test)]
mod tests {
#[test]
fn a_client_failure_names_its_error_without_quoting_data() {
let stderr =
b"psql:-:42: ERROR: duplicate key value violates unique constraint \"users_pkey\"\n\
DETAIL: Key (email)=(alice@example.test) already exists.\n\
CONTEXT: COPY users, line 7: \"7\\talice@example.test\"\n\
psql:-:99: ERROR: schema \"drizzle\" already exists\n";
let reason = client_reason(stderr);
assert_eq!(
reason,
": ERROR: duplicate key value violates unique constraint \"users_pkey\" | ERROR: schema \"drizzle\" already exists"
);
assert!(!reason.contains("alice") && !reason.contains("COPY"));
assert_eq!(client_reason(b""), "");
assert_eq!(client_reason(b"just noise\n"), "");
}
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, 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_eq!(mode, 0o600);
let joined = args.join(" ");
assert!(!joined.contains(&target.password));
assert!(!joined.contains(&target.user));
}
}