diff --git a/.changeset/migrate-held-descriptor.md b/.changeset/migrate-held-descriptor.md new file mode 100644 index 000000000..58a6911ef --- /dev/null +++ b/.changeset/migrate-held-descriptor.md @@ -0,0 +1,11 @@ +--- +--- + +fix(migrate): open the migration target through a held descriptor rather than its path (#1162) + +The target directory is pinned before the store opens and named through its descriptor as +`/proc/self/fd/`, so the store's open, every manifest write and the summary all resolve to the +inode the security checks judged, however the operator's path is renamed afterwards. That narrows +the TOCTOU window between the check and the store's open; it does not close it, because heed +canonicalises the spelling before `mdb_env_open` (`heed-0.20.5/src/env.rs:239,305`), so the +mapping still resolves an absolute name. diff --git a/crates/nostream-cli/src/commands/migrate.rs b/crates/nostream-cli/src/commands/migrate.rs index 85ece3a1a..3833e1298 100644 --- a/crates/nostream-cli/src/commands/migrate.rs +++ b/crates/nostream-cli/src/commands/migrate.rs @@ -14,6 +14,8 @@ use std::fs; use std::io; use std::io::Write; #[cfg(unix)] +use std::os::fd::AsRawFd; +#[cfg(unix)] use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt}; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; @@ -45,6 +47,21 @@ pub struct MigrateOptions { /// `migrate pg-to-lmdb`: the copy, or the verification pass when `verify` is set. #[cfg(unix)] pub fn run(options: MigrateOptions, out: &mut dyn Write) -> Result { + run_with(options, out, || {}) +} + +/// The command over a step injected between the target's pin and the root derived from it. +/// +/// Nothing in the command renames its target, so production passes an empty closure; it is how a +/// test reaches the interval between the pin and the store's open, which no request the command +/// makes can block on — the same split `refuse_unsafe_target_for`'s `caller` makes for the uid +/// branch. +#[cfg(unix)] +fn run_with( + options: MigrateOptions, + out: &mut dyn Write, + mut after_pin: impl FnMut(), +) -> Result { let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() @@ -63,14 +80,20 @@ pub fn run(options: MigrateOptions, out: &mut dyn Write) -> Result Result Result Result Result { refuse_zero_batch(options)?; - let existing = read_manifest(&options.target)?; + let existing = read_manifest(root, &options.target)?; let mut manifest = existing.clone().unwrap_or_else(Manifest::fresh); // A store that already holds rows and carries no manifest is not this tool's. Copying over @@ -172,11 +204,11 @@ pub async fn migrate_with( // R6: written before the first `read_batch`, so a store this tool has begun to fill always // carries a manifest and a crash after the first batch resumes rather than being refused. if existing.is_none() { - write_manifest(&options.target, &manifest)?; + write_manifest(root, &options.target, &manifest)?; } if manifest.complete() { - return verify_with(target, options, out).await; + return verify_with(target, root, options, out).await; } let started = Instant::now(); @@ -225,7 +257,7 @@ pub async fn migrate_with( entry.checksum = sum.to_hex(); entry.after = after.as_deref().map(hex::encode).unwrap_or_default(); entry.complete = complete; - write_manifest(&options.target, &manifest)?; + write_manifest(root, &options.target, &manifest)?; if complete { break; @@ -237,13 +269,13 @@ pub async fn migrate_with( let rate = events.saturating_mul(1_000) / ms.max(1); writeln!(out, "Migrated {total} rows in {ms} ms").map_err(write_failed)?; writeln!(out, "Events throughput: {rate} events/s").map_err(write_failed)?; - // Where the copy landed: a target that was redirected or mistyped is visible here rather - // than as a store the operator cannot find. + // Where the copy landed, resolved through the root it wrote through: a target that was + // redirected or mistyped is visible here rather than as a store the operator cannot find. writeln!( out, "Store: {}", - fs::canonicalize(store_path(options)) - .unwrap_or_else(|_| store_path(options)) + fs::canonicalize(store_path(root)) + .unwrap_or_else(|_| store_path(root)) .display() ) .map_err(write_failed)?; @@ -256,13 +288,17 @@ pub async fn migrate_with( /// /// Every table is paged to its end, so a table longer than one page is read rather than cut at /// its first. The pass writes nothing to the store and never opens the source. +/// +/// `root` is the path the store and the manifest are read through: the target's own descriptor +/// spelling where procfs answers, and the operator's path otherwise. pub async fn verify_with( target: &dyn MigrationTarget, + root: &Path, options: &MigrateOptions, out: &mut dyn Write, ) -> Result { refuse_zero_batch(options)?; - let Some(manifest) = read_manifest(&options.target)? else { + let Some(manifest) = read_manifest(root, &options.target)? else { return no_manifest(&options.target, out); }; @@ -485,6 +521,16 @@ fn sum_words(limbs: &mut [u64; 4], words: &[[u8; 8]]) { } } +/// A message about `root` rewritten to name the target the operator typed. +/// +/// The root is the pin's descriptor spelling where procfs answers, and a descriptor number dies +/// with this process and means nothing in the operator's shell: every message the command builds +/// from a root-joined path passes through here first. Where the root is the target itself — no +/// procfs, or a caller that opens the operator's own path — this replaces the text with itself. +fn operator_message(message: String, root: &Path, target: &Path) -> String { + message.replace(&root.display().to_string(), &target.display().to_string()) +} + /// The manifest's path under a target root. fn manifest_path(target: &Path) -> PathBuf { target.join(MANIFEST_FILE) @@ -499,22 +545,31 @@ fn named_list(names: &[&str]) -> String { } } -/// The manifest at the target, or `None` when there is none. -fn read_manifest(target: &Path) -> Result, CliError> { - let path = manifest_path(target); +/// The manifest at `root`, or `None` when there is none. +/// +/// `target` is the path the operator named: the root's spelling is translated back to it in every +/// message here, because a descriptor number means nothing in their shell. +fn read_manifest(root: &Path, target: &Path) -> Result, CliError> { + let shown = |message: String| operator_message(message, root, target); + let path = manifest_path(root); let bytes = match fs::read(&path) { Ok(bytes) => bytes, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(error) => return Err(CliError::Migrate(format!("{}: {error}", path.display()))), + Err(error) => { + return Err(CliError::Migrate(shown(format!( + "{}: {error}", + path.display() + )))); + } }; let manifest: Manifest = serde_json::from_slice(&bytes) - .map_err(|error| CliError::Migrate(format!("{}: {error}", path.display())))?; + .map_err(|error| CliError::Migrate(shown(format!("{}: {error}", path.display()))))?; if manifest.format != MANIFEST_FORMAT { - return Err(CliError::Migrate(format!( + return Err(CliError::Migrate(shown(format!( "{}: manifest format {} is not supported; this tool reads and writes {MANIFEST_FORMAT}", path.display(), manifest.format - ))); + )))); } // A manifest is this tool's only when it describes all nine tables and the two it leaves @@ -529,21 +584,21 @@ fn read_manifest(target: &Path) -> Result, CliError> { if named != expected { let missing: Vec<&str> = expected.difference(&named).copied().collect(); let unknown: Vec<&str> = named.difference(&expected).copied().collect(); - return Err(CliError::Migrate(format!( + return Err(CliError::Migrate(shown(format!( "{}: the manifest does not name this tool's nine tables (missing: {}; unknown: {})", path.display(), named_list(&missing), named_list(&unknown) - ))); + )))); } if manifest.not_migrated != MigratedTable::NOT_MIGRATED { let named: Vec<&str> = manifest.not_migrated.iter().map(String::as_str).collect(); - return Err(CliError::Migrate(format!( + return Err(CliError::Migrate(shown(format!( "{}: the manifest's not_migrated is not the two tables this tool leaves alone (it \ names: {})", path.display(), named_list(&named) - ))); + )))); } Ok(Some(manifest)) } @@ -556,20 +611,24 @@ fn read_manifest(target: &Path) -> Result, CliError> { /// world-readable copy of it; the store's own files are heed's 0600. Creating exclusively /// refuses an entry already at the temporary path, which is how a planted symlink would /// otherwise redirect the write and be renamed into place. -fn write_manifest(target: &Path, manifest: &Manifest) -> Result<(), CliError> { - let path = manifest_path(target); +/// +/// `target` is the path the operator named: the root's spelling is translated back to it in every +/// message here. +fn write_manifest(root: &Path, target: &Path, manifest: &Manifest) -> Result<(), CliError> { + let shown = |message: String| operator_message(message, root, target); + let path = manifest_path(root); let temporary = path.with_extension("json.tmp"); let bytes = serde_json::to_vec_pretty(manifest) - .map_err(|error| CliError::Migrate(format!("{}: {error}", path.display())))?; + .map_err(|error| CliError::Migrate(shown(format!("{}: {error}", path.display()))))?; match fs::remove_file(&temporary) { Ok(()) => {} Err(error) if error.kind() == io::ErrorKind::NotFound => {} Err(error) => { - return Err(CliError::Migrate(format!( + return Err(CliError::Migrate(shown(format!( "{}: {error}", temporary.display() - ))); + )))); } } @@ -584,28 +643,29 @@ fn write_manifest(target: &Path, manifest: &Manifest) -> Result<(), CliError> { open_options.mode(0o600); let mut file = open_options .open(&temporary) - .map_err(|error| CliError::Migrate(format!("{}: {error}", temporary.display())))?; + .map_err(|error| CliError::Migrate(shown(format!("{}: {error}", temporary.display()))))?; file.write_all(&bytes) .and_then(|()| file.sync_all()) - .map_err(|error| CliError::Migrate(format!("{}: {error}", temporary.display())))?; + .map_err(|error| CliError::Migrate(shown(format!("{}: {error}", temporary.display()))))?; drop(file); fs::rename(&temporary, &path) - .map_err(|error| CliError::Migrate(format!("{}: {error}", path.display())))?; - sync_directory_of(&path) + .map_err(|error| CliError::Migrate(shown(format!("{}: {error}", path.display()))))?; + sync_directory_of(&path, root, target) } /// Makes a rename inside a directory durable. /// /// A rename changes the directory, not the file, and an unsynced directory can lose that /// entry on power loss even though the file's own content was synced. -fn sync_directory_of(path: &Path) -> Result<(), CliError> { +fn sync_directory_of(path: &Path, root: &Path, target: &Path) -> Result<(), CliError> { + let shown = |message: String| operator_message(message, root, target); let parent = path.parent().unwrap_or_else(|| Path::new(".")); let directory = fs::File::open(parent) - .map_err(|error| CliError::Migrate(format!("{}: {error}", parent.display())))?; + .map_err(|error| CliError::Migrate(shown(format!("{}: {error}", parent.display()))))?; directory .sync_all() - .map_err(|error| CliError::Migrate(format!("{}: {error}", parent.display()))) + .map_err(|error| CliError::Migrate(shown(format!("{}: {error}", parent.display())))) } /// The source the run reads, as the setting that named it: `db.internal:5432/nostream (from @@ -761,7 +821,7 @@ fn effective_uid() -> Option { #[cfg(unix)] fn refuse_unsafe_target_for(options: &MigrateOptions, caller: Option) -> Result<(), CliError> { - for path in [&options.target, &store_path(options)] { + for path in [&options.target, &store_path(&options.target)] { let metadata = match fs::symlink_metadata(path) { Ok(metadata) => metadata, Err(error) if error.kind() == io::ErrorKind::NotFound => continue, @@ -919,13 +979,35 @@ fn refuse_swappable_ancestry(target: &Path, caller: Option) -> Result<(), C } } -/// A handle and device/inode pin that closes the TOCTOU window between target creation -/// and store open. Holding the file handle keeps the directory inode active, and verify -/// ensures the directory opened by LMDB is the exact inode judged by the security checks. +/// The root `path` is opened through: the descriptor's own procfs spelling where procfs +/// answers, and `path` unchanged where it does not. +/// +/// The answer is a parameter rather than a probe, so a test can drive the branch a host without +/// `/proc` would take — the same split `refuse_unsafe_target_for` makes for the caller's uid. +#[cfg(unix)] +fn root_for(handle: &fs::File, path: &Path, procfs: bool) -> PathBuf { + if procfs { + PathBuf::from(format!("/proc/self/fd/{}", handle.as_raw_fd())) + } else { + path.to_path_buf() + } +} + +/// A handle and device/inode pin on the target directory, taken before the store opens. +/// +/// Holding the handle keeps the directory inode alive and names it through `root`, so the store +/// and every manifest write after the pin resolve to the inode the security checks judged, +/// however the operator's path is renamed afterwards. That narrows the TOCTOU window between +/// target creation and store open and does not close it: heed canonicalises the spelling before +/// `mdb_env_open` (`heed-0.20.5/src/env.rs:239,305`), so the mapping itself still resolves a +/// name. `verify` is the post-open cross-check of the operator's path, and the only check where +/// procfs is absent. #[cfg(unix)] #[derive(Debug)] struct TargetPin { - _handle: fs::File, + handle: fs::File, + /// The path the pin was taken at, which is the root where procfs does not answer. + path: PathBuf, dev: u64, ino: u64, } @@ -939,12 +1021,23 @@ impl TargetPin { .metadata() .map_err(|error| CliError::Migrate(format!("{}: {error}", path.display())))?; Ok(Self { - _handle: file, + handle: file, + path: path.to_path_buf(), dev: metadata.dev(), ino: metadata.ino(), }) } + /// The root the store and the manifest are opened through: the pin's own descriptor where + /// procfs answers, and the path the pin was taken at otherwise. + fn root(&self) -> PathBuf { + root_for( + &self.handle, + &self.path, + Path::new("/proc/self/fd").is_dir(), + ) + } + fn verify(&self, path: &Path) -> Result<(), CliError> { let metadata = fs::symlink_metadata(path) .map_err(|error| CliError::Migrate(format!("{}: {error}", path.display())))?; @@ -964,12 +1057,20 @@ impl TargetPin { #[cfg(not(unix))] #[derive(Debug)] -struct TargetPin; +struct TargetPin { + path: PathBuf, +} #[cfg(not(unix))] impl TargetPin { - fn pin(_path: &Path) -> Result { - Ok(Self) + fn pin(path: &Path) -> Result { + Ok(Self { + path: path.to_path_buf(), + }) + } + + fn root(&self) -> PathBuf { + self.path.clone() } fn verify(&self, _path: &Path) -> Result<(), CliError> { @@ -978,7 +1079,8 @@ impl TargetPin { } /// Creates the target when it is missing, judges what is on disk, and pins the directory -/// handle to close the TOCTOU window before the store opens. +/// handle the store is opened through. The pin narrows, and does not close, the TOCTOU window +/// between this check and the store's open. #[cfg(unix)] fn create_target(options: &MigrateOptions) -> Result { fs::DirBuilder::new() @@ -1015,7 +1117,7 @@ fn no_store(options: &MigrateOptions, out: &mut dyn Write) -> Result Result PathBuf { - nostream_storage::backend::store_dir(&options.target) +/// The store's directory under a root: the environment `LmdbBackend::open` would create. +fn store_path(root: &Path) -> PathBuf { + nostream_storage::backend::store_dir(root) } /// Whether the target already holds an LMDB environment, asked the way R8 asks it: `/ @@ -1084,7 +1186,7 @@ fn check_resume_store( return Err(CliError::Migrate(format!( "No store at {}: the manifest records progress, so a re-run resumes once the store is \ back. To start over, use a fresh --target, or remove {} and the store together", - store_path(options).display(), + store_path(&options.target).display(), manifest_path(&options.target).display() ))); } @@ -1092,17 +1194,20 @@ fn check_resume_store( } /// Opens the store a copy writes, creating it when it is not there. -async fn open_target(root: &Path) -> Result { +/// +/// A failure names `target`, the path the operator typed: the open went through `root`, whose +/// spelling means nothing outside this process. +async fn open_target(root: &Path, target: &Path) -> Result { LmdbBackend::open(root) .await - .map_err(|error| CliError::Migrate(error.to_string())) + .map_err(|error| CliError::Migrate(operator_message(error.to_string(), root, target))) } /// Opens the store a verify reads, read-only and creating nothing (R8). -async fn open_existing_target(root: &Path) -> Result { +async fn open_existing_target(root: &Path, target: &Path) -> Result { LmdbBackend::open_existing(root) .await - .map_err(|error| CliError::Migrate(error.to_string())) + .map_err(|error| CliError::Migrate(operator_message(error.to_string(), root, target))) } /// A failure of one table's read or write, naming the table so an operator knows which row @@ -1329,7 +1434,7 @@ mod tests { check_resume_store(Some(&manifest), &options) .expect("the store the manifest needs is there"); - open_target(&options.target) + open_target(&options.target, &options.target) .await .expect("the writable open after the check succeeds"); } @@ -1404,4 +1509,191 @@ mod tests { "{error}" ); } + + /// A host with procfs names the pinned directory by its descriptor, and one without it has + /// nothing but the path: both halves are the `root_for` branch, and the third assertion is + /// the wiring from the real probe to the helper on a host where it answers. + #[test] + #[cfg(unix)] + #[allow(clippy::expect_used)] + fn the_root_is_the_descriptor_when_procfs_answers_and_the_path_otherwise() { + let temporary = tempfile::tempdir().expect("a temporary directory"); + let target = temporary.path().join("target"); + fs::create_dir(&target).expect("the target is created"); + let handle = fs::File::open(&target).expect("the target is opened"); + + assert_eq!( + root_for(&handle, &target, true), + PathBuf::from(format!("/proc/self/fd/{}", handle.as_raw_fd())), + "the descriptor branch names the handle's own number" + ); + assert_eq!( + root_for(&handle, &target, false), + target, + "without procfs the operator's path is the root, unchanged" + ); + + if Path::new("/proc/self/fd").is_dir() { + let pin = TargetPin::pin(&target).expect("the target is pinned"); + assert_eq!( + pin.root(), + PathBuf::from(format!("/proc/self/fd/{}", pin.handle.as_raw_fd())), + "the pin's root is its own descriptor" + ); + } + } + + /// The swap this job exists for: the pin is taken, the target is renamed away through its + /// parent and a fresh directory takes its name, and the store is then opened through the + /// descriptor. The store lands in the directory the pin holds whatever the operator's path + /// now names, and `verify` refuses the path that no longer denotes it. + #[cfg(target_os = "linux")] + #[tokio::test] + #[allow(clippy::expect_used)] + async fn a_target_swapped_after_the_pin_keeps_the_store_in_the_pinned_directory() { + let temporary = tempfile::tempdir().expect("a temporary directory"); + let target = temporary.path().join("target"); + fs::create_dir(&target).expect("the target is created"); + let options = MigrateOptions { + target: target.clone(), + batch_size: 1_000, + verify: false, + }; + let pin = create_target(&options).expect("the target is pinned"); + + let moved = temporary.path().join("moved"); + fs::rename(&target, &moved).expect("the target is renamed away"); + fs::create_dir(&target).expect("the replacement is created"); + + open_target(&pin.root(), &target) + .await + .expect("the store opens through the descriptor"); + + assert!( + fs::metadata(moved.join("lmdb").join("data.mdb")).is_ok(), + "the store landed in the directory the pin holds" + ); + assert!( + fs::metadata(target.join("lmdb")).is_err(), + "and nothing was written into the replacement" + ); + let error = pin + .verify(&target) + .expect_err("the operator's path no longer names the pinned inode"); + assert!( + error + .to_string() + .contains("replaced between check and open"), + "{error}" + ); + } + + /// Copies an environment's files into a directory of their own, so the copy is an inode no + /// environment in this process has opened: heed registers an environment by its canonical + /// path, and a second open of one path with different flags is refused. + #[allow(clippy::expect_used)] + fn copy_store(from: &Path, into: &Path) { + fs::create_dir_all(into).expect("the copied store directory is made"); + for entry in fs::read_dir(from).expect("the store directory reads") { + let entry = entry.expect("an entry reads"); + fs::copy(entry.path(), into.join(entry.file_name())).expect("the store file is copied"); + } + } + + /// An environment with no rows and a manifest that records it complete, both written where + /// the command is not going to look: a test copies them to its target, so what the command + /// opens there is an inode this process has never opened. + #[allow(clippy::expect_used)] + fn prepared_migration() -> tempfile::TempDir { + let prepared = tempfile::tempdir().expect("a temporary directory"); + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("the test runtime builds") + .block_on(async { + LmdbBackend::open(prepared.path()) + .await + .expect("the store opens"); + }); + let mut manifest = Manifest::fresh(); + for table in MigratedTable::ALL { + manifest.entry(table).complete = true; + } + write_manifest(prepared.path(), prepared.path(), &manifest) + .expect("the manifest is written"); + prepared + } + + /// Runs the command over a target that is swapped in the interval between its pin and the + /// store's open: the target is renamed away through its parent, and a fresh directory takes + /// its name holding a store of its own. + /// + /// The step also asserts that it ran: both tests below would pass on an unswapped target, so + /// a deleted `after_pin()` call would leave them green and the seam unguarded. + #[allow(clippy::expect_used)] + fn run_over_a_swap(verify: bool) -> (CommandOutput, String) { + let prepared = prepared_migration(); + let temporary = tempfile::tempdir().expect("a temporary directory"); + let target = temporary.path().join("target"); + let moved = temporary.path().join("moved"); + copy_store(&prepared.path().join("lmdb"), &target.join("lmdb")); + fs::copy( + prepared.path().join(MANIFEST_FILE), + target.join(MANIFEST_FILE), + ) + .expect("the manifest is copied"); + + let stepped = std::cell::Cell::new(false); + let mut out = Vec::new(); + let output = run_with( + MigrateOptions { + target: target.clone(), + batch_size: 1_000, + verify, + }, + &mut out, + || { + stepped.set(true); + fs::rename(&target, &moved).expect("the target is renamed away"); + copy_store(&prepared.path().join("lmdb"), &target.join("lmdb")); + }, + ) + .expect("the command answers rather than failing"); + assert!( + stepped.get(), + "the command ran the step between the pin and the store's open" + ); + ( + output, + String::from_utf8(out).expect("the command writes utf-8"), + ) + } + + /// `run`'s `--verify` arm takes its own pin, and this is the half no grep can show: only the + /// pinned directory holds the manifest, so an arm that opened the bare path answers + /// `No manifest at …` and exits 1 where this exits 0. + #[cfg(target_os = "linux")] + #[test] + #[allow(clippy::expect_used)] + fn the_verify_arm_reads_the_store_its_pin_names_rather_than_the_replacement() { + let (output, text) = run_over_a_swap(true); + assert_eq!(output.exit_code, 0, "got:\n{text}"); + assert!( + text.contains("Verified 9 tables"), + "the arm read the store its pin names, got:\n{text}" + ); + } + + /// The same swap on the other arm that verifies: a complete manifest with no `--verify` set. + #[cfg(target_os = "linux")] + #[test] + #[allow(clippy::expect_used)] + fn the_completed_manifest_arm_reads_the_store_its_pin_names_rather_than_the_replacement() { + let (output, text) = run_over_a_swap(false); + assert_eq!(output.exit_code, 0, "got:\n{text}"); + assert!( + text.contains("Verified 9 tables"), + "the arm read the store its pin names, got:\n{text}" + ); + } } diff --git a/crates/nostream-cli/tests/migrate_cli.rs b/crates/nostream-cli/tests/migrate_cli.rs index 834a6797c..9842ecacf 100644 --- a/crates/nostream-cli/tests/migrate_cli.rs +++ b/crates/nostream-cli/tests/migrate_cli.rs @@ -13,6 +13,7 @@ #![cfg(unix)] use std::collections::BTreeMap; +use std::os::fd::AsRawFd; use std::process::Command; use std::sync::Mutex; use std::time::Duration; @@ -415,7 +416,7 @@ async fn a_clean_run_copies_every_table_and_a_second_run_writes_nothing() { let options = options(directory.path(), 1_000); let mut out = Vec::new(); - let output = migrate::migrate_with(&source, &target, &options, &mut out) + let output = migrate::migrate_with(&source, &target, &options.target, &options, &mut out) .await .expect("the copy runs"); assert_eq!(output.exit_code, 0); @@ -532,7 +533,7 @@ async fn a_clean_run_copies_every_table_and_a_second_run_writes_nothing() { .expect("the usage reads") .used_bytes; let mut out = Vec::new(); - let output = migrate::migrate_with(&counting, &target, &options, &mut out) + let output = migrate::migrate_with(&counting, &target, &options.target, &options, &mut out) .await .expect("the second run succeeds"); assert_eq!(output.exit_code, 0); @@ -601,6 +602,7 @@ async fn an_interrupted_run_resumes_to_the_clean_run_manifest() { migrate::migrate_with( &StubSource::new(source_rows()), &clean_target, + &clean_options.target, &clean_options, &mut Vec::new(), ) @@ -615,9 +617,15 @@ async fn an_interrupted_run_resumes_to_the_clean_run_manifest() { .expect("the store opens"); let options = options(directory.path(), 1); let failing = StubSource::failing_at(source_rows(), 1); - let error = migrate::migrate_with(&failing, &target, &options, &mut Vec::new()) - .await - .expect_err("the second read fails"); + let error = migrate::migrate_with( + &failing, + &target, + &options.target, + &options, + &mut Vec::new(), + ) + .await + .expect_err("the second read fails"); assert!( matches!(error, nostream_cli::CliError::Migrate(_)), "a migration failure is the variant `main` prints as `Migration failed:` and exits 1 for" @@ -637,7 +645,7 @@ async fn an_interrupted_run_resumes_to_the_clean_run_manifest() { // The healthy source over the same target, at --batch-size 1 too. let resumed = StubSource::new(source_rows()); let mut out = Vec::new(); - let output = migrate::migrate_with(&resumed, &target, &options, &mut out) + let output = migrate::migrate_with(&resumed, &target, &options.target, &options, &mut out) .await .expect("the resumed run succeeds"); let calls = resumed.calls(); @@ -668,10 +676,12 @@ async fn manifest_of(rows: Vec) -> Value { let target = LmdbBackend::open(directory.path()) .await .expect("the store opens"); + let options = options(directory.path(), 1_000); migrate::migrate_with( &StubSource::new(rows), &target, - &options(directory.path(), 1_000), + &options.target, + &options, &mut Vec::new(), ) .await @@ -741,9 +751,15 @@ async fn verify_accepts_the_runs_own_target_and_rejects_a_changed_row() { .collect(); // Five events at --batch-size 2 is three pages, so a verify that reads one page sees two. let options = options(directory.path(), 2); - migrate::migrate_with(&StubSource::new(rows), &target, &options, &mut Vec::new()) - .await - .expect("the copy succeeds"); + migrate::migrate_with( + &StubSource::new(rows), + &target, + &options.target, + &options, + &mut Vec::new(), + ) + .await + .expect("the copy succeeds"); let before = target .map_usage() @@ -751,7 +767,7 @@ async fn verify_accepts_the_runs_own_target_and_rejects_a_changed_row() { .expect("the usage reads") .used_bytes; let mut out = Vec::new(); - let output = migrate::verify_with(&target, &options, &mut out) + let output = migrate::verify_with(&target, &options.target, &options, &mut out) .await .expect("the verify runs"); assert_eq!(output.exit_code, 0); @@ -766,7 +782,7 @@ async fn verify_accepts_the_runs_own_target_and_rejects_a_changed_row() { .expect("the changed row is written"); let mut out = Vec::new(); - let output = migrate::verify_with(&target, &options, &mut out) + let output = migrate::verify_with(&target, &options.target, &options, &mut out) .await .expect("the verify runs"); assert_eq!(output.exit_code, 1); @@ -854,6 +870,7 @@ fn verify_creates_nothing_and_rejects_a_target_with_no_store_or_no_manifest() { migrate::migrate_with( &StubSource::new(source_rows()), &target, + ©.target, ©, &mut Vec::new(), ) @@ -933,10 +950,12 @@ async fn a_crash_between_the_first_batch_and_the_manifest_write_resumes_to_the_c let clean_store = LmdbBackend::open(clean.path()) .await .expect("the store opens"); + let clean_options = options(clean.path(), 1_000); migrate::migrate_with( &StubSource::new(source_rows()), &clean_store, - &options(clean.path(), 1_000), + &clean_options.target, + &clean_options, &mut Vec::new(), ) .await @@ -959,6 +978,7 @@ async fn a_crash_between_the_first_batch_and_the_manifest_write_resumes_to_the_c let error = migrate::migrate_with( &StubSource::failing_at(source_rows(), 0), &store, + &options.target, &options, &mut Vec::new(), ) @@ -997,9 +1017,10 @@ async fn a_crash_between_the_first_batch_and_the_manifest_write_resumes_to_the_c // The resume replays that batch from the fresh manifest's own cursor. let resumed = StubSource::new(source_rows()); - let output = migrate::migrate_with(&resumed, &store, &options, &mut Vec::new()) - .await - .expect("the resume succeeds"); + let output = + migrate::migrate_with(&resumed, &store, &options.target, &options, &mut Vec::new()) + .await + .expect("the resume succeeds"); assert_eq!(output.exit_code, 0); assert_eq!( resumed.calls().first(), @@ -1102,9 +1123,15 @@ async fn the_run_prints_a_rate_consistent_with_its_own_events_and_milliseconds() let options = options(directory.path(), 200); let mut out = Vec::new(); - migrate::migrate_with(&StubSource::new(rows), &target, &options, &mut out) - .await - .expect("the copy succeeds"); + migrate::migrate_with( + &StubSource::new(rows), + &target, + &options.target, + &options, + &mut out, + ) + .await + .expect("the copy succeeds"); let (rows, ms, rate, store) = summary(&output_text(out)); assert_eq!( store, @@ -1159,6 +1186,7 @@ async fn a_migrated_event_keeps_first_seen_deduplication_and_its_deleted_state() migrate::migrate_with( &StubSource::new(rows.clone()), &target, + &options(directory.path(), 1_000).target, &options(directory.path(), 1_000), &mut Vec::new(), ) @@ -1265,9 +1293,15 @@ async fn a_refused_row_stops_the_run_and_keeps_the_resume_point() { .collect(); // The refused row is in the second batch of two. let options = options(directory.path(), 2); - let error = migrate::migrate_with(&StubSource::new(rows), &target, &options, &mut Vec::new()) - .await - .expect_err("the refused key fails the batch"); + let error = migrate::migrate_with( + &StubSource::new(rows), + &target, + &options.target, + &options, + &mut Vec::new(), + ) + .await + .expect_err("the refused key fails the batch"); assert!( matches!(error, nostream_cli::CliError::Migrate(_)), "a migration failure is the variant `main` prints as `Migration failed:` and exits 1 for" @@ -1293,9 +1327,15 @@ async fn a_refused_row_stops_the_run_and_keeps_the_resume_point() { // The resume point is usable: a healthy source continues where the refused row stopped. let resumed = StubSource::new(vec![MigrationRow::Event(event_record(3, "fine"))]); - let output = migrate::migrate_with(&resumed, &target, &options, &mut Vec::new()) - .await - .expect("the run resumes after the refusal"); + let output = migrate::migrate_with( + &resumed, + &target, + &options.target, + &options, + &mut Vec::new(), + ) + .await + .expect("the run resumes after the refusal"); assert_eq!(output.exit_code, 0); assert_eq!(resumed.calls()[0].0, MigratedTable::Events); assert_eq!( @@ -1330,6 +1370,7 @@ async fn a_target_with_rows_and_no_manifest_is_refused() { let error = migrate::migrate_with( &source, &target, + &options(directory.path(), 1_000).target, &options(directory.path(), 1_000), &mut Vec::new(), ) @@ -1372,6 +1413,7 @@ async fn a_target_with_rows_and_no_manifest_is_refused() { let output = migrate::migrate_with( &StubSource::new(source_rows()), &clean, + &options(empty.path(), 1_000).target, &options(empty.path(), 1_000), &mut Vec::new(), ) @@ -1409,6 +1451,7 @@ async fn a_manifest_of_another_format_is_refused_before_anything_is_written() { let error = migrate::migrate_with( &source, &target, + &options(directory.path(), 1_000).target, &options(directory.path(), 1_000), &mut Vec::new(), ) @@ -1428,9 +1471,15 @@ async fn a_manifest_of_another_format_is_refused_before_anything_is_written() { "nothing was written" ); - let error = migrate::verify_with(&target, &options(directory.path(), 1_000), &mut Vec::new()) - .await - .expect_err("format 2 is refused by verify too"); + let verify_options = options(directory.path(), 1_000); + let error = migrate::verify_with( + &target, + &verify_options.target, + &verify_options, + &mut Vec::new(), + ) + .await + .expect_err("format 2 is refused by verify too"); assert!(error.to_string().contains("format 2"), "{error}"); } @@ -1457,6 +1506,7 @@ async fn a_manifest_that_does_not_name_the_nine_tables_is_refused() { let error = migrate::migrate_with( &source, &target, + &options(directory.path(), 1_000).target, &options(directory.path(), 1_000), &mut Vec::new(), ) @@ -1495,6 +1545,7 @@ async fn a_manifest_that_does_not_name_the_nine_tables_is_refused() { let error = migrate::migrate_with( &StubSource::new(source_rows()), &target, + &options(directory.path(), 1_000).target, &options(directory.path(), 1_000), &mut Vec::new(), ) @@ -1530,6 +1581,7 @@ async fn a_manifest_that_does_not_name_the_nine_tables_is_refused() { let error = migrate::migrate_with( &StubSource::new(source_rows()), &target, + &options(directory.path(), 1_000).target, &options(directory.path(), 1_000), &mut Vec::new(), ) @@ -1550,19 +1602,15 @@ async fn a_zero_batch_is_refused_instead_of_looping() { .await .expect("the store opens"); + let zero = options(directory.path(), 0); let source = StubSource::new(source_rows()); - let error = migrate::migrate_with( - &source, - &target, - &options(directory.path(), 0), - &mut Vec::new(), - ) - .await - .expect_err("a batch of zero is refused"); + let error = migrate::migrate_with(&source, &target, &zero.target, &zero, &mut Vec::new()) + .await + .expect_err("a batch of zero is refused"); assert!(error.to_string().contains("--batch-size"), "{error}"); assert_eq!(source.calls().len(), 0, "nothing was read"); - let error = migrate::verify_with(&target, &options(directory.path(), 0), &mut Vec::new()) + let error = migrate::verify_with(&target, &zero.target, &zero, &mut Vec::new()) .await .expect_err("a batch of zero is refused by verify too"); assert!(error.to_string().contains("--batch-size"), "{error}"); @@ -1760,6 +1808,7 @@ fn a_manifest_that_records_progress_over_a_missing_store_is_refused() { migrate::migrate_with( &StubSource::failing_at(source_rows(), 1), &target, + &partial_options.target, &partial_options, &mut Vec::new(), ) @@ -1840,6 +1889,7 @@ fn a_manifest_that_records_progress_over_a_missing_store_is_refused() { let output = migrate::migrate_with( &StubSource::new(source_rows()), &target, + ©.target, ©, &mut Vec::new(), ) @@ -1912,6 +1962,7 @@ fn the_binary_verifies_a_store_this_process_wrote() { let output = migrate::migrate_with( &StubSource::new(source_rows()), &target, + &options(directory.path(), 1_000).target, &options(directory.path(), 1_000), &mut Vec::new(), ) @@ -1962,6 +2013,7 @@ async fn the_row_checksum_matches_an_independent_computation() { migrate::migrate_with( &source, &target, + &options(directory.path(), 1_000).target, &options(directory.path(), 1_000), &mut Vec::new(), ) @@ -2012,6 +2064,7 @@ async fn a_manifest_that_counts_rows_over_a_store_without_them_is_refused() { let error = migrate::migrate_with( &StubSource::new(source_rows()), &target, + &options(directory.path(), 1_000).target, &options(directory.path(), 1_000), &mut Vec::new(), ) @@ -2046,6 +2099,7 @@ async fn the_manifest_is_private_and_its_temporary_path_is_not_followed() { migrate::migrate_with( &StubSource::new(vec![MigrationRow::Event(event_record(1, "golden"))]), &target, + &options(directory.path(), 1_000).target, &options(directory.path(), 1_000), &mut Vec::new(), ) @@ -2504,6 +2558,7 @@ async fn the_summary_names_the_canonical_store_not_the_argument() { migrate::migrate_with( &StubSource::new(vec![MigrationRow::Event(event_record(1, "golden"))]), &target, + &options(&argument, 1_000).target, &options(&argument, 1_000), &mut out, ) @@ -2574,3 +2629,138 @@ fn a_schemeless_source_uri_is_refused() { "the password is not printed: {stderr}" ); } + +// --------------------------------------------------------------------------------------- +// The descriptor: the store, the manifest and the summary follow the pinned directory. +// --------------------------------------------------------------------------------------- + +// The attack's own order, so the store's open is the one under test: the target is pinned, the +// pin's descriptor becomes the root, the target is renamed away through its parent and a fresh +// directory takes the name, and only then is the store opened. A path-based open would put the +// store, the manifest and the summary in the replacement. +#[cfg(target_os = "linux")] +#[tokio::test] +async fn a_copy_through_the_descriptor_writes_the_manifest_into_the_pinned_directory() { + use std::os::unix::fs::PermissionsExt; + + let temporary = tempfile::tempdir().expect("a temporary directory"); + let target = temporary.path().join("target"); + std::fs::create_dir(&target).expect("the target is created"); + let pin = std::fs::File::open(&target).expect("the target is pinned"); + let root = std::path::PathBuf::from(format!("/proc/self/fd/{}", pin.as_raw_fd())); + + let moved = temporary.path().join("moved"); + std::fs::rename(&target, &moved).expect("the target is renamed away"); + std::fs::create_dir(&target).expect("the replacement is created"); + + let store = LmdbBackend::open(&root).await.expect("the store opens"); + let mut out = Vec::new(); + let output = migrate::migrate_with( + &StubSource::new(source_rows()), + &store, + &root, + &options(&target, 1_000), + &mut out, + ) + .await + .expect("the copy succeeds"); + + // The narrowing, recorded rather than tested: heed resolved the descriptor spelling to an + // absolute name before it mapped the store, so the environment is named by the pinned + // directory's current path. + let landed = std::fs::canonicalize(moved.join("lmdb")).expect("the store exists"); + assert_eq!(store.env().path(), landed.as_path()); + assert_eq!(output.exit_code, 0); + let manifest = std::fs::symlink_metadata(moved.join("migration-manifest.json")) + .expect("the manifest is in the pinned directory"); + assert!( + !manifest.file_type().is_symlink(), + "the manifest is a file, not a link" + ); + assert_eq!( + manifest.permissions().mode() & 0o777, + 0o600, + "the manifest is readable by its owner alone" + ); + assert!( + entries(&target).is_empty(), + "nothing was written into the replacement" + ); + let text = output_text(out); + assert!( + text.contains(&format!("Store: {}", landed.display())), + "the summary names where the store landed, got:\n{text}" + ); +} + +// The verify half: the manifest it reads is the pinned directory's, which after the swap the +// operator's path no longer holds. A path-based verify answers `No manifest at …` here. +#[cfg(target_os = "linux")] +#[tokio::test] +async fn a_verify_through_the_descriptor_reads_the_pinned_store() { + let temporary = tempfile::tempdir().expect("a temporary directory"); + let target = temporary.path().join("target"); + std::fs::create_dir(&target).expect("the target is created"); + let pin = std::fs::File::open(&target).expect("the target is pinned"); + let root = std::path::PathBuf::from(format!("/proc/self/fd/{}", pin.as_raw_fd())); + + let store = LmdbBackend::open(&root).await.expect("the store opens"); + migrate::migrate_with( + &StubSource::new(source_rows()), + &store, + &root, + &options(&target, 1_000), + &mut Vec::new(), + ) + .await + .expect("the copy succeeds"); + + let moved = temporary.path().join("moved"); + std::fs::rename(&target, &moved).expect("the target is renamed away"); + std::fs::create_dir(&target).expect("the replacement is created"); + + let mut out = Vec::new(); + let output = migrate::verify_with(&store, &root, &options(&target, 1_000), &mut out) + .await + .expect("the verify reads the pinned manifest"); + + assert_eq!(output.exit_code, 0); + assert!( + output_text(out).contains("Verified 9 tables"), + "the verify read the manifest through the descriptor" + ); +} + +// A store that will not open names the target the operator typed, not the descriptor the command +// opened it through: `/proc/self/fd/` dies with this process and means nothing in their shell. +#[cfg(target_os = "linux")] +#[test] +fn a_store_that_will_not_open_names_the_target_not_the_descriptor() { + let directory = tempfile::tempdir().expect("a temporary directory"); + let target = directory.path().join("target"); + std::fs::create_dir(&target).expect("the target is created"); + let store = target.join("lmdb"); + std::fs::create_dir(&store).expect("the store directory is made"); + std::fs::write(store.join("data.mdb"), b"not an lmdb file").expect("the file is written"); + // A complete manifest, so both pre-checks pass and the run reaches the store's open. + write_manifest_fixture(&target, true); + + let output = Command::new(env!("CARGO_BIN_EXE_nostream-cli")) + .args(["migrate", "pg-to-lmdb", "--target"]) + .arg(&target) + .arg("--verify") + .env("DB_URI", "not-a-url") + .output() + .expect("the binary runs"); + + assert_eq!(output.status.code(), Some(1)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains(&store.display().to_string()), + "the failure names the store the operator named: {stderr}" + ); + assert!( + !stderr.contains("/proc/self/fd"), + "and never the descriptor: {stderr}" + ); +} diff --git a/docs/rewrite/decisions/0012-pg-to-lmdb-migration.md b/docs/rewrite/decisions/0012-pg-to-lmdb-migration.md index aece0b436..f06738470 100644 --- a/docs/rewrite/decisions/0012-pg-to-lmdb-migration.md +++ b/docs/rewrite/decisions/0012-pg-to-lmdb-migration.md @@ -154,6 +154,28 @@ effective uid, read from `/proc/self/status`, because `std::fs` exposes the file not the caller's and the alternative was a dependency for one integer. The target the run writes into is printed with the summary. +The target is then opened through a descriptor held from before the store's open, not through its +path: the pin's own directory handle is named `/proc/self/fd/` (the answer is probed at run +time, so a host without procfs, and macOS, keeps the path), and the store root, every manifest +write and the summary's `Store:` line resolve through it. What that changes is who can win the +interval: an actor who renames the target away after the pin no longer redirects the store into +the replacement, and `verify` — a post-open cross-check of `stat` against the pinned inode where +procfs answers, and the only check where it does not — refuses a run whose operator's path no +longer denotes the pinned directory. It narrows the window and does not close it: heed +canonicalises the path before `mdb_env_open` (`heed-0.20.5/src/env.rs:239,305`), so the mapping +still resolves an absolute name, and a rename inside that pair still reaches the store. Closing +it needs an fd-relative environment open inside heed, which is a dependency change and not a +change here. + +No line the command prints names the descriptor: every message built from a root-joined path is +translated back to the target the operator typed, because `/proc/self/fd/` dies with the +process and is not a path anyone can act on. The cost of the pin, recorded rather than left to be +discovered: `--verify` now opens the target directory itself, so it needs **read** permission on +the target where the path-only version needed search alone, and a `0300` target is refused by the +pin with the target's own path in the line. That is accepted and not mitigated — the target is a +directory this command writes into, the copy arm has always needed the write bit, and a +directory the caller may only search is not one to trust with a store. + `nostream-cli migrate pg-to-lmdb` takes `--target `, `--batch-size ` and `--verify`, and nothing else. `--target` is required with no default: a default of the working directory would let a mistyped run write a store where none was meant, and verify needs it too because