diff --git a/crates/tessera-cli/src/legacy_import.rs b/crates/tessera-cli/src/legacy_import.rs index 06bb1d4..96744c7 100644 --- a/crates/tessera-cli/src/legacy_import.rs +++ b/crates/tessera-cli/src/legacy_import.rs @@ -33,6 +33,9 @@ pub struct ImportArgs { /// Reconcile counts, times and sizes without downloading or writing snapshots. #[arg(long)] inventory_only: bool, + /// The AWS CLI to run; a field only so tests can substitute a fake one. + #[arg(skip = PathBuf::from("aws"))] + program: PathBuf, } #[derive(Clone, Copy, ValueEnum)] @@ -96,6 +99,12 @@ struct Report { } pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> { + let report = reconcile(vault, args)?; + println!("{}", serde_json::to_string_pretty(&report)?); + Ok(()) +} + +fn reconcile(vault: &Vault, args: ImportArgs) -> Result { ensure!( !args.prefix.is_empty() && args.prefix.ends_with('/'), "provide a per-application prefix ending in '/'" @@ -173,7 +182,7 @@ pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> { .map(|path| import_history(vault, path)) .transpose()? }; - let report = Report { + Ok(Report { application: args.application, bucket: args.bucket, prefix: args.prefix, @@ -181,13 +190,11 @@ pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> { 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"); + let mut cmd = Command::new(&args.program); cmd.args([ "--no-cli-pager", "--no-cli-auto-prompt", @@ -285,3 +292,496 @@ fn import_history(vault: &Vault, path: &std::path::Path) -> Result { vault.import_legacy_payload(manifest, staged, taken_at)?; Ok(id) } + +/// These drive `reconcile` against a stand-in `aws` (a shell script that serves a local directory), so the +/// listing, conditional download, receipts and history paths all run for real; only S3 is faked. +#[cfg(all(test, unix))] +mod tests { + use super::*; + use serde_json::{json, Value}; + use std::{fs, os::unix::fs::PermissionsExt, path::Path}; + + const ETAG: &str = "\"9b2cf535f27731c974343645a3985328\""; + const WHEN: &str = "2026-01-02T03:04:05+00:00"; + + struct Fixture { + dir: tempfile::TempDir, + vault: Vault, + listing: Vec, + } + + impl Fixture { + fn new() -> Self { + let dir = tempfile::tempdir().unwrap(); + let vault = Vault::init(dir.path().join("vault"), "synthetic-passphrase").unwrap(); + let fake = dir.path().join("fake"); + fs::create_dir_all(fake.join("obj")).unwrap(); + fs::create_dir_all(fake.join("meta")).unwrap(); + let script = format!( + r#"#!/bin/sh +D='{}' +op="$6" +echo "$op" >> "$D/calls" +case "$op" in + list-objects-v2) + [ -f "$D/list.fail" ] && exit 1 + cat "$D/list.json" ;; + get-object) + for a in "$@"; do + last="$a" + case "$a" in --key=*) key="${{a#--key=}}" ;; esac + done + name=$(basename "$key") + [ -f "$D/get.fail.$name" ] && exit 1 + cp "$D/obj/$name" "$last" + cat "$D/meta/$name.json" ;; +esac +"#, + fake.display() + ); + let program = dir.path().join("aws"); + fs::write(&program, script).unwrap(); + fs::set_permissions(&program, fs::Permissions::from_mode(0o755)).unwrap(); + let fixture = Self { + dir, + vault, + listing: vec![], + }; + fixture.publish(); + fixture + } + + fn fake(&self) -> std::path::PathBuf { + self.dir.path().join("fake") + } + + fn publish(&self) { + fs::write( + self.fake().join("list.json"), + json!({ "Contents": self.listing }).to_string(), + ) + .unwrap(); + } + + /// Put an object in the listing and on the fake bucket, with matching download metadata. + fn add(&mut self, key: &str, body: &[u8]) { + self.add_listed(key, body, body.len() as u64, ETAG); + let name = key.rsplit('/').next().unwrap(); + fs::write(self.fake().join("obj").join(name), body).unwrap(); + self.meta(key, ETAG, body.len() as u64, WHEN); + } + + /// Only the listing entry, for metadata the object itself would not match. + fn add_listed(&mut self, key: &str, _body: &[u8], size: u64, etag: &str) { + self.listing.push(json!({ + "Key": key, "ETag": etag, "Size": size, "LastModified": WHEN + })); + self.publish(); + } + + fn meta(&self, key: &str, etag: &str, length: u64, modified: &str) { + let name = key.rsplit('/').next().unwrap(); + fs::write( + self.fake().join("meta").join(format!("{name}.json")), + json!({"ETag": etag, "ContentLength": length, "LastModified": modified}) + .to_string(), + ) + .unwrap(); + } + + fn calls(&self) -> Vec { + fs::read_to_string(self.fake().join("calls")) + .unwrap_or_default() + .lines() + .map(str::to_owned) + .collect() + } + + fn args(&self) -> ImportArgs { + ImportArgs { + bucket: "legacy-bucket".into(), + prefix: "backups/shop/".into(), + endpoint: None, + orbit_id: Uuid::from_u128(7), + application: "shop".into(), + engine: Engine::Postgres, + history: None, + inventory_only: false, + program: self.dir.path().join("aws"), + } + } + + fn run(&self, args: ImportArgs) -> Result { + reconcile(&self.vault, args) + } + + fn snapshots(&self) -> usize { + self.vault.list_snapshots().unwrap().len() + } + + fn receipts(&self) -> usize { + fs::read_dir(self.vault.root().join("keys/legacy-imports")) + .map(|entries| entries.count()) + .unwrap_or(0) + } + } + + fn gzip_header(rest: &[u8]) -> Vec { + [&[0x1f, 0x8b][..], rest].concat() + } + + fn statuses(report: &Report) -> Vec<&'static str> { + report.objects.iter().map(|o| o.status).collect() + } + + // ---- arguments are validated before anything is listed ---- + + #[test] + fn bad_arguments_are_refused_before_aws_is_run() { + let fx = Fixture::new(); + type Tweak = fn(&mut ImportArgs); + let cases: [(&str, Tweak); 11] = [ + ("empty prefix", |a| a.prefix = String::new()), + ("prefix without a trailing slash", |a| { + a.prefix = "backups/shop".into() + }), + ("blank application", |a| a.application = " ".into()), + ("long application", |a| a.application = "a".repeat(129)), + ("control in application", |a| { + a.application = "sh\nop".into() + }), + ("plain http endpoint", |a| { + a.endpoint = Some("http://s3.example.com".into()) + }), + ("http on another loopback port form", |a| { + a.endpoint = Some("http://localhost:9000".into()) + }), + ("credentials in the endpoint", |a| { + a.endpoint = Some("https://user:pw@s3.example.com".into()) + }), + ("query in the endpoint", |a| { + a.endpoint = Some("https://s3.example.com/?x=1".into()) + }), + ("fragment in the endpoint", |a| { + a.endpoint = Some("https://s3.example.com/#x".into()) + }), + ("newline in the endpoint", |a| { + a.endpoint = Some("https://s3.example.com/\nx".into()) + }), + ]; + for (what, tweak) in cases { + let mut args = fx.args(); + tweak(&mut args); + assert!(fx.run(args).is_err(), "{what} must be refused"); + } + assert!(fx.calls().is_empty(), "aws was never run"); + let mut ok = fx.args(); + ok.endpoint = Some("http://127.0.0.1:9000".into()); + assert!(fx.run(ok).is_ok(), "a local test endpoint is allowed"); + let mut ok = fx.args(); + ok.endpoint = Some("https://s3.example.com".into()); + assert!(fx.run(ok).is_ok()); + } + + // ---- inventory ---- + + #[test] + fn inventory_counts_only_sql_archives_under_the_prefix_and_writes_nothing() { + let mut fx = Fixture::new(); + fx.add("backups/shop/a.sql", b"select 1;"); + fx.add("backups/shop/b.sql.gz", &gzip_header(b"zz")); + fx.add("backups/shop/readme.txt", b"not a dump"); + fx.add("backups/shop/nested/c.sql", b"select 3;"); + fx.add("backups/shop/d.sql.bak", b"select 4;"); + fx.add("backups/other/e.sql", b"another application"); + fx.add("backups/shopping/f.sql", b"prefix lookalike"); + let mut args = fx.args(); + args.inventory_only = true; + let report = fx.run(args).unwrap(); + assert_eq!(report.count, 3, "a, b and nested/c"); + assert_eq!(report.bytes, 9 + 4 + 9); + assert_eq!(statuses(&report), ["inventoried"; 3]); + assert!(report.history_snapshot_id.is_none()); + assert_eq!(fx.snapshots(), 0); + assert_eq!(fx.receipts(), 0); + assert_eq!(fx.calls(), ["list-objects-v2"], "no object was downloaded"); + } + + #[test] + fn inventory_only_ignores_a_history_export() { + let fx = Fixture::new(); + let history = fx.dir.path().join("history.sqlite"); + fs::write(&history, b"SQLite format 3\0 rows").unwrap(); + let mut args = fx.args(); + args.inventory_only = true; + args.history = Some(history); + let report = fx.run(args).unwrap(); + assert!(report.history_snapshot_id.is_none()); + assert_eq!(fx.snapshots(), 0); + } + + #[test] + fn an_empty_or_missing_listing_is_a_clean_zero() { + let fx = Fixture::new(); + let report = fx.run(fx.args()).unwrap(); + assert_eq!((report.count, report.bytes), (0, 0)); + fs::write(fx.fake().join("list.json"), "{}").unwrap(); + assert_eq!(fx.run(fx.args()).unwrap().count, 0); + } + + #[test] + fn listing_failures_stop_the_run() { + let fx = Fixture::new(); + fs::write(fx.fake().join("list.fail"), "").unwrap(); + let err = fx.run(fx.args()).err().unwrap(); + assert!(format!("{err:#}").contains("could not list"), "{err:#}"); + fs::remove_file(fx.fake().join("list.fail")).unwrap(); + for broken in [ + "", + "not json", + r#"{"Contents":[{"Key":"x"}]}"#, + r#"{"Contents":"x"}"#, + ] { + fs::write(fx.fake().join("list.json"), broken).unwrap(); + assert!(fx.run(fx.args()).is_err(), "listing {broken:?}"); + } + let missing = ImportArgs { + program: fx.dir.path().join("no-such-aws"), + ..fx.args() + }; + assert!(fx.run(missing).is_err(), "no aws binary is an error"); + assert_eq!(fx.snapshots(), 0); + } + + #[test] + fn untrustworthy_inventory_metadata_is_refused() { + for (size, etag) in [(0, ETAG), (5, ""), (5, "*")] { + let mut fx = Fixture::new(); + fx.add_listed("backups/shop/a.sql", b"", size, etag); + let err = fx.run(fx.args()).err().unwrap(); + assert!( + format!("{err:#}").contains("invalid legacy archive metadata"), + "size {size} etag {etag:?}: {err:#}" + ); + assert_eq!(fx.snapshots(), 0); + } + } + + #[test] + fn an_inventory_whose_sizes_overflow_is_refused() { + let mut fx = Fixture::new(); + fx.add_listed("backups/shop/a.sql", b"", u64::MAX, ETAG); + fx.add_listed("backups/shop/b.sql", b"", 2, "\"other\""); + let mut args = fx.args(); + args.inventory_only = true; + let err = fx.run(args).err().unwrap(); + assert!(format!("{err:#}").contains("overflow"), "{err:#}"); + } + + // ---- import ---- + + #[test] + fn importing_stores_each_archive_once_and_a_rerun_changes_nothing() { + let mut fx = Fixture::new(); + fx.add("backups/shop/a.sql", b"create table a();"); + fx.add("backups/shop/b.sql.gz", &gzip_header(b"compressed")); + let first = fx.run(fx.args()).unwrap(); + assert_eq!(statuses(&first), ["imported", "imported"]); + assert_eq!((fx.snapshots(), fx.receipts()), (2, 2)); + let stored = fx + .vault + .get_snapshot(first.objects[0].snapshot_id) + .unwrap() + .expect("stored under the reported id"); + assert_eq!(stored.manifest.orbit_id, Uuid::from_u128(7)); + assert_eq!(stored.manifest.orbit_name, "shop"); + assert_eq!(stored.manifest.provider, "postgres"); + assert_eq!(stored.manifest.labels, ["legacy-import"]); + assert_eq!(stored.manifest.restore_hints["format"], "plain"); + assert_eq!(stored.manifest.restore_hints["legacy"]["etag"], ETAG); + let gz = fx + .vault + .get_snapshot(first.objects[1].snapshot_id) + .unwrap() + .unwrap(); + assert_eq!(gz.manifest.restore_hints["format"], "sql_gzip"); + assert_eq!( + stored.taken_at, + "2026-01-02T03:04:05Z".parse::>().unwrap(), + "the snapshot keeps the original time, not the import time" + ); + let calls_before = fx.calls().len(); + let second = fx.run(fx.args()).unwrap(); + assert_eq!(statuses(&second), ["already_imported", "already_imported"]); + assert_eq!( + fx.calls().len(), + calls_before + 1, + "the rerun listed but downloaded nothing" + ); + assert_eq!((fx.snapshots(), fx.receipts()), (2, 2)); + assert_eq!( + first.objects[0].snapshot_id, second.objects[0].snapshot_id, + "ids are derived, so a rerun finds its own work" + ); + } + + #[test] + fn the_engine_orbit_and_endpoint_decide_the_mysql_manifest_and_the_snapshot_id() { + let mut fx = Fixture::new(); + fx.add("backups/shop/a.sql", b"create table a();"); + let mut mysql = fx.args(); + mysql.engine = Engine::Mysql; + let first = fx.run(mysql).unwrap(); + let stored = fx + .vault + .get_snapshot(first.objects[0].snapshot_id) + .unwrap() + .unwrap(); + assert_eq!(stored.manifest.provider, "mysql"); + // another orbit is a different import of the same bytes, not a duplicate + let mut other = fx.args(); + other.orbit_id = Uuid::from_u128(8); + let second = fx.run(other).unwrap(); + assert_ne!(first.objects[0].snapshot_id, second.objects[0].snapshot_id); + assert_eq!(statuses(&second), ["imported"]); + // so is another endpoint + let mut elsewhere = fx.args(); + elsewhere.endpoint = Some("https://s3.example.com".into()); + let third = fx.run(elsewhere).unwrap(); + assert_ne!(first.objects[0].snapshot_id, third.objects[0].snapshot_id); + assert_eq!(fx.snapshots(), 3); + } + + #[test] + fn an_object_that_changed_since_the_inventory_is_not_imported() { + for (what, etag, length, modified) in [ + ("etag", "\"changed\"", 17, WHEN), + ("length", ETAG, 18, WHEN), + ("time", ETAG, 17, "2026-01-02T03:04:06+00:00"), + ] { + let mut fx = Fixture::new(); + fx.add("backups/shop/a.sql", b"create table a();"); + fx.meta("backups/shop/a.sql", etag, length, modified); + let err = fx.run(fx.args()).err().unwrap(); + assert!( + format!("{err:#}").contains("changed since inventory"), + "{what}: {err:#}" + ); + assert_eq!((fx.snapshots(), fx.receipts()), (0, 0), "{what}"); + } + } + + #[test] + fn a_downloaded_file_of_the_wrong_size_is_not_imported() { + let mut fx = Fixture::new(); + fx.add("backups/shop/a.sql", b"create table a();"); + // the metadata agrees with the listing but fewer bytes arrived + fs::write(fx.fake().join("obj/a.sql"), b"create").unwrap(); + let err = fx.run(fx.args()).err().unwrap(); + assert!(format!("{err:#}").contains("changed since inventory")); + assert_eq!(fx.snapshots(), 0); + } + + #[test] + fn a_gzip_named_archive_must_start_with_the_gzip_signature() { + let mut fx = Fixture::new(); + fx.add("backups/shop/b.sql.gz", b"plainly not gzip"); + let err = fx.run(fx.args()).err().unwrap(); + assert!(format!("{err:#}").contains("gzip header"), "{err:#}"); + assert_eq!((fx.snapshots(), fx.receipts()), (0, 0)); + // a one-byte file cannot even hold the signature + let mut tiny = Fixture::new(); + tiny.add("backups/shop/t.sql.gz", &[0x1f]); + assert!(tiny.run(tiny.args()).is_err()); + assert_eq!(tiny.snapshots(), 0); + } + + #[test] + fn a_plain_sql_archive_is_not_inspected_for_a_signature() { + let mut fx = Fixture::new(); + fx.add("backups/shop/a.sql", &gzip_header(b"gz bytes in a .sql")); + let report = fx.run(fx.args()).unwrap(); + assert_eq!(statuses(&report), ["imported"]); + } + + #[test] + fn a_failed_download_stops_the_run_and_a_retry_resumes_where_it_left_off() { + let mut fx = Fixture::new(); + fx.add("backups/shop/a.sql", b"create table a();"); + fx.add("backups/shop/b.sql", b"create table b();"); + fs::write(fx.fake().join("get.fail.b.sql"), "").unwrap(); + let err = fx.run(fx.args()).err().unwrap(); + assert!(format!("{err:#}").contains("download failed"), "{err:#}"); + assert_eq!((fx.snapshots(), fx.receipts()), (1, 1), "a was kept"); + fs::remove_file(fx.fake().join("get.fail.b.sql")).unwrap(); + let retry = fx.run(fx.args()).unwrap(); + assert_eq!(statuses(&retry), ["already_imported", "imported"]); + assert_eq!((fx.snapshots(), fx.receipts()), (2, 2)); + } + + #[test] + fn a_receipt_keeps_an_archive_from_returning_after_its_snapshot_is_forgotten() { + let mut fx = Fixture::new(); + fx.add("backups/shop/a.sql", b"create table a();"); + let first = fx.run(fx.args()).unwrap(); + let id = first.objects[0].snapshot_id; + assert!(fx.vault.legacy_import_exists(id).unwrap()); + fx.vault.forget(&[id]).unwrap(); + assert_eq!(fx.snapshots(), 0); + let again = fx.run(fx.args()).unwrap(); + assert_eq!(statuses(&again), ["already_imported"]); + assert_eq!(fx.snapshots(), 0, "retention's decision is not undone"); + } + + // ---- the operator-history export ---- + + #[test] + fn a_history_export_must_be_a_sqlite_file() { + let fx = Fixture::new(); + let write = |name: &str, bytes: &[u8]| { + let path = fx.dir.path().join(name); + fs::write(&path, bytes).unwrap(); + path + }; + for (name, bytes) in [ + ("empty", &b""[..]), + ("short", b"SQLite"), + ("text", b"just a text file, long enough to read"), + ("near", b"SQLite format 3 not-nul-terminated"), + ("wal", b"SQLite format 4\0 later version"), + ] { + let mut args = fx.args(); + args.history = Some(write(name, bytes)); + assert!(fx.run(args).is_err(), "{name} must be refused"); + } + let mut missing = fx.args(); + missing.history = Some(Path::new("/definitely/not/here.sqlite").into()); + assert!(fx.run(missing).is_err()); + assert_eq!(fx.snapshots(), 0); + } + + #[test] + fn a_history_export_is_stored_once_and_identified_by_its_content() { + let fx = Fixture::new(); + let path = fx.dir.path().join("history.sqlite"); + fs::write(&path, b"SQLite format 3\0 first export").unwrap(); + let mut args = fx.args(); + args.history = Some(path.clone()); + let first = fx.run(args.clone()).unwrap(); + let id = first.history_snapshot_id.expect("history imported"); + assert_eq!(fx.snapshots(), 1); + let stored = fx.vault.get_snapshot(id).unwrap().unwrap(); + assert_eq!(stored.manifest.provider, "legacy-history"); + assert_eq!(stored.manifest.orbit_id, Uuid::nil()); + assert_eq!(stored.manifest.restore_hints["format"], "sqlite"); + // same bytes: same snapshot, nothing new stored + let second = fx.run(args.clone()).unwrap(); + assert_eq!(second.history_snapshot_id, Some(id)); + assert_eq!(fx.snapshots(), 1); + // different bytes: a different snapshot + fs::write(&path, b"SQLite format 3\0 second export").unwrap(); + let third = fx.run(args).unwrap(); + assert_ne!(third.history_snapshot_id, Some(id)); + assert_eq!(fx.snapshots(), 2); + } +}