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:
@@ -20,5 +20,9 @@ tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
uuid.workspace = true
|
||||
base64 = "0.22"
|
||||
tempfile.workspace = true
|
||||
sha2.workspace = true
|
||||
hex.workspace = true
|
||||
rustls = { version = "=0.23.23", default-features = false, features = ["ring", "std"] }
|
||||
rustls-pemfile = "=2.2.0"
|
||||
rustls-native-certs = "0.8"
|
||||
|
||||
@@ -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")
|
||||
|
||||
381
crates/tessera-agent/src/jobs.rs
Normal file
381
crates/tessera-agent/src/jobs.rs
Normal file
@@ -0,0 +1,381 @@
|
||||
use crate::{http, restore, Cli};
|
||||
use anyhow::{Context, Result};
|
||||
use base64::Engine as _;
|
||||
use serde::Deserialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::File,
|
||||
io::{self, Seek, SeekFrom},
|
||||
path::{Path, PathBuf},
|
||||
process::Stdio,
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
use tessera_core::job::{
|
||||
CaptureFormat, CaptureLease, CaptureProgress, CaptureReport, ResticCaptureCommit, CAPTURE_HEARTBEAT_SECONDS,
|
||||
};
|
||||
use tessera_core::restore::DatabaseIdentity;
|
||||
use tessera_providers::{MysqlSource, PostgresSource};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Profile {
|
||||
source: Option<Source>,
|
||||
#[serde(default)]
|
||||
paths: Vec<PathBuf>,
|
||||
restic_repository: Option<String>,
|
||||
restic_password_file: Option<PathBuf>,
|
||||
rest_server_password_file: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
targets: HashMap<Uuid, restore::Target>,
|
||||
#[serde(default = "default_timeout")]
|
||||
timeout_seconds: u64,
|
||||
}
|
||||
|
||||
fn default_timeout() -> u64 {
|
||||
3600
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "engine", rename_all = "snake_case")]
|
||||
pub(super) enum Source {
|
||||
Postgres(PostgresSource),
|
||||
Mysql(MysqlSource),
|
||||
}
|
||||
|
||||
impl Source {
|
||||
pub(super) async fn identity(&self) -> Result<DatabaseIdentity> {
|
||||
match self {
|
||||
Self::Postgres(source) => source.identity().await,
|
||||
Self::Mysql(source) => source.identity().await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct Hub {
|
||||
pub(super) url: String,
|
||||
pub(super) token: String,
|
||||
}
|
||||
|
||||
pub fn require_secure_hub(url: &str) -> Result<()> {
|
||||
let local = ["http://127.0.0.1:", "http://localhost:"]
|
||||
.into_iter()
|
||||
.any(|prefix| {
|
||||
url.strip_prefix(prefix)
|
||||
.is_some_and(|port| port.parse::<u16>().is_ok())
|
||||
});
|
||||
anyhow::ensure!(
|
||||
url.starts_with("https://") || local,
|
||||
"remote Wormhole connections require an HTTPS hub"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn run(cli: &Cli, path: &Path) -> Result<()> {
|
||||
let profiles: HashMap<Uuid, Profile> =
|
||||
serde_json::from_reader(File::open(path).context("open capture profiles")?)
|
||||
.map_err(|_| anyhow::anyhow!("invalid capture profiles"))?;
|
||||
anyhow::ensure!(!profiles.is_empty(), "capture profile file is empty");
|
||||
anyhow::ensure!(
|
||||
profiles.values().all(|profile| profile.timeout_seconds > 0),
|
||||
"capture timeout must be positive"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
profiles
|
||||
.values()
|
||||
.all(|profile| profile.source.is_some() || !profile.paths.is_empty() || !profile.targets.is_empty()),
|
||||
"application requires a source or at least one restore target"
|
||||
);
|
||||
let url = cli
|
||||
.hub_url
|
||||
.as_deref()
|
||||
.context("TESSERA_HUB_URL")?
|
||||
.trim_end_matches('/');
|
||||
require_secure_hub(url)?;
|
||||
let token = cli
|
||||
.upload_token
|
||||
.as_deref()
|
||||
.context("TESSERA_UPLOAD_TOKEN")?;
|
||||
anyhow::ensure!(
|
||||
!token.is_empty() && token.bytes().all(|b| b.is_ascii_graphic()),
|
||||
"invalid upload token"
|
||||
);
|
||||
let hub = Arc::new(Hub {
|
||||
url: url.to_owned(),
|
||||
token: token.to_owned(),
|
||||
});
|
||||
let mut workers = tokio::task::JoinSet::new();
|
||||
for (id, profile) in profiles {
|
||||
let hub = Arc::clone(&hub);
|
||||
workers.spawn(async move {
|
||||
loop {
|
||||
if let Err(error) = async {
|
||||
let restored = restore::poll(
|
||||
&hub,
|
||||
id,
|
||||
profile.source.as_ref(),
|
||||
&profile.targets,
|
||||
profile.timeout_seconds,
|
||||
)
|
||||
.await?;
|
||||
if !restored && (profile.source.is_some() || !profile.paths.is_empty()) {
|
||||
poll(&hub, id, &profile).await?;
|
||||
}
|
||||
Ok::<_, anyhow::Error>(())
|
||||
}
|
||||
.await
|
||||
{
|
||||
tracing::warn!(application_id = %id, %error, "capture polling failed");
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
workers
|
||||
.join_next()
|
||||
.await
|
||||
.context("capture worker missing")??;
|
||||
anyhow::bail!("capture worker stopped")
|
||||
}
|
||||
|
||||
async fn poll(hub: &Arc<Hub>, id: Uuid, profile: &Profile) -> Result<()> {
|
||||
let reply = hub
|
||||
.post(format!("capture/{id}/claim"), serde_json::Value::Null, None)
|
||||
.await?;
|
||||
let Some(lease) = serde_json::from_str::<Option<CaptureLease>>(&reply)? else {
|
||||
return Ok(());
|
||||
};
|
||||
anyhow::ensure!(
|
||||
lease.profile.application_id == id,
|
||||
"hub returned a different application"
|
||||
);
|
||||
let work = capture(hub, &lease, profile);
|
||||
tokio::pin!(work);
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut work => return result,
|
||||
_ = tokio::time::sleep(Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS)) => {
|
||||
hub.report(&lease, CaptureProgress::Heartbeat).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn capture(hub: &Arc<Hub>, lease: &CaptureLease, profile: &Profile) -> Result<()> {
|
||||
hub.report(lease, CaptureProgress::Dumping).await?;
|
||||
if lease.profile.format == CaptureFormat::Filesystem {
|
||||
if profile.paths.is_empty() {
|
||||
hub.report(lease, CaptureProgress::DumpFailed).await?;
|
||||
anyhow::bail!("filesystem profile requires paths");
|
||||
}
|
||||
hub.report(lease, CaptureProgress::Uploading).await?;
|
||||
return commit_backup(hub, lease, profile, None, None).await;
|
||||
}
|
||||
let Some(source) = &profile.source else {
|
||||
hub.report(lease, CaptureProgress::DumpFailed).await?;
|
||||
anyhow::bail!("capture source is missing");
|
||||
};
|
||||
let result = tokio::time::timeout(Duration::from_secs(profile.timeout_seconds), async {
|
||||
let stage = tempfile::tempfile().context("create private staging file")?;
|
||||
let before = probe_identity(source).await;
|
||||
match (source, lease.profile.format) {
|
||||
(Source::Postgres(source), CaptureFormat::PostgresCustom) => {
|
||||
source.dump_to(stage.try_clone()?, "custom").await?
|
||||
}
|
||||
(Source::Postgres(source), CaptureFormat::PostgresSql) => {
|
||||
source.dump_to(stage.try_clone()?, "plain").await?
|
||||
}
|
||||
(Source::Mysql(source), CaptureFormat::MysqlSql) => {
|
||||
source.dump_to(stage.try_clone()?).await?
|
||||
}
|
||||
_ => anyhow::bail!("capture profile engine does not match the assignment"),
|
||||
}
|
||||
let identity = match before {
|
||||
Some(identity)
|
||||
if lease.profile.format.engine().is_some_and(|engine| identity.valid(engine))
|
||||
&& probe_identity(source).await.as_ref() == Some(&identity) =>
|
||||
{
|
||||
Some(identity)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
Ok::<_, anyhow::Error>((stage, identity))
|
||||
})
|
||||
.await;
|
||||
let (stage, identity) = match result {
|
||||
Ok(Ok(stage)) => stage,
|
||||
_ => {
|
||||
hub.report(lease, CaptureProgress::DumpFailed).await?;
|
||||
anyhow::bail!("database dump failed or timed out");
|
||||
}
|
||||
};
|
||||
hub.report(lease, CaptureProgress::Uploading).await?;
|
||||
if lease.restic {
|
||||
return commit_backup(hub, lease, profile, Some(stage), identity).await;
|
||||
}
|
||||
|
||||
let identity = identity
|
||||
.map(|value| serde_json::to_vec(&value))
|
||||
.transpose()?
|
||||
.map(|value| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(value));
|
||||
|
||||
if hub
|
||||
.upload(
|
||||
format!("capture/{}/payload", lease.job_id),
|
||||
stage,
|
||||
Duration::from_secs(profile.timeout_seconds),
|
||||
"x-tessera-lease-id",
|
||||
lease.lease_id,
|
||||
identity,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
hub.report(lease, CaptureProgress::UploadFailed).await?;
|
||||
anyhow::bail!("backup upload failed");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn commit_backup(
|
||||
hub: &Arc<Hub>,
|
||||
lease: &CaptureLease,
|
||||
profile: &Profile,
|
||||
stage: Option<File>,
|
||||
identity: Option<DatabaseIdentity>,
|
||||
) -> Result<()> {
|
||||
let result = tokio::time::timeout(Duration::from_secs(profile.timeout_seconds), async {
|
||||
let repository = profile.restic_repository.as_deref().context("configure the profile Restic repository")?;
|
||||
let mut command = crate::restic_command(repository)?;
|
||||
if let Some(path) = &profile.restic_password_file {
|
||||
command.env_remove("RESTIC_PASSWORD").env_remove("RESTIC_PASSWORD_COMMAND")
|
||||
.env("RESTIC_PASSWORD_FILE", path);
|
||||
}
|
||||
if let Some(path) = &profile.rest_server_password_file {
|
||||
let password = tokio::fs::read_to_string(path).await.context("read Rest Server password")?;
|
||||
command.env("RESTIC_REST_USERNAME", lease.profile.orbit_id.to_string())
|
||||
.env("RESTIC_REST_PASSWORD", password.trim_end_matches(['\r', '\n']));
|
||||
}
|
||||
command.args(["backup", "--json", "--quiet", "--tag", &format!("tessera-{}", lease.job_id)]);
|
||||
let sha256 = if let Some(mut file) = stage {
|
||||
let (file, hash) = tokio::task::spawn_blocking(move || {
|
||||
let (_, hash) = digest_file(&mut file)?;
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
Ok::<_, anyhow::Error>((file, hash))
|
||||
}).await??;
|
||||
command.args(["--stdin", "--stdin-filename", "payload"]).stdin(Stdio::from(file));
|
||||
Some(hash)
|
||||
} else {
|
||||
command.arg("--").args(&profile.paths);
|
||||
None
|
||||
};
|
||||
let snapshot_id = crate::restic_snapshot(command).await?;
|
||||
let body = serde_json::to_value(ResticCaptureCommit { lease_id: lease.lease_id, snapshot_id, identity, sha256 })?;
|
||||
for _ in 0..3 {
|
||||
if hub.post(format!("capture/{}/restic", lease.job_id), body.clone(), None).await.is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
anyhow::bail!("could not register the Restic snapshot")
|
||||
}).await;
|
||||
match result {
|
||||
Ok(Ok(())) => Ok(()),
|
||||
failure => {
|
||||
hub.report(lease, CaptureProgress::UploadFailed).await?;
|
||||
failure.context("Restic backup timed out")?
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn probe_identity(source: &Source) -> Option<DatabaseIdentity> {
|
||||
tokio::time::timeout(Duration::from_secs(10), source.identity())
|
||||
.await
|
||||
.ok()?
|
||||
.ok()
|
||||
}
|
||||
|
||||
impl Hub {
|
||||
pub(super) async fn post(
|
||||
self: &Arc<Self>,
|
||||
path: String,
|
||||
body: serde_json::Value,
|
||||
restore: Option<Uuid>,
|
||||
) -> Result<String> {
|
||||
let hub = Arc::clone(self);
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let restore = restore.map(|token| token.to_string());
|
||||
let mut headers = vec![("x-tessera-upload-token", hub.token.as_str())];
|
||||
if let Some(token) = &restore {
|
||||
headers.push(("x-tessera-restore-token", token.as_str()));
|
||||
}
|
||||
http::post_json(
|
||||
&format!("{}/api/v1/wormhole/{path}", hub.url),
|
||||
&body,
|
||||
&headers,
|
||||
)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
async fn report(
|
||||
self: &Arc<Self>,
|
||||
lease: &CaptureLease,
|
||||
progress: CaptureProgress,
|
||||
) -> Result<()> {
|
||||
let body = CaptureReport {
|
||||
lease_id: lease.lease_id,
|
||||
progress,
|
||||
};
|
||||
self.post(
|
||||
format!("capture/{}/report", lease.job_id),
|
||||
serde_json::to_value(body)?,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn upload(
|
||||
self: &Arc<Self>,
|
||||
path: String,
|
||||
mut file: File,
|
||||
timeout: Duration,
|
||||
lease_header: &'static str,
|
||||
lease: Uuid,
|
||||
identity: Option<String>,
|
||||
) -> Result<()> {
|
||||
let hub = Arc::clone(self);
|
||||
let url = format!("{}/api/v1/wormhole/{path}", hub.url);
|
||||
let lease = lease.to_string();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let (len, digest) = digest_file(&mut file)?;
|
||||
let mut headers = vec![
|
||||
("x-tessera-upload-token", hub.token.as_str()),
|
||||
(lease_header, lease.as_str()),
|
||||
("x-tessera-sha256", digest.as_str()),
|
||||
];
|
||||
if let Some(value) = &identity {
|
||||
headers.push(("x-tessera-source-identity", value.as_str()));
|
||||
}
|
||||
for _ in 0..3 {
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
if http::post_file(&url, &mut file, len, &headers, timeout).is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
anyhow::bail!("backup upload retry limit reached")
|
||||
})
|
||||
.await?
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn digest_file(file: &mut File) -> Result<(u64, String)> {
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
let mut digest = Sha256::new();
|
||||
let len = io::copy(file, &mut digest)?;
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
Ok((len, hex::encode(digest.finalize())))
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
mod http;
|
||||
mod jobs;
|
||||
mod restore;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use base64::Engine;
|
||||
use clap::{Parser, Subcommand};
|
||||
use tessera_core::config::ProviderKind;
|
||||
use tessera_core::{config::ProviderKind, WormholeCredentials};
|
||||
use tessera_providers::provider_from_config;
|
||||
use tracing::info;
|
||||
|
||||
@@ -18,6 +20,10 @@ struct Cli {
|
||||
upload_token: Option<String>,
|
||||
#[arg(long, env = "TESSERA_ORBIT_ID")]
|
||||
orbit_id: Option<String>,
|
||||
#[arg(long, env = "TESSERA_CAPTURE_PROFILES")]
|
||||
capture_profiles: Option<std::path::PathBuf>,
|
||||
#[arg(long, env = "TESSERA_WORMHOLE_CREDENTIALS")]
|
||||
credentials: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Subcommand)]
|
||||
@@ -34,34 +40,100 @@ enum AgentCmd {
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt::init();
|
||||
let cli = Cli::parse();
|
||||
let mut cli = Cli::parse();
|
||||
if !matches!(&cli.command, Some(AgentCmd::Pair { .. })) {
|
||||
load_credentials(&mut cli)?;
|
||||
}
|
||||
match cli.command.clone().unwrap_or(AgentCmd::Run) {
|
||||
AgentCmd::Run => run_daemon(&cli).await?,
|
||||
AgentCmd::Run => tokio::select! {
|
||||
result = run_daemon(&cli) => result?,
|
||||
result = shutdown_signal() => result?,
|
||||
},
|
||||
AgentCmd::Pair { code, name } => pair(&cli, &code, &name)?,
|
||||
AgentCmd::Beam => beam_once(&cli).await?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn shutdown_signal() -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
|
||||
tokio::select! {
|
||||
result = tokio::signal::ctrl_c() => result?,
|
||||
_ = term.recv() => {}
|
||||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
tokio::signal::ctrl_c().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pair(cli: &Cli, code: &str, name: &str) -> Result<()> {
|
||||
let hub = cli
|
||||
.hub_url
|
||||
.clone()
|
||||
.unwrap_or_else(|| "http://127.0.0.1:8787".into());
|
||||
if let Some(path) = &cli.credentials {
|
||||
anyhow::ensure!(!path.try_exists()?, "credentials file already exists");
|
||||
jobs::require_secure_hub(hub.trim_end_matches('/'))?;
|
||||
}
|
||||
let body = serde_json::json!({ "code": code, "outpost_name": name });
|
||||
let raw = http::post_json(
|
||||
&format!("{hub}/api/v1/wormhole/claim"),
|
||||
&format!("{}/api/v1/wormhole/claim", hub.trim_end_matches('/')),
|
||||
&body,
|
||||
&[],
|
||||
)?;
|
||||
let res: serde_json::Value = serde_json::from_str(&raw)?;
|
||||
println!("TESSERA_UPLOAD_TOKEN={}", res["upload_token"]);
|
||||
println!("TESSERA_HUB_URL={}", res["hub_url"]);
|
||||
println!("Outpost {}", res["outpost_id"]);
|
||||
let mut credentials: WormholeCredentials = serde_json::from_str(&raw)?;
|
||||
if cli.hub_url.is_some()
|
||||
&& (hub.starts_with("https://") || !credentials.hub_url.starts_with("https://"))
|
||||
{
|
||||
credentials.hub_url = hub;
|
||||
}
|
||||
if let Some(path) = &cli.credentials {
|
||||
let parent = path
|
||||
.parent()
|
||||
.filter(|parent| !parent.as_os_str().is_empty())
|
||||
.unwrap_or_else(|| std::path::Path::new("."));
|
||||
let file =
|
||||
tempfile::NamedTempFile::new_in(parent).context("create private credentials file")?;
|
||||
serde_json::to_writer(file.as_file(), &credentials)?;
|
||||
file.as_file().sync_all()?;
|
||||
file.persist_noclobber(path)
|
||||
.context("save pairing credentials (file must not exist)")?;
|
||||
println!("Saved credentials for outpost {}", credentials.outpost_id);
|
||||
} else {
|
||||
println!("TESSERA_UPLOAD_TOKEN={}", credentials.upload_token);
|
||||
println!("TESSERA_HUB_URL={}", credentials.hub_url);
|
||||
println!("Outpost {}", credentials.outpost_id);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_credentials(cli: &mut Cli) -> Result<()> {
|
||||
let Some(path) = &cli.credentials else {
|
||||
return Ok(());
|
||||
};
|
||||
let file = std::fs::File::open(path).context("open paired credentials")?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
anyhow::ensure!(
|
||||
file.metadata()?.permissions().mode() & 0o077 == 0,
|
||||
"paired credentials require owner-only permissions"
|
||||
);
|
||||
}
|
||||
let credentials: WormholeCredentials = serde_json::from_reader(file)
|
||||
.map_err(|_| anyhow::anyhow!("invalid pairing credentials"))?;
|
||||
cli.hub_url.get_or_insert(credentials.hub_url);
|
||||
cli.upload_token.get_or_insert(credentials.upload_token);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_daemon(cli: &Cli) -> Result<()> {
|
||||
if let Some(path) = &cli.capture_profiles {
|
||||
return jobs::run(cli, path).await;
|
||||
}
|
||||
info!("outpost online — wormhole listening for beam cycles");
|
||||
loop {
|
||||
if let Err(e) = beam_once(cli).await {
|
||||
@@ -117,42 +189,17 @@ async fn beam_once(cli: &Cli) -> Result<()> {
|
||||
&[("x-tessera-upload-token", &token)],
|
||||
)?;
|
||||
|
||||
info!("beamed {} bytes via wormhole session {session_id}", capture.payload.len());
|
||||
info!(
|
||||
"beamed {} bytes via wormhole session {session_id}",
|
||||
capture.payload.len()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn beam_restic(repository: &str, hub: &str, token: &str, orbit_id: uuid::Uuid) -> Result<()> {
|
||||
let authority = repository
|
||||
.strip_prefix("rest:https://")
|
||||
.and_then(|url| url.split('/').next());
|
||||
anyhow::ensure!(
|
||||
authority.is_some_and(|host| !host.is_empty() && !host.contains('@')),
|
||||
"TESSERA_RESTIC_REPOSITORY must be a rest:https:// URL without embedded credentials"
|
||||
);
|
||||
let output = tokio::process::Command::new("restic")
|
||||
.env("RESTIC_REPOSITORY", repository)
|
||||
.env_remove("RESTIC_REPOSITORY_FILE")
|
||||
.args(["backup", "--json", "--quiet", "--force", "--", "."])
|
||||
.stdin(std::process::Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.output()
|
||||
.await
|
||||
.context("starting restic (install restic on PATH)")?;
|
||||
anyhow::ensure!(
|
||||
output.status.success(),
|
||||
"restic backup failed ({}): {}",
|
||||
output.status,
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
);
|
||||
let summary: serde_json::Value = serde_json::from_str(
|
||||
std::str::from_utf8(&output.stdout)?
|
||||
.lines()
|
||||
.last()
|
||||
.context("missing restic summary")?,
|
||||
)?;
|
||||
let snapshot = summary["snapshot_id"]
|
||||
.as_str()
|
||||
.context("missing restic snapshot ID")?;
|
||||
let mut command = restic_command(repository)?;
|
||||
command.args(["backup", "--json", "--quiet", "--", "."]);
|
||||
let snapshot = restic_snapshot(command).await?;
|
||||
let body = serde_json::json!({ "orbit_id": orbit_id, "snapshot_id": snapshot });
|
||||
let reply = http::post_json(
|
||||
&format!("{hub}/api/v1/wormhole/restic/commit"),
|
||||
@@ -167,8 +214,36 @@ async fn beam_restic(repository: &str, hub: &str, token: &str, orbit_id: uuid::U
|
||||
info!(
|
||||
snapshot,
|
||||
registered,
|
||||
stored_bytes = summary["data_added_packed"].as_u64(),
|
||||
"committed Restic backup"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
fn restic_command(repository: &str) -> Result<tokio::process::Command> {
|
||||
let authority = repository
|
||||
.strip_prefix("rest:https://")
|
||||
.and_then(|url| url.split('/').next());
|
||||
anyhow::ensure!(
|
||||
authority.is_some_and(|host| !host.is_empty() && !host.contains('@')),
|
||||
"TESSERA_RESTIC_REPOSITORY must be a rest:https:// URL without embedded credentials"
|
||||
);
|
||||
let mut command = tokio::process::Command::new("restic");
|
||||
command.env("RESTIC_REPOSITORY", repository)
|
||||
.env_remove("RESTIC_REPOSITORY_FILE")
|
||||
.stdin(std::process::Stdio::null())
|
||||
.kill_on_drop(true);
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
async fn restic_snapshot(mut command: tokio::process::Command) -> Result<String> {
|
||||
let output = command.output().await.context("starting restic (install restic on PATH)")?;
|
||||
anyhow::ensure!(output.status.success(), "restic backup failed ({})", output.status);
|
||||
let summary: serde_json::Value = serde_json::from_str(
|
||||
std::str::from_utf8(&output.stdout)?
|
||||
.lines()
|
||||
.last()
|
||||
.context("missing restic summary")?,
|
||||
)?;
|
||||
Ok(summary["snapshot_id"].as_str().context("missing restic snapshot ID")?.to_owned())
|
||||
}
|
||||
|
||||
235
crates/tessera-agent/src/restore.rs
Normal file
235
crates/tessera-agent/src/restore.rs
Normal file
@@ -0,0 +1,235 @@
|
||||
use crate::{
|
||||
http,
|
||||
jobs::{digest_file, Hub, Source},
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use serde::Deserialize;
|
||||
use std::{collections::HashMap, fs::File, sync::Arc, time::Duration};
|
||||
use tessera_core::{
|
||||
job::{CaptureFormat, CAPTURE_HEARTBEAT_SECONDS},
|
||||
restore::{DatabaseIdentity, RestoreLease, RestoreProgress},
|
||||
};
|
||||
use tessera_providers::{MysqlRestore, PostgresRestore};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "engine", rename_all = "snake_case")]
|
||||
pub(super) enum Target {
|
||||
Postgres(PostgresRestore),
|
||||
Mysql(MysqlRestore),
|
||||
}
|
||||
|
||||
impl Target {
|
||||
async fn identity(&self) -> Result<DatabaseIdentity> {
|
||||
match self {
|
||||
Self::Postgres(target) => target.connection.identity().await,
|
||||
Self::Mysql(target) => target.connection.identity().await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn prepare(&self, input: File, lease: &RestoreLease) -> Result<File> {
|
||||
match (self, lease.artifact.format) {
|
||||
(
|
||||
Self::Postgres(target),
|
||||
format @ (CaptureFormat::PostgresCustom | CaptureFormat::PostgresSql),
|
||||
) => {
|
||||
target
|
||||
.prepare(input, format, &lease.job.target.identity)
|
||||
.await
|
||||
}
|
||||
(Self::Mysql(target), CaptureFormat::MysqlSql) => {
|
||||
target.prepare(input, &lease.job.target.identity).await
|
||||
}
|
||||
_ => anyhow::bail!("local restore target engine does not match the assignment"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn safety(&self, stage: File) -> Result<()> {
|
||||
match self {
|
||||
Self::Postgres(target) => target.connection.safety_dump_to(stage).await,
|
||||
Self::Mysql(target) => target.connection.dump_to(stage).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn apply(&self, script: File) -> Result<()> {
|
||||
match self {
|
||||
Self::Postgres(target) => target.apply(script).await,
|
||||
Self::Mysql(target) => target.apply(script).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn poll(
|
||||
hub: &Arc<Hub>,
|
||||
application: Uuid,
|
||||
source: Option<&Source>,
|
||||
targets: &HashMap<Uuid, Target>,
|
||||
timeout_seconds: u64,
|
||||
) -> Result<bool> {
|
||||
for (target_id, target) in targets {
|
||||
let reply = hub
|
||||
.post(
|
||||
format!("restore-targets/{target_id}/claim"),
|
||||
serde_json::Value::Null,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
let Some(lease) = serde_json::from_str::<Option<RestoreLease>>(&reply)? else {
|
||||
continue;
|
||||
};
|
||||
ensure!(
|
||||
lease.job.target.id == *target_id && lease.job.target.application_id == application,
|
||||
"hub returned an unexpected restore target"
|
||||
);
|
||||
let work = run(
|
||||
hub,
|
||||
&lease,
|
||||
target,
|
||||
source,
|
||||
Duration::from_secs(timeout_seconds),
|
||||
);
|
||||
tokio::pin!(work);
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut work => return result.map(|()| true),
|
||||
_ = tokio::time::sleep(Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS)) => {
|
||||
report(hub, &lease, RestoreProgress::Heartbeat).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
async fn run(
|
||||
hub: &Arc<Hub>,
|
||||
lease: &RestoreLease,
|
||||
target: &Target,
|
||||
source: Option<&Source>,
|
||||
timeout: Duration,
|
||||
) -> Result<()> {
|
||||
report(hub, lease, RestoreProgress::Checking).await?;
|
||||
let downloaded = tokio::time::timeout(timeout, async {
|
||||
let input = download(hub, lease, timeout).await?;
|
||||
target.prepare(input, lease).await
|
||||
})
|
||||
.await;
|
||||
let script = match downloaded {
|
||||
Ok(Ok(script)) => script,
|
||||
_ => {
|
||||
report(hub, lease, RestoreProgress::InvalidPayload).await?;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
let verified = tokio::time::timeout(timeout, async {
|
||||
let identity = target.identity().await?;
|
||||
ensure!(
|
||||
identity == lease.job.target.identity && identity != lease.artifact.identity,
|
||||
"restore target identity does not match"
|
||||
);
|
||||
if let Some(source) = source {
|
||||
if let Ok(Ok(source_identity)) =
|
||||
tokio::time::timeout(Duration::from_secs(10), source.identity()).await
|
||||
{
|
||||
ensure!(
|
||||
source_identity != identity,
|
||||
"target resolves to the local backup source"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok::<_, anyhow::Error>(identity)
|
||||
})
|
||||
.await;
|
||||
let identity = match verified {
|
||||
Ok(Ok(identity)) => identity,
|
||||
_ => {
|
||||
report(hub, lease, RestoreProgress::WrongTarget).await?;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
report(hub, lease, RestoreProgress::Safety).await?;
|
||||
let safety = tokio::time::timeout(timeout, async {
|
||||
let stage = tempfile::tempfile().context("create private safety staging")?;
|
||||
target.safety(stage.try_clone()?).await?;
|
||||
ensure!(
|
||||
target.identity().await? == identity,
|
||||
"target changed during safety capture"
|
||||
);
|
||||
hub.upload(
|
||||
format!("restore/{}/safety", lease.job.id),
|
||||
stage,
|
||||
timeout,
|
||||
"x-tessera-restore-token",
|
||||
lease.token,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})
|
||||
.await;
|
||||
if !matches!(safety, Ok(Ok(()))) {
|
||||
report(hub, lease, RestoreProgress::SafetyFailed).await?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// The permit is single-use. A lost response leaves the target locked for reconciliation.
|
||||
hub.post(
|
||||
format!("restore/{}/apply", lease.job.id),
|
||||
serde_json::Value::Null,
|
||||
Some(lease.token),
|
||||
)
|
||||
.await?;
|
||||
let applied = matches!(
|
||||
tokio::time::timeout(timeout, target.apply(script)).await,
|
||||
Ok(Ok(()))
|
||||
);
|
||||
report(
|
||||
hub,
|
||||
lease,
|
||||
if applied {
|
||||
RestoreProgress::Applied
|
||||
} else {
|
||||
RestoreProgress::ApplyFailed
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn report(hub: &Arc<Hub>, lease: &RestoreLease, progress: RestoreProgress) -> Result<()> {
|
||||
hub.post(
|
||||
format!("restore/{}/report", lease.job.id),
|
||||
serde_json::to_value(progress)?,
|
||||
Some(lease.token),
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn download(hub: &Arc<Hub>, lease: &RestoreLease, timeout: Duration) -> Result<File> {
|
||||
let hub = hub.clone();
|
||||
let id = lease.job.id;
|
||||
let token = lease.token.to_string();
|
||||
let digest = lease.artifact.sha256.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut file = tempfile::tempfile().context("create private restore staging")?;
|
||||
let size = http::get_file(
|
||||
&format!("{}/api/v1/wormhole/restore/{id}/payload", hub.url),
|
||||
&mut file,
|
||||
&[
|
||||
("x-tessera-upload-token", &hub.token),
|
||||
("x-tessera-restore-token", &token),
|
||||
],
|
||||
timeout,
|
||||
)?;
|
||||
let (bytes, computed) = digest_file(&mut file)?;
|
||||
ensure!(
|
||||
size == bytes && computed == digest,
|
||||
"restore payload checksum mismatch"
|
||||
);
|
||||
Ok(file)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
@@ -14,6 +14,10 @@ tessera-store = { path = "../tessera-store" }
|
||||
tessera-demo = { path = "../tessera-demo" }
|
||||
tessera-providers = { path = "../tessera-providers" }
|
||||
anyhow.workspace = true
|
||||
chrono.workspace = true
|
||||
tempfile.workspace = true
|
||||
sha2.workspace = true
|
||||
hex.workspace = true
|
||||
clap.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use anyhow::{Context, Result};
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::net::{IpAddr, TcpStream};
|
||||
|
||||
pub fn get(url: &str) -> Result<String> {
|
||||
request("GET", url, None, None)
|
||||
@@ -24,8 +24,21 @@ fn request(
|
||||
content_type: Option<&str>,
|
||||
) -> Result<String> {
|
||||
let (host, port, path) = parse_url(url)?;
|
||||
let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?;
|
||||
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
|
||||
if let Ok(token) = std::env::var("TESSERA_ADMIN_TOKEN") {
|
||||
let token = token.trim();
|
||||
if !token.is_empty() {
|
||||
anyhow::ensure!(
|
||||
host == "localhost" || host.parse::<IpAddr>().is_ok_and(|ip| ip.is_loopback()),
|
||||
"the HTTP CLI requires a loopback hub URL when using an admin token"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
token.bytes().all(|byte| byte.is_ascii_graphic()),
|
||||
"invalid admin token"
|
||||
);
|
||||
req.push_str(&format!("Authorization: Bearer {token}\r\n"));
|
||||
}
|
||||
}
|
||||
if let Some(b) = body {
|
||||
req.push_str(&format!("Content-Length: {}\r\n", b.len()));
|
||||
if let Some(ct) = content_type {
|
||||
@@ -36,6 +49,7 @@ fn request(
|
||||
} else {
|
||||
req.push_str("\r\n");
|
||||
}
|
||||
let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?;
|
||||
stream.write_all(req.as_bytes())?;
|
||||
let mut buf = String::new();
|
||||
stream.read_to_string(&mut buf)?;
|
||||
|
||||
287
crates/tessera-cli/src/legacy_import.rs
Normal file
287
crates/tessera-cli/src/legacy_import.rs
Normal file
@@ -0,0 +1,287 @@
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use chrono::{DateTime, Utc};
|
||||
use clap::{Args, ValueEnum};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{self, Read, Seek, SeekFrom},
|
||||
path::PathBuf,
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
use tessera_core::SnapshotManifest;
|
||||
use tessera_store::Vault;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Args, Clone)]
|
||||
pub struct ImportArgs {
|
||||
#[arg(long)]
|
||||
bucket: String,
|
||||
#[arg(long)]
|
||||
prefix: String,
|
||||
#[arg(long)]
|
||||
endpoint: Option<String>,
|
||||
#[arg(long)]
|
||||
orbit_id: Uuid,
|
||||
#[arg(long)]
|
||||
application: String,
|
||||
#[arg(long, value_enum)]
|
||||
engine: Engine,
|
||||
/// Consistent SQLite export of the old service's job history.
|
||||
#[arg(long)]
|
||||
history: Option<PathBuf>,
|
||||
/// Reconcile counts, times and sizes without downloading or writing snapshots.
|
||||
#[arg(long)]
|
||||
inventory_only: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, ValueEnum)]
|
||||
enum Engine {
|
||||
Postgres,
|
||||
Mysql,
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Postgres => "postgres",
|
||||
Self::Mysql => "mysql",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct Listing {
|
||||
#[serde(default)]
|
||||
contents: Vec<Object>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(rename_all(deserialize = "PascalCase"))]
|
||||
struct Object {
|
||||
key: String,
|
||||
#[serde(rename(deserialize = "ETag"))]
|
||||
etag: String,
|
||||
size: u64,
|
||||
last_modified: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct Downloaded {
|
||||
#[serde(rename = "ETag")]
|
||||
etag: String,
|
||||
content_length: u64,
|
||||
last_modified: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Entry {
|
||||
snapshot_id: Uuid,
|
||||
#[serde(flatten)]
|
||||
object: Object,
|
||||
status: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Report {
|
||||
application: String,
|
||||
bucket: String,
|
||||
prefix: String,
|
||||
count: usize,
|
||||
bytes: u64,
|
||||
history_snapshot_id: Option<Uuid>,
|
||||
objects: Vec<Entry>,
|
||||
}
|
||||
|
||||
pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> {
|
||||
ensure!(
|
||||
!args.prefix.is_empty() && args.prefix.ends_with('/'),
|
||||
"provide a per-application prefix ending in '/'"
|
||||
);
|
||||
ensure!(
|
||||
!args.application.trim().is_empty()
|
||||
&& args.application.len() <= 128
|
||||
&& !args.application.chars().any(char::is_control),
|
||||
"invalid application name"
|
||||
);
|
||||
if let Some(endpoint) = &args.endpoint {
|
||||
ensure!(
|
||||
(endpoint.starts_with("https://") || endpoint.starts_with("http://127.0.0.1:"))
|
||||
&& !endpoint.contains(['@', '?', '#', '\r', '\n']),
|
||||
"use an HTTPS S3 endpoint without embedded credentials"
|
||||
);
|
||||
}
|
||||
let output = aws(&args, "list-objects-v2")
|
||||
.arg(format!("--prefix={}", args.prefix))
|
||||
.output()
|
||||
.context("run AWS CLI S3 inventory")?;
|
||||
ensure!(
|
||||
output.status.success(),
|
||||
"could not list legacy S3 objects ({})",
|
||||
output.status
|
||||
);
|
||||
let listing: Listing =
|
||||
serde_json::from_slice(&output.stdout).context("parse legacy S3 inventory")?;
|
||||
let mut objects = Vec::new();
|
||||
let mut bytes = 0u64;
|
||||
for object in listing.contents {
|
||||
if !object.key.starts_with(&args.prefix)
|
||||
|| !(object.key.ends_with(".sql") || object.key.ends_with(".sql.gz"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
ensure!(
|
||||
object.size > 0 && !object.etag.is_empty() && object.etag != "*",
|
||||
"invalid legacy archive metadata"
|
||||
);
|
||||
bytes = bytes
|
||||
.checked_add(object.size)
|
||||
.context("legacy inventory byte count overflow")?;
|
||||
let key = serde_json::to_vec(&(
|
||||
"s3-legacy",
|
||||
&args.endpoint,
|
||||
&args.bucket,
|
||||
&object.key,
|
||||
&object.etag,
|
||||
object.size,
|
||||
object.last_modified,
|
||||
args.orbit_id,
|
||||
))?;
|
||||
let snapshot_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, &key);
|
||||
let status = if args.inventory_only {
|
||||
"inventoried"
|
||||
} else if vault.legacy_import_exists(snapshot_id)? {
|
||||
"already_imported"
|
||||
} else if import_object(vault, &args, &object, snapshot_id)? {
|
||||
"imported"
|
||||
} else {
|
||||
"already_imported"
|
||||
};
|
||||
objects.push(Entry {
|
||||
snapshot_id,
|
||||
object,
|
||||
status,
|
||||
});
|
||||
}
|
||||
let history_snapshot_id = if args.inventory_only {
|
||||
None
|
||||
} else {
|
||||
args.history
|
||||
.as_ref()
|
||||
.map(|path| import_history(vault, path))
|
||||
.transpose()?
|
||||
};
|
||||
let report = Report {
|
||||
application: args.application,
|
||||
bucket: args.bucket,
|
||||
prefix: args.prefix,
|
||||
count: objects.len(),
|
||||
bytes,
|
||||
history_snapshot_id,
|
||||
objects,
|
||||
};
|
||||
println!("{}", serde_json::to_string_pretty(&report)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn aws(args: &ImportArgs, operation: &str) -> Command {
|
||||
let mut cmd = Command::new("aws");
|
||||
cmd.args([
|
||||
"--no-cli-pager",
|
||||
"--no-cli-auto-prompt",
|
||||
"--output",
|
||||
"json",
|
||||
"s3api",
|
||||
operation,
|
||||
])
|
||||
.arg(format!("--bucket={}", args.bucket))
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
if let Some(endpoint) = &args.endpoint {
|
||||
cmd.arg(format!("--endpoint-url={endpoint}"));
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
fn import_object(vault: &Vault, args: &ImportArgs, object: &Object, id: Uuid) -> Result<bool> {
|
||||
let file = tempfile::NamedTempFile::new()?;
|
||||
let output = aws(args, "get-object")
|
||||
.arg(format!("--key={}", object.key))
|
||||
.arg(format!("--if-match={}", object.etag))
|
||||
.arg(file.path())
|
||||
.output()
|
||||
.context("run conditional AWS CLI S3 download")?;
|
||||
ensure!(
|
||||
output.status.success(),
|
||||
"legacy archive download failed ({})",
|
||||
output.status
|
||||
);
|
||||
let received: Downloaded =
|
||||
serde_json::from_slice(&output.stdout).context("parse downloaded object metadata")?;
|
||||
ensure!(
|
||||
received.etag == object.etag
|
||||
&& received.last_modified == object.last_modified
|
||||
&& received.content_length == object.size
|
||||
&& file.as_file().metadata()?.len() == object.size,
|
||||
"legacy object changed since inventory"
|
||||
);
|
||||
let mut file = file.reopen()?;
|
||||
let format = if object.key.ends_with(".sql.gz") {
|
||||
let mut signature = [0; 2];
|
||||
file.read_exact(&mut signature)?;
|
||||
ensure!(
|
||||
signature == [0x1f, 0x8b],
|
||||
"legacy archive is missing a gzip header"
|
||||
);
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
"sql_gzip"
|
||||
} else {
|
||||
"plain"
|
||||
};
|
||||
let manifest = SnapshotManifest {
|
||||
snapshot_id: id,
|
||||
orbit_id: args.orbit_id,
|
||||
orbit_name: args.application.clone(),
|
||||
provider: args.engine.name().into(),
|
||||
labels: vec!["legacy-import".into()],
|
||||
paths: vec![],
|
||||
restore_hints: serde_json::json!({
|
||||
"format": format, "legacy": { "bucket": args.bucket, "key": object.key,
|
||||
"etag": object.etag, "bytes": object.size, "last_modified": object.last_modified }
|
||||
}),
|
||||
};
|
||||
vault.import_legacy_payload(manifest, file, object.last_modified)
|
||||
}
|
||||
|
||||
fn import_history(vault: &Vault, path: &std::path::Path) -> Result<Uuid> {
|
||||
let mut original = File::open(path).context("open legacy history export")?;
|
||||
let mut signature = [0; 16];
|
||||
original.read_exact(&mut signature)?;
|
||||
ensure!(
|
||||
&signature == b"SQLite format 3\0",
|
||||
"legacy history must be a consistent SQLite export"
|
||||
);
|
||||
original.seek(SeekFrom::Start(0))?;
|
||||
let mut staged = tempfile::tempfile()?;
|
||||
let bytes = io::copy(&mut original, &mut staged)?;
|
||||
staged.seek(SeekFrom::Start(0))?;
|
||||
let mut digest = Sha256::new();
|
||||
io::copy(&mut staged, &mut digest)?;
|
||||
let checksum = hex::encode(digest.finalize());
|
||||
let key = format!("legacy-history:{checksum}");
|
||||
let id = Uuid::new_v5(&Uuid::NAMESPACE_URL, key.as_bytes());
|
||||
let taken_at: DateTime<Utc> = original.metadata()?.modified()?.into();
|
||||
let manifest = SnapshotManifest {
|
||||
snapshot_id: id,
|
||||
orbit_id: Uuid::nil(),
|
||||
orbit_name: "Legacy operator history".into(),
|
||||
provider: "legacy-history".into(),
|
||||
labels: vec!["legacy-history".into()],
|
||||
paths: vec![],
|
||||
restore_hints: serde_json::json!({"format": "sqlite", "sha256": checksum, "legacy_bytes": bytes}),
|
||||
};
|
||||
vault.import_legacy_payload(manifest, staged, taken_at)?;
|
||||
Ok(id)
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
mod http;
|
||||
mod legacy_import;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::{Args, Parser, Subcommand};
|
||||
@@ -50,6 +51,13 @@ enum Commands {
|
||||
orbit: Option<String>,
|
||||
},
|
||||
List,
|
||||
/// Reconcile and import immutable legacy SQL archives from an S3 prefix.
|
||||
LegacyImport(legacy_import::ImportArgs),
|
||||
/// Export the private legacy operator-history SQLite archive.
|
||||
LegacyHistory {
|
||||
snapshot_id: Uuid,
|
||||
output: String,
|
||||
},
|
||||
Reconstitute {
|
||||
snapshot_id: Uuid,
|
||||
target: String,
|
||||
@@ -163,6 +171,25 @@ fn main() -> Result<()> {
|
||||
}
|
||||
Commands::Snap { orbit } => cmd_snap(&cli, orbit)?,
|
||||
Commands::List => cmd_list(&cli)?,
|
||||
Commands::LegacyImport(args) => {
|
||||
let vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(&cli)?)?;
|
||||
legacy_import::run(&vault, args)?;
|
||||
}
|
||||
Commands::LegacyHistory {
|
||||
snapshot_id,
|
||||
output,
|
||||
} => {
|
||||
let vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(&cli)?)?;
|
||||
let snapshot = vault
|
||||
.get_snapshot(snapshot_id)?
|
||||
.context("legacy history archive not found")?;
|
||||
anyhow::ensure!(
|
||||
snapshot.manifest.provider == "legacy-history",
|
||||
"snapshot is not a legacy history archive"
|
||||
);
|
||||
vault.restore_snapshot(snapshot_id, std::path::Path::new(&output))?;
|
||||
println!("Exported legacy history {snapshot_id}");
|
||||
}
|
||||
Commands::Reconstitute {
|
||||
snapshot_id,
|
||||
target,
|
||||
@@ -257,8 +284,10 @@ fn cmd_orbit(
|
||||
serde_json::json!({ "connection_url": path.context("--path or connection url required")? })
|
||||
}
|
||||
"wormhole" => {
|
||||
anyhow::ensure!(path.is_none() && schedule.is_none() && !dry_run,
|
||||
"Wormhole paths and scheduling are set on the outpost");
|
||||
anyhow::ensure!(
|
||||
path.is_none() && schedule.is_none() && !dry_run,
|
||||
"Wormhole paths and scheduling are set on the outpost"
|
||||
);
|
||||
serde_json::json!({})
|
||||
}
|
||||
_ => anyhow::bail!("unknown provider"),
|
||||
|
||||
@@ -58,6 +58,47 @@ impl RetentionPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum CaptureRetention {
|
||||
Age { days: u16 },
|
||||
Count { #[serde(default = "fallback_count")] keep: u16 },
|
||||
}
|
||||
|
||||
fn fallback_count() -> u16 {
|
||||
5
|
||||
}
|
||||
|
||||
impl Default for CaptureRetention {
|
||||
fn default() -> Self {
|
||||
Self::Age { days: 14 }
|
||||
}
|
||||
}
|
||||
|
||||
impl CaptureRetention {
|
||||
pub fn is_valid(self) -> bool {
|
||||
match self {
|
||||
Self::Age { days } => days > 0,
|
||||
Self::Count { keep } => keep > 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn evaluate_capture_retention(
|
||||
policy: CaptureRetention,
|
||||
mut snapshots: Vec<SnapshotRef>,
|
||||
now: DateTime<Utc>,
|
||||
) -> Vec<Uuid> {
|
||||
snapshots.sort_unstable_by_key(|snapshot| std::cmp::Reverse((snapshot.taken_at, snapshot.id)));
|
||||
snapshots.into_iter().enumerate().skip(1).filter_map(|(index, snapshot)| {
|
||||
let expired = match policy {
|
||||
CaptureRetention::Age { days } => now.signed_duration_since(snapshot.taken_at).num_days() >= i64::from(days),
|
||||
CaptureRetention::Count { keep } => index >= usize::from(keep),
|
||||
};
|
||||
expired.then_some(snapshot.id)
|
||||
}).collect()
|
||||
}
|
||||
|
||||
/// Keep the newest snapshot in each of the most recent occupied UTC periods.
|
||||
pub fn evaluate_gfs(policy: &RetentionPolicy, mut snapshots: Vec<SnapshotRef>) -> Vec<Uuid> {
|
||||
if !policy.has_tiers() {
|
||||
@@ -160,6 +201,19 @@ mod tests {
|
||||
use super::*;
|
||||
use chrono::{Duration, TimeZone, Timelike};
|
||||
|
||||
#[test]
|
||||
fn capture_retention_keeps_one_old_archive_or_the_latest_five() {
|
||||
let now = Utc::now();
|
||||
let snapshots: Vec<_> = (0..6).map(|i| SnapshotRef {
|
||||
id: Uuid::new_v4(),
|
||||
taken_at: now - Duration::days(15 + i),
|
||||
}).collect();
|
||||
assert_eq!(evaluate_capture_retention(CaptureRetention::default(), snapshots.clone(), now),
|
||||
snapshots[1..].iter().map(|snap| snap.id).collect::<Vec<_>>());
|
||||
assert_eq!(evaluate_capture_retention(CaptureRetention::Count { keep: 5 }, snapshots.clone(), now),
|
||||
[snapshots[5].id]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gfs_keeps_the_newest_in_each_period_and_combines_tiers() {
|
||||
let policy = RetentionPolicy {
|
||||
|
||||
89
crates/tessera-core/src/job.rs
Normal file
89
crates/tessera-core/src/job.rs
Normal file
@@ -0,0 +1,89 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CaptureFormat {
|
||||
PostgresCustom,
|
||||
PostgresSql,
|
||||
MysqlSql,
|
||||
Filesystem,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CaptureProfile {
|
||||
pub application_id: Uuid,
|
||||
pub orbit_id: Uuid,
|
||||
pub outpost_id: Uuid,
|
||||
pub format: CaptureFormat,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub schedule: Option<CaptureSchedule>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub retention: Option<crate::decay::CaptureRetention>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CaptureSchedule {
|
||||
pub hour: u8,
|
||||
#[serde(default)]
|
||||
pub minute: u8,
|
||||
pub timezone: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct CaptureJob {
|
||||
pub id: Uuid,
|
||||
pub profile: CaptureProfile,
|
||||
pub actor: String,
|
||||
pub status: String,
|
||||
pub phase: String,
|
||||
pub created_at: i64,
|
||||
pub updated_at: i64,
|
||||
pub snapshot_id: Option<Uuid>,
|
||||
pub offsite_status: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct CaptureEvent {
|
||||
pub at: i64,
|
||||
pub phase: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct CaptureLease {
|
||||
pub job_id: Uuid,
|
||||
pub profile: CaptureProfile,
|
||||
pub lease_id: Uuid,
|
||||
#[serde(default)]
|
||||
pub restic: bool,
|
||||
}
|
||||
|
||||
pub const CAPTURE_LEASE_SECONDS: i64 = 90;
|
||||
pub const CAPTURE_HEARTBEAT_SECONDS: u64 = 20;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CaptureProgress {
|
||||
Heartbeat,
|
||||
Dumping,
|
||||
Uploading,
|
||||
DumpFailed,
|
||||
UploadFailed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct CaptureReport {
|
||||
pub lease_id: Uuid,
|
||||
pub progress: CaptureProgress,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ResticCaptureCommit {
|
||||
pub lease_id: Uuid,
|
||||
pub snapshot_id: String,
|
||||
pub identity: Option<crate::restore::DatabaseIdentity>,
|
||||
pub sha256: Option<String>,
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
pub mod config;
|
||||
pub mod decay;
|
||||
pub mod errors;
|
||||
pub mod job;
|
||||
|
||||
pub mod manifest;
|
||||
pub mod orbit;
|
||||
pub mod reconstitute;
|
||||
pub mod restore;
|
||||
pub mod wormhole;
|
||||
|
||||
pub use config::*;
|
||||
|
||||
109
crates/tessera-core/src/restore.rs
Normal file
109
crates/tessera-core/src/restore.rs
Normal file
@@ -0,0 +1,109 @@
|
||||
use crate::job::CaptureFormat;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Engine {
|
||||
Postgres,
|
||||
Mysql,
|
||||
}
|
||||
|
||||
impl CaptureFormat {
|
||||
pub fn engine(self) -> Option<Engine> {
|
||||
match self {
|
||||
Self::PostgresCustom | Self::PostgresSql => Some(Engine::Postgres),
|
||||
Self::MysqlSql => Some(Engine::Mysql),
|
||||
Self::Filesystem => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct DatabaseIdentity {
|
||||
pub instance: String,
|
||||
pub database: String,
|
||||
}
|
||||
|
||||
impl DatabaseIdentity {
|
||||
pub fn valid(&self, engine: Engine) -> bool {
|
||||
let instance_valid = match engine {
|
||||
Engine::Postgres => self
|
||||
.instance
|
||||
.parse::<u64>()
|
||||
.is_ok_and(|id| id.to_string() == self.instance),
|
||||
Engine::Mysql => {
|
||||
Uuid::parse_str(&self.instance).is_ok_and(|id| id.to_string() == self.instance)
|
||||
}
|
||||
};
|
||||
instance_valid
|
||||
&& (1..=255).contains(&self.database.len())
|
||||
&& !self.database.chars().any(char::is_control)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RestoreTarget {
|
||||
pub id: Uuid,
|
||||
pub application_id: Uuid,
|
||||
pub outpost_id: Uuid,
|
||||
pub name: String,
|
||||
pub engine: Engine,
|
||||
pub identity: DatabaseIdentity,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RestoreRequest {
|
||||
pub snapshot_id: Uuid,
|
||||
pub target_id: Uuid,
|
||||
pub confirmation: String,
|
||||
}
|
||||
|
||||
impl RestoreRequest {
|
||||
pub fn confirmation(snapshot: Uuid, target: Uuid) -> String {
|
||||
format!("RESTORE {snapshot} TO {target}")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct RestoreJob {
|
||||
pub id: Uuid,
|
||||
pub snapshot_id: Uuid,
|
||||
pub target: RestoreTarget,
|
||||
pub actor: String,
|
||||
pub status: String,
|
||||
pub phase: String,
|
||||
pub safety_snapshot_id: Option<Uuid>,
|
||||
pub created_at: i64,
|
||||
pub updated_at: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct RestoreArtifact {
|
||||
pub format: CaptureFormat,
|
||||
pub identity: DatabaseIdentity,
|
||||
pub sha256: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct RestoreLease {
|
||||
pub job: RestoreJob,
|
||||
pub token: Uuid,
|
||||
pub artifact: RestoreArtifact,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum RestoreProgress {
|
||||
Heartbeat,
|
||||
Checking,
|
||||
Safety,
|
||||
InvalidPayload,
|
||||
WrongTarget,
|
||||
SafetyFailed,
|
||||
Applied,
|
||||
ApplyFailed,
|
||||
}
|
||||
@@ -18,7 +18,15 @@ pub struct PairingCode {
|
||||
pub hub_outpost_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct OutpostSummary {
|
||||
pub id: Uuid,
|
||||
pub name: Option<String>,
|
||||
pub last_seen: Option<String>,
|
||||
pub pairing_state: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
pub struct WormholeCredentials {
|
||||
pub outpost_id: Uuid,
|
||||
pub upload_token: String,
|
||||
|
||||
@@ -14,8 +14,10 @@ tessera-store = { path = "../tessera-store" }
|
||||
tessera-providers = { path = "../tessera-providers" }
|
||||
tessera-demo = { path = "../tessera-demo" }
|
||||
anyhow.workspace = true
|
||||
argon2.workspace = true
|
||||
axum.workspace = true
|
||||
chrono.workspace = true
|
||||
chrono-tz = "0.10"
|
||||
cron.workspace = true
|
||||
include_dir = "0.7"
|
||||
rand.workspace = true
|
||||
@@ -23,12 +25,14 @@ serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
rusqlite.workspace = true
|
||||
tokio.workspace = true
|
||||
tokio-util = { version = "0.7", features = ["io"] }
|
||||
tower-http.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
utoipa.workspace = true
|
||||
uuid.workspace = true
|
||||
hex.workspace = true
|
||||
sha2.workspace = true
|
||||
base64 = "0.22"
|
||||
tempfile.workspace = true
|
||||
indexmap = "=2.2.6"
|
||||
|
||||
@@ -65,7 +65,7 @@ fn presented_token(headers: &HeaderMap) -> Option<&str> {
|
||||
}
|
||||
}
|
||||
|
||||
fn tokens_match(expected: &str, presented: &str) -> bool {
|
||||
pub(crate) fn tokens_match(expected: &str, presented: &str) -> bool {
|
||||
let expected = expected.as_bytes();
|
||||
let presented = presented.as_bytes();
|
||||
let mut diff = expected.len() ^ presented.len();
|
||||
@@ -133,3 +133,174 @@ mod tests {
|
||||
.is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SessionGate {
|
||||
config: Option<std::sync::Arc<OperatorConfig>>,
|
||||
state: std::sync::Arc<std::sync::Mutex<SessionState>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SessionState {
|
||||
sessions: std::collections::HashMap<uuid::Uuid, BrowserSession>,
|
||||
attempts: std::collections::VecDeque<std::time::Instant>,
|
||||
}
|
||||
|
||||
struct OperatorConfig {
|
||||
name: String,
|
||||
password_hash: String,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct BrowserSession {
|
||||
pub id: uuid::Uuid,
|
||||
pub csrf: uuid::Uuid,
|
||||
pub actor: String,
|
||||
expires: std::time::Instant,
|
||||
}
|
||||
|
||||
impl SessionGate {
|
||||
pub const COOKIE: &str = "__Host-tessera-session";
|
||||
pub const DURATION: std::time::Duration = std::time::Duration::from_secs(8 * 3600);
|
||||
|
||||
pub fn from_env() -> anyhow::Result<Self> {
|
||||
let config = match std::env::var("TESSERA_OPERATOR_PASSWORD_HASH") {
|
||||
Ok(password_hash) => {
|
||||
let name =
|
||||
std::env::var("TESSERA_OPERATOR_NAME").unwrap_or_else(|_| "operator".into());
|
||||
anyhow::ensure!(
|
||||
(1..=64).contains(&name.len())
|
||||
&& name
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)),
|
||||
"invalid operator name"
|
||||
);
|
||||
let parsed = argon2::PasswordHash::new(&password_hash)
|
||||
.map_err(|_| anyhow::anyhow!("invalid operator Argon2id hash"))?;
|
||||
anyhow::ensure!(
|
||||
parsed.algorithm.as_str() == "argon2id",
|
||||
"operator password requires Argon2id"
|
||||
);
|
||||
Some(std::sync::Arc::new(OperatorConfig {
|
||||
name,
|
||||
password_hash,
|
||||
}))
|
||||
}
|
||||
Err(std::env::VarError::NotPresent) => None,
|
||||
Err(_) => anyhow::bail!("operator password hash must be UTF-8"),
|
||||
};
|
||||
Ok(Self {
|
||||
config,
|
||||
state: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn enabled(&self) -> bool {
|
||||
self.config.is_some()
|
||||
}
|
||||
|
||||
pub fn active(&self, headers: &HeaderMap) -> Option<BrowserSession> {
|
||||
let id = cookie_id(headers)?;
|
||||
let mut state = self.state.lock().unwrap();
|
||||
state
|
||||
.sessions
|
||||
.retain(|_, session| session.expires > std::time::Instant::now());
|
||||
state.sessions.get(&id).cloned()
|
||||
}
|
||||
|
||||
pub fn login(&self, headers: &HeaderMap, password: &str) -> Result<BrowserSession, StatusCode> {
|
||||
use argon2::PasswordVerifier;
|
||||
let config = self.config.as_ref().ok_or(StatusCode::NOT_FOUND)?;
|
||||
{
|
||||
let mut state = self.state.lock().unwrap();
|
||||
state
|
||||
.attempts
|
||||
.retain(|attempt| attempt.elapsed() < std::time::Duration::from_secs(60));
|
||||
if state.attempts.len() >= 10 {
|
||||
return Err(StatusCode::TOO_MANY_REQUESTS);
|
||||
}
|
||||
state.attempts.push_back(std::time::Instant::now());
|
||||
}
|
||||
let hash = argon2::PasswordHash::new(&config.password_hash)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
argon2::Argon2::default()
|
||||
.verify_password(password.as_bytes(), &hash)
|
||||
.map_err(|_| StatusCode::UNAUTHORIZED)?;
|
||||
if let Some(id) = cookie_id(headers) {
|
||||
self.remove(id);
|
||||
}
|
||||
let session = BrowserSession {
|
||||
id: uuid::Uuid::new_v4(),
|
||||
csrf: uuid::Uuid::new_v4(),
|
||||
actor: config.name.clone(),
|
||||
expires: std::time::Instant::now() + Self::DURATION,
|
||||
};
|
||||
let mut state = self.state.lock().unwrap();
|
||||
state
|
||||
.sessions
|
||||
.retain(|_, session| session.expires > std::time::Instant::now());
|
||||
state.sessions.insert(session.id, session.clone());
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
pub fn remove(&self, id: uuid::Uuid) {
|
||||
self.state.lock().unwrap().sessions.remove(&id);
|
||||
}
|
||||
}
|
||||
|
||||
fn cookie_id(headers: &HeaderMap) -> Option<uuid::Uuid> {
|
||||
headers
|
||||
.get_all(axum::http::header::COOKIE)
|
||||
.iter()
|
||||
.filter_map(|header| header.to_str().ok())
|
||||
.flat_map(|line| line.split(';'))
|
||||
.find_map(|pair| {
|
||||
let (name, id) = pair.trim().split_once('=')?;
|
||||
(name == SessionGate::COOKIE)
|
||||
.then(|| uuid::Uuid::parse_str(id).ok())
|
||||
.flatten()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn print_operator_hash() -> anyhow::Result<()> {
|
||||
use argon2::password_hash::{rand_core::OsRng, PasswordHasher, SaltString};
|
||||
use std::io::BufRead;
|
||||
let mut password = String::new();
|
||||
std::io::stdin().lock().read_line(&mut password)?;
|
||||
let password = password.trim_end_matches(['\n', '\r']);
|
||||
anyhow::ensure!(
|
||||
(12..=1024).contains(&password.len()),
|
||||
"operator password must be 12–1024 bytes"
|
||||
);
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
let hash = argon2::Argon2::default()
|
||||
.hash_password(password.as_bytes(), &salt)
|
||||
.map_err(|_| anyhow::anyhow!("could not hash operator password"))?;
|
||||
println!("{hash}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl SessionGate {
|
||||
pub fn fixture() -> Self {
|
||||
use argon2::password_hash::{PasswordHasher, SaltString};
|
||||
let salt = SaltString::encode_b64(b"synthetic-fixture").unwrap();
|
||||
let password_hash = argon2::Argon2::default()
|
||||
.hash_password(b"fixture-operator-password", &salt)
|
||||
.unwrap()
|
||||
.to_string();
|
||||
Self {
|
||||
config: Some(std::sync::Arc::new(OperatorConfig {
|
||||
name: "fixture-operator".into(),
|
||||
password_hash,
|
||||
})),
|
||||
state: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn expire(&self) {
|
||||
for session in self.state.lock().unwrap().sessions.values_mut() {
|
||||
session.expires = std::time::Instant::now();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
108
crates/tessera-hub/src/api/catalog.rs
Normal file
108
crates/tessera-hub/src/api/catalog.rs
Normal file
@@ -0,0 +1,108 @@
|
||||
use super::routes::{require_admin, require_admin_mutation};
|
||||
use crate::state::HubState;
|
||||
use axum::{
|
||||
body::Body,
|
||||
extract::{ConnectInfo, Path, State},
|
||||
http::{header, HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use std::net::SocketAddr;
|
||||
use tokio_util::io::ReaderStream;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(super) fn routes() -> Router<HubState> {
|
||||
Router::new()
|
||||
.route("/api/v1/snapshots/:id", axum::routing::delete(delete))
|
||||
.route("/api/v1/snapshots/:id/download", get(download))
|
||||
}
|
||||
|
||||
async fn download(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
let snapshot = state
|
||||
.vault
|
||||
.read()
|
||||
.await
|
||||
.get_snapshot(id)
|
||||
.map_err(internal)?
|
||||
.filter(|snapshot| snapshot.manifest.provider != "legacy-history")
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let staging = tempfile::tempdir_in(&state.data_dir).map_err(internal)?;
|
||||
let path = staging.path().join("download");
|
||||
let size = state
|
||||
.export_snapshot(id, path.clone())
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let file = tokio::fs::File::open(path).await.map_err(internal)?;
|
||||
let extension = match snapshot
|
||||
.manifest
|
||||
.restore_hints
|
||||
.get("format")
|
||||
.and_then(|format| format.as_str())
|
||||
{
|
||||
Some("plain") => "sql",
|
||||
Some("sql_gzip") => "sql.gz",
|
||||
Some("sqlite") => "sqlite",
|
||||
Some("tar") => "tar",
|
||||
_ => "dump",
|
||||
};
|
||||
Ok((
|
||||
[
|
||||
(header::CONTENT_TYPE, "application/octet-stream".to_owned()),
|
||||
(
|
||||
header::CONTENT_DISPOSITION,
|
||||
format!("attachment; filename=\"{id}.{extension}\""),
|
||||
),
|
||||
(header::CONTENT_LENGTH, size.to_string()),
|
||||
(header::CACHE_CONTROL, "no-store".to_owned()),
|
||||
],
|
||||
Body::from_stream(ReaderStream::new(file)),
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
|
||||
async fn delete(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
||||
let mut vault = state.vault.clone().write_owned().await;
|
||||
if state.db.snapshot_in_restore(id).map_err(internal)?
|
||||
|| state.db.offsite_pending(id).map_err(internal)? || state.active_exports().await.contains(&id)
|
||||
{
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
if vault.get_snapshot(id).map_err(internal)?.is_none_or(|snapshot| snapshot.manifest.provider == "legacy-history") {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
state
|
||||
.db
|
||||
.audit(
|
||||
"snapshot.delete_requested",
|
||||
&format!("actor={actor} snapshot={id}"),
|
||||
)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
tokio::task::spawn_blocking(move || vault.forget(&[id]))
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.map_err(internal)?;
|
||||
state
|
||||
.db
|
||||
.audit("snapshot.deleted", &format!("actor={actor} snapshot={id}"))
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
fn internal(_: impl std::fmt::Display) -> StatusCode {
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
428
crates/tessera-hub/src/api/jobs.rs
Normal file
428
crates/tessera-hub/src/api/jobs.rs
Normal file
@@ -0,0 +1,428 @@
|
||||
use super::routes::{require_admin, require_admin_mutation, upload_token};
|
||||
use crate::state::HubState;
|
||||
use axum::{
|
||||
body::{Body, HttpBody},
|
||||
extract::{rejection::JsonRejection, ConnectInfo, Path, Query, State},
|
||||
http::{header, HeaderMap, StatusCode},
|
||||
routing::{get, post},
|
||||
Json, Router,
|
||||
};
|
||||
use base64::Engine;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{net::SocketAddr, pin::Pin, time::Duration};
|
||||
use tessera_core::job::{
|
||||
CaptureEvent, CaptureFormat, CaptureJob, CaptureLease, CaptureProfile, CaptureReport, ResticCaptureCommit,
|
||||
};
|
||||
use tessera_core::{restore::DatabaseIdentity, SnapshotManifest};
|
||||
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(super) fn routes() -> Router<HubState> {
|
||||
Router::new()
|
||||
.route(
|
||||
"/api/v1/capture-profiles",
|
||||
get(profiles).post(register_profile),
|
||||
)
|
||||
.route("/api/v1/capture-profiles/:id/jobs", post(enqueue))
|
||||
.route("/api/v1/capture-jobs", get(history))
|
||||
.route("/api/v1/capture-jobs/:id", get(job))
|
||||
.route("/api/v1/capture-jobs/:id/events", get(events))
|
||||
.route("/api/v1/wormhole/capture/:application/claim", post(claim))
|
||||
.route("/api/v1/wormhole/capture/:id/report", post(report))
|
||||
.route("/api/v1/wormhole/capture/:id/payload", post(upload))
|
||||
.route("/api/v1/wormhole/capture/:id/restic", post(commit_restic))
|
||||
}
|
||||
|
||||
async fn profiles(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<Vec<CaptureProfile>>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
state.db.capture_profiles().map(Json).map_err(internal)
|
||||
}
|
||||
|
||||
async fn register_profile(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(profile): Json<CaptureProfile>,
|
||||
) -> Result<(StatusCode, Json<CaptureProfile>), StatusCode> {
|
||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
||||
if profile
|
||||
.retention
|
||||
.is_some_and(|retention| !retention.is_valid())
|
||||
{
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
if let Some(schedule) = &profile.schedule {
|
||||
crate::scheduler::capture_schedule(schedule).ok_or(StatusCode::BAD_REQUEST)?;
|
||||
}
|
||||
let _vault = state.vault.write().await;
|
||||
if !state
|
||||
.db
|
||||
.register_capture_profile(&profile, now())
|
||||
.map_err(internal)?
|
||||
{
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
state
|
||||
.db
|
||||
.audit(
|
||||
"capture.profile_registered",
|
||||
&format!("actor={actor} application={}", profile.application_id),
|
||||
)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
Ok((StatusCode::CREATED, Json(profile)))
|
||||
}
|
||||
|
||||
async fn enqueue(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<(StatusCode, Json<CaptureJob>), StatusCode> {
|
||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
||||
let job = state
|
||||
.db
|
||||
.enqueue_capture(id, &actor.name, now())
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
Ok((StatusCode::ACCEPTED, Json(job)))
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct JobFilter {
|
||||
application_id: Option<Uuid>,
|
||||
status: Option<String>,
|
||||
limit: Option<u16>,
|
||||
}
|
||||
|
||||
async fn history(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Query(filter): Query<JobFilter>,
|
||||
) -> Result<Json<Vec<CaptureJob>>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
if filter
|
||||
.status
|
||||
.as_deref()
|
||||
.is_some_and(|status| !matches!(status, "queued" | "running" | "completed" | "failed"))
|
||||
{
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
state
|
||||
.db
|
||||
.capture_jobs(
|
||||
filter.application_id,
|
||||
filter.status.as_deref(),
|
||||
filter.limit.unwrap_or(50).clamp(1, 200),
|
||||
)
|
||||
.map(Json)
|
||||
.map_err(internal)
|
||||
}
|
||||
|
||||
async fn events(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<Vec<CaptureEvent>>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
state
|
||||
.db
|
||||
.capture_job(id)
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
state.db.capture_events(id).map(Json).map_err(internal)
|
||||
}
|
||||
|
||||
async fn job(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<CaptureJob>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
state
|
||||
.db
|
||||
.capture_job(id)
|
||||
.map_err(internal)?
|
||||
.map(Json)
|
||||
.ok_or(StatusCode::NOT_FOUND)
|
||||
}
|
||||
|
||||
async fn claim(
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(application): Path<Uuid>,
|
||||
) -> Result<Json<Option<CaptureLease>>, StatusCode> {
|
||||
let outpost = outpost(&state, &headers)?;
|
||||
let mut lease = state.db.claim_capture(outpost, application, now()).map_err(internal)?;
|
||||
if let Some(lease) = &mut lease {
|
||||
lease.restic |= lease.profile.format == CaptureFormat::Filesystem
|
||||
|| state.vault.read().await.outpost_repository_configured(lease.profile.orbit_id).map_err(internal)?;
|
||||
}
|
||||
Ok(Json(lease))
|
||||
}
|
||||
|
||||
async fn report(
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
body: Result<Json<CaptureReport>, JsonRejection>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let outpost = outpost(&state, &headers)?;
|
||||
let Json(body) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
|
||||
if !state
|
||||
.db
|
||||
.report_capture(outpost, id, body, now())
|
||||
.map_err(internal)?
|
||||
{
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn upload(
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
body: Body,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let outpost = outpost(&state, &headers)?;
|
||||
let lease = Uuid::parse_str(header_value(&headers, "x-tessera-lease-id")?)
|
||||
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let job = state
|
||||
.db
|
||||
.capture_upload(outpost, id, lease, now())
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::CONFLICT)?;
|
||||
if job.profile.format == CaptureFormat::Filesystem
|
||||
|| state.db.restic_required(job.profile.orbit_id).map_err(internal)?
|
||||
|| state.vault.read().await.outpost_repository_configured(job.profile.orbit_id).map_err(internal)?
|
||||
{
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
let identity = headers
|
||||
.get("x-tessera-source-identity")
|
||||
.map(|header| {
|
||||
let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(header.as_bytes())
|
||||
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let identity: DatabaseIdentity =
|
||||
serde_json::from_slice(&decoded).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
if !job.profile.format.engine().is_some_and(|engine| identity.valid(engine)) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
Ok(identity)
|
||||
})
|
||||
.transpose()?;
|
||||
let (file, expected) = receive_payload(&state, &headers, body, job.profile.format).await?;
|
||||
if let Some(snapshot) = job.snapshot_id {
|
||||
return Ok(Json(serde_json::json!({ "snapshot_id": snapshot })));
|
||||
}
|
||||
let orbit_id = job.profile.orbit_id;
|
||||
let manifest = capture_manifest(&state, &job, identity, Some(hex::encode(expected))).await?;
|
||||
let vault = state.vault.clone().read_owned().await;
|
||||
let db = state.db.clone();
|
||||
let offsite_enabled = state.offsite.is_some();
|
||||
let (snapshot, created) = tokio::task::spawn_blocking(move || {
|
||||
// SQLite fencing covers metadata publication. Restic work happens before the transaction.
|
||||
let prepared = if vault.has_published_snapshot(id)? {
|
||||
None
|
||||
} else {
|
||||
Some(vault.prepare_payload(manifest, file, false)?)
|
||||
};
|
||||
let mut wrote = false;
|
||||
let published = db.publish_capture(outpost, id, lease, offsite_enabled, |_| {
|
||||
if !vault.has_published_snapshot(id)? {
|
||||
vault.publish_prepared(
|
||||
prepared
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("prepared snapshot missing"))?,
|
||||
)?;
|
||||
wrote = true;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
// Preserve a prepared copy on an ambiguous commit error for reconciliation.
|
||||
if !wrote {
|
||||
if let Some(snap) = prepared.as_ref() {
|
||||
if let Err(error) = vault.discard_prepared(snap) {
|
||||
tracing::warn!(%id, %error, "could not discard unpublished capture");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok::<_, anyhow::Error>(published)
|
||||
})
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::CONFLICT)?;
|
||||
if created && state.prune_orbit(orbit_id).await.is_err() {
|
||||
tracing::warn!(%id, %orbit_id, "could not apply capture retention");
|
||||
}
|
||||
Ok(Json(serde_json::json!({ "snapshot_id": snapshot })))
|
||||
}
|
||||
|
||||
async fn commit_restic(
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(commit): Json<ResticCaptureCommit>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let outpost = outpost(&state, &headers)?;
|
||||
let job = state.db.capture_upload(outpost, id, commit.lease_id, now())
|
||||
.map_err(internal)?.ok_or(StatusCode::CONFLICT)?;
|
||||
if let Some(snapshot) = job.snapshot_id {
|
||||
return Ok(Json(serde_json::json!({ "snapshot_id": snapshot })));
|
||||
}
|
||||
let engine = job.profile.format.engine();
|
||||
if commit.identity.as_ref().is_some_and(|identity| !engine.is_some_and(|engine| identity.valid(engine)))
|
||||
|| (engine.is_some() && !commit.sha256.as_ref().is_some_and(|hash| {
|
||||
hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||
}))
|
||||
|| (engine.is_none() && commit.sha256.is_some())
|
||||
{
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let orbit_id = job.profile.orbit_id;
|
||||
let manifest = capture_manifest(&state, &job, commit.identity, commit.sha256).await?;
|
||||
let vault = state.vault.clone().read_owned().await;
|
||||
let db = state.db.clone();
|
||||
let offsite = state.offsite.is_some() && engine.is_some();
|
||||
let (snapshot, created) = tokio::task::spawn_blocking(move || {
|
||||
let prepared = vault.prepare_outpost_capture(manifest, outpost, &commit.snapshot_id)?;
|
||||
db.publish_capture(outpost, id, commit.lease_id, offsite, |_| {
|
||||
if !vault.has_published_snapshot(id)? {
|
||||
vault.publish_prepared(&prepared)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}).await.map_err(internal)?.map_err(internal)?.ok_or(StatusCode::CONFLICT)?;
|
||||
if created && state.prune_orbit(orbit_id).await.is_err() {
|
||||
tracing::warn!(%id, %orbit_id, "could not apply capture retention");
|
||||
}
|
||||
Ok(Json(serde_json::json!({ "snapshot_id": snapshot })))
|
||||
}
|
||||
|
||||
async fn capture_manifest(
|
||||
state: &HubState,
|
||||
job: &CaptureJob,
|
||||
identity: Option<DatabaseIdentity>,
|
||||
digest: Option<String>,
|
||||
) -> Result<SnapshotManifest, StatusCode> {
|
||||
let id = job.id;
|
||||
let orbit_id = job.profile.orbit_id;
|
||||
let orbit = state
|
||||
.db
|
||||
.list_orbits()
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.into_iter()
|
||||
.find(|orbit| orbit.id == orbit_id)
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let (engine, format) = match job.profile.format {
|
||||
CaptureFormat::PostgresCustom => ("postgres", "custom"),
|
||||
CaptureFormat::PostgresSql => ("postgres", "plain"),
|
||||
CaptureFormat::MysqlSql => ("mysql", "plain"),
|
||||
CaptureFormat::Filesystem => ("filesystem", "tar"),
|
||||
};
|
||||
Ok(SnapshotManifest {
|
||||
snapshot_id: id,
|
||||
orbit_id,
|
||||
orbit_name: orbit.name,
|
||||
labels: vec![engine.into()],
|
||||
provider: engine.into(),
|
||||
paths: vec![],
|
||||
restore_hints: serde_json::json!({
|
||||
"engine": engine, "format": format, "job_id": id, "outpost_id": job.profile.outpost_id,
|
||||
"application_id": job.profile.application_id, "sha256": digest,
|
||||
"queued_at": job.created_at, "uploaded_at": now(), "source_identity": identity
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn receive_payload(
|
||||
state: &HubState,
|
||||
headers: &HeaderMap,
|
||||
mut body: Body,
|
||||
format: CaptureFormat,
|
||||
) -> Result<(std::fs::File, [u8; 32]), StatusCode> {
|
||||
let length = header_value(headers, header::CONTENT_LENGTH.as_str())?
|
||||
.parse::<u64>()
|
||||
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
if length == 0 || length > 100 * 1024 * 1024 * 1024 {
|
||||
return Err(StatusCode::PAYLOAD_TOO_LARGE);
|
||||
}
|
||||
let mut expected = [0u8; 32];
|
||||
hex::decode_to_slice(header_value(headers, "x-tessera-sha256")?, &mut expected)
|
||||
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
|
||||
let file = tempfile::tempfile_in(&state.data_dir).map_err(internal)?;
|
||||
let mut file = tokio::fs::File::from_std(file);
|
||||
let mut digest = Sha256::new();
|
||||
let mut bytes = 0;
|
||||
loop {
|
||||
let next = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx));
|
||||
let Some(frame) = tokio::time::timeout(Duration::from_secs(30), next)
|
||||
.await
|
||||
.map_err(|_| StatusCode::REQUEST_TIMEOUT)?
|
||||
else {
|
||||
break;
|
||||
};
|
||||
let frame = frame.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
if let Ok(chunk) = frame.into_data() {
|
||||
bytes += chunk.len() as u64;
|
||||
if bytes > length {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
digest.update(&chunk);
|
||||
file.write_all(&chunk).await.map_err(internal)?;
|
||||
}
|
||||
}
|
||||
if bytes != length || digest.finalize()[..] != expected {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
file.flush().await.map_err(internal)?;
|
||||
if format == CaptureFormat::PostgresCustom {
|
||||
let mut signature = [0; 5];
|
||||
file.seek(std::io::SeekFrom::Start(0))
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
if file.read_exact(&mut signature).await.is_err() || &signature != b"PGDMP" {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
}
|
||||
Ok((file.into_std().await, expected))
|
||||
}
|
||||
|
||||
pub(super) fn header_value<'a>(headers: &'a HeaderMap, name: &str) -> Result<&'a str, StatusCode> {
|
||||
headers
|
||||
.get(name)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.ok_or(StatusCode::BAD_REQUEST)
|
||||
}
|
||||
|
||||
pub(super) fn outpost(state: &HubState, headers: &HeaderMap) -> Result<Uuid, StatusCode> {
|
||||
let token = upload_token(state, headers)?;
|
||||
let id = state
|
||||
.db
|
||||
.upload_token_outpost(token)
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let id = Uuid::parse_str(&id).map_err(internal)?;
|
||||
state.db.touch_outpost(id).map_err(internal)?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
pub(super) fn now() -> i64 {
|
||||
chrono::Utc::now().timestamp()
|
||||
}
|
||||
|
||||
pub(super) fn internal(_: impl std::fmt::Display) -> StatusCode {
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
mod catalog;
|
||||
mod jobs;
|
||||
mod orbit;
|
||||
mod restore;
|
||||
mod routes;
|
||||
mod session;
|
||||
|
||||
pub use orbit::run_orbit_internal;
|
||||
pub use routes::router;
|
||||
|
||||
@@ -2,15 +2,50 @@ use crate::db::OrbitRow;
|
||||
use crate::state::HubState;
|
||||
use anyhow::{Context, Result};
|
||||
use tessera_core::manifest::SnapshotManifest;
|
||||
use tessera_providers::{FilesystemConfig, PostgresProvider};
|
||||
use tessera_providers::{FilesystemConfig, MysqlSource, PostgresProvider, PostgresSource};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub async fn run_orbit_internal(state: HubState, orbit_id: Uuid) -> Result<Option<Uuid>> {
|
||||
let orbits = state.db.list_orbits().await?;
|
||||
let orbit = orbits
|
||||
.into_iter()
|
||||
.find(|o| o.id == orbit_id)
|
||||
.context("orbit not found")?;
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(tag = "engine", rename_all = "snake_case")]
|
||||
pub(super) enum DatabaseSource {
|
||||
Postgres(PostgresSource),
|
||||
Mysql(MysqlSource),
|
||||
}
|
||||
|
||||
impl DatabaseSource {
|
||||
pub(super) fn valid_endpoint(&self) -> bool {
|
||||
let (host, port, database, user, password_file) = match self {
|
||||
Self::Postgres(source) if source.bastion.is_none() => (
|
||||
&source.host,
|
||||
source.port,
|
||||
&source.database,
|
||||
&source.user,
|
||||
&source.password_file,
|
||||
),
|
||||
Self::Mysql(MysqlSource::Direct {
|
||||
host,
|
||||
port,
|
||||
database,
|
||||
user,
|
||||
password_file,
|
||||
..
|
||||
}) => (host, *port, database, user, password_file),
|
||||
_ => return false,
|
||||
};
|
||||
port != 0
|
||||
&& password_file.is_absolute()
|
||||
&& [host, database, user]
|
||||
.iter()
|
||||
.all(|value| !value.trim().is_empty() && !value.chars().any(char::is_control))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run_orbit_internal(state: HubState, orbit: OrbitRow) -> Result<Option<Uuid>> {
|
||||
anyhow::ensure!(
|
||||
orbit.provider != "wormhole",
|
||||
"Wormhole backups are started by the outpost agent"
|
||||
);
|
||||
let orbit_id = orbit.id;
|
||||
anyhow::ensure!(
|
||||
state.active_orbits.lock().await.insert(orbit_id),
|
||||
"orbit already running"
|
||||
@@ -49,6 +84,23 @@ async fn run_orbit_row(state: &HubState, orbit: OrbitRow) -> Result<Option<Uuid>
|
||||
manifest.paths = config.paths;
|
||||
(None, config.max_file_bytes)
|
||||
}
|
||||
"database" => {
|
||||
let source = serde_json::from_value::<DatabaseSource>(config)?;
|
||||
let file = tempfile::tempfile()?;
|
||||
let (engine, format) = match source {
|
||||
DatabaseSource::Postgres(source) => {
|
||||
source.dump_to(file.try_clone()?, "plain").await?;
|
||||
("postgres", "plain")
|
||||
}
|
||||
DatabaseSource::Mysql(source) => {
|
||||
source.dump_to(file.try_clone()?).await?;
|
||||
("mysql", "plain")
|
||||
}
|
||||
};
|
||||
manifest.provider = engine.into();
|
||||
manifest.restore_hints = serde_json::json!({"engine": engine, "format": format});
|
||||
(Some(file), None)
|
||||
}
|
||||
"postgres" => {
|
||||
let provider = PostgresProvider::from_config(&config)?;
|
||||
let file = tempfile::tempfile()?;
|
||||
|
||||
441
crates/tessera-hub/src/api/restore.rs
Normal file
441
crates/tessera-hub/src/api/restore.rs
Normal file
@@ -0,0 +1,441 @@
|
||||
use super::{
|
||||
jobs::{header_value, internal, now, outpost, receive_payload},
|
||||
routes::{require_admin, require_admin_mutation},
|
||||
};
|
||||
use crate::state::HubState;
|
||||
use axum::{
|
||||
body::Body,
|
||||
extract::{rejection::JsonRejection, ConnectInfo, Path, State},
|
||||
http::{header, HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, post},
|
||||
Json, Router,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use std::net::SocketAddr;
|
||||
use tessera_core::{
|
||||
job::CaptureFormat,
|
||||
restore::{
|
||||
Engine, RestoreArtifact, RestoreJob, RestoreLease, RestoreProgress, RestoreRequest,
|
||||
RestoreTarget,
|
||||
},
|
||||
SnapshotManifest,
|
||||
};
|
||||
use tokio_util::io::ReaderStream;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(super) fn routes() -> Router<HubState> {
|
||||
Router::new()
|
||||
.route("/api/v1/restore-targets", post(register))
|
||||
.route("/api/v1/capture-profiles/:id/restore-targets", get(targets))
|
||||
.route("/api/v1/snapshots/:id/restore-targets", get(snapshot_targets))
|
||||
.route("/api/v1/restore-jobs", post(enqueue))
|
||||
.route("/api/v1/snapshots/:id/restore-jobs", get(history))
|
||||
.route("/api/v1/restore-jobs/:id", get(job).delete(cancel))
|
||||
.route("/api/v1/restore-jobs/:id/reconcile", post(reconcile))
|
||||
.route("/api/v1/wormhole/restore-targets/:id/claim", post(claim))
|
||||
.route("/api/v1/wormhole/restore/:id/payload", get(payload))
|
||||
.route("/api/v1/wormhole/restore/:id/report", post(report))
|
||||
.route("/api/v1/wormhole/restore/:id/safety", post(safety))
|
||||
.route("/api/v1/wormhole/restore/:id/apply", post(apply))
|
||||
}
|
||||
|
||||
async fn register(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(target): Json<RestoreTarget>,
|
||||
) -> Result<(StatusCode, Json<RestoreTarget>), StatusCode> {
|
||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
||||
if target.name.trim().is_empty()
|
||||
|| target.name.len() > 128
|
||||
|| target.name.chars().any(char::is_control)
|
||||
|| !target.identity.valid(target.engine)
|
||||
{
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let profiles = state.db.capture_profiles().map_err(internal)?;
|
||||
if !profiles.iter().any(|profile| {
|
||||
profile.application_id == target.application_id && profile.format.engine() == Some(target.engine)
|
||||
}) {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
if !state
|
||||
.db
|
||||
.register_restore_target(&target)
|
||||
.map_err(internal)?
|
||||
{
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
state
|
||||
.db
|
||||
.audit(
|
||||
"restore.target_registered",
|
||||
&format!("actor={actor} target={}", target.id),
|
||||
)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
Ok((StatusCode::CREATED, Json(target)))
|
||||
}
|
||||
|
||||
async fn targets(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(application): Path<Uuid>,
|
||||
) -> Result<Json<Vec<RestoreTarget>>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
state
|
||||
.db
|
||||
.restore_targets(application)
|
||||
.map(Json)
|
||||
.map_err(internal)
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct SnapshotTarget {
|
||||
#[serde(flatten)]
|
||||
target: RestoreTarget,
|
||||
ineligible_reason: Option<&'static str>,
|
||||
}
|
||||
|
||||
async fn snapshot_targets(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(snapshot): Path<Uuid>,
|
||||
) -> Result<Json<Vec<SnapshotTarget>>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
let vault = state.vault.read().await;
|
||||
let snap = vault
|
||||
.get_snapshot(snapshot)
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let (application, artifact) =
|
||||
artifact(&snap.manifest).ok_or(StatusCode::UNPROCESSABLE_ENTITY)?;
|
||||
let targets = state
|
||||
.db
|
||||
.restore_targets_with_activity(application)
|
||||
.map_err(internal)?;
|
||||
let responses = targets
|
||||
.into_iter()
|
||||
.map(|(target, active)| {
|
||||
let ineligible_reason = if active {
|
||||
crate::db::restore_target_mismatch(&target, &artifact)
|
||||
} else {
|
||||
Some("Outpost is no longer paired")
|
||||
};
|
||||
SnapshotTarget { target, ineligible_reason }
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(responses))
|
||||
}
|
||||
|
||||
async fn enqueue(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(request): Json<RestoreRequest>,
|
||||
) -> Result<(StatusCode, Json<RestoreJob>), StatusCode> {
|
||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
||||
if request.confirmation != RestoreRequest::confirmation(request.snapshot_id, request.target_id)
|
||||
{
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
// The catalogue lock serializes creation of the durable pin with deletion.
|
||||
let vault = state.vault.read().await;
|
||||
let snap = vault
|
||||
.get_snapshot(request.snapshot_id)
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let (application, artifact) =
|
||||
artifact(&snap.manifest).ok_or(StatusCode::UNPROCESSABLE_ENTITY)?;
|
||||
let job = state
|
||||
.db
|
||||
.enqueue_restore(
|
||||
request.snapshot_id,
|
||||
application,
|
||||
request.target_id,
|
||||
&actor.name,
|
||||
&artifact,
|
||||
now(),
|
||||
)
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::UNPROCESSABLE_ENTITY)?;
|
||||
Ok((StatusCode::ACCEPTED, Json(job)))
|
||||
}
|
||||
|
||||
pub(super) fn artifact(manifest: &SnapshotManifest) -> Option<(Uuid, RestoreArtifact)> {
|
||||
let hints = &manifest.restore_hints;
|
||||
let application = Uuid::parse_str(hints.get("application_id")?.as_str()?).ok()?;
|
||||
let format = match (manifest.provider.as_str(), hints.get("format")?.as_str()?) {
|
||||
("postgres", "custom") => CaptureFormat::PostgresCustom,
|
||||
("postgres", "plain") => CaptureFormat::PostgresSql,
|
||||
("mysql", "plain") => CaptureFormat::MysqlSql,
|
||||
_ => return None,
|
||||
};
|
||||
let sha256 = hints.get("sha256")?.as_str()?.to_owned();
|
||||
if sha256.len() != 64 || !sha256.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let identity: tessera_core::restore::DatabaseIdentity =
|
||||
serde_json::from_value(hints.get("source_identity")?.clone()).ok()?;
|
||||
if !format.engine().is_some_and(|engine| identity.valid(engine)) {
|
||||
return None;
|
||||
}
|
||||
Some((
|
||||
application,
|
||||
RestoreArtifact {
|
||||
format,
|
||||
identity,
|
||||
sha256,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
async fn job(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<RestoreJob>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
state
|
||||
.db
|
||||
.restore_job(id, now())
|
||||
.map_err(internal)?
|
||||
.map(Json)
|
||||
.ok_or(StatusCode::NOT_FOUND)
|
||||
}
|
||||
|
||||
async fn history(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(snapshot): Path<Uuid>,
|
||||
) -> Result<Json<Vec<RestoreJob>>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
state
|
||||
.db
|
||||
.restore_history(snapshot, now())
|
||||
.map(Json)
|
||||
.map_err(internal)
|
||||
}
|
||||
|
||||
async fn cancel(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
||||
if !state
|
||||
.db
|
||||
.cancel_restore(id, &actor.name, now())
|
||||
.map_err(internal)?
|
||||
{
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Reconcile {
|
||||
confirmation: String,
|
||||
}
|
||||
|
||||
async fn reconcile(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(body): Json<Reconcile>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
||||
if body.confirmation != format!("RECONCILE {id}") {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
if !state
|
||||
.db
|
||||
.reconcile_restore(id, &actor.name, now())
|
||||
.map_err(internal)?
|
||||
{
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn claim(
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(target): Path<Uuid>,
|
||||
) -> Result<Json<Option<RestoreLease>>, StatusCode> {
|
||||
let outpost = outpost(&state, &headers)?;
|
||||
state
|
||||
.db
|
||||
.claim_restore(outpost, target, now())
|
||||
.map(Json)
|
||||
.map_err(internal)
|
||||
}
|
||||
|
||||
fn auth(state: &HubState, headers: &HeaderMap) -> Result<(Uuid, Uuid), StatusCode> {
|
||||
let outpost = outpost(state, headers)?;
|
||||
let token =
|
||||
header_value(headers, "x-tessera-restore-token").map_err(|_| StatusCode::UNAUTHORIZED)?;
|
||||
Ok((
|
||||
outpost,
|
||||
Uuid::parse_str(token).map_err(|_| StatusCode::UNAUTHORIZED)?,
|
||||
))
|
||||
}
|
||||
|
||||
async fn payload(
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let (outpost, token) = auth(&state, &headers)?;
|
||||
let (job, artifact, _) = state
|
||||
.db
|
||||
.restore_access(outpost, id, token, now())
|
||||
.map_err(internal)?
|
||||
.filter(|(job, _, _)| job.phase == "checking")
|
||||
.ok_or(StatusCode::FORBIDDEN)?;
|
||||
let staging = tempfile::tempdir_in(&state.data_dir).map_err(internal)?;
|
||||
let path = staging.path().join("restore");
|
||||
let size = state
|
||||
.export_snapshot(job.snapshot_id, path.clone())
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
if state
|
||||
.db
|
||||
.restore_access(outpost, id, token, now())
|
||||
.map_err(internal)?
|
||||
.is_none_or(|(job, _, _)| job.phase != "checking")
|
||||
{
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
let file = tokio::fs::File::open(path).await.map_err(internal)?;
|
||||
Ok((
|
||||
[
|
||||
(header::CONTENT_TYPE, "application/octet-stream".to_owned()),
|
||||
(header::CONTENT_LENGTH, size.to_string()),
|
||||
(header::CACHE_CONTROL, "no-store".to_owned()),
|
||||
(
|
||||
axum::http::HeaderName::from_static("x-tessera-sha256"),
|
||||
artifact.sha256,
|
||||
),
|
||||
],
|
||||
Body::from_stream(ReaderStream::new(file)),
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
|
||||
async fn report(
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
body: Result<Json<RestoreProgress>, JsonRejection>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let (outpost, token) = auth(&state, &headers)?;
|
||||
let Json(progress) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
|
||||
if !state
|
||||
.db
|
||||
.report_restore(outpost, id, token, progress, now())
|
||||
.map_err(internal)?
|
||||
{
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn safety(
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
body: Body,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let (outpost, token) = auth(&state, &headers)?;
|
||||
let (job, _, safety_id) = state
|
||||
.db
|
||||
.restore_access(outpost, id, token, now())
|
||||
.map_err(internal)?
|
||||
.filter(|(job, _, _)| matches!(job.phase.as_str(), "safety" | "ready"))
|
||||
.ok_or(StatusCode::FORBIDDEN)?;
|
||||
let (format, provider, format_name) = match job.target.engine {
|
||||
Engine::Postgres => (CaptureFormat::PostgresCustom, "postgres", "custom"),
|
||||
Engine::Mysql => (CaptureFormat::MysqlSql, "mysql", "plain"),
|
||||
};
|
||||
let (file, expected) = receive_payload(&state, &headers, body, format).await?;
|
||||
if let Some(snapshot) = job.safety_snapshot_id {
|
||||
return Ok(Json(serde_json::json!({ "snapshot_id": snapshot })));
|
||||
}
|
||||
let vault = state.vault.clone().read_owned().await;
|
||||
let db = state.db.clone();
|
||||
let saved = tokio::task::spawn_blocking(move || {
|
||||
let input = vault
|
||||
.get_snapshot(job.snapshot_id)?
|
||||
.ok_or_else(|| anyhow::anyhow!("pinned snapshot missing"))?;
|
||||
let manifest = SnapshotManifest {
|
||||
snapshot_id: safety_id,
|
||||
orbit_id: input.manifest.orbit_id,
|
||||
orbit_name: input.manifest.orbit_name,
|
||||
provider: provider.into(),
|
||||
labels: vec!["restore-safety".into()],
|
||||
paths: vec![],
|
||||
restore_hints: serde_json::json!({
|
||||
"format": format_name, "safety_for": id, "target_id": job.target.id,
|
||||
"sha256": hex::encode(expected),
|
||||
}),
|
||||
};
|
||||
let prepared = if vault.has_published_snapshot(safety_id)? {
|
||||
None
|
||||
} else {
|
||||
let prepared = vault.prepare_payload(manifest, file, false)?;
|
||||
if let Err(error) = vault.verify_prepared_payload(&prepared, &expected) {
|
||||
let _ = vault.discard_prepared(&prepared);
|
||||
return Err(error);
|
||||
}
|
||||
Some(prepared)
|
||||
};
|
||||
let mut wrote = false;
|
||||
let result = db.record_safety(outpost, id, token, now(), |expected_id| {
|
||||
anyhow::ensure!(expected_id == safety_id, "stale safety snapshot");
|
||||
if !vault.has_published_snapshot(safety_id)? {
|
||||
vault.publish_prepared(
|
||||
prepared
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("safety snapshot missing"))?,
|
||||
)?;
|
||||
wrote = true;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
if !wrote {
|
||||
if let Some(prepared) = &prepared {
|
||||
let _ = vault.discard_prepared(prepared);
|
||||
}
|
||||
}
|
||||
Ok::<_, anyhow::Error>(result)
|
||||
})
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::CONFLICT)?;
|
||||
Ok(Json(serde_json::json!({ "snapshot_id": saved })))
|
||||
}
|
||||
|
||||
async fn apply(
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let (outpost, token) = auth(&state, &headers)?;
|
||||
if !state
|
||||
.db
|
||||
.authorize_apply(outpost, id, token, now())
|
||||
.map_err(internal)?
|
||||
{
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::db::OrbitRow;
|
||||
use crate::state::HubState;
|
||||
use crate::state::{HubState, ManagedRetention};
|
||||
use crate::upload::write_at;
|
||||
use axum::{
|
||||
extract::{ConnectInfo, Path, State},
|
||||
@@ -9,6 +9,8 @@ use axum::{
|
||||
Json, Router,
|
||||
};
|
||||
use base64::Engine;
|
||||
use rand::Rng;
|
||||
use tessera_core::OutpostSummary;
|
||||
use include_dir::{include_dir, Dir};
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::net::SocketAddr;
|
||||
@@ -39,8 +41,11 @@ static WEB_DIST: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/../../web/dist");
|
||||
),
|
||||
components(schemas(
|
||||
SnapshotSummary,
|
||||
OrbitRow,
|
||||
CaptureSnapshotSummary,
|
||||
OrbitResponse,
|
||||
CreateOrbitRequest,
|
||||
OrbitSource,
|
||||
OrbitAccess,
|
||||
RetentionUpdate,
|
||||
RetentionPolicy,
|
||||
ReconstituteRequest,
|
||||
@@ -62,14 +67,107 @@ struct SnapshotSummary {
|
||||
taken_at: chrono::DateTime<chrono::Utc>,
|
||||
orbit_name: String,
|
||||
size_bytes: u64,
|
||||
capture: Option<CaptureSnapshotSummary>,
|
||||
stored_bytes: Option<u64>,
|
||||
new_data_chunks: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, utoipa::ToSchema)]
|
||||
struct CaptureSnapshotSummary {
|
||||
job_id: Uuid,
|
||||
application_id: Uuid,
|
||||
engine: &'static str,
|
||||
format: &'static str,
|
||||
restore_ready: bool,
|
||||
}
|
||||
|
||||
impl CaptureSnapshotSummary {
|
||||
fn from_manifest(manifest: &SnapshotManifest) -> Option<Self> {
|
||||
let hints = &manifest.restore_hints;
|
||||
let job_id = Uuid::parse_str(hints.get("job_id")?.as_str()?).ok()?;
|
||||
let application_id = Uuid::parse_str(hints.get("application_id")?.as_str()?).ok()?;
|
||||
let (engine, format) = match (manifest.provider.as_str(), hints.get("format")?.as_str()?) {
|
||||
("postgres", "custom") => ("postgres", "custom"),
|
||||
("postgres", "plain") => ("postgres", "plain"),
|
||||
("mysql", "plain") => ("mysql", "plain"),
|
||||
_ => return None,
|
||||
};
|
||||
Some(Self {
|
||||
job_id, application_id, engine, format,
|
||||
restore_ready: super::restore::artifact(manifest).is_some(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, utoipa::ToSchema)]
|
||||
struct OrbitResponse {
|
||||
id: Uuid,
|
||||
name: String,
|
||||
provider: String,
|
||||
source: Option<OrbitSource>,
|
||||
access: OrbitAccess,
|
||||
schedule: Option<String>,
|
||||
decay_preset: String,
|
||||
retention: Option<RetentionPolicy>,
|
||||
dry_run: bool,
|
||||
last_status: String,
|
||||
application_id: Option<Uuid>,
|
||||
#[schema(value_type = Option<Object>)]
|
||||
capture_schedule: Option<tessera_core::job::CaptureSchedule>,
|
||||
#[schema(value_type = Option<Object>)]
|
||||
capture_retention: Option<tessera_core::decay::CaptureRetention>,
|
||||
retention_source: &'static str,
|
||||
}
|
||||
|
||||
impl From<OrbitRow> for OrbitResponse {
|
||||
fn from(row: OrbitRow) -> Self {
|
||||
let source = match row.provider.as_str() {
|
||||
"filesystem" => Some(OrbitSource::Filesystem),
|
||||
"postgres" | "database" => Some(OrbitSource::Database),
|
||||
"wormhole" => serde_json::from_str::<serde_json::Value>(&row.provider_config)
|
||||
.ok().and_then(|config| serde_json::from_value(config["source"].clone()).ok()),
|
||||
_ => None,
|
||||
};
|
||||
let access = if row.provider == "wormhole" { OrbitAccess::Outpost } else { OrbitAccess::Hub };
|
||||
Self {
|
||||
source,
|
||||
access,
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
provider: row.provider,
|
||||
schedule: row.schedule,
|
||||
decay_preset: row.decay_preset,
|
||||
retention: row.retention,
|
||||
dry_run: row.dry_run,
|
||||
last_status: row.last_status,
|
||||
application_id: None,
|
||||
capture_schedule: None,
|
||||
capture_retention: None,
|
||||
retention_source: "orbit",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum OrbitSource {
|
||||
Filesystem,
|
||||
Database,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum OrbitAccess {
|
||||
Hub,
|
||||
Outpost,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
struct CreateOrbitRequest {
|
||||
name: String,
|
||||
provider: String,
|
||||
provider: Option<String>,
|
||||
source: Option<OrbitSource>,
|
||||
access: Option<OrbitAccess>,
|
||||
provider_config: serde_json::Value,
|
||||
schedule: Option<String>,
|
||||
decay_preset: Option<String>,
|
||||
@@ -133,12 +231,53 @@ struct ReconstituteStartResponse {
|
||||
session: ReconstituteSession,
|
||||
}
|
||||
|
||||
fn require_admin(
|
||||
pub(super) struct OperatorActor {
|
||||
pub(super) name: String,
|
||||
browser: bool,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for OperatorActor {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.name.fmt(formatter)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn require_admin(
|
||||
state: &HubState,
|
||||
peer: SocketAddr,
|
||||
headers: &HeaderMap,
|
||||
) -> Result<(), StatusCode> {
|
||||
state.admin.authorize(peer, headers)
|
||||
authorize_operator(state, peer, headers, false).map(|_| ())
|
||||
}
|
||||
|
||||
pub(super) fn require_admin_mutation(
|
||||
state: &HubState,
|
||||
peer: SocketAddr,
|
||||
headers: &HeaderMap,
|
||||
) -> Result<OperatorActor, StatusCode> {
|
||||
authorize_operator(state, peer, headers, true)
|
||||
}
|
||||
|
||||
fn authorize_operator(
|
||||
state: &HubState,
|
||||
peer: SocketAddr,
|
||||
headers: &HeaderMap,
|
||||
mutation: bool,
|
||||
) -> Result<OperatorActor, StatusCode> {
|
||||
if state.admin.token.is_some() && state.admin.authorize(peer, headers).is_ok() {
|
||||
return Ok(OperatorActor { name: "api-token".into(), browser: false });
|
||||
}
|
||||
if let Some(session) = state.sessions.active(headers) {
|
||||
if mutation {
|
||||
super::session::require_csrf(headers, &session.csrf.to_string())?;
|
||||
}
|
||||
return Ok(OperatorActor { name: session.actor, browser: true });
|
||||
}
|
||||
if !state.sessions.enabled() {
|
||||
state.admin.authorize(peer, headers)?;
|
||||
return Ok(OperatorActor { name: "loopback".into(), browser: false });
|
||||
}
|
||||
Err(StatusCode::UNAUTHORIZED)
|
||||
}
|
||||
|
||||
pub fn router(state: HubState) -> Router {
|
||||
@@ -153,6 +292,7 @@ pub fn router(state: HubState) -> Router {
|
||||
"/api/v1/reconstitute/:id",
|
||||
get(reconstitute_status).delete(abort_reconstitute),
|
||||
)
|
||||
.route("/api/v1/wormhole/outposts", get(outposts))
|
||||
.route("/api/v1/wormhole/pairing", post(pairing_start))
|
||||
.route("/api/v1/wormhole/claim", post(pairing_claim))
|
||||
.route("/api/v1/wormhole/upload/init", post(wormhole_upload_init))
|
||||
@@ -161,6 +301,10 @@ pub fn router(state: HubState) -> Router {
|
||||
"/api/v1/wormhole/restic/commit",
|
||||
post(wormhole_restic_commit),
|
||||
)
|
||||
.merge(super::jobs::routes())
|
||||
.merge(super::catalog::routes())
|
||||
.merge(super::session::routes())
|
||||
.merge(super::restore::routes())
|
||||
.with_state(state);
|
||||
|
||||
let api = api.route(
|
||||
@@ -188,10 +332,12 @@ async fn list_snapshots(
|
||||
let snaps = vault.list_snapshots().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let out = snaps
|
||||
.into_iter()
|
||||
.filter(|s| s.manifest.provider != "legacy-history")
|
||||
.map(|s| SnapshotSummary {
|
||||
id: s.id,
|
||||
orbit_id: s.manifest.orbit_id,
|
||||
taken_at: s.taken_at,
|
||||
capture: CaptureSnapshotSummary::from_manifest(&s.manifest),
|
||||
orbit_name: s.manifest.orbit_name,
|
||||
size_bytes: s.size_bytes,
|
||||
stored_bytes: s.stored_bytes,
|
||||
@@ -201,36 +347,103 @@ async fn list_snapshots(
|
||||
Ok(Json(out))
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/orbits", responses((status = 200, body = [OrbitRow])))]
|
||||
#[utoipa::path(get, path = "/api/v1/orbits", responses((status = 200, body = [OrbitResponse])))]
|
||||
async fn list_orbits(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<Vec<OrbitRow>>, StatusCode> {
|
||||
) -> Result<Json<Vec<OrbitResponse>>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
state
|
||||
let profiles: std::collections::HashMap<_, _> = state
|
||||
.db
|
||||
.list_orbits()
|
||||
.await
|
||||
.map(Json)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
||||
.capture_profiles()
|
||||
.map_err(super::jobs::internal)?
|
||||
.into_iter()
|
||||
.map(|profile| (profile.orbit_id, profile))
|
||||
.collect();
|
||||
let rows = state.db.list_orbits().await.map_err(super::jobs::internal)?;
|
||||
let responses = rows
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
let mut response = OrbitResponse::from(row);
|
||||
if let Some(profile) = profiles.get(&response.id) {
|
||||
response.application_id = Some(profile.application_id);
|
||||
response.source = Some(if profile.format == tessera_core::job::CaptureFormat::Filesystem {
|
||||
OrbitSource::Filesystem
|
||||
} else {
|
||||
OrbitSource::Database
|
||||
});
|
||||
response.capture_schedule = profile.schedule.clone();
|
||||
(response.capture_retention, response.retention_source) =
|
||||
match ManagedRetention::resolve(profile, response.retention) {
|
||||
ManagedRetention::Orbit(_) => (None, "orbit"),
|
||||
ManagedRetention::Profile(policy) => (Some(policy), "profile"),
|
||||
ManagedRetention::Default(policy) => (Some(policy), "default"),
|
||||
};
|
||||
}
|
||||
response
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(responses))
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/orbits", request_body = CreateOrbitRequest, responses((status = 200, body = OrbitRow)))]
|
||||
#[utoipa::path(post, path = "/api/v1/orbits", request_body = CreateOrbitRequest, responses((status = 200, body = OrbitResponse), (status = 400)))]
|
||||
async fn create_orbit(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(req): Json<CreateOrbitRequest>,
|
||||
) -> Result<Json<OrbitRow>, (StatusCode, &'static str)> {
|
||||
require_admin(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
|
||||
) -> Result<Json<OrbitResponse>, (StatusCode, &'static str)> {
|
||||
require_admin_mutation(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
|
||||
if req.name.trim().is_empty() {
|
||||
return Err((StatusCode::BAD_REQUEST, "orbit name is required"));
|
||||
}
|
||||
let (decay_preset, retention) = retention_settings(req.decay_preset, req.retention)?;
|
||||
let (provider, config) = match (req.source, req.access, req.provider.as_deref()) {
|
||||
(Some(OrbitSource::Filesystem), Some(OrbitAccess::Hub), None) => {
|
||||
let config: tessera_providers::FilesystemConfig = serde_json::from_value(req.provider_config.clone())
|
||||
.map_err(|_| (StatusCode::BAD_REQUEST, "invalid filesystem configuration"))?;
|
||||
if config.paths.is_empty() || config.paths.iter().any(|path| path.trim().is_empty()) {
|
||||
return Err((StatusCode::BAD_REQUEST, "at least one filesystem path is required"));
|
||||
}
|
||||
("filesystem", req.provider_config)
|
||||
}
|
||||
(Some(OrbitSource::Database), Some(OrbitAccess::Hub), None) => {
|
||||
let source: super::orbit::DatabaseSource = serde_json::from_value(req.provider_config.clone())
|
||||
.map_err(|_| (StatusCode::BAD_REQUEST, "invalid database configuration"))?;
|
||||
if !source.valid_endpoint() {
|
||||
return Err((StatusCode::BAD_REQUEST, "invalid database endpoint or password file path"));
|
||||
}
|
||||
("database", req.provider_config)
|
||||
}
|
||||
(Some(source), Some(OrbitAccess::Outpost), None)
|
||||
if req.provider_config.as_object().is_some_and(|config| config.is_empty())
|
||||
&& !req.dry_run.unwrap_or(false) =>
|
||||
{
|
||||
("wormhole", serde_json::json!({ "source": source }))
|
||||
}
|
||||
(None, None, Some("filesystem" | "postgres" | "wormhole")) =>
|
||||
(req.provider.as_deref().unwrap(), req.provider_config),
|
||||
_ => return Err((StatusCode::BAD_REQUEST, "invalid backup source or access")),
|
||||
};
|
||||
let schedule = req.schedule.filter(|expression| !expression.trim().is_empty());
|
||||
if let Some(expression) = &schedule {
|
||||
if provider == "wormhole" {
|
||||
return Err((StatusCode::BAD_REQUEST, "set the schedule on the Outpost capture profile"));
|
||||
}
|
||||
crate::scheduler::orbit_schedule(expression)
|
||||
.map_err(|_| (StatusCode::BAD_REQUEST, "invalid cron schedule (UTC)"))?;
|
||||
}
|
||||
if provider == "postgres" {
|
||||
tessera_providers::PostgresProvider::from_config(&config)
|
||||
.map_err(|_| (StatusCode::BAD_REQUEST, "invalid PostgreSQL connection URL or dump format"))?;
|
||||
}
|
||||
let row = OrbitRow {
|
||||
id: Uuid::new_v4(),
|
||||
name: req.name,
|
||||
provider: req.provider,
|
||||
provider_config: serde_json::to_string(&req.provider_config).unwrap_or_else(|_| "{}".into()),
|
||||
schedule: req.schedule,
|
||||
provider: provider.to_owned(),
|
||||
provider_config: config.to_string(),
|
||||
schedule,
|
||||
decay_preset,
|
||||
retention,
|
||||
dry_run: req.dry_run.unwrap_or(false),
|
||||
@@ -241,7 +454,7 @@ async fn create_orbit(
|
||||
.upsert_orbit(&row)
|
||||
.await
|
||||
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "could not save orbit"))?;
|
||||
Ok(Json(row))
|
||||
Ok(Json(row.into()))
|
||||
}
|
||||
|
||||
fn retention_settings(
|
||||
@@ -274,7 +487,7 @@ async fn update_orbit_retention(
|
||||
Path(id): Path<Uuid>,
|
||||
Json(req): Json<RetentionUpdate>,
|
||||
) -> Result<StatusCode, (StatusCode, &'static str)> {
|
||||
require_admin(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
|
||||
require_admin_mutation(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
|
||||
if req.decay_preset.is_none() && req.retention.is_none() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
@@ -297,15 +510,23 @@ async fn update_orbit_retention(
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/orbits/{id}/run", params(("id" = Uuid, Path, description = "orbit id")), responses((status = 204, headers(("X-Tessera-Snapshot-Id" = Uuid, description = "New retained snapshot ID when a capture writes to the vault")))))]
|
||||
#[utoipa::path(post, path = "/api/v1/orbits/{id}/run", params(("id" = Uuid, Path, description = "orbit id")), responses((status = 204, headers(("X-Tessera-Snapshot-Id" = Uuid, description = "New retained snapshot ID when a capture writes to the vault"))), (status = 404), (status = 409)))]
|
||||
async fn trigger_orbit(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<(StatusCode, HeaderMap), (StatusCode, String)> {
|
||||
require_admin(&state, peer, &headers).map_err(|status| (status, "unauthorized".into()))?;
|
||||
let snapshot_id = crate::api::run_orbit_internal(state, id)
|
||||
require_admin_mutation(&state, peer, &headers).map_err(|status| (status, "unauthorized".into()))?;
|
||||
let orbit = state.db.list_orbits().await
|
||||
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "could not read orbits".into()))?
|
||||
.into_iter()
|
||||
.find(|orbit| orbit.id == id)
|
||||
.ok_or((StatusCode::NOT_FOUND, "orbit not found".into()))?;
|
||||
if orbit.provider == "wormhole" {
|
||||
return Err((StatusCode::CONFLICT, "queue the capture through its Outpost profile or run the legacy agent".into()));
|
||||
}
|
||||
let snapshot_id = crate::api::run_orbit_internal(state, orbit)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
tracing::warn!(orbit_id = %id, %error, "capture did not complete");
|
||||
@@ -331,7 +552,17 @@ async fn start_reconstitute(
|
||||
headers: HeaderMap,
|
||||
Json(req): Json<ReconstituteRequest>,
|
||||
) -> Result<Json<ReconstituteStartResponse>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
||||
let destination = if actor.browser {
|
||||
browser_export_path(&state, &req.target_path)?
|
||||
} else {
|
||||
req.target_path.clone().into()
|
||||
};
|
||||
let vault = state.vault.read().await;
|
||||
if vault.get_snapshot(req.snapshot_id).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.is_none_or(|snapshot| snapshot.manifest.provider == "legacy-history") {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
let session_id = Uuid::new_v4();
|
||||
let session = ReconstituteSession {
|
||||
snapshot_id: req.snapshot_id,
|
||||
@@ -344,9 +575,9 @@ async fn start_reconstitute(
|
||||
.write()
|
||||
.await
|
||||
.insert(session_id, session.clone());
|
||||
drop(vault);
|
||||
|
||||
let state_bg = state.clone();
|
||||
let target = req.target_path;
|
||||
tokio::spawn(async move {
|
||||
for remaining in (0..RECONSTITUTE_GRACE_SECS).rev() {
|
||||
{
|
||||
@@ -371,14 +602,7 @@ async fn start_reconstitute(
|
||||
s.state = ReconstituteState::Restoring;
|
||||
s.seconds_remaining = 0;
|
||||
}
|
||||
let dest = std::path::PathBuf::from(&target);
|
||||
let result = {
|
||||
let vault = state_bg.vault.clone().read_owned().await;
|
||||
tokio::task::spawn_blocking(move || vault.restore_snapshot(req.snapshot_id, &dest))
|
||||
.await
|
||||
.map_err(anyhow::Error::from)
|
||||
.and_then(|result| result)
|
||||
};
|
||||
let result = state_bg.export_snapshot(req.snapshot_id, destination).await;
|
||||
let mut map = state_bg.reconstitute_sessions.write().await;
|
||||
if let Some(s) = map.get_mut(&session_id) {
|
||||
s.state = if result.is_ok() {
|
||||
@@ -396,6 +620,39 @@ async fn start_reconstitute(
|
||||
}))
|
||||
}
|
||||
|
||||
fn browser_export_path(state: &HubState, requested: &str) -> Result<std::path::PathBuf, StatusCode> {
|
||||
use std::path::{Component, Path};
|
||||
let mut components = Path::new(requested).components();
|
||||
let Some(Component::Normal(name)) = components.next() else { return Err(StatusCode::BAD_REQUEST) };
|
||||
if components.next().is_some() || name.len() > 255 {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let directory = state.data_dir.join("exports");
|
||||
let mut builder = std::fs::DirBuilder::new();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
builder.mode(0o700);
|
||||
}
|
||||
match builder.create(&directory) {
|
||||
Ok(()) => (),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => (),
|
||||
Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR),
|
||||
}
|
||||
let metadata = std::fs::symlink_metadata(&directory).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
if !metadata.is_dir() {
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if metadata.permissions().mode() & 0o077 != 0 {
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
Ok(directory.join(name))
|
||||
}
|
||||
|
||||
async fn reconstitute_status(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
@@ -413,7 +670,7 @@ async fn abort_reconstitute(
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
require_admin_mutation(&state, peer, &headers)?;
|
||||
let mut map = state.reconstitute_sessions.write().await;
|
||||
if let Some(s) = map.get_mut(&id) {
|
||||
if matches!(
|
||||
@@ -427,23 +684,27 @@ async fn abort_reconstitute(
|
||||
Err(StatusCode::BAD_REQUEST)
|
||||
}
|
||||
|
||||
async fn outposts(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<Vec<OutpostSummary>>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
state.db.list_outposts().map(Json).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/wormhole/pairing", responses((status = 200, body = PairingResponse)))]
|
||||
async fn pairing_start(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<PairingResponse>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
let code: String = (0..6)
|
||||
.map(|_| {
|
||||
let n = rand::random::<u8>() % 36;
|
||||
if n < 10 {
|
||||
(b'0' + n) as char
|
||||
} else {
|
||||
(b'A' + n - 10) as char
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
require_admin_mutation(&state, peer, &headers)?;
|
||||
const ALPHABET: &[u8] = b"23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||
let code: String = {
|
||||
let mut random = rand::thread_rng();
|
||||
(0..12).map(|_| ALPHABET[random.gen_range(0..ALPHABET.len())] as char).collect()
|
||||
};
|
||||
let expires = chrono::Utc::now() + chrono::Duration::minutes(10);
|
||||
let outpost_id = Uuid::new_v4();
|
||||
let upload_token = hex::encode(Uuid::new_v4().as_bytes());
|
||||
@@ -467,10 +728,14 @@ async fn pairing_claim(
|
||||
State(state): State<HubState>,
|
||||
Json(req): Json<ClaimRequest>,
|
||||
) -> Result<Json<ClaimResponse>, StatusCode> {
|
||||
let name = req.outpost_name.trim();
|
||||
if name.is_empty() || name.len() > 128 || name.chars().any(char::is_control) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
let claimed = state
|
||||
.db
|
||||
.claim_wormhole_code(&req.code, &req.outpost_name, &now)
|
||||
.claim_wormhole_code(&req.code, name, &now)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::GONE)?;
|
||||
let hub_url = std::env::var("TESSERA_PUBLIC_URL").unwrap_or_else(|_| {
|
||||
@@ -482,7 +747,7 @@ async fn pairing_claim(
|
||||
});
|
||||
state
|
||||
.db
|
||||
.audit("wormhole.paired", &req.outpost_name)
|
||||
.audit("wormhole.paired", name)
|
||||
.await
|
||||
.ok();
|
||||
let outpost_id = Uuid::parse_str(&claimed.1).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
@@ -499,7 +764,8 @@ async fn wormhole_upload_init(
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<UploadInit>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
verify_upload_token(&state, &headers)?;
|
||||
super::jobs::outpost(&state, &headers)?;
|
||||
reject_managed_orbit(&state, body.orbit_id)?;
|
||||
if state
|
||||
.vault
|
||||
.read()
|
||||
@@ -538,12 +804,13 @@ async fn wormhole_upload_chunk(
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<UploadChunk>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
verify_upload_token(&state, &headers)?;
|
||||
super::jobs::outpost(&state, &headers)?;
|
||||
let session = state
|
||||
.db
|
||||
.upload_session(&body.session_id.to_string())
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
reject_managed_orbit(&state, session.orbit_id)?;
|
||||
if session.sealed {
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
@@ -608,16 +875,7 @@ fn restrict_part(path: &std::path::Path) {
|
||||
let _ = path;
|
||||
}
|
||||
|
||||
fn verify_upload_token(state: &HubState, headers: &HeaderMap) -> Result<(), StatusCode> {
|
||||
let token = upload_token(state, headers)?;
|
||||
if state.upload_token_valid(token) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StatusCode::UNAUTHORIZED)
|
||||
}
|
||||
}
|
||||
|
||||
fn upload_token<'a>(state: &HubState, headers: &'a HeaderMap) -> Result<&'a str, StatusCode> {
|
||||
pub(super) fn upload_token<'a>(state: &HubState, headers: &'a HeaderMap) -> Result<&'a str, StatusCode> {
|
||||
if !state.accept_plain_upload {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
@@ -633,13 +891,7 @@ async fn wormhole_restic_commit(
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<ResticCommit>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let token = upload_token(&state, &headers)?;
|
||||
let outpost_id = state
|
||||
.db
|
||||
.upload_token_outpost(token)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.and_then(|id| Uuid::parse_str(&id).ok())
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let outpost_id = super::jobs::outpost(&state, &headers)?;
|
||||
if body.snapshot_id.len() != 64 || !body.snapshot_id.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
@@ -653,6 +905,7 @@ async fn wormhole_restic_commit(
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let orbit_id = orbit.id;
|
||||
let mut vault = state.vault.clone().write_owned().await;
|
||||
reject_managed_orbit(&state, orbit_id)?;
|
||||
let (snapshot, created) = tokio::task::spawn_blocking(move || {
|
||||
let manifest = SnapshotManifest {
|
||||
snapshot_id: Uuid::nil(),
|
||||
@@ -689,6 +942,15 @@ async fn wormhole_restic_commit(
|
||||
Ok(Json(serde_json::json!({ "snapshot_id": snapshot })))
|
||||
}
|
||||
|
||||
fn reject_managed_orbit(state: &HubState, orbit_id: Uuid) -> Result<(), StatusCode> {
|
||||
if state.db.managed_orbit(orbit_id).map_err(super::jobs::internal)?
|
||||
|| state.db.restic_required(orbit_id).map_err(super::jobs::internal)?
|
||||
{
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn seal_upload(
|
||||
state: &HubState,
|
||||
session_id: Uuid,
|
||||
@@ -715,6 +977,7 @@ async fn seal_upload(
|
||||
restore_hints: serde_json::json!({ "session_id": session_id }),
|
||||
};
|
||||
let vault = state.vault.clone().read_owned().await;
|
||||
reject_managed_orbit(state, orbit_id)?;
|
||||
if vault
|
||||
.outpost_repository_configured(orbit_id)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
@@ -776,3 +1039,142 @@ fn content_type(path: &str) -> &'static str {
|
||||
"text/html"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::body::{to_bytes, Body};
|
||||
use axum::http::Request;
|
||||
use tower::ServiceExt;
|
||||
|
||||
#[tokio::test]
|
||||
async fn orbit_creation_validates_cron_and_direct_run_preserves_wormhole_status() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault").await.unwrap();
|
||||
state.admin.token = None;
|
||||
state.accept_plain_upload = true;
|
||||
let app = router(state.clone());
|
||||
let post = |path: &str, body: serde_json::Value| {
|
||||
Request::post(path)
|
||||
.extension(ConnectInfo("127.0.0.1:1234".parse::<SocketAddr>().unwrap()))
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.header("x-tessera-upload-token", "fixture-token")
|
||||
.body(Body::from(body.to_string()))
|
||||
.unwrap()
|
||||
};
|
||||
for (provider, schedule, expected) in [
|
||||
("filesystem", Some("bad cron"), StatusCode::BAD_REQUEST),
|
||||
("postgres", None, StatusCode::BAD_REQUEST),
|
||||
("filesystem", Some("0 2 * * *"), StatusCode::OK),
|
||||
("wormhole", None, StatusCode::OK),
|
||||
] {
|
||||
let response = app.clone().oneshot(post("/api/v1/orbits", serde_json::json!({
|
||||
"name": provider, "provider": provider, "provider_config": {}, "schedule": schedule
|
||||
}))).await.unwrap();
|
||||
assert_eq!(response.status(), expected);
|
||||
}
|
||||
let rows = state.db.list_orbits().await.unwrap();
|
||||
assert_eq!(rows.len(), 2);
|
||||
let orbit = rows.iter().find(|row| row.provider == "wormhole").unwrap();
|
||||
let response = app.clone().oneshot(post(
|
||||
&format!("/api/v1/orbits/{}/run", orbit.id), serde_json::Value::Null,
|
||||
)).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::CONFLICT);
|
||||
assert_eq!(state.db.list_orbits().await.unwrap()[1].last_status, "idle");
|
||||
|
||||
let outpost = Uuid::new_v4();
|
||||
state.db.insert_wormhole_token("fixture-token", &outpost.to_string(), "fixture-code", "9999").unwrap();
|
||||
state.db.claim_wormhole_code("fixture-code", "fixture", "2026").unwrap().unwrap();
|
||||
{
|
||||
let conn = rusqlite::Connection::open(dir.path().join("tessera.db")).unwrap();
|
||||
conn.execute("UPDATE outposts SET last_seen = NULL", []).unwrap();
|
||||
}
|
||||
let response = app.oneshot(post("/api/v1/wormhole/upload/init", serde_json::json!({
|
||||
"orbit_id": orbit.id, "total_bytes": 42
|
||||
}))).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert!(state.db.list_outposts().unwrap()[0].last_seen.is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn new_orbits_validate_source_access_and_keep_provider_internal() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault").await.unwrap();
|
||||
state.admin.token = None;
|
||||
let app = router(state);
|
||||
for (source, access, config, expected) in [
|
||||
("filesystem", "hub", serde_json::json!({"paths": ["/data/source"]}), StatusCode::OK),
|
||||
("filesystem", "hub", serde_json::json!({"paths": []}), StatusCode::BAD_REQUEST),
|
||||
("filesystem", "outpost", serde_json::json!({}), StatusCode::OK),
|
||||
("database", "outpost", serde_json::json!({}), StatusCode::OK),
|
||||
("vm", "outpost", serde_json::json!({}), StatusCode::UNPROCESSABLE_ENTITY),
|
||||
] {
|
||||
let request = Request::post("/api/v1/orbits")
|
||||
.extension(ConnectInfo("127.0.0.1:1234".parse::<SocketAddr>().unwrap()))
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(serde_json::json!({
|
||||
"name": "test", "source": source, "access": access, "provider_config": config,
|
||||
}).to_string())).unwrap();
|
||||
let response = app.clone().oneshot(request).await.unwrap();
|
||||
assert_eq!(response.status(), expected);
|
||||
if expected == StatusCode::OK {
|
||||
let body = axum::body::to_bytes(response.into_body(), 65536).await.unwrap();
|
||||
let orbit: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
assert_eq!(orbit["source"], source);
|
||||
assert_eq!(orbit["access"], access);
|
||||
assert!(orbit.get("provider_config").is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn orbit_responses_and_schema_hide_provider_config() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault")
|
||||
.await
|
||||
.unwrap();
|
||||
state.admin.token = None;
|
||||
let app = router(state.clone());
|
||||
let input = serde_json::json!({
|
||||
"name": "billing",
|
||||
"provider": "postgres",
|
||||
"provider_config": {
|
||||
"connection_url": "postgres://user:synthetic-password@db/billing",
|
||||
"token": "synthetic-token",
|
||||
"secret_ref": "synthetic-reference",
|
||||
}
|
||||
});
|
||||
let request = |method: &str, uri: &str, body: Body| {
|
||||
Request::builder()
|
||||
.method(method)
|
||||
.uri(uri)
|
||||
.extension(ConnectInfo("127.0.0.1:1234".parse::<SocketAddr>().unwrap()))
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(body)
|
||||
.unwrap()
|
||||
};
|
||||
for (method, path, body) in [
|
||||
("POST", "/api/v1/orbits", Body::from(input.to_string())),
|
||||
("GET", "/api/v1/orbits", Body::empty()),
|
||||
("GET", "/api-doc/openapi.json", Body::empty()),
|
||||
] {
|
||||
let response = app.clone().oneshot(request(method, path, body)).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let bytes = to_bytes(response.into_body(), 100_000).await.unwrap();
|
||||
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
|
||||
let orbit = match path {
|
||||
"/api-doc/openapi.json" => &json["components"]["schemas"]["OrbitResponse"]["properties"],
|
||||
_ if method == "GET" => &json[0],
|
||||
_ => &json,
|
||||
};
|
||||
assert!(orbit.get("id").is_some());
|
||||
assert!(orbit.get("provider_config").is_none());
|
||||
assert!(!String::from_utf8_lossy(&bytes).contains("synthetic-"));
|
||||
}
|
||||
let rows = state.db.list_orbits().await.unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&rows[0].provider_config).unwrap(),
|
||||
input["provider_config"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
254
crates/tessera-hub/src/api/session.rs
Normal file
254
crates/tessera-hub/src/api/session.rs
Normal file
@@ -0,0 +1,254 @@
|
||||
use crate::admin::{tokens_match, SessionGate};
|
||||
use crate::state::HubState;
|
||||
use axum::{
|
||||
extract::{ConnectInfo, State},
|
||||
http::{header, HeaderMap, HeaderValue, StatusCode},
|
||||
routing::{get, post},
|
||||
Json, Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::net::SocketAddr;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Status {
|
||||
login_enabled: bool,
|
||||
authorized: bool,
|
||||
actor: Option<String>,
|
||||
csrf: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Login {
|
||||
password: String,
|
||||
}
|
||||
|
||||
pub(super) fn routes() -> Router<HubState> {
|
||||
Router::new()
|
||||
.route("/api/v1/operator/session", get(status).delete(logout))
|
||||
.route("/api/v1/operator/login", post(login))
|
||||
}
|
||||
|
||||
async fn status(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> (HeaderMap, Json<Status>) {
|
||||
let browser = state.sessions.active(&headers);
|
||||
let authorized = browser.is_some()
|
||||
|| (!state.sessions.enabled() && state.admin.token.is_none() && peer.ip().is_loopback());
|
||||
(
|
||||
no_store(),
|
||||
Json(Status {
|
||||
login_enabled: state.sessions.enabled(),
|
||||
authorized,
|
||||
actor: browser.as_ref().map(|session| session.actor.clone()),
|
||||
csrf: browser.map(|session| session.csrf.to_string()),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
async fn login(
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(input): Json<Login>,
|
||||
) -> Result<(HeaderMap, Json<Status>), StatusCode> {
|
||||
if input.password.is_empty() || input.password.len() > 1024 {
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
let gate = state.sessions.clone();
|
||||
let session = tokio::task::spawn_blocking(move || gate.login(&headers, &input.password))
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)??;
|
||||
state
|
||||
.db
|
||||
.audit("operator.login", &session.actor)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let mut headers = no_store();
|
||||
headers.insert(header::SET_COOKIE, cookie(Some(&session.id.to_string()))?);
|
||||
Ok((
|
||||
headers,
|
||||
Json(Status {
|
||||
login_enabled: true,
|
||||
authorized: true,
|
||||
actor: Some(session.actor),
|
||||
csrf: Some(session.csrf.to_string()),
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
async fn logout(
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<(StatusCode, HeaderMap), StatusCode> {
|
||||
let session = state
|
||||
.sessions
|
||||
.active(&headers)
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
require_csrf(&headers, &session.csrf.to_string())?;
|
||||
state.sessions.remove(session.id);
|
||||
state
|
||||
.db
|
||||
.audit("operator.logout", &session.actor)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let mut headers = no_store();
|
||||
headers.insert(header::SET_COOKIE, cookie(None)?);
|
||||
Ok((StatusCode::NO_CONTENT, headers))
|
||||
}
|
||||
|
||||
pub(super) fn require_csrf(headers: &HeaderMap, expected: &str) -> Result<(), StatusCode> {
|
||||
if headers
|
||||
.get("x-tessera-csrf")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.is_some_and(|value| tokens_match(expected, value))
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StatusCode::FORBIDDEN)
|
||||
}
|
||||
}
|
||||
|
||||
fn no_store() -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||
headers
|
||||
}
|
||||
|
||||
fn cookie(id: Option<&str>) -> Result<HeaderValue, StatusCode> {
|
||||
let value = format!(
|
||||
"{}={}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age={}",
|
||||
SessionGate::COOKIE,
|
||||
id.unwrap_or_default(),
|
||||
if id.is_some() {
|
||||
SessionGate::DURATION.as_secs()
|
||||
} else {
|
||||
0
|
||||
},
|
||||
);
|
||||
HeaderValue::from_str(&value).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::body::{to_bytes, Body};
|
||||
use axum::http::Request;
|
||||
use tower::ServiceExt;
|
||||
|
||||
#[tokio::test]
|
||||
async fn operator_session_requires_csrf_and_expires_without_disabling_cli() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault")
|
||||
.await
|
||||
.unwrap();
|
||||
state.sessions = SessionGate::fixture();
|
||||
state.admin.token = Some("fixture-api-token".into());
|
||||
let app = crate::api::router(state.clone());
|
||||
let request = |method: &str, uri: &str, body: &'static str| {
|
||||
Request::builder()
|
||||
.method(method)
|
||||
.uri(uri)
|
||||
.extension(ConnectInfo("127.0.0.1:1234".parse::<SocketAddr>().unwrap()))
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(body))
|
||||
.unwrap()
|
||||
};
|
||||
let anonymous = app
|
||||
.clone()
|
||||
.oneshot(request("GET", "/api/v1/orbits", ""))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(anonymous.status(), StatusCode::UNAUTHORIZED);
|
||||
let denied = app
|
||||
.clone()
|
||||
.oneshot(request(
|
||||
"POST",
|
||||
"/api/v1/operator/login",
|
||||
r#"{"password":"wrong"}"#,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(denied.status(), StatusCode::UNAUTHORIZED);
|
||||
let login = app
|
||||
.clone()
|
||||
.oneshot(request(
|
||||
"POST",
|
||||
"/api/v1/operator/login",
|
||||
r#"{"password":"fixture-operator-password"}"#,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(login.status(), StatusCode::OK);
|
||||
let set_cookie = login.headers()[header::SET_COOKIE].to_str().unwrap();
|
||||
assert!(set_cookie.contains("HttpOnly; Secure; SameSite=Strict"));
|
||||
let cookie = HeaderValue::from_str(set_cookie.split(';').next().unwrap()).unwrap();
|
||||
let bytes = to_bytes(login.into_body(), 1024).await.unwrap();
|
||||
let status: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(status["actor"], "fixture-operator");
|
||||
let csrf = HeaderValue::from_str(status["csrf"].as_str().unwrap()).unwrap();
|
||||
let mut action = request("POST", "/api/v1/wormhole/pairing", "");
|
||||
action.headers_mut().insert(header::COOKIE, cookie.clone());
|
||||
let denied = app.clone().oneshot(action).await.unwrap();
|
||||
assert_eq!(denied.status(), StatusCode::FORBIDDEN);
|
||||
let mut action = request("POST", "/api/v1/wormhole/pairing", "");
|
||||
action.headers_mut().insert(header::COOKIE, cookie.clone());
|
||||
action.headers_mut().insert("x-tessera-csrf", csrf.clone());
|
||||
assert_eq!(
|
||||
app.clone().oneshot(action).await.unwrap().status(),
|
||||
StatusCode::OK
|
||||
);
|
||||
let mut action = request("DELETE", "/api/v1/operator/session", "");
|
||||
action.headers_mut().insert(header::COOKIE, cookie.clone());
|
||||
action.headers_mut().insert("x-tessera-csrf", csrf);
|
||||
assert_eq!(
|
||||
app.clone().oneshot(action).await.unwrap().status(),
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
let mut action = request("GET", "/api/v1/orbits", "");
|
||||
action.headers_mut().insert(header::COOKIE, cookie);
|
||||
assert_eq!(
|
||||
app.clone().oneshot(action).await.unwrap().status(),
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
|
||||
let login = app
|
||||
.clone()
|
||||
.oneshot(request(
|
||||
"POST",
|
||||
"/api/v1/operator/login",
|
||||
r#"{"password":"fixture-operator-password"}"#,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
let cookie = HeaderValue::from_str(
|
||||
login.headers()[header::SET_COOKIE]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
state.sessions.expire();
|
||||
let mut action = request("GET", "/api/v1/orbits", "");
|
||||
action.headers_mut().insert(header::COOKIE, cookie);
|
||||
assert_eq!(
|
||||
app.clone().oneshot(action).await.unwrap().status(),
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
let mut cli = request("GET", "/api/v1/orbits", "");
|
||||
cli.headers_mut().insert(
|
||||
header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer fixture-api-token"),
|
||||
);
|
||||
assert_eq!(app.oneshot(cli).await.unwrap().status(), StatusCode::OK);
|
||||
let connection = rusqlite::Connection::open(dir.path().join("tessera.db")).unwrap();
|
||||
let audited: i64 = connection.query_row(
|
||||
"SELECT COUNT(*) FROM audit_log WHERE event IN ('operator.login','operator.logout') AND detail = 'fixture-operator'",
|
||||
[], |row| row.get(0),
|
||||
).unwrap();
|
||||
assert_eq!(audited, 3);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
mod jobs;
|
||||
mod restore;
|
||||
pub(crate) use restore::restore_target_mismatch;
|
||||
|
||||
use anyhow::Result;
|
||||
use rusqlite::{params, Connection, OptionalExtension};
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tessera_core::decay::RetentionPolicy;
|
||||
use tessera_core::{decay::RetentionPolicy, OutpostSummary};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -10,7 +14,7 @@ pub struct Db {
|
||||
conn: Arc<Mutex<Connection>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
|
||||
#[derive(Clone)]
|
||||
pub struct OrbitRow {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
@@ -18,7 +22,6 @@ pub struct OrbitRow {
|
||||
pub provider_config: String,
|
||||
pub schedule: Option<String>,
|
||||
pub decay_preset: String,
|
||||
#[serde(default)]
|
||||
pub retention: Option<RetentionPolicy>,
|
||||
pub dry_run: bool,
|
||||
pub last_status: String,
|
||||
@@ -91,12 +94,24 @@ impl Db {
|
||||
"INTEGER NOT NULL DEFAULT 0",
|
||||
)?;
|
||||
ensure_column(&conn, "orbits", "retention", "TEXT")?;
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO outposts(id, name, pairing_state)
|
||||
SELECT outpost_id, outpost_name, 'active' FROM wormhole_tokens WHERE state = 'active'",
|
||||
[],
|
||||
)?;
|
||||
jobs::migrate(&conn)?;
|
||||
restore::migrate(&conn)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn list_orbits(&self) -> Result<Vec<OrbitRow>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare("SELECT id, name, provider, provider_config, schedule, decay_preset, dry_run, last_status, retention FROM orbits ORDER BY name")?;
|
||||
let mut stmt = conn.prepare("SELECT o.id, o.name, o.provider, o.provider_config, o.schedule, o.decay_preset, o.dry_run,
|
||||
CASE WHEN p.application_id IS NULL THEN o.last_status ELSE COALESCE((
|
||||
SELECT j.status FROM capture_jobs j WHERE j.application_id = p.application_id
|
||||
ORDER BY j.created_at DESC, j.rowid DESC LIMIT 1
|
||||
), 'idle') END, o.retention
|
||||
FROM orbits o LEFT JOIN capture_profiles p ON p.orbit_id = o.id ORDER BY o.name")?;
|
||||
let rows = stmt.query_map([], |r| {
|
||||
Ok(OrbitRow {
|
||||
id: Uuid::parse_str(&r.get::<_, String>(0)?).unwrap_or_else(|_| Uuid::new_v4()),
|
||||
@@ -233,26 +248,48 @@ impl Db {
|
||||
outpost_name: &str,
|
||||
now: &str,
|
||||
) -> Result<Option<(String, String)>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let changed = conn.execute(
|
||||
"UPDATE wormhole_tokens SET state = 'active', outpost_name = ?2 WHERE code = ?1 AND state = 'code_shown' AND expires_at > ?3",
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction()?;
|
||||
let claimed: Option<(String, String)> = tx.query_row(
|
||||
"UPDATE wormhole_tokens SET state = 'active', outpost_name = ?2
|
||||
WHERE token = (SELECT token FROM wormhole_tokens
|
||||
WHERE code = ?1 AND state = 'code_shown' AND expires_at > ?3
|
||||
ORDER BY expires_at DESC LIMIT 1)
|
||||
RETURNING token, outpost_id",
|
||||
params![code, outpost_name, now],
|
||||
)?;
|
||||
if changed != 1 {
|
||||
return Ok(None);
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
).optional()?;
|
||||
if let Some((_, outpost)) = &claimed {
|
||||
tx.execute(
|
||||
"INSERT INTO outposts(id, name, last_seen, pairing_state) VALUES (?1, ?2, ?3, 'active')
|
||||
ON CONFLICT(id) DO UPDATE SET name = excluded.name, last_seen = excluded.last_seen, pairing_state = 'active'",
|
||||
params![outpost, outpost_name, now],
|
||||
)?;
|
||||
}
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT token, outpost_id FROM wormhole_tokens WHERE code = ?1 AND state = 'active'",
|
||||
)?;
|
||||
let mut rows = stmt.query(params![code])?;
|
||||
let Some(row) = rows.next()? else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some((row.get(0)?, row.get(1)?)))
|
||||
tx.commit()?;
|
||||
Ok(claimed)
|
||||
}
|
||||
|
||||
pub fn upload_token_active(&self, token: &str) -> Result<bool> {
|
||||
Ok(self.upload_token_outpost(token)?.is_some())
|
||||
pub fn list_outposts(&self) -> Result<Vec<OutpostSummary>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare("SELECT id, name, last_seen, pairing_state FROM outposts ORDER BY name, id")?;
|
||||
let rows = stmt.query_map([], |row| {
|
||||
let id = Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| {
|
||||
rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(err))
|
||||
})?;
|
||||
Ok(OutpostSummary { id, name: row.get(1)?, last_seen: row.get(2)?, pairing_state: row.get(3)? })
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn touch_outpost(&self, id: Uuid) -> Result<()> {
|
||||
let now = chrono::Utc::now();
|
||||
let recent = (now - chrono::Duration::seconds(30)).to_rfc3339();
|
||||
self.conn.lock().unwrap().execute(
|
||||
"UPDATE outposts SET last_seen = ?2 WHERE id = ?1 AND (last_seen IS NULL OR last_seen < ?3)",
|
||||
params![id.to_string(), now.to_rfc3339(), recent],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn upload_token_outpost(&self, token: &str) -> Result<Option<String>> {
|
||||
|
||||
693
crates/tessera-hub/src/db/jobs.rs
Normal file
693
crates/tessera-hub/src/db/jobs.rs
Normal file
@@ -0,0 +1,693 @@
|
||||
use super::*;
|
||||
use rusqlite::{types::Type, Row, TransactionBehavior};
|
||||
use tessera_core::job::{
|
||||
CaptureEvent, CaptureJob, CaptureLease, CaptureProfile, CaptureProgress, CaptureReport,
|
||||
CAPTURE_LEASE_SECONDS,
|
||||
};
|
||||
|
||||
pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS capture_profiles (
|
||||
application_id TEXT PRIMARY KEY,
|
||||
orbit_id TEXT NOT NULL UNIQUE,
|
||||
outpost_id TEXT NOT NULL,
|
||||
profile TEXT NOT NULL,
|
||||
registered_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS capture_jobs (
|
||||
id TEXT PRIMARY KEY,
|
||||
application_id TEXT NOT NULL,
|
||||
actor TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'queued',
|
||||
phase TEXT NOT NULL DEFAULT 'queued',
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
lease_id TEXT,
|
||||
lease_until INTEGER,
|
||||
snapshot_id TEXT,
|
||||
schedule_slot INTEGER,
|
||||
offsite_status TEXT,
|
||||
offsite_attempt_at INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS capture_jobs_queue
|
||||
ON capture_jobs(application_id, status, created_at);
|
||||
CREATE INDEX IF NOT EXISTS capture_jobs_history
|
||||
ON capture_jobs(application_id, created_at);
|
||||
CREATE TABLE IF NOT EXISTS capture_events (
|
||||
id INTEGER PRIMARY KEY, job_id TEXT NOT NULL, at INTEGER NOT NULL, phase TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS capture_events_job ON capture_events(job_id, id);
|
||||
CREATE TRIGGER IF NOT EXISTS capture_events_queued AFTER INSERT ON capture_jobs
|
||||
BEGIN
|
||||
INSERT INTO capture_events(job_id, at, phase) VALUES (NEW.id, NEW.updated_at, NEW.phase);
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS capture_events_progress AFTER UPDATE OF phase ON capture_jobs
|
||||
WHEN OLD.phase <> NEW.phase OR OLD.lease_id IS NOT NEW.lease_id
|
||||
BEGIN
|
||||
INSERT INTO capture_events(job_id, at, phase) VALUES (NEW.id, NEW.updated_at, NEW.phase);
|
||||
DELETE FROM capture_events WHERE job_id = NEW.id AND id < COALESCE((
|
||||
SELECT id FROM capture_events WHERE job_id = NEW.id ORDER BY id DESC LIMIT 1 OFFSET 63
|
||||
), 0);
|
||||
END;",
|
||||
)?;
|
||||
ensure_column(
|
||||
conn,
|
||||
"capture_profiles",
|
||||
"registered_at",
|
||||
"INTEGER NOT NULL DEFAULT 0",
|
||||
)?;
|
||||
ensure_column(conn, "capture_jobs", "schedule_slot", "INTEGER")?;
|
||||
ensure_column(conn, "capture_jobs", "offsite_status", "TEXT")?;
|
||||
ensure_column(
|
||||
conn,
|
||||
"capture_jobs",
|
||||
"offsite_attempt_at",
|
||||
"INTEGER NOT NULL DEFAULT 0",
|
||||
)?;
|
||||
conn.execute(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS capture_jobs_slot ON capture_jobs(application_id, schedule_slot)",
|
||||
[],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const JOB_VIEW: &str = "SELECT j.id, p.profile, j.actor, j.status, j.phase, j.created_at,
|
||||
j.updated_at, j.snapshot_id, j.offsite_status FROM capture_jobs j JOIN capture_profiles p USING(application_id)";
|
||||
|
||||
pub(super) fn invalid_column(
|
||||
index: usize,
|
||||
error: impl std::error::Error + Send + Sync + 'static,
|
||||
) -> rusqlite::Error {
|
||||
rusqlite::Error::FromSqlConversionFailure(index, Type::Text, Box::new(error))
|
||||
}
|
||||
|
||||
fn parse_profile(row: &Row<'_>, index: usize) -> rusqlite::Result<CaptureProfile> {
|
||||
serde_json::from_str(&row.get::<_, String>(index)?).map_err(|err| invalid_column(index, err))
|
||||
}
|
||||
|
||||
fn read_job(row: &Row<'_>) -> rusqlite::Result<CaptureJob> {
|
||||
Ok(CaptureJob {
|
||||
id: Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| invalid_column(0, err))?,
|
||||
profile: parse_profile(row, 1)?,
|
||||
actor: row.get(2)?,
|
||||
status: row.get(3)?,
|
||||
phase: row.get(4)?,
|
||||
created_at: row.get(5)?,
|
||||
updated_at: row.get(6)?,
|
||||
snapshot_id: row
|
||||
.get::<_, Option<String>>(7)?
|
||||
.map(|value| Uuid::parse_str(&value))
|
||||
.transpose()
|
||||
.map_err(|err| invalid_column(7, err))?,
|
||||
offsite_status: row.get(8)?,
|
||||
})
|
||||
}
|
||||
|
||||
impl Db {
|
||||
pub fn register_capture_profile(&self, profile: &CaptureProfile, now: i64) -> Result<bool> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let changed = conn.execute(
|
||||
"INSERT INTO capture_profiles (application_id, orbit_id, outpost_id, profile, registered_at)
|
||||
SELECT ?1, ?2, ?3, ?4, ?5
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM orbits WHERE id = ?2 AND provider = 'wormhole' AND dry_run = 0
|
||||
AND COALESCE(json_extract(provider_config, '$.source'), ?6) = ?6
|
||||
)
|
||||
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = ?3 AND state = 'active')
|
||||
ON CONFLICT DO NOTHING",
|
||||
params![profile.application_id.to_string(), profile.orbit_id.to_string(),
|
||||
profile.outpost_id.to_string(), serde_json::to_string(profile)?, now,
|
||||
if profile.format.engine().is_some() { "database" } else { "filesystem" }],
|
||||
)?;
|
||||
Ok(changed == 1)
|
||||
}
|
||||
|
||||
pub fn capture_profiles(&self) -> Result<Vec<CaptureProfile>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt =
|
||||
conn.prepare("SELECT profile FROM capture_profiles ORDER BY application_id")?;
|
||||
let rows = stmt.query_map([], |row| parse_profile(row, 0))?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn capture_schedule_cursors(&self) -> Result<Vec<(CaptureProfile, i64)>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT p.profile, COALESCE(MAX(j.schedule_slot), p.registered_at)
|
||||
FROM capture_profiles p LEFT JOIN capture_jobs j USING(application_id)
|
||||
GROUP BY p.application_id",
|
||||
)?;
|
||||
let rows = stmt.query_map([], |row| Ok((parse_profile(row, 0)?, row.get(1)?)))?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn enqueue_scheduled_capture(&self, application: Uuid, slot: i64, now: i64) -> Result<()> {
|
||||
self.conn.lock().unwrap().execute(
|
||||
"INSERT INTO capture_jobs (id, application_id, actor, created_at, updated_at, schedule_slot)
|
||||
SELECT ?1, application_id, 'scheduler', ?4, ?4, ?3 FROM capture_profiles p
|
||||
WHERE application_id = ?2
|
||||
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = p.outpost_id AND state = 'active')
|
||||
ON CONFLICT(application_id, schedule_slot) DO NOTHING",
|
||||
params![Uuid::new_v4().to_string(), application.to_string(), slot, now],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn enqueue_capture(
|
||||
&self,
|
||||
application_id: Uuid,
|
||||
actor: &str,
|
||||
now: i64,
|
||||
) -> Result<Option<CaptureJob>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let id = Uuid::new_v4();
|
||||
conn.execute(
|
||||
"INSERT INTO capture_jobs (id, application_id, actor, created_at, updated_at)
|
||||
SELECT ?1, application_id, ?3, ?4, ?4 FROM capture_profiles p
|
||||
WHERE application_id = ?2
|
||||
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = p.outpost_id AND state = 'active')",
|
||||
params![id.to_string(), application_id.to_string(), actor, now],
|
||||
)?;
|
||||
capture_job(&conn, id)
|
||||
}
|
||||
|
||||
pub fn capture_jobs(
|
||||
&self,
|
||||
application: Option<Uuid>,
|
||||
status: Option<&str>,
|
||||
limit: u16,
|
||||
) -> Result<Vec<CaptureJob>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(&format!(
|
||||
"{JOB_VIEW} WHERE (?1 IS NULL OR j.application_id = ?1) AND (?2 IS NULL OR j.status = ?2)
|
||||
ORDER BY j.created_at DESC, j.rowid DESC LIMIT ?3"
|
||||
))?;
|
||||
let rows = stmt.query_map(
|
||||
params![application.map(|id| id.to_string()), status, limit],
|
||||
read_job,
|
||||
)?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn capture_events(&self, job: Uuid) -> Result<Vec<CaptureEvent>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt =
|
||||
conn.prepare("SELECT at, phase FROM capture_events WHERE job_id = ?1 ORDER BY id")?;
|
||||
let rows = stmt.query_map([job.to_string()], |row| {
|
||||
Ok(CaptureEvent {
|
||||
at: row.get(0)?,
|
||||
phase: row.get(1)?,
|
||||
})
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn capture_job(&self, id: Uuid) -> Result<Option<CaptureJob>> {
|
||||
capture_job(&self.conn.lock().unwrap(), id)
|
||||
}
|
||||
|
||||
pub fn capture_profile_for_orbit(&self, orbit: Uuid) -> Result<Option<CaptureProfile>> {
|
||||
Ok(self
|
||||
.conn
|
||||
.lock()
|
||||
.unwrap()
|
||||
.query_row(
|
||||
"SELECT profile FROM capture_profiles WHERE orbit_id = ?1",
|
||||
[orbit.to_string()],
|
||||
|row| parse_profile(row, 0),
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn managed_orbit(&self, orbit_id: Uuid) -> Result<bool> {
|
||||
Ok(self.conn.lock().unwrap().query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM capture_profiles WHERE orbit_id = ?1)",
|
||||
[orbit_id.to_string()],
|
||||
|row| row.get(0),
|
||||
)?)
|
||||
}
|
||||
|
||||
pub fn pending_offsite(&self) -> Result<Vec<Uuid>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id FROM capture_jobs WHERE offsite_status IN ('pending', 'failed')
|
||||
ORDER BY offsite_attempt_at, rowid LIMIT 10",
|
||||
)?;
|
||||
let rows = stmt.query_map([], |row| {
|
||||
Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| invalid_column(0, err))
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn set_offsite_result(&self, job: Uuid, success: bool) -> Result<()> {
|
||||
self.conn.lock().unwrap().execute(
|
||||
"UPDATE capture_jobs SET offsite_status = ?2, offsite_attempt_at = ?3 WHERE id = ?1",
|
||||
params![
|
||||
job.to_string(),
|
||||
if success { "copied" } else { "failed" },
|
||||
chrono::Utc::now().timestamp()
|
||||
],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn offsite_pending(&self, id: Uuid) -> Result<bool> {
|
||||
Ok(self.conn.lock().unwrap().query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM capture_jobs WHERE snapshot_id = ?1 AND offsite_status IN ('pending', 'failed'))",
|
||||
[id.to_string()], |row| row.get(0),
|
||||
)?)
|
||||
}
|
||||
|
||||
pub fn restic_required(&self, orbit: Uuid) -> Result<bool> {
|
||||
Ok(self.conn.lock().unwrap().query_row(
|
||||
"SELECT json_extract(provider_config, '$.source') IS NOT NULL FROM orbits WHERE id = ?1",
|
||||
[orbit.to_string()], |row| row.get(0),
|
||||
).optional()?.unwrap_or(false))
|
||||
}
|
||||
|
||||
pub fn capture_upload(
|
||||
&self,
|
||||
outpost: Uuid,
|
||||
id: Uuid,
|
||||
lease: Uuid,
|
||||
now: i64,
|
||||
) -> Result<Option<CaptureJob>> {
|
||||
capture_upload(&self.conn.lock().unwrap(), outpost, id, lease, now)
|
||||
}
|
||||
|
||||
pub fn publish_capture(
|
||||
&self,
|
||||
outpost: Uuid,
|
||||
id: Uuid,
|
||||
lease: Uuid,
|
||||
offsite_enabled: bool,
|
||||
publish: impl FnOnce(&CaptureJob) -> Result<()>,
|
||||
) -> Result<Option<(Uuid, bool)>> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
let Some(job) = capture_upload(&tx, outpost, id, lease, now)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
if let Some(snapshot_id) = job.snapshot_id {
|
||||
return Ok(Some((snapshot_id, false)));
|
||||
}
|
||||
publish(&job)?;
|
||||
tx.execute(
|
||||
"UPDATE capture_jobs SET status = 'completed', phase = 'completed', snapshot_id = ?1, updated_at = ?2, offsite_status = ?3
|
||||
WHERE id = ?1",
|
||||
params![id.to_string(), now, offsite_enabled.then_some("pending")],
|
||||
)?;
|
||||
tx.execute(
|
||||
"INSERT INTO audit_log (at, event, detail) VALUES (datetime('now'), 'capture.completed', ?1)",
|
||||
[format!("actor={} job={id} snapshot={id}", job.actor)],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(Some((id, true)))
|
||||
}
|
||||
|
||||
pub fn incomplete_publications(&self) -> Result<Vec<Uuid>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt =
|
||||
conn.prepare("SELECT id FROM capture_jobs WHERE status IN ('running', 'failed')")?;
|
||||
let rows = stmt.query_map([], |row| {
|
||||
Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| invalid_column(0, err))
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn reconcile_capture(
|
||||
&self,
|
||||
snapshot: Uuid,
|
||||
orbit: Uuid,
|
||||
offsite_enabled: bool,
|
||||
) -> Result<()> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction()?;
|
||||
let changed = tx.execute(
|
||||
"UPDATE capture_jobs SET status = 'completed', phase = 'completed',
|
||||
snapshot_id = id, updated_at = ?3, offsite_status = ?4
|
||||
WHERE id = ?1 AND status <> 'completed' AND application_id IN (
|
||||
SELECT application_id FROM capture_profiles WHERE orbit_id = ?2
|
||||
)",
|
||||
params![
|
||||
snapshot.to_string(),
|
||||
orbit.to_string(),
|
||||
chrono::Utc::now().timestamp(),
|
||||
offsite_enabled.then_some("pending")
|
||||
],
|
||||
)?;
|
||||
if changed == 1 {
|
||||
tx.execute(
|
||||
"INSERT INTO audit_log (at, event, detail) VALUES (datetime('now'), 'capture.reconciled', ?1)",
|
||||
[format!("snapshot={snapshot}")],
|
||||
)?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn claim_capture(
|
||||
&self,
|
||||
outpost: Uuid,
|
||||
application: Uuid,
|
||||
now: i64,
|
||||
) -> Result<Option<CaptureLease>> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let candidate = tx.query_row(
|
||||
"SELECT j.id, p.profile, json_extract(o.provider_config, '$.source') IS NOT NULL
|
||||
FROM capture_jobs j JOIN capture_profiles p USING(application_id) JOIN orbits o ON o.id = p.orbit_id
|
||||
WHERE p.outpost_id = ?1 AND p.application_id = ?2
|
||||
AND (j.status = 'queued' OR (j.status = 'running' AND j.lease_until <= ?3))
|
||||
AND NOT EXISTS (SELECT 1 FROM capture_jobs active WHERE active.application_id = j.application_id
|
||||
AND active.status = 'running' AND active.lease_until > ?3)
|
||||
AND NOT EXISTS (SELECT 1 FROM restore_jobs r JOIN restore_targets t ON t.id = r.target_id
|
||||
WHERE t.application_id = j.application_id AND
|
||||
(r.status IN ('applying','recovery_required') OR (r.status = 'running' AND r.lease_until > ?3)))
|
||||
ORDER BY j.created_at, j.rowid LIMIT 1",
|
||||
params![outpost.to_string(), application.to_string(), now],
|
||||
|row| Ok((row.get::<_, String>(0)?, parse_profile(row, 1)?, row.get::<_, bool>(2)?)),
|
||||
).optional()?;
|
||||
let Some((id, profile, restic)) = candidate else {
|
||||
return Ok(None);
|
||||
};
|
||||
let job_id = Uuid::parse_str(&id)?;
|
||||
let lease_id = Uuid::new_v4();
|
||||
tx.execute(
|
||||
"UPDATE capture_jobs SET status = 'running', phase = 'claimed',
|
||||
lease_id = ?2, lease_until = ?3, updated_at = ?4 WHERE id = ?1",
|
||||
params![id, lease_id.to_string(), now + CAPTURE_LEASE_SECONDS, now],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(Some(CaptureLease {
|
||||
job_id,
|
||||
profile,
|
||||
lease_id,
|
||||
restic,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn report_capture(
|
||||
&self,
|
||||
outpost: Uuid,
|
||||
job: Uuid,
|
||||
report: CaptureReport,
|
||||
now: i64,
|
||||
) -> Result<bool> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let (phase, prior, status) = match report.progress {
|
||||
CaptureProgress::Heartbeat => (None, None, "running"),
|
||||
CaptureProgress::Dumping => (Some("dumping"), Some("claimed"), "running"),
|
||||
CaptureProgress::Uploading => (Some("uploading"), Some("dumping"), "running"),
|
||||
CaptureProgress::DumpFailed => (Some("dump_failed"), Some("dumping"), "failed"),
|
||||
CaptureProgress::UploadFailed => (Some("upload_failed"), Some("uploading"), "failed"),
|
||||
};
|
||||
let changed = conn.execute(
|
||||
"UPDATE capture_jobs SET status = ?6, phase = COALESCE(?5, phase), updated_at = ?4, lease_until = ?7
|
||||
WHERE id = ?1 AND lease_id = ?2 AND status = 'running' AND lease_until > ?4
|
||||
AND (?8 IS NULL OR phase = ?8 OR phase = ?5)
|
||||
AND application_id IN (SELECT application_id FROM capture_profiles WHERE outpost_id = ?3)",
|
||||
params![job.to_string(), report.lease_id.to_string(), outpost.to_string(), now,
|
||||
phase, status, now + CAPTURE_LEASE_SECONDS, prior],
|
||||
)?;
|
||||
Ok(changed == 1)
|
||||
}
|
||||
}
|
||||
|
||||
fn capture_upload(
|
||||
conn: &Connection,
|
||||
outpost: Uuid,
|
||||
id: Uuid,
|
||||
lease: Uuid,
|
||||
now: i64,
|
||||
) -> Result<Option<CaptureJob>> {
|
||||
Ok(conn.query_row(
|
||||
&format!("{JOB_VIEW} WHERE j.id = ?1 AND p.outpost_id = ?2 AND j.lease_id = ?3
|
||||
AND (j.status = 'completed' OR (j.status = 'running' AND j.phase = 'uploading' AND j.lease_until > ?4))"),
|
||||
params![id.to_string(), outpost.to_string(), lease.to_string(), now],
|
||||
read_job,
|
||||
).optional()?)
|
||||
}
|
||||
|
||||
fn capture_job(conn: &Connection, id: Uuid) -> Result<Option<CaptureJob>> {
|
||||
Ok(conn
|
||||
.query_row(
|
||||
&format!("{JOB_VIEW} WHERE j.id = ?1"),
|
||||
[id.to_string()],
|
||||
read_job,
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tessera_core::job::CaptureFormat;
|
||||
|
||||
async fn profile(db: &Db, outpost_id: Uuid) -> CaptureProfile {
|
||||
let orbit_id = Uuid::new_v4();
|
||||
db.upsert_orbit(&OrbitRow {
|
||||
id: orbit_id,
|
||||
name: "fixture".into(),
|
||||
provider: "wormhole".into(),
|
||||
provider_config: "{}".into(),
|
||||
schedule: None,
|
||||
decay_preset: "week-of-dailies".into(),
|
||||
retention: None,
|
||||
dry_run: false,
|
||||
last_status: "idle".into(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
CaptureProfile {
|
||||
application_id: Uuid::new_v4(),
|
||||
orbit_id,
|
||||
outpost_id,
|
||||
format: CaptureFormat::PostgresCustom,
|
||||
schedule: None,
|
||||
retention: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queue_survives_restart_and_fences_competing_agents() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("old.db");
|
||||
Connection::open(&path).unwrap().execute_batch(
|
||||
"CREATE TABLE orbits (id TEXT PRIMARY KEY, name TEXT, provider TEXT, provider_config TEXT,
|
||||
schedule TEXT, decay_preset TEXT, dry_run INTEGER, last_status TEXT);
|
||||
INSERT INTO orbits VALUES ('20200000-0000-0000-0000-000000000000', 'old', 'postgres',
|
||||
'{\"connection_url\":\"synthetic-secret\"}', NULL, 'week-of-dailies', 0, 'idle');"
|
||||
).unwrap();
|
||||
let outpost = Uuid::new_v4();
|
||||
let other = Uuid::new_v4();
|
||||
let db = Db::connect(&path).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
let a = profile(&db, outpost).await;
|
||||
let b = profile(&db, outpost).await;
|
||||
let app = a.application_id;
|
||||
assert!(!db.register_capture_profile(&a, 100).unwrap());
|
||||
assert!(db.enqueue_capture(app, "fixture", 100).unwrap().is_none());
|
||||
for (id, token) in [(outpost, "token-a"), (other, "token-b")] {
|
||||
db.insert_wormhole_token(token, &id.to_string(), token, "9999")
|
||||
.unwrap();
|
||||
db.claim_wormhole_code(token, "agent", "2026")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
assert!(db.register_capture_profile(&a, 100).unwrap());
|
||||
assert!(db.register_capture_profile(&b, 100).unwrap());
|
||||
let queued = db.enqueue_capture(app, "fixture", 100).unwrap().unwrap();
|
||||
db.enqueue_capture(app, "fixture", 100).unwrap().unwrap();
|
||||
db.enqueue_capture(b.application_id, "fixture", 100)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
drop(db);
|
||||
let db = Db::connect(&path).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
assert!(
|
||||
db.list_orbits()
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|orbit| orbit.name == "old"
|
||||
&& orbit.provider_config.contains("synthetic-secret"))
|
||||
);
|
||||
assert_eq!(db.capture_job(queued.id).unwrap().unwrap().status, "queued");
|
||||
assert_eq!(db.capture_job(queued.id).unwrap().unwrap().actor, "fixture");
|
||||
assert!(db.claim_capture(other, app, 100).unwrap().is_none());
|
||||
let second = Db::connect(&path).await.unwrap();
|
||||
let race = std::thread::scope(|scope| {
|
||||
let first = scope.spawn(|| db.claim_capture(outpost, app, 100).unwrap());
|
||||
let second = scope.spawn(|| second.claim_capture(outpost, app, 100).unwrap());
|
||||
[first.join().unwrap(), second.join().unwrap()]
|
||||
});
|
||||
assert_eq!(race.iter().flatten().count(), 1);
|
||||
let lease = race.into_iter().flatten().next().unwrap();
|
||||
assert_eq!(lease.job_id, queued.id);
|
||||
assert!(db
|
||||
.claim_capture(outpost, b.application_id, 101)
|
||||
.unwrap()
|
||||
.is_some());
|
||||
let report = |lease_id, progress| CaptureReport { lease_id, progress };
|
||||
assert!(!db
|
||||
.report_capture(
|
||||
other,
|
||||
queued.id,
|
||||
report(lease.lease_id, CaptureProgress::Dumping),
|
||||
101
|
||||
)
|
||||
.unwrap());
|
||||
assert!(db
|
||||
.report_capture(
|
||||
outpost,
|
||||
queued.id,
|
||||
report(lease.lease_id, CaptureProgress::Dumping),
|
||||
101
|
||||
)
|
||||
.unwrap());
|
||||
drop(db);
|
||||
let db = Db::connect(&path).await.unwrap();
|
||||
let retry = db.claim_capture(outpost, app, 191).unwrap().unwrap();
|
||||
assert_eq!(retry.job_id, queued.id);
|
||||
assert_ne!(retry.lease_id, lease.lease_id);
|
||||
assert!(!db
|
||||
.report_capture(
|
||||
outpost,
|
||||
queued.id,
|
||||
report(lease.lease_id, CaptureProgress::Heartbeat),
|
||||
192
|
||||
)
|
||||
.unwrap());
|
||||
assert!(db
|
||||
.report_capture(
|
||||
outpost,
|
||||
queued.id,
|
||||
report(retry.lease_id, CaptureProgress::Dumping),
|
||||
192
|
||||
)
|
||||
.unwrap());
|
||||
assert!(db
|
||||
.report_capture(
|
||||
outpost,
|
||||
queued.id,
|
||||
report(retry.lease_id, CaptureProgress::DumpFailed),
|
||||
193
|
||||
)
|
||||
.unwrap());
|
||||
assert_eq!(db.capture_job(queued.id).unwrap().unwrap().status, "failed");
|
||||
assert!(db.claim_capture(outpost, app, 194).unwrap().is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_orbit_uses_latest_job_even_after_a_success() {
|
||||
let db = Db::connect(std::path::Path::new(":memory:")).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
let outpost = Uuid::new_v4();
|
||||
db.insert_wormhole_token("token", &outpost.to_string(), "code", "9999").unwrap();
|
||||
db.claim_wormhole_code("code", "agent", "2026").unwrap().unwrap();
|
||||
let profile = profile(&db, outpost).await;
|
||||
let app = profile.application_id;
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
assert!(db.register_capture_profile(&profile, now).unwrap());
|
||||
for (progress, expected) in [
|
||||
(CaptureProgress::Uploading, "completed"),
|
||||
(CaptureProgress::DumpFailed, "failed"),
|
||||
] {
|
||||
let job = db.enqueue_capture(app, "fixture", now).unwrap().unwrap();
|
||||
assert_eq!(db.list_orbits().await.unwrap()[0].last_status, "queued");
|
||||
let lease = db.claim_capture(outpost, app, now).unwrap().unwrap();
|
||||
assert_eq!(db.list_orbits().await.unwrap()[0].last_status, "running");
|
||||
for progress in [CaptureProgress::Dumping, progress] {
|
||||
assert!(db.report_capture(outpost, job.id, CaptureReport {
|
||||
lease_id: lease.lease_id, progress,
|
||||
}, now).unwrap());
|
||||
}
|
||||
if expected == "completed" {
|
||||
assert!(db.publish_capture(outpost, job.id, lease.lease_id, false, |_| Ok(())).unwrap().is_some());
|
||||
}
|
||||
assert_eq!(db.list_orbits().await.unwrap()[0].last_status, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn daily_slots_are_caught_up_once_and_offline_jobs_are_visible() {
|
||||
use chrono::{TimeZone, Utc};
|
||||
use tessera_core::job::CaptureSchedule;
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("jobs.db");
|
||||
let db = Db::connect(&path).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
let outpost = Uuid::new_v4();
|
||||
db.insert_wormhole_token("test", &outpost.to_string(), "code", "9999")
|
||||
.unwrap();
|
||||
db.claim_wormhole_code("code", "fixture", "2026")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let mut a = profile(&db, outpost).await;
|
||||
let mut b = profile(&db, outpost).await;
|
||||
a.schedule = Some(CaptureSchedule {
|
||||
hour: 2,
|
||||
minute: 0,
|
||||
timezone: "Asia/Jakarta".into(),
|
||||
});
|
||||
b.schedule = a.schedule.clone();
|
||||
let registered = Utc.with_ymd_and_hms(2026, 11, 7, 18, 0, 0).unwrap();
|
||||
for p in [&a, &b] {
|
||||
assert!(db
|
||||
.register_capture_profile(p, registered.timestamp())
|
||||
.unwrap());
|
||||
}
|
||||
let tick = crate::scheduler::tick_capture_schedules;
|
||||
tick(&db, registered).unwrap();
|
||||
assert!(db.capture_jobs(None, None, 100).unwrap().is_empty());
|
||||
let now = Utc.with_ymd_and_hms(2026, 11, 8, 19, 5, 0).unwrap();
|
||||
tick(&db, now).unwrap();
|
||||
drop(db);
|
||||
let db = Db::connect(&path).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
tick(&db, now).unwrap();
|
||||
let all = db.capture_jobs(None, Some("queued"), 100).unwrap();
|
||||
assert_eq!(all.len(), 4);
|
||||
let history = db
|
||||
.capture_jobs(Some(a.application_id), Some("queued"), 100)
|
||||
.unwrap();
|
||||
assert_eq!(history.len(), 2);
|
||||
assert!(history.iter().all(|job| job.actor == "scheduler"));
|
||||
let first = db
|
||||
.claim_capture(outpost, a.application_id, now.timestamp())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
for (progress, offset) in [
|
||||
(CaptureProgress::Dumping, 1),
|
||||
(CaptureProgress::Heartbeat, 2),
|
||||
(CaptureProgress::DumpFailed, 3),
|
||||
] {
|
||||
assert!(db
|
||||
.report_capture(
|
||||
outpost,
|
||||
first.job_id,
|
||||
CaptureReport {
|
||||
lease_id: first.lease_id,
|
||||
progress
|
||||
},
|
||||
now.timestamp() + offset
|
||||
)
|
||||
.unwrap());
|
||||
}
|
||||
let failed = db
|
||||
.capture_jobs(Some(a.application_id), Some("failed"), 100)
|
||||
.unwrap();
|
||||
assert_eq!(failed.len(), 1);
|
||||
let events = db.capture_events(first.job_id).unwrap();
|
||||
assert_eq!(
|
||||
events
|
||||
.iter()
|
||||
.map(|event| event.phase.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["queued", "claimed", "dumping", "dump_failed"]
|
||||
);
|
||||
}
|
||||
}
|
||||
560
crates/tessera-hub/src/db/restore.rs
Normal file
560
crates/tessera-hub/src/db/restore.rs
Normal file
@@ -0,0 +1,560 @@
|
||||
use super::{jobs::invalid_column, *};
|
||||
use rusqlite::{Row, Transaction, TransactionBehavior};
|
||||
use tessera_core::{
|
||||
job::CAPTURE_LEASE_SECONDS,
|
||||
restore::{RestoreArtifact, RestoreJob, RestoreLease, RestoreProgress, RestoreTarget},
|
||||
};
|
||||
|
||||
pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS restore_targets (
|
||||
id TEXT PRIMARY KEY,
|
||||
application_id TEXT NOT NULL,
|
||||
outpost_id TEXT NOT NULL,
|
||||
identity TEXT NOT NULL UNIQUE,
|
||||
profile TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS restore_jobs (
|
||||
id TEXT PRIMARY KEY,
|
||||
snapshot_id TEXT NOT NULL,
|
||||
target_id TEXT NOT NULL,
|
||||
actor TEXT NOT NULL,
|
||||
artifact TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'queued',
|
||||
phase TEXT NOT NULL DEFAULT 'queued',
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
lease_token TEXT,
|
||||
lease_until INTEGER,
|
||||
attempt_safety_id TEXT,
|
||||
safety_id TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS restore_jobs_target ON restore_jobs(target_id, status);
|
||||
CREATE INDEX IF NOT EXISTS restore_jobs_snapshot ON restore_jobs(snapshot_id, safety_id, status);",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const VIEW: &str =
|
||||
"SELECT j.id, j.snapshot_id, t.profile, j.actor, j.status, j.phase, j.safety_id, j.created_at,
|
||||
j.updated_at, j.artifact, j.attempt_safety_id
|
||||
FROM restore_jobs j JOIN restore_targets t ON t.id = j.target_id";
|
||||
|
||||
fn uuid(row: &Row<'_>, index: usize) -> rusqlite::Result<Uuid> {
|
||||
Uuid::parse_str(&row.get::<_, String>(index)?).map_err(|err| invalid_column(index, err))
|
||||
}
|
||||
|
||||
fn json<T: serde::de::DeserializeOwned>(row: &Row<'_>, index: usize) -> rusqlite::Result<T> {
|
||||
serde_json::from_str(&row.get::<_, String>(index)?).map_err(|err| invalid_column(index, err))
|
||||
}
|
||||
|
||||
fn read_job(row: &Row<'_>) -> rusqlite::Result<RestoreJob> {
|
||||
Ok(RestoreJob {
|
||||
id: uuid(row, 0)?,
|
||||
snapshot_id: uuid(row, 1)?,
|
||||
target: json(row, 2)?,
|
||||
actor: row.get(3)?,
|
||||
status: row.get(4)?,
|
||||
phase: row.get(5)?,
|
||||
safety_snapshot_id: row
|
||||
.get::<_, Option<String>>(6)?
|
||||
.map(|id| Uuid::parse_str(&id))
|
||||
.transpose()
|
||||
.map_err(|err| invalid_column(6, err))?,
|
||||
created_at: row.get(7)?,
|
||||
updated_at: row.get(8)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn restore_target_mismatch(
|
||||
target: &RestoreTarget,
|
||||
artifact: &RestoreArtifact,
|
||||
) -> Option<&'static str> {
|
||||
if Some(target.engine) != artifact.format.engine() {
|
||||
Some("Database engine differs from the snapshot")
|
||||
} else if target.identity == artifact.identity {
|
||||
Some("Target is the source database")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl Db {
|
||||
pub fn register_restore_target(&self, target: &RestoreTarget) -> Result<bool> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let changed = conn.execute(
|
||||
"INSERT INTO restore_targets(id, application_id, outpost_id, identity, profile)
|
||||
SELECT ?1, ?2, ?3, ?4, ?5
|
||||
WHERE EXISTS (SELECT 1 FROM capture_profiles WHERE application_id = ?2)
|
||||
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = ?3 AND state = 'active')
|
||||
ON CONFLICT DO NOTHING",
|
||||
params![
|
||||
target.id.to_string(),
|
||||
target.application_id.to_string(),
|
||||
target.outpost_id.to_string(),
|
||||
serde_json::to_string(&(target.engine, &target.identity))?,
|
||||
serde_json::to_string(target)?,
|
||||
],
|
||||
)?;
|
||||
Ok(changed == 1)
|
||||
}
|
||||
|
||||
pub fn restore_targets(&self, application: Uuid) -> Result<Vec<RestoreTarget>> {
|
||||
Ok(self.restore_targets_with_activity(application)?
|
||||
.into_iter().map(|(target, _)| target).collect())
|
||||
}
|
||||
|
||||
pub fn restore_targets_with_activity(&self, application: Uuid) -> Result<Vec<(RestoreTarget, bool)>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT t.profile, EXISTS (SELECT 1 FROM wormhole_tokens
|
||||
WHERE outpost_id = t.outpost_id AND state = 'active')
|
||||
FROM restore_targets t WHERE t.application_id = ?1 ORDER BY t.id",
|
||||
)?;
|
||||
let rows = stmt.query_map([application.to_string()], |row| Ok((json(row, 0)?, row.get(1)?)))?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn enqueue_restore(
|
||||
&self,
|
||||
snapshot: Uuid,
|
||||
application: Uuid,
|
||||
target: Uuid,
|
||||
actor: &str,
|
||||
artifact: &RestoreArtifact,
|
||||
now: i64,
|
||||
) -> Result<Option<RestoreJob>> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let registered: Option<RestoreTarget> = tx.query_row(
|
||||
"SELECT t.profile FROM restore_targets t WHERE t.id = ?1 AND t.application_id = ?2
|
||||
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = t.outpost_id AND state = 'active')",
|
||||
params![target.to_string(), application.to_string()],
|
||||
|row| json(row, 0),
|
||||
).optional()?;
|
||||
let Some(registered) = registered else {
|
||||
return Ok(None);
|
||||
};
|
||||
if restore_target_mismatch(®istered, artifact).is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
let id = Uuid::new_v4();
|
||||
tx.execute(
|
||||
"INSERT INTO restore_jobs(id, snapshot_id, target_id, actor, artifact, created_at, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6)",
|
||||
params![id.to_string(), snapshot.to_string(), target.to_string(), actor,
|
||||
serde_json::to_string(artifact)?, now],
|
||||
)?;
|
||||
audit(
|
||||
&tx,
|
||||
"restore.queued",
|
||||
&format!("actor={actor} job={id} snapshot={snapshot} target={target}"),
|
||||
)?;
|
||||
let job = tx.query_row(
|
||||
&format!("{VIEW} WHERE j.id = ?1"),
|
||||
[id.to_string()],
|
||||
read_job,
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(Some(job))
|
||||
}
|
||||
|
||||
pub fn restore_job(&self, id: Uuid, now: i64) -> Result<Option<RestoreJob>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
expire_destructive(&conn, now)?;
|
||||
Ok(conn
|
||||
.query_row(
|
||||
&format!("{VIEW} WHERE j.id = ?1"),
|
||||
[id.to_string()],
|
||||
read_job,
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn restore_history(&self, snapshot: Uuid, now: i64) -> Result<Vec<RestoreJob>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
expire_destructive(&conn, now)?;
|
||||
let mut stmt = conn.prepare(&format!(
|
||||
"{VIEW} WHERE j.snapshot_id = ?1 ORDER BY j.rowid DESC LIMIT 25"
|
||||
))?;
|
||||
let rows = stmt.query_map([snapshot.to_string()], read_job)?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn snapshot_in_restore(&self, id: Uuid) -> Result<bool> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
Ok(conn.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE (snapshot_id = ?1 OR safety_id = ?1 OR attempt_safety_id = ?1)
|
||||
AND status IN ('queued','running','applying','recovery_required'))",
|
||||
[id.to_string()], |row| row.get(0),
|
||||
)?)
|
||||
}
|
||||
|
||||
pub fn claim_restore(
|
||||
&self,
|
||||
outpost: Uuid,
|
||||
target: Uuid,
|
||||
now: i64,
|
||||
) -> Result<Option<RestoreLease>> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
expire_destructive(&tx, now)?;
|
||||
let selected = tx.query_row(
|
||||
&format!("{VIEW} WHERE t.id = ?1 AND t.outpost_id = ?2
|
||||
AND (j.status = 'queued' OR (j.status = 'running' AND j.lease_until <= ?3))
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM restore_jobs active JOIN restore_targets owner ON owner.id = active.target_id
|
||||
WHERE owner.application_id = t.application_id
|
||||
AND (active.status IN ('applying','recovery_required')
|
||||
OR (active.status = 'running' AND active.lease_until > ?3))
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM capture_jobs c WHERE c.application_id = t.application_id
|
||||
AND c.status = 'running' AND c.lease_until > ?3
|
||||
)
|
||||
ORDER BY j.created_at, j.rowid LIMIT 1"),
|
||||
params![target.to_string(), outpost.to_string(), now],
|
||||
|row| Ok((read_job(row)?, json(row, 9)?)),
|
||||
).optional()?;
|
||||
let Some((mut job, artifact)) = selected else {
|
||||
tx.commit()?;
|
||||
return Ok(None);
|
||||
};
|
||||
let token = Uuid::new_v4();
|
||||
tx.execute(
|
||||
"UPDATE restore_jobs SET status = 'running', phase = 'claimed', lease_token = ?2, lease_until = ?3,
|
||||
attempt_safety_id = ?4, safety_id = NULL, updated_at = ?5 WHERE id = ?1",
|
||||
params![job.id.to_string(), token.to_string(), now + CAPTURE_LEASE_SECONDS,
|
||||
Uuid::new_v4().to_string(), now],
|
||||
)?;
|
||||
job.status = "running".into();
|
||||
job.phase = "claimed".into();
|
||||
job.safety_snapshot_id = None;
|
||||
job.updated_at = now;
|
||||
tx.commit()?;
|
||||
Ok(Some(RestoreLease {
|
||||
job,
|
||||
token,
|
||||
artifact,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn restore_access(
|
||||
&self,
|
||||
outpost: Uuid,
|
||||
id: Uuid,
|
||||
token: Uuid,
|
||||
now: i64,
|
||||
) -> Result<Option<(RestoreJob, RestoreArtifact, Uuid)>> {
|
||||
restore_access(&self.conn.lock().unwrap(), outpost, id, token, now)
|
||||
}
|
||||
|
||||
pub fn record_safety(
|
||||
&self,
|
||||
outpost: Uuid,
|
||||
id: Uuid,
|
||||
token: Uuid,
|
||||
now: i64,
|
||||
publish: impl FnOnce(Uuid) -> Result<()>,
|
||||
) -> Result<Option<Uuid>> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let Some((job, _, expected)) = restore_access(&tx, outpost, id, token, now)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
if job.status != "running" {
|
||||
return Ok(None);
|
||||
}
|
||||
if let Some(safety) = job.safety_snapshot_id {
|
||||
return Ok(Some(safety));
|
||||
}
|
||||
if job.phase != "safety" {
|
||||
return Ok(None);
|
||||
}
|
||||
publish(expected)?;
|
||||
tx.execute("UPDATE restore_jobs SET phase = 'ready', safety_id = ?2, updated_at = ?3 WHERE id = ?1",
|
||||
params![id.to_string(), expected.to_string(), now])?;
|
||||
audit(
|
||||
&tx,
|
||||
"restore.safety_committed",
|
||||
&format!("job={id} snapshot={expected}"),
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(Some(expected))
|
||||
}
|
||||
|
||||
pub fn authorize_apply(&self, outpost: Uuid, id: Uuid, token: Uuid, now: i64) -> Result<bool> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let Some((job, _, _)) = restore_access(&tx, outpost, id, token, now)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
if job.status != "running" || job.phase != "ready" || job.safety_snapshot_id.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
tx.execute("UPDATE restore_jobs SET status = 'applying', phase = 'applying', updated_at = ?2, lease_until = ?3 WHERE id = ?1",
|
||||
params![id.to_string(), now, now + CAPTURE_LEASE_SECONDS])?;
|
||||
audit(
|
||||
&tx,
|
||||
"restore.apply_authorized",
|
||||
&format!("job={id} target={}", job.target.id),
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn report_restore(
|
||||
&self,
|
||||
outpost: Uuid,
|
||||
id: Uuid,
|
||||
token: Uuid,
|
||||
progress: RestoreProgress,
|
||||
now: i64,
|
||||
) -> Result<bool> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let Some((job, _, _)) = restore_access(&tx, outpost, id, token, now)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
let (status, phase) = match progress {
|
||||
RestoreProgress::Heartbeat => (job.status.as_str(), job.phase.as_str()),
|
||||
RestoreProgress::Checking if job.phase == "claimed" => ("running", "checking"),
|
||||
RestoreProgress::Safety if job.phase == "checking" => ("running", "safety"),
|
||||
RestoreProgress::InvalidPayload if job.phase == "checking" => {
|
||||
("failed", "invalid_payload")
|
||||
}
|
||||
RestoreProgress::WrongTarget if job.phase == "checking" => ("failed", "wrong_target"),
|
||||
RestoreProgress::SafetyFailed if matches!(job.phase.as_str(), "safety" | "ready") => {
|
||||
("failed", "safety_failed")
|
||||
}
|
||||
RestoreProgress::Applied if job.status == "applying" => ("completed", "completed"),
|
||||
RestoreProgress::ApplyFailed if job.status == "applying" => {
|
||||
("recovery_required", "apply_failed")
|
||||
}
|
||||
_ => return Ok(false),
|
||||
};
|
||||
tx.execute("UPDATE restore_jobs SET status = ?2, phase = ?3, updated_at = ?4, lease_until = ?5 WHERE id = ?1",
|
||||
params![id.to_string(), status, phase, now, now + CAPTURE_LEASE_SECONDS])?;
|
||||
if !matches!(progress, RestoreProgress::Heartbeat) {
|
||||
audit(&tx, "restore.phase", &format!("job={id} phase={phase}"))?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn reconcile_restore(&self, id: Uuid, actor: &str, now: i64) -> Result<bool> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
expire_destructive(&tx, now)?;
|
||||
let changed = tx.execute(
|
||||
"UPDATE restore_jobs SET status = 'reconciled', phase = 'reconciled', updated_at = ?2
|
||||
WHERE id = ?1 AND status = 'recovery_required'",
|
||||
params![id.to_string(), now],
|
||||
)?;
|
||||
if changed == 1 {
|
||||
audit(
|
||||
&tx,
|
||||
"restore.reconciled",
|
||||
&format!("actor={actor} job={id}"),
|
||||
)?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(changed == 1)
|
||||
}
|
||||
|
||||
pub fn cancel_restore(&self, id: Uuid, actor: &str, now: i64) -> Result<bool> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let changed = tx.execute(
|
||||
"UPDATE restore_jobs SET status = 'cancelled', phase = 'cancelled', updated_at = ?2
|
||||
WHERE id = ?1 AND status IN ('queued','running')",
|
||||
params![id.to_string(), now],
|
||||
)?;
|
||||
if changed == 1 {
|
||||
audit(&tx, "restore.cancelled", &format!("actor={actor} job={id}"))?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(changed == 1)
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_access(
|
||||
conn: &Connection,
|
||||
outpost: Uuid,
|
||||
id: Uuid,
|
||||
token: Uuid,
|
||||
now: i64,
|
||||
) -> Result<Option<(RestoreJob, RestoreArtifact, Uuid)>> {
|
||||
Ok(conn
|
||||
.query_row(
|
||||
&format!(
|
||||
"{VIEW} WHERE j.id = ?1 AND t.outpost_id = ?2 AND j.lease_token = ?3
|
||||
AND j.lease_until > ?4 AND j.status IN ('running', 'applying')"
|
||||
),
|
||||
params![id.to_string(), outpost.to_string(), token.to_string(), now],
|
||||
|row| Ok((read_job(row)?, json(row, 9)?, uuid(row, 10)?)),
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
fn expire_destructive(conn: &Connection, now: i64) -> Result<()> {
|
||||
conn.execute(
|
||||
"UPDATE restore_jobs SET status = 'recovery_required', phase = 'lease_lost', updated_at = ?1
|
||||
WHERE status = 'applying' AND lease_until <= ?1",
|
||||
[now],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn audit(tx: &Transaction<'_>, event: &str, detail: &str) -> Result<()> {
|
||||
tx.execute(
|
||||
"INSERT INTO audit_log(at, event, detail) VALUES (datetime('now'), ?1, ?2)",
|
||||
params![event, detail],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tessera_core::{
|
||||
job::{CaptureFormat, CaptureProfile},
|
||||
restore::{DatabaseIdentity, Engine},
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn expired_apply_survives_restart_and_fences_the_target_until_reconciled() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let path = root.path().join("restore.db");
|
||||
let db = Db::connect(&path).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
let outpost = Uuid::new_v4();
|
||||
db.insert_wormhole_token("synthetic-token", &outpost.to_string(), "code", "9999")
|
||||
.unwrap();
|
||||
db.claim_wormhole_code("code", "fixture", "2026")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let orbit = Uuid::new_v4();
|
||||
db.upsert_orbit(&OrbitRow {
|
||||
id: orbit,
|
||||
name: "fixture".into(),
|
||||
provider: "wormhole".into(),
|
||||
provider_config: "{}".into(),
|
||||
schedule: None,
|
||||
decay_preset: "week-of-dailies".into(),
|
||||
retention: None,
|
||||
dry_run: false,
|
||||
last_status: "idle".into(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let app = Uuid::new_v4();
|
||||
assert!(db
|
||||
.register_capture_profile(
|
||||
&CaptureProfile {
|
||||
application_id: app,
|
||||
orbit_id: orbit,
|
||||
outpost_id: outpost,
|
||||
format: CaptureFormat::PostgresCustom,
|
||||
schedule: None,
|
||||
retention: None,
|
||||
},
|
||||
100
|
||||
)
|
||||
.unwrap());
|
||||
let target = Uuid::new_v4();
|
||||
assert!(db
|
||||
.register_restore_target(&RestoreTarget {
|
||||
id: target,
|
||||
application_id: app,
|
||||
outpost_id: outpost,
|
||||
name: "target".into(),
|
||||
engine: Engine::Postgres,
|
||||
identity: DatabaseIdentity {
|
||||
instance: "123".into(),
|
||||
database: "target".into()
|
||||
},
|
||||
})
|
||||
.unwrap());
|
||||
let snapshot = Uuid::new_v4();
|
||||
let artifact = RestoreArtifact {
|
||||
format: CaptureFormat::PostgresCustom,
|
||||
sha256: "0".repeat(64),
|
||||
identity: DatabaseIdentity {
|
||||
instance: "123".into(),
|
||||
database: "source".into(),
|
||||
},
|
||||
};
|
||||
let registered = db.restore_targets_with_activity(app).unwrap().pop().unwrap();
|
||||
assert!(registered.1);
|
||||
let same_source = RestoreArtifact { identity: registered.0.identity.clone(), ..artifact.clone() };
|
||||
assert_eq!(restore_target_mismatch(®istered.0, &same_source), Some("Target is the source database"));
|
||||
assert!(db.enqueue_restore(snapshot, app, target, "fixture", &same_source, 100).unwrap().is_none());
|
||||
let job = db
|
||||
.enqueue_restore(snapshot, app, target, "fixture", &artifact, 100)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let next_snapshot = Uuid::new_v4();
|
||||
let next = db
|
||||
.enqueue_restore(next_snapshot, app, target, "fixture", &artifact, 101)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let lease = db.claim_restore(outpost, target, 102).unwrap().unwrap();
|
||||
assert_eq!(lease.job.id, job.id);
|
||||
assert!(db.claim_restore(outpost, target, 103).unwrap().is_none());
|
||||
assert!(db.snapshot_in_restore(snapshot).unwrap());
|
||||
assert!(!db
|
||||
.authorize_apply(outpost, job.id, lease.token, 104)
|
||||
.unwrap());
|
||||
assert!(db
|
||||
.report_restore(outpost, job.id, lease.token, RestoreProgress::Checking, 104)
|
||||
.unwrap());
|
||||
assert!(db
|
||||
.report_restore(outpost, job.id, lease.token, RestoreProgress::Safety, 105)
|
||||
.unwrap());
|
||||
assert!(db
|
||||
.record_safety(outpost, job.id, lease.token, 106, |_| anyhow::bail!(
|
||||
"synthetic write failure"
|
||||
))
|
||||
.is_err());
|
||||
assert!(!db
|
||||
.authorize_apply(outpost, job.id, lease.token, 107)
|
||||
.unwrap());
|
||||
let safety = db
|
||||
.record_safety(outpost, job.id, lease.token, 108, |_| Ok(()))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(db
|
||||
.authorize_apply(outpost, job.id, lease.token, 109)
|
||||
.unwrap());
|
||||
assert!(!db
|
||||
.authorize_apply(outpost, job.id, lease.token, 110)
|
||||
.unwrap());
|
||||
drop(db);
|
||||
let db = Db::connect(&path).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
let late = 109 + CAPTURE_LEASE_SECONDS;
|
||||
assert!(db.claim_restore(outpost, target, late).unwrap().is_none());
|
||||
assert!(db
|
||||
.restore_access(outpost, job.id, lease.token, late)
|
||||
.unwrap()
|
||||
.is_none());
|
||||
assert!(!db
|
||||
.authorize_apply(outpost, job.id, lease.token, late)
|
||||
.unwrap());
|
||||
let interrupted = db.restore_job(job.id, late).unwrap().unwrap();
|
||||
assert_eq!(interrupted.status, "recovery_required");
|
||||
assert_eq!(interrupted.safety_snapshot_id, Some(safety));
|
||||
assert!(db.snapshot_in_restore(snapshot).unwrap());
|
||||
assert!(db.snapshot_in_restore(safety).unwrap());
|
||||
assert!(db.reconcile_restore(job.id, "fixture", late + 1).unwrap());
|
||||
assert!(!db.snapshot_in_restore(snapshot).unwrap());
|
||||
assert!(!db.snapshot_in_restore(safety).unwrap());
|
||||
let retry = db
|
||||
.claim_restore(outpost, target, late + 2)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(retry.job.id, next.id);
|
||||
assert_ne!(retry.token, lease.token);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,9 @@ use tracing_subscriber::EnvFilter;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
if std::env::args().nth(1).as_deref() == Some("--hash-operator-password") {
|
||||
return admin::print_operator_hash();
|
||||
}
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::from_default_env().add_directive("tessera_hub=info".parse()?))
|
||||
.init();
|
||||
@@ -56,8 +59,15 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
state.configure_offsite()?;
|
||||
state.reconcile_capture_catalog().await?;
|
||||
state.start_offsite_worker();
|
||||
scheduler::start_orbit_scheduler(state.clone()).await?;
|
||||
state.admin.log_policy();
|
||||
if state.sessions.enabled() {
|
||||
tracing::info!("operator sessions enabled; CLI access uses a separate admin token");
|
||||
} else {
|
||||
state.admin.log_policy();
|
||||
}
|
||||
|
||||
if let Some(wormhole) = mtls::from_env()? {
|
||||
state.wormhole_mtls = true;
|
||||
|
||||
@@ -1,46 +1,130 @@
|
||||
use crate::state::HubState;
|
||||
use anyhow::Result;
|
||||
use anyhow::{Context, Result};
|
||||
use chrono::{DateTime, NaiveTime, TimeZone, Utc};
|
||||
use chrono_tz::Tz;
|
||||
use cron::Schedule;
|
||||
use std::str::FromStr;
|
||||
use tessera_core::job::CaptureSchedule;
|
||||
use tokio::time::{sleep, Duration};
|
||||
use tracing::{error, info};
|
||||
|
||||
pub async fn start_orbit_scheduler(state: HubState) -> Result<()> {
|
||||
let db = state.db.clone();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
if let Err(e) = tick_schedules(state.clone()).await {
|
||||
if let Err(e) = tick_capture_schedules(&db, Utc::now()) {
|
||||
error!("capture scheduler tick: {e}");
|
||||
}
|
||||
sleep(Duration::from_secs(30)).await;
|
||||
}
|
||||
});
|
||||
tokio::spawn(async move {
|
||||
let mut previous = Utc::now();
|
||||
loop {
|
||||
let now = Utc::now();
|
||||
if let Err(e) = tick_schedules(state.clone(), previous, now).await {
|
||||
error!("scheduler tick: {e}");
|
||||
}
|
||||
previous = now;
|
||||
sleep(Duration::from_secs(30)).await;
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn tick_schedules(state: HubState) -> Result<()> {
|
||||
pub(crate) fn orbit_schedule(expression: &str) -> Result<Schedule, cron::error::Error> {
|
||||
if expression.split_whitespace().count() == 5 {
|
||||
Schedule::from_str(&format!("0 {expression}"))
|
||||
} else {
|
||||
Schedule::from_str(expression)
|
||||
}
|
||||
}
|
||||
|
||||
async fn tick_schedules(
|
||||
state: HubState,
|
||||
previous: DateTime<Utc>,
|
||||
now: DateTime<Utc>,
|
||||
) -> Result<()> {
|
||||
let orbits = state.db.list_orbits().await?;
|
||||
let now = chrono::Utc::now();
|
||||
for orbit in orbits {
|
||||
let Some(cron_expr) = orbit.schedule.as_ref() else {
|
||||
if orbit.provider == "wormhole" {
|
||||
continue;
|
||||
}
|
||||
let Some(cron_expr) = orbit
|
||||
.schedule
|
||||
.as_deref()
|
||||
.filter(|expr| !expr.trim().is_empty())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let schedule = match Schedule::from_str(cron_expr) {
|
||||
let schedule = match orbit_schedule(cron_expr) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
error!("bad cron on orbit {}: {e}", orbit.name);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let upcoming = schedule.upcoming(chrono::Utc).take(1).collect::<Vec<_>>();
|
||||
if let Some(next) = upcoming.first() {
|
||||
let delta = (*next - now).num_seconds().abs();
|
||||
if delta < 35 {
|
||||
info!("scheduler firing orbit {}", orbit.name);
|
||||
if let Err(e) = crate::api::run_orbit_internal(state.clone(), orbit.id).await {
|
||||
error!("orbit {} failed: {e}", orbit.name);
|
||||
}
|
||||
if schedule
|
||||
.after(&previous)
|
||||
.next()
|
||||
.is_some_and(|slot| slot <= now)
|
||||
{
|
||||
info!("scheduler firing orbit {}", orbit.name);
|
||||
let orbit_id = orbit.id;
|
||||
if let Err(e) = crate::api::run_orbit_internal(state.clone(), orbit).await {
|
||||
error!("orbit {orbit_id} failed: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn capture_schedule(schedule: &CaptureSchedule) -> Option<(NaiveTime, Tz)> {
|
||||
let time = NaiveTime::from_hms_opt(u32::from(schedule.hour), u32::from(schedule.minute), 0)?;
|
||||
Some((time, schedule.timezone.parse().ok()?))
|
||||
}
|
||||
|
||||
pub(crate) fn tick_capture_schedules(db: &crate::db::Db, now: DateTime<Utc>) -> Result<()> {
|
||||
for (profile, cursor) in db.capture_schedule_cursors()? {
|
||||
let Some(schedule) = &profile.schedule else {
|
||||
continue;
|
||||
};
|
||||
let (time, tz) = capture_schedule(schedule).context("invalid stored capture schedule")?;
|
||||
let start = DateTime::from_timestamp(cursor, 0).context("invalid schedule cursor")?;
|
||||
let end = now.with_timezone(&tz).date_naive();
|
||||
let mut date = start.with_timezone(&tz).date_naive();
|
||||
for _ in 0..32 {
|
||||
if date > end {
|
||||
break;
|
||||
}
|
||||
if let Some(slot) = tz.from_local_datetime(&date.and_time(time)).earliest() {
|
||||
if slot.timestamp() > cursor && slot <= now {
|
||||
db.enqueue_scheduled_capture(
|
||||
profile.application_id,
|
||||
slot.timestamp(),
|
||||
now.timestamp(),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
date = date.succ_opt().context("schedule date overflow")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn orbit_cron_accepts_legacy_minutes_and_explicit_seconds() {
|
||||
let before = Utc.with_ymd_and_hms(2026, 11, 10, 1, 59, 55).unwrap();
|
||||
let slot = Utc.with_ymd_and_hms(2026, 11, 10, 2, 0, 0).unwrap();
|
||||
for expression in ["0 2 * * *", "0 0 2 * * *"] {
|
||||
let schedule = orbit_schedule(expression).unwrap();
|
||||
assert_eq!(schedule.after(&before).next(), Some(slot));
|
||||
assert!(schedule.after(&slot).next().unwrap() > slot);
|
||||
}
|
||||
assert!(orbit_schedule("60 2 * * *").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,45 @@
|
||||
use crate::admin::AdminGate;
|
||||
use crate::admin::{AdminGate, SessionGate};
|
||||
use crate::db::Db;
|
||||
use anyhow::Result;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tessera_core::reconstitute::ReconstituteSession;
|
||||
use tessera_store::Vault;
|
||||
use tessera_core::decay::{
|
||||
evaluate_capture_retention, evaluate_gfs, CaptureRetention, RetentionPolicy, SnapshotRef,
|
||||
};
|
||||
use tessera_core::job::CaptureProfile;
|
||||
|
||||
use tessera_core::reconstitute::{ReconstituteSession, ReconstituteState};
|
||||
use tessera_store::{Offsite, Vault};
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(crate) enum ManagedRetention {
|
||||
Orbit(RetentionPolicy),
|
||||
Profile(CaptureRetention),
|
||||
Default(CaptureRetention),
|
||||
}
|
||||
|
||||
impl ManagedRetention {
|
||||
pub(crate) fn resolve(profile: &CaptureProfile, orbit: Option<RetentionPolicy>) -> Self {
|
||||
match (profile.retention, orbit) {
|
||||
(Some(policy), _) => Self::Profile(policy),
|
||||
(None, Some(policy)) => Self::Orbit(policy),
|
||||
(None, None) => Self::Default(CaptureRetention::default()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HubState {
|
||||
pub db: Db,
|
||||
pub data_dir: PathBuf,
|
||||
pub vault_passphrase: String,
|
||||
pub offsite: Option<Arc<Offsite>>,
|
||||
pub vault: Arc<RwLock<Vault>>,
|
||||
pub reconstitute_sessions: Arc<RwLock<HashMap<Uuid, ReconstituteSession>>>,
|
||||
pub active_orbits: Arc<Mutex<HashSet<Uuid>>>,
|
||||
pub admin: AdminGate,
|
||||
pub sessions: SessionGate,
|
||||
pub wormhole_mtls: bool,
|
||||
/// Token uploads are accepted on this listener. Plain HTTP turns this off
|
||||
/// when wormhole mTLS is required, so those routes are not a bypass.
|
||||
@@ -42,26 +64,197 @@ impl HubState {
|
||||
Ok(Self {
|
||||
db,
|
||||
data_dir,
|
||||
vault_passphrase: vault_pass.to_string(),
|
||||
offsite: None,
|
||||
vault: Arc::new(RwLock::new(vault)),
|
||||
reconstitute_sessions: Arc::new(RwLock::new(HashMap::new())),
|
||||
active_orbits: Arc::new(Mutex::new(HashSet::new())),
|
||||
admin: AdminGate::from_env(),
|
||||
sessions: SessionGate::from_env()?,
|
||||
wormhole_mtls: false,
|
||||
accept_plain_upload: true,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn upload_token_valid(&self, token: &str) -> bool {
|
||||
self.db.upload_token_active(token).unwrap_or(false)
|
||||
pub fn configure_offsite(&mut self) -> Result<()> {
|
||||
let Some(repository) = std::env::var_os("TESSERA_OFFSITE_REPOSITORY") else {
|
||||
return Ok(());
|
||||
};
|
||||
let repository = repository
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("off-site repository must be UTF-8"))?;
|
||||
let password = std::env::var_os("TESSERA_OFFSITE_PASSWORD_FILE").ok_or_else(|| {
|
||||
anyhow::anyhow!("TESSERA_OFFSITE_PASSWORD_FILE is required for off-site copies")
|
||||
})?;
|
||||
self.offsite = Some(Arc::new(Offsite::new(
|
||||
repository,
|
||||
std::path::Path::new(&password),
|
||||
)?));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn reconcile_capture_catalog(&self) -> Result<()> {
|
||||
let vault = self.vault.clone().read_owned().await;
|
||||
let db = self.db.clone();
|
||||
let offsite_enabled = self.offsite.is_some();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
for id in db.incomplete_publications()? {
|
||||
let Some(snap) = vault.get_snapshot(id)? else {
|
||||
continue;
|
||||
};
|
||||
if snap
|
||||
.manifest
|
||||
.restore_hints
|
||||
.get("job_id")
|
||||
.and_then(|id| id.as_str())
|
||||
.and_then(|id| Uuid::parse_str(id).ok())
|
||||
== Some(snap.id)
|
||||
{
|
||||
let offsite = offsite_enabled && snap.manifest.restore_hints["format"] != "tar";
|
||||
db.reconcile_capture(snap.id, snap.manifest.orbit_id, offsite)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
pub fn start_offsite_worker(&self) {
|
||||
let Some(offsite) = self.offsite.clone() else {
|
||||
return;
|
||||
};
|
||||
let state = self.clone();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
match state.db.pending_offsite() {
|
||||
Ok(jobs) => {
|
||||
for id in jobs {
|
||||
let offsite = offsite.clone();
|
||||
let prepared = state.vault.read().await.prepare_offsite_copy(id);
|
||||
let success = match prepared {
|
||||
Ok(copy) => offsite.copy_capture(copy).await.is_ok(),
|
||||
Err(_) => false,
|
||||
};
|
||||
if !success {
|
||||
tracing::warn!(%id, "off-site capture copy failed");
|
||||
}
|
||||
if state.db.set_offsite_result(id, success).is_err() {
|
||||
tracing::warn!(%id, "could not save off-site copy status");
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => tracing::warn!("could not read off-site copy queue"),
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub async fn export_snapshot(&self, snapshot: Uuid, dest: PathBuf) -> Result<u64> {
|
||||
let vault = self.vault.clone().read_owned().await;
|
||||
let local_dest = dest.clone();
|
||||
let (local, published) = tokio::task::spawn_blocking(move || {
|
||||
(
|
||||
vault.restore_snapshot(snapshot, &local_dest),
|
||||
vault.has_published_snapshot(snapshot),
|
||||
)
|
||||
})
|
||||
.await?;
|
||||
if local.is_err() && published? {
|
||||
if let Some(offsite) = &self.offsite {
|
||||
return offsite.restore(snapshot, &dest).await;
|
||||
}
|
||||
}
|
||||
local
|
||||
}
|
||||
|
||||
pub async fn active_exports(&self) -> HashSet<Uuid> {
|
||||
self.reconstitute_sessions
|
||||
.read()
|
||||
.await
|
||||
.values()
|
||||
.filter_map(|session| {
|
||||
matches!(
|
||||
session.state,
|
||||
ReconstituteState::Countdown
|
||||
| ReconstituteState::Confirming
|
||||
| ReconstituteState::Restoring
|
||||
)
|
||||
.then_some(session.snapshot_id)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub async fn prune_orbit(&self, orbit_id: Uuid) -> Result<Vec<Uuid>> {
|
||||
let mut vault = self.vault.clone().write_owned().await;
|
||||
let (preset, retention) = self.db.orbit_retention(orbit_id)?;
|
||||
let profile = self.db.capture_profile_for_orbit(orbit_id)?;
|
||||
let active_exports = self.active_exports().await;
|
||||
let db = self.db.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
vault.prune_orbit_with_decay(orbit_id, &preset, retention.as_ref())
|
||||
let Some(profile) = profile else {
|
||||
return vault.prune_orbit_with_decay(orbit_id, &preset, retention.as_ref());
|
||||
};
|
||||
let snapshots = vault
|
||||
.list_snapshots()?
|
||||
.into_iter()
|
||||
.filter(|snapshot| snapshot.manifest.orbit_id == orbit_id)
|
||||
.map(|snapshot| SnapshotRef {
|
||||
id: snapshot.id,
|
||||
taken_at: snapshot.taken_at,
|
||||
})
|
||||
.collect();
|
||||
let expired = match ManagedRetention::resolve(&profile, retention) {
|
||||
ManagedRetention::Orbit(policy) => evaluate_gfs(&policy, snapshots),
|
||||
ManagedRetention::Profile(policy) | ManagedRetention::Default(policy) => {
|
||||
evaluate_capture_retention(policy, snapshots, chrono::Utc::now())
|
||||
}
|
||||
};
|
||||
let mut deletable = Vec::new();
|
||||
for id in expired {
|
||||
if !active_exports.contains(&id) && !db.offsite_pending(id)? && !db.snapshot_in_restore(id)? {
|
||||
deletable.push(id);
|
||||
}
|
||||
}
|
||||
vault.forget(&deletable)?;
|
||||
Ok(deletable)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tessera_core::job::CaptureFormat;
|
||||
|
||||
#[test]
|
||||
fn managed_retention_prefers_profile_then_orbit_then_default() {
|
||||
let mut profile = CaptureProfile {
|
||||
application_id: Uuid::nil(),
|
||||
orbit_id: Uuid::nil(),
|
||||
outpost_id: Uuid::nil(),
|
||||
format: CaptureFormat::PostgresCustom,
|
||||
schedule: None,
|
||||
retention: None,
|
||||
};
|
||||
let orbit = RetentionPolicy {
|
||||
keep_daily: 3,
|
||||
keep_weekly: 0,
|
||||
keep_monthly: 0,
|
||||
keep_yearly: 0,
|
||||
};
|
||||
assert!(matches!(
|
||||
ManagedRetention::resolve(&profile, None),
|
||||
ManagedRetention::Default(CaptureRetention::Age { days: 14 })
|
||||
));
|
||||
assert!(matches!(
|
||||
ManagedRetention::resolve(&profile, Some(orbit)),
|
||||
ManagedRetention::Orbit(policy) if policy == orbit
|
||||
));
|
||||
profile.retention = Some(CaptureRetention::Count { keep: 5 });
|
||||
assert!(matches!(
|
||||
ManagedRetention::resolve(&profile, Some(orbit)),
|
||||
ManagedRetention::Profile(CaptureRetention::Count { keep: 5 })
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,4 +12,7 @@ serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio = { workspace = true, features = ["process", "fs"] }
|
||||
tracing.workspace = true
|
||||
tempfile.workspace = true
|
||||
regex = "1"
|
||||
uuid.workspace = true
|
||||
walkdir.workspace = true
|
||||
|
||||
@@ -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?)
|
||||
}
|
||||
@@ -8,7 +8,9 @@
|
||||
|
||||
mod crypto;
|
||||
mod index;
|
||||
mod offsite;
|
||||
mod restic;
|
||||
mod vault;
|
||||
|
||||
pub use offsite::{Offsite, OffsiteCopy};
|
||||
pub use vault::*;
|
||||
|
||||
170
crates/tessera-store/src/offsite.rs
Normal file
170
crates/tessera-store/src/offsite.rs
Normal file
@@ -0,0 +1,170 @@
|
||||
use crate::restic;
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use std::{
|
||||
fs,
|
||||
io::Write,
|
||||
path::{Path, PathBuf},
|
||||
process::{Output, Stdio},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::process::Command;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct Offsite {
|
||||
repo: restic::Repository,
|
||||
}
|
||||
|
||||
pub struct OffsiteCopy {
|
||||
pub(crate) snapshot: Uuid,
|
||||
pub(crate) source: restic::Repository,
|
||||
pub(crate) restic_id: String,
|
||||
}
|
||||
|
||||
impl Offsite {
|
||||
pub fn new(repository: &str, password_file: &Path) -> Result<Self> {
|
||||
let location = repository
|
||||
.strip_prefix("s3:https://")
|
||||
.or_else(|| {
|
||||
repository
|
||||
.strip_prefix("s3:http://")
|
||||
.filter(|rest| rest.starts_with("127.0.0.1:"))
|
||||
})
|
||||
.context("off-site repository requires an S3 HTTPS endpoint")?;
|
||||
let parts: Vec<_> = location.splitn(3, '/').collect();
|
||||
ensure!(
|
||||
parts.len() == 3
|
||||
&& parts.iter().all(|part| !part.is_empty())
|
||||
&& !repository.contains(['@', '?', '#', '\n', '\r']),
|
||||
"use a dedicated S3 bucket prefix without embedded credentials"
|
||||
);
|
||||
let password =
|
||||
fs::read_to_string(password_file).context("read off-site Restic password")?;
|
||||
let password = password.trim_end_matches(['\r', '\n']);
|
||||
ensure!(!password.is_empty(), "off-site Restic password is empty");
|
||||
Ok(Self {
|
||||
repo: restic::Repository {
|
||||
path: PathBuf::from(repository),
|
||||
password: password.into(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn command(&self) -> Command {
|
||||
let mut command = Command::from(self.repo.command());
|
||||
command
|
||||
.args(["-o", "s3.retries=1", "--stuck-request-timeout=15s"])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true);
|
||||
command
|
||||
}
|
||||
|
||||
async fn copy_from(&self, source: &restic::Repository, id: &str) -> Result<()> {
|
||||
restic::validate_id(id)?;
|
||||
let mut password = tempfile::NamedTempFile::new()?;
|
||||
writeln!(password, "{}", source.password)?;
|
||||
let probe = run(self.command().args(["snapshots", "--json"]), 10).await?;
|
||||
if probe.status.code() == Some(10) {
|
||||
safe(run(self.command().arg("init"), 30).await?, "init")?;
|
||||
} else {
|
||||
safe(probe, "probe")?;
|
||||
}
|
||||
safe(
|
||||
run(
|
||||
self.command()
|
||||
.env_remove("RESTIC_FROM_PASSWORD")
|
||||
.env_remove("RESTIC_FROM_PASSWORD_COMMAND")
|
||||
.env_remove("RESTIC_FROM_REPOSITORY_FILE")
|
||||
.env_remove("RESTIC_FROM_KEY_HINT")
|
||||
.arg("copy")
|
||||
.arg("--from-repo")
|
||||
.arg(&source.path)
|
||||
.arg("--from-password-file")
|
||||
.arg(password.path())
|
||||
.arg(id),
|
||||
3600,
|
||||
)
|
||||
.await?,
|
||||
"copy",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn tagged_snapshot(&self, snapshot: Uuid) -> Result<Option<String>> {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Copy {
|
||||
id: String,
|
||||
}
|
||||
let output = safe(
|
||||
run(
|
||||
self.command().args([
|
||||
"snapshots",
|
||||
"--json",
|
||||
"--tag",
|
||||
&restic::tessera_tag(snapshot),
|
||||
]),
|
||||
15,
|
||||
)
|
||||
.await?,
|
||||
"list",
|
||||
)?;
|
||||
let mut snapshots: Vec<Copy> = serde_json::from_slice(&output.stdout)?;
|
||||
Ok(snapshots.pop().map(|copy| copy.id))
|
||||
}
|
||||
|
||||
pub async fn restore(&self, snapshot: Uuid, dest: &Path) -> Result<u64> {
|
||||
let id = self
|
||||
.tagged_snapshot(snapshot)
|
||||
.await?
|
||||
.context("snapshot not found in off-site repository")?;
|
||||
restic::validate_id(&id)?;
|
||||
let parent = dest
|
||||
.parent()
|
||||
.filter(|path| !path.as_os_str().is_empty())
|
||||
.unwrap_or(Path::new("."));
|
||||
fs::create_dir_all(parent)?;
|
||||
let file = tempfile::NamedTempFile::new_in(parent)?;
|
||||
safe(
|
||||
run(
|
||||
self.command()
|
||||
.args(["dump", &id, restic::PAYLOAD])
|
||||
.stdout(Stdio::from(file.reopen()?)),
|
||||
3600,
|
||||
)
|
||||
.await?,
|
||||
"dump",
|
||||
)?;
|
||||
let size = file.as_file().metadata()?.len();
|
||||
file.as_file().sync_all()?;
|
||||
file.persist(dest)?;
|
||||
Ok(size)
|
||||
}
|
||||
|
||||
pub async fn copy_capture(&self, copy: OffsiteCopy) -> Result<()> {
|
||||
self.copy_from(©.source, ©.restic_id).await?;
|
||||
ensure!(
|
||||
self.tagged_snapshot(copy.snapshot).await?.is_some(),
|
||||
"off-site snapshot tag not found after copy"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(command: &mut Command, seconds: u64) -> Result<Output> {
|
||||
let result = tokio::time::timeout(
|
||||
Duration::from_secs(seconds),
|
||||
command.spawn()?.wait_with_output(),
|
||||
)
|
||||
.await
|
||||
.context("off-site Restic operation timed out")??;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn safe(output: Output, step: &str) -> Result<Output> {
|
||||
ensure!(
|
||||
output.status.success(),
|
||||
"off-site Restic {step} failed ({})",
|
||||
output.status
|
||||
);
|
||||
Ok(output)
|
||||
}
|
||||
@@ -8,6 +8,11 @@ pub(crate) const PREFIX: &str = "restic:";
|
||||
pub(crate) const OUTPOST_PREFIX: &str = "restic-outpost:";
|
||||
pub(crate) const PAYLOAD: &str = "/payload";
|
||||
|
||||
pub(crate) fn tessera_tag(snapshot: uuid::Uuid) -> String {
|
||||
format!("tessera-{snapshot}")
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Repository {
|
||||
pub path: PathBuf,
|
||||
pub password: String,
|
||||
@@ -25,6 +30,10 @@ pub(crate) struct Summary {
|
||||
struct Snapshot {
|
||||
id: String,
|
||||
summary: Option<Summary>,
|
||||
#[serde(default)]
|
||||
tags: Vec<String>,
|
||||
#[serde(default)]
|
||||
paths: Vec<String>,
|
||||
}
|
||||
|
||||
impl Repository {
|
||||
@@ -109,7 +118,12 @@ impl Repository {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn snapshot_summary(&self, id: &str) -> Result<Summary> {
|
||||
pub fn snapshot_summary(
|
||||
&self,
|
||||
id: &str,
|
||||
tag: Option<&str>,
|
||||
expected_path: Option<&str>,
|
||||
) -> Result<Summary> {
|
||||
validate_id(id)?;
|
||||
let output = checked(
|
||||
self.command().args(["snapshots", "--json", id]).output()?,
|
||||
@@ -118,7 +132,11 @@ impl Repository {
|
||||
let snapshots: Vec<Snapshot> = serde_json::from_slice(&output.stdout)?;
|
||||
snapshots
|
||||
.into_iter()
|
||||
.find(|snap| snap.id == id)
|
||||
.find(|snap| {
|
||||
snap.id == id
|
||||
&& tag.is_none_or(|tag| snap.tags.iter().any(|value| value == tag))
|
||||
&& expected_path.is_none_or(|path| snap.paths == [path])
|
||||
})
|
||||
.and_then(|snap| snap.summary)
|
||||
.context("outpost snapshot or backup summary is missing")
|
||||
}
|
||||
|
||||
@@ -148,7 +148,7 @@ impl Vault {
|
||||
return Ok(Some((id, false)));
|
||||
}
|
||||
let repo = self.outpost_repository(manifest.orbit_id, config);
|
||||
let summary = repo.snapshot_summary(restic_id)?;
|
||||
let summary = repo.snapshot_summary(restic_id, None, None)?;
|
||||
manifest.snapshot_id = id;
|
||||
manifest.restore_hints = serde_json::json!({ "format": "tar" });
|
||||
self.write_snapshot(
|
||||
@@ -166,6 +166,29 @@ impl Vault {
|
||||
Ok(Some((id, true)))
|
||||
}
|
||||
|
||||
pub fn prepare_outpost_capture(
|
||||
&self,
|
||||
manifest: SnapshotManifest,
|
||||
outpost_id: Uuid,
|
||||
restic_id: &str,
|
||||
) -> Result<StoredSnapshot> {
|
||||
let config = self.outpost_config(manifest.orbit_id)?;
|
||||
anyhow::ensure!(config.outpost_id == outpost_id, "repository belongs to another outpost");
|
||||
let repo = self.outpost_repository(manifest.orbit_id, config);
|
||||
let id = manifest.snapshot_id;
|
||||
let expected_path = (manifest.provider != "filesystem").then_some(restic::PAYLOAD);
|
||||
let summary = repo.snapshot_summary(restic_id, Some(&restic::tessera_tag(id)), expected_path)?;
|
||||
Ok(StoredSnapshot {
|
||||
id,
|
||||
taken_at: Utc::now(),
|
||||
manifest,
|
||||
size_bytes: summary.total_bytes_processed,
|
||||
tree_root: format!("{}{restic_id}", restic::OUTPOST_PREFIX),
|
||||
stored_bytes: Some(summary.data_added_packed),
|
||||
new_data_chunks: Some(summary.data_blobs),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn snapshot_files(
|
||||
&self,
|
||||
mut manifest: SnapshotManifest,
|
||||
@@ -209,7 +232,7 @@ impl Vault {
|
||||
manifest.restore_hints = serde_json::json!({ "format": "tar" });
|
||||
let exclude = restic::literal_pattern(&vault)?;
|
||||
self.restic_snapshot(manifest, dry_run, |cmd| {
|
||||
cmd.args(["--force", "--exclude", &exclude]);
|
||||
cmd.args(["--exclude", &exclude]);
|
||||
if let Some(max) = max_file_bytes {
|
||||
cmd.arg("--exclude-larger-than").arg(max.to_string());
|
||||
}
|
||||
@@ -218,6 +241,19 @@ impl Vault {
|
||||
}
|
||||
|
||||
pub fn snapshot_payload(
|
||||
&self,
|
||||
manifest: SnapshotManifest,
|
||||
payload: File,
|
||||
dry_run: bool,
|
||||
) -> Result<StoredSnapshot> {
|
||||
let snap = self.prepare_payload(manifest, payload, dry_run)?;
|
||||
if !dry_run {
|
||||
self.publish_prepared(&snap)?;
|
||||
}
|
||||
Ok(snap)
|
||||
}
|
||||
|
||||
pub fn prepare_payload(
|
||||
&self,
|
||||
manifest: SnapshotManifest,
|
||||
mut payload: File,
|
||||
@@ -227,13 +263,13 @@ impl Vault {
|
||||
// Restic rejects empty stdin. A relative filename keeps the same restore path.
|
||||
let temp = tempfile::tempdir()?;
|
||||
File::create(temp.path().join("payload"))?;
|
||||
return self.restic_snapshot(manifest, dry_run, |cmd| {
|
||||
return self.prepare_restic_snapshot(manifest, dry_run, |cmd| {
|
||||
cmd.current_dir(temp.path())
|
||||
.args(["--force", "--", "payload"]);
|
||||
});
|
||||
}
|
||||
payload.seek(SeekFrom::Start(0))?;
|
||||
self.restic_snapshot(manifest, dry_run, |cmd| {
|
||||
self.prepare_restic_snapshot(manifest, dry_run, |cmd| {
|
||||
cmd.args(["--stdin", "--stdin-filename", restic::PAYLOAD])
|
||||
.stdin(Stdio::from(payload));
|
||||
})
|
||||
@@ -244,6 +280,19 @@ impl Vault {
|
||||
manifest: SnapshotManifest,
|
||||
dry_run: bool,
|
||||
source: impl FnOnce(&mut Command),
|
||||
) -> Result<StoredSnapshot> {
|
||||
let snap = self.prepare_restic_snapshot(manifest, dry_run, source)?;
|
||||
if !dry_run {
|
||||
self.publish_prepared(&snap)?;
|
||||
}
|
||||
Ok(snap)
|
||||
}
|
||||
|
||||
fn prepare_restic_snapshot(
|
||||
&self,
|
||||
manifest: SnapshotManifest,
|
||||
dry_run: bool,
|
||||
source: impl FnOnce(&mut Command),
|
||||
) -> Result<StoredSnapshot> {
|
||||
let taken_at = Utc::now();
|
||||
let temp;
|
||||
@@ -261,7 +310,7 @@ impl Vault {
|
||||
repo.init()
|
||||
.context("opening the deduplicated vault (restic must be on PATH)")?;
|
||||
let mut cmd = repo.command();
|
||||
cmd.args(["backup", "--json", "--quiet"]);
|
||||
cmd.args(["backup", "--json", "--quiet", "--tag", &restic::tessera_tag(manifest.snapshot_id)]);
|
||||
if dry_run {
|
||||
cmd.arg("--dry-run");
|
||||
}
|
||||
@@ -286,12 +335,79 @@ impl Vault {
|
||||
stored_bytes: Some(summary.data_added_packed),
|
||||
new_data_chunks: Some(summary.data_blobs),
|
||||
};
|
||||
if !dry_run {
|
||||
self.write_snapshot(&snap, false)?;
|
||||
}
|
||||
Ok(snap)
|
||||
}
|
||||
|
||||
pub fn import_legacy_payload(
|
||||
&self, manifest: SnapshotManifest, payload: File, taken_at: chrono::DateTime<Utc>,
|
||||
) -> Result<bool> {
|
||||
let id = manifest.snapshot_id;
|
||||
let receipts = self.root.join("keys/legacy-imports");
|
||||
fs::create_dir_all(&receipts)?;
|
||||
restrict_dir(&receipts)?;
|
||||
let receipt = receipts.join(id.to_string());
|
||||
if receipt.try_exists()? {
|
||||
return Ok(false);
|
||||
}
|
||||
let snapshots = self.root.join("snapshots");
|
||||
let already_imported = || -> Result<bool> {
|
||||
Ok(self.has_published_snapshot(id)? || snapshots.join(format!("{id}.expired")).try_exists()?)
|
||||
};
|
||||
let imported = if already_imported()? {
|
||||
false
|
||||
} else {
|
||||
let mut prepared = self.prepare_payload(manifest, payload, false)?;
|
||||
prepared.taken_at = taken_at;
|
||||
match self.publish_prepared(&prepared) {
|
||||
Ok(()) => true,
|
||||
Err(_) if already_imported()? => {
|
||||
self.discard_prepared(&prepared)?;
|
||||
false
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
};
|
||||
let marker = tempfile::NamedTempFile::new_in(&receipts)?;
|
||||
marker.as_file().sync_all()?;
|
||||
match marker.persist_noclobber(&receipt) {
|
||||
Ok(_) => sync_directory(&receipts)?,
|
||||
Err(error) if error.error.kind() == std::io::ErrorKind::AlreadyExists => (),
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
Ok(imported)
|
||||
}
|
||||
|
||||
pub fn legacy_import_exists(&self, id: Uuid) -> Result<bool> {
|
||||
Ok(self.root.join("keys/legacy-imports").join(id.to_string()).try_exists()?)
|
||||
}
|
||||
|
||||
pub fn verify_prepared_payload(&self, snap: &StoredSnapshot, expected: &[u8; 32]) -> Result<()> {
|
||||
use sha2::{Digest, Sha256};
|
||||
let id = snap.tree_root.strip_prefix(restic::PREFIX).context("prepared payload is missing")?;
|
||||
let mut file = tempfile::tempfile()?;
|
||||
self.restic.dump(id, restic::PAYLOAD, file.try_clone()?)?;
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
let mut digest = Sha256::new();
|
||||
std::io::copy(&mut file, &mut digest)?;
|
||||
anyhow::ensure!(digest.finalize()[..] == expected[..], "stored payload checksum mismatch");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn publish_prepared(&self, snap: &StoredSnapshot) -> Result<()> {
|
||||
self.write_snapshot(snap, false)
|
||||
}
|
||||
|
||||
pub fn discard_prepared(&self, snap: &StoredSnapshot) -> Result<()> {
|
||||
if let Some(id) = snap.tree_root.strip_prefix(restic::PREFIX) {
|
||||
self.restic.forget(&[id.to_owned()])?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn has_published_snapshot(&self, id: Uuid) -> Result<bool> {
|
||||
Ok(self.root.join("snapshots").join(format!("{id}.json.enc")).try_exists()?)
|
||||
}
|
||||
|
||||
fn index_path(&self) -> PathBuf {
|
||||
self.root.join("index/tessera-main.json")
|
||||
}
|
||||
@@ -435,13 +551,30 @@ impl Vault {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn prepare_offsite_copy(&self, id: Uuid) -> Result<crate::OffsiteCopy> {
|
||||
let snapshot = self.read_snapshot_file(&self.root.join("snapshots").join(format!("{id}.json.enc")))?;
|
||||
anyhow::ensure!(snapshot.manifest.restore_hints.get("job_id").is_some(), "snapshot is not a capture job");
|
||||
let (source, restic_id) = if let Some(id) = snapshot.tree_root.strip_prefix(restic::OUTPOST_PREFIX) {
|
||||
let orbit = snapshot.manifest.orbit_id;
|
||||
(self.outpost_repository(orbit, self.outpost_config(orbit)?), id)
|
||||
} else {
|
||||
(self.restic.clone(), snapshot.tree_root.strip_prefix(restic::PREFIX).context("capture Restic snapshot missing")?)
|
||||
};
|
||||
Ok(crate::OffsiteCopy { snapshot: id, source, restic_id: restic_id.to_owned() })
|
||||
}
|
||||
|
||||
pub fn get_snapshot(&self, id: Uuid) -> Result<Option<StoredSnapshot>> {
|
||||
for suffix in [".json.enc", ".json"] {
|
||||
let path = self.root.join("snapshots").join(format!("{id}{suffix}"));
|
||||
if path.try_exists()? {
|
||||
return self.read_snapshot_file(&path).map(Some);
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub fn restore_snapshot(&self, id: Uuid, dest: &Path) -> Result<u64> {
|
||||
let enc = self.root.join("snapshots").join(format!("{id}.json.enc"));
|
||||
let plain = self.root.join("snapshots").join(format!("{id}.json"));
|
||||
let path = if enc.exists() { enc } else { plain };
|
||||
let snap = self
|
||||
.read_snapshot_file(&path)
|
||||
.context("snapshot metadata")?;
|
||||
let snap = self.get_snapshot(id)?.context("snapshot metadata not found")?;
|
||||
let parent = dest
|
||||
.parent()
|
||||
.filter(|p| !p.as_os_str().is_empty())
|
||||
@@ -450,8 +583,9 @@ impl Vault {
|
||||
let mut temp = tempfile::NamedTempFile::new_in(parent)?;
|
||||
if let Some(id) = snap.tree_root.strip_prefix(restic::OUTPOST_PREFIX) {
|
||||
let orbit_id = snap.manifest.orbit_id;
|
||||
let path = if snap.manifest.restore_hints["format"] == "tar" { "/" } else { restic::PAYLOAD };
|
||||
self.outpost_repository(orbit_id, self.outpost_config(orbit_id)?)
|
||||
.dump(id, "/", temp.reopen()?)?;
|
||||
.dump(id, path, temp.reopen()?)?;
|
||||
} else if let Some(id) = snap.tree_root.strip_prefix(restic::PREFIX) {
|
||||
let path = if snap.manifest.provider == "filesystem" {
|
||||
"/"
|
||||
@@ -548,7 +682,9 @@ impl Vault {
|
||||
|
||||
pub fn prune_with_decay(&mut self, preset: &str) -> Result<Vec<Uuid>> {
|
||||
let snaps = self.list_snapshots()?;
|
||||
self.prune_snapshots(preset, None, snaps.into_iter())
|
||||
self.prune_snapshots(preset, None, snaps.into_iter()
|
||||
.filter(|snapshot| snapshot.manifest.provider != "legacy-history"
|
||||
&& snapshot.manifest.restore_hints.get("job_id").is_none()))
|
||||
}
|
||||
|
||||
pub fn prune_orbit_with_decay(
|
||||
|
||||
Reference in New Issue
Block a user