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:
2026-11-10 23:26:49 +07:00
parent 30a1a9b8f0
commit 6320b6f244
96 changed files with 11061 additions and 725 deletions

View File

@@ -3,66 +3,154 @@ use rustls::pki_types::ServerName;
use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, Read, Write};
use std::net::TcpStream;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::sync::Arc;
use std::time::Duration;
pub fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)]) -> Result<String> {
let payload = serde_json::to_string(body)?;
request(
"POST",
url,
Some(&payload),
Some((&mut payload.as_bytes(), payload.len() as u64)),
Some("application/json"),
headers,
Duration::from_secs(30),
)
}
pub fn post_file(
url: &str,
file: &mut File,
len: u64,
headers: &[(&str, &str)],
timeout: Duration,
) -> Result<String> {
request(
"POST",
url,
Some((file, len)),
Some("application/octet-stream"),
headers,
timeout,
)
}
pub fn get_file(
url: &str,
file: &mut File,
headers: &[(&str, &str)],
timeout: Duration,
) -> Result<u64> {
let (mut response, length) = response("GET", url, None, None, headers, timeout)?;
let length = length.context("missing restore payload length")?;
anyhow::ensure!(
length > 0 && length <= 100 * 1024 * 1024 * 1024,
"invalid restore payload length"
);
let read = std::io::copy(&mut response.by_ref().take(length), file)?;
anyhow::ensure!(read == length, "incomplete restore payload");
Ok(length)
}
fn request(
method: &str,
url: &str,
body: Option<&str>,
body: Option<(&mut dyn Read, u64)>,
content_type: Option<&str>,
headers: &[(&str, &str)],
timeout: Duration,
) -> Result<String> {
let (mut response, length) = response(method, url, body, content_type, headers, timeout)?;
let length = length.unwrap_or(64 * 1024);
anyhow::ensure!(length <= 64 * 1024, "hub JSON response too large");
let mut body = String::new();
let read = response.by_ref().take(length).read_to_string(&mut body)?;
if length < 64 * 1024 {
anyhow::ensure!(read as u64 == length, "incomplete hub response");
}
Ok(body.trim().to_owned())
}
fn response(
method: &str,
url: &str,
body: Option<(&mut dyn Read, u64)>,
content_type: Option<&str>,
headers: &[(&str, &str)],
timeout: Duration,
) -> Result<(BufReader<Socket>, Option<u64>)> {
let (https, host, port, path) = parse_url(url)?;
let mut stream: Box<dyn ReadWrite> = if https {
Box::new(connect_mtls(&host, port)?)
let mut stream: Socket = if https {
Box::new(connect_tls(&host, port, timeout)?)
} else {
Box::new(TcpStream::connect((host.as_str(), port)).context("connect")?)
Box::new(connect(&host, port, timeout)?)
};
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
for (k, v) in headers {
anyhow::ensure!(
v.bytes().all(|b| b.is_ascii_graphic() || b == b' '),
"invalid HTTP header value"
);
req.push_str(&format!("{k}: {v}\r\n"));
}
if let Some(b) = body {
req.push_str(&format!("Content-Length: {}\r\n", b.len()));
if let Some((_, len)) = &body {
req.push_str(&format!("Content-Length: {len}\r\n"));
if let Some(ct) = content_type {
req.push_str(&format!("Content-Type: {ct}\r\n"));
}
req.push_str("\r\n");
req.push_str(b);
} else {
req.push_str("\r\n");
}
req.push_str("\r\n");
stream.write_all(req.as_bytes())?;
let mut buf = String::new();
stream.read_to_string(&mut buf)?;
let (response_headers, body) = buf.split_once("\r\n\r\n").context("invalid hub response")?;
let status = response_headers
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(1))
if let Some((reader, len)) = body {
anyhow::ensure!(
std::io::copy(&mut reader.take(len), &mut stream)? == len,
"incomplete upload"
);
}
stream.flush()?;
let mut response = BufReader::new(stream);
let mut line = String::new();
response.by_ref().take(16 * 1024).read_line(&mut line)?;
let status = line
.split_whitespace()
.nth(1)
.context("missing hub response status")?
.parse::<u16>()?;
anyhow::ensure!((200..300).contains(&status), "hub returned HTTP {status}");
Ok(body.trim().to_string())
let mut length = None;
let mut header_bytes = 0;
loop {
line.clear();
let read = response.by_ref().take(16 * 1024).read_line(&mut line)?;
header_bytes += read;
anyhow::ensure!(
read != 0 && header_bytes < 16 * 1024,
"invalid hub response headers"
);
if line == "\r\n" {
break;
}
if let Some((name, value)) = line.split_once(':') {
if name.eq_ignore_ascii_case("content-length") {
length = Some(value.trim().parse()?);
}
}
}
Ok((response, if status == 204 { Some(0) } else { length }))
}
type Socket = Box<dyn ReadWrite>;
trait ReadWrite: Read + Write {}
impl<T: Read + Write> ReadWrite for T {}
fn parse_url(url: &str) -> Result<(bool, String, u16, String)> {
anyhow::ensure!(
!url.bytes().any(|b| b.is_ascii_control() || b == b' '),
"invalid hub URL"
);
let (https, rest) = if let Some(rest) = url.strip_prefix("https://") {
(true, rest)
} else if let Some(rest) = url.strip_prefix("http://") {
@@ -71,6 +159,10 @@ fn parse_url(url: &str) -> Result<(bool, String, u16, String)> {
anyhow::bail!("hub url must start with http:// or https://");
};
let (host_port, path) = rest.split_once('/').unwrap_or((rest, ""));
anyhow::ensure!(
!host_port.is_empty() && !host_port.contains(['@', '?', '#']),
"invalid hub authority"
);
let path = if path.is_empty() {
"/".to_string()
} else {
@@ -84,37 +176,66 @@ fn parse_url(url: &str) -> Result<(bool, String, u16, String)> {
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}"))?;
fn connect(host: &str, port: u16, timeout: Duration) -> Result<TcpStream> {
for address in (host, port).to_socket_addrs()? {
if let Ok(socket) = TcpStream::connect_timeout(&address, Duration::from_secs(5)) {
socket.set_read_timeout(Some(timeout))?;
socket.set_write_timeout(Some(Duration::from_secs(30)))?;
return Ok(socket);
}
}
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}"))?;
anyhow::bail!("could not connect to hub")
}
fn connect_tls(
host: &str,
port: u16,
timeout: Duration,
) -> Result<StreamOwned<ClientConnection, TcpStream>> {
let _ = rustls::crypto::ring::default_provider().install_default();
let mut roots = RootCertStore::empty();
if let Some(ca) = std::env::var_os("TESSERA_WORMHOLE_CA") {
for ca_cert in load_certs(std::path::Path::new(&ca))? {
roots
.add(ca_cert)
.map_err(|error| anyhow::anyhow!("hub CA: {error}"))?;
}
} else {
let native = rustls_native_certs::load_native_certs();
roots.add_parsable_certificates(native.certs);
}
anyhow::ensure!(!roots.is_empty(), "no trusted hub CA certificates");
let builder = ClientConfig::builder().with_root_certificates(roots);
let client = match (
std::env::var_os("TESSERA_WORMHOLE_CLIENT_CERT"),
std::env::var_os("TESSERA_WORMHOLE_CLIENT_KEY"),
) {
(Some(cert), Some(key)) => builder
.with_client_auth_cert(
load_certs(std::path::Path::new(&cert))?,
load_key(std::path::Path::new(&key))?,
)
.map_err(|error| anyhow::anyhow!("client certificate: {error}"))?,
(None, None) => builder.with_no_client_auth(),
_ => anyhow::bail!("configure both Wormhole client certificate and key"),
};
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")?;
let tcp = connect(host, port, timeout)?;
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}"))?);
fn load_certs(path: &std::path::Path) -> Result<Vec<rustls::pki_types::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")
}
fn load_key(path: &str) -> Result<rustls::pki_types::PrivateKeyDer<'static>> {
let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {path}"))?);
fn load_key(path: &std::path::Path) -> Result<rustls::pki_types::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("no private key in client key file")