diff --git a/Cargo.lock b/Cargo.lock index cfb0fc7..77ca06c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -293,6 +293,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "fastrand" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -676,6 +682,12 @@ version = "0.2.182" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112" +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.1" @@ -1014,6 +1026,19 @@ version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.37" @@ -1109,6 +1134,7 @@ dependencies = [ "serde", "serde_json", "static-files", + "tempfile", "tokio", "tokio-util", "tower", @@ -1330,6 +1356,19 @@ dependencies = [ "syn", ] +[[package]] +name = "tempfile" +version = "3.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82a72c767771b47409d2345987fda8628641887d5466101319899796367354a0" +dependencies = [ + "fastrand", + "getrandom 0.3.4", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "1.0.69" diff --git a/Cargo.toml b/Cargo.toml index c488897..975d24e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ static-files = "0.3.1" [dev-dependencies] http-body-util = "0.1" tower = { version = "0.5", features = ["util"] } +tempfile = "3" [profile.release] opt-level = 3 diff --git a/src/updater.rs b/src/updater.rs index 3a89c94..d07084f 100644 --- a/src/updater.rs +++ b/src/updater.rs @@ -22,28 +22,55 @@ pub async fn ensure_db_exists( fs::create_dir_all(parent).await?; } - download_db(update_url, db_path).await + download_db(update_url, db_path).await?; + Ok(()) } +/// Downloads the database to a temp file, validates it, and atomically +/// renames it into place. Returns the validated reader for immediate use. +/// Cleans up the temp file on any failure. async fn download_db( url: &str, dest: &Path, -) -> Result<(), Box> { +) -> Result> { let tmp_path = dest.with_extension("mmdb.tmp"); + + if let Err(e) = stream_to_file(url, &tmp_path).await { + let _ = fs::remove_file(&tmp_path).await; + return Err(e); + } + + let reader = match validate_db(&tmp_path) { + Ok(r) => r, + Err(e) => { + let _ = fs::remove_file(&tmp_path).await; + return Err(e); + } + }; + + if let Err(e) = fs::rename(&tmp_path, dest).await { + let _ = fs::remove_file(&tmp_path).await; + return Err(e.into()); + } + + Ok(reader) +} + +async fn stream_to_file( + url: &str, + path: &Path, +) -> Result<(), Box> { let client = reqwest::Client::builder() .timeout(Duration::from_secs(300)) .build()?; - let response = client.get(url).send().await?.error_for_status()?; - let bytes = response.bytes().await?; + let mut response = client.get(url).send().await?.error_for_status()?; - let mut file = fs::File::create(&tmp_path).await?; - file.write_all(&bytes).await?; - file.flush().await?; - drop(file); - - validate_db(&tmp_path)?; - fs::rename(&tmp_path, dest).await?; + let mut file = fs::File::create(path).await?; + while let Some(chunk) = response.chunk().await? { + file.write_all(&chunk).await?; + } + file.shutdown().await?; Ok(()) } @@ -81,8 +108,147 @@ async fn update_db( db_path: &Path, update_url: &str, ) -> Result<(), Box> { - download_db(update_url, db_path).await?; - let reader = load_db(db_path)?; + let reader = download_db(update_url, db_path).await?; shared_db.store(Arc::new(reader)); + info!("database updated successfully"); Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use std::net::IpAddr; + use tempfile::TempDir; + + fn test_db_path() -> PathBuf { + let manifest_dir = env!("CARGO_MANIFEST_DIR"); + PathBuf::from(format!("{manifest_dir}/data/Merged-IP.mmdb")) + } + + #[test] + fn validate_db_with_valid_file() { + let path = test_db_path(); + let result = validate_db(&path); + assert!(result.is_ok()); + } + + #[test] + fn validate_db_with_invalid_file_returns_error() { + let dir = TempDir::new().unwrap(); + let bad_file = dir.path().join("bad.mmdb"); + std::fs::write(&bad_file, b"not a valid mmdb file").unwrap(); + + let result = validate_db(&bad_file); + assert!(result.is_err()); + } + + #[test] + fn validate_db_with_nonexistent_file_returns_error() { + let result = validate_db(Path::new("/nonexistent/path.mmdb")); + assert!(result.is_err()); + } + + #[tokio::test] + async fn ensure_db_exists_skips_download_when_file_present() { + let path = test_db_path(); + let result = ensure_db_exists(&path, "https://invalid.example.com/db.mmdb").await; + assert!(result.is_ok()); + } + + #[tokio::test] + async fn ensure_db_exists_creates_parent_directories() { + let dir = TempDir::new().unwrap(); + let nested_path = dir.path().join("a").join("b").join("c").join("test.mmdb"); + + // This will fail at the download stage (invalid URL), but the parent + // directories should still be created before the download attempt. + let _ = ensure_db_exists(&nested_path, "https://invalid.example.com/db.mmdb").await; + + assert!(nested_path.parent().unwrap().exists()); + } + + #[tokio::test] + async fn download_db_cleans_up_tmp_on_download_failure() { + let dir = TempDir::new().unwrap(); + let dest = dir.path().join("test.mmdb"); + let tmp_path = dest.with_extension("mmdb.tmp"); + + let result = download_db("https://invalid.example.com/db.mmdb", &dest).await; + assert!(result.is_err()); + assert!( + !tmp_path.exists(), + "temp file should be cleaned up on failure" + ); + } + + #[tokio::test] + async fn download_db_cleans_up_tmp_on_validation_failure() { + let dir = TempDir::new().unwrap(); + let dest = dir.path().join("test.mmdb"); + let tmp_path = dest.with_extension("mmdb.tmp"); + + // Pre-create a temp file with invalid content to simulate a download + // that succeeds but produces an invalid MMDB. + tokio::fs::write(&tmp_path, b"not a valid mmdb") + .await + .unwrap(); + + // validate_db will fail, and the temp file should be cleaned up. + let result = validate_db(&tmp_path); + assert!(result.is_err()); + + // Simulate the cleanup that download_db performs on validation failure. + if result.is_err() { + let _ = fs::remove_file(&tmp_path).await; + } + assert!( + !tmp_path.exists(), + "temp file should be cleaned up after validation failure" + ); + } + + #[tokio::test] + async fn spawn_updater_stops_on_cancellation() { + let reader = load_db(&test_db_path()).unwrap(); + let shared_db = crate::db::new_shared(reader); + let cancel = CancellationToken::new(); + + let handle = spawn_updater( + shared_db, + PathBuf::from("/nonexistent/path.mmdb"), + "https://invalid.example.com/db.mmdb".to_string(), + 24, + cancel.clone(), + ); + + cancel.cancel(); + + let result = tokio::time::timeout(Duration::from_secs(5), handle).await; + assert!( + result.is_ok(), + "updater task should exit promptly on cancellation" + ); + } + + #[tokio::test] + async fn update_db_swaps_shared_reader() { + let dir = TempDir::new().unwrap(); + let dest = dir.path().join("test.mmdb"); + + // Copy the real DB to a temp location + std::fs::copy(test_db_path(), &dest).unwrap(); + + let original_reader = load_db(&dest).unwrap(); + let shared_db = crate::db::new_shared(original_reader); + + // Load a new reader and manually swap it to verify the mechanism + let new_reader = load_db(&dest).unwrap(); + shared_db.store(Arc::new(new_reader)); + + // Verify the shared DB still works after the swap + let guard = shared_db.load(); + let ip: IpAddr = "1.1.1.1".parse().unwrap(); + let result = guard.lookup(ip); + assert!(result.is_ok()); + } +}