diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 0d42cd2771..06da218ccd 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -4090,13 +4090,32 @@ struct Ran { #[cfg(not(target_arch = "wasm32"))] fn write_file_output(s: &Session, path: &std::path::Path, bytes: &[u8]) -> Result<(), String> { - // A new file has no canonical path yet: resolve its folder, so a file created inside a loaded - // source directory is refused as well as one replaced there. - let resolved = path.canonicalize().or_else(|error| { + refuse_own_source(s, path)?; + rustgis_data::io::write_atomic(path, bytes).map_err(|error| error.to_string()) +} + +/// `path` resolved: a new file has no canonical path yet, so its folder is resolved instead, and a +/// file created inside a loaded source directory is refused as well as one replaced there. +#[cfg(not(target_arch = "wasm32"))] +fn resolved(path: &std::path::Path) -> std::io::Result { + path.canonicalize().or_else(|error| { let parent = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(std::path::Path::new(".")); path.file_name().map(|name| parent.canonicalize().map(|p| p.join(name))).unwrap_or(Err(error)) - }); - if let Ok(destination) = resolved { + }) +} + +/// Whether `source`, a file a layer or table was read from, is `path` or holds it ([`names_file`]). +#[cfg(not(target_arch = "wasm32"))] +pub(in crate::cmd) fn reads(source: &str, path: &std::path::Path) -> bool { + resolved(path).is_ok_and(|destination| names_file(source, &destination)) +} + +/// Refuses a destination that holds what the session reads: the open project's file, the source +/// of a layer or a table, or a local tile archive ([`names_file`]). Tool outputs check it once +/// their file is made; the feature and table exports, before they read or write anything. +#[cfg(not(target_arch = "wasm32"))] +pub(in crate::cmd) fn refuse_own_source(s: &Session, path: &std::path::Path) -> Result<(), String> { + if let Ok(destination) = resolved(path) { if s.path.iter().chain(s.opened_package.iter()).any(|project| project.canonicalize().is_ok_and(|project| project == destination)) { return Err("destination is the open project's file; choose a different output file".into()); } @@ -4125,7 +4144,7 @@ fn write_file_output(s: &Session, path: &std::path::Path, bytes: &[u8]) -> Resul } } } - rustgis_data::io::write_atomic(path, bytes).map_err(|error| error.to_string()) + Ok(()) } /// Whether a loaded source reads `destination`: the file itself, a directory's contents, the diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 36fd72fbef..242d469dc2 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -65,6 +65,48 @@ pub fn gpkg_table(p: &Value, ext: &str) -> Result { Ok(GpkgTable { mode, name }) } +/// What an export reads its rows from: a layer's or table's name, the files it was read from, and +/// the GeoPackage table, when it says. +#[cfg(not(target_arch = "wasm32"))] +pub(super) struct Own<'a> { + pub(super) kind: &'static str, + pub(super) name: &'a str, + pub(super) files: Vec<&'a str>, + pub(super) table: Option<&'a str>, +} + +/// Refuses an export written at `path` (not downloaded) over a file the session reads, before +/// anything is read or written: a row limit or a definition query would cut the source itself. A +/// Shapefile's companion files count too. A table added to a GeoPackage leaves the others alone, +/// and a table replaced by name is refused only when it is the one `own` reads (a layer read from +/// another replaced table is refreshed). +#[cfg(not(target_arch = "wasm32"))] +fn refuse_own_source(s: &Session, path: &str, gpkg: &GpkgTable, downloaded: bool, own: &Own) -> Result<(), String> { + if !downloaded { + let path = Path::new(path); + match gpkg.mode { + GpkgMode::NewFile => { + super::gp::refuse_own_source(s, path)?; + if path.extension().is_some_and(|e| e.eq_ignore_ascii_case("shp")) { + for ext in ["dbf", "shx", "prj", "cpg"] { + super::gp::refuse_own_source(s, &path.with_extension(ext))?; + } + } + } + GpkgMode::AddTable => {} + GpkgMode::ReplaceTable => { + let target = gpkg.name.as_deref().unwrap_or(own.name); + // A table it doesn't name is taken for the one replaced. + let same = own.table.is_none_or(|table| table.eq_ignore_ascii_case(target.trim())); + if same && own.files.iter().any(|file| super::gp::reads(file, path)) { + return Err(format!("destination is the source of {} '{}'; choose a different output file", own.kind, own.name)); + } + } + } + } + Ok(()) +} + /// A committed overwrite's declaration changes. File and column names stay literal when /// the front end formats the notice. fn declaration_change_note(path: &str, table: Option<&str>, changes: &DeclarationChanges) -> Option { @@ -721,6 +763,17 @@ pub(crate) fn layer_work(s: &Session, p: &Value) -> Result { let (boxes, map) = (s.constructions.clone(), s.map().instance_id()); let project = s.project.coordinate_system; let download = s.download_room()?; + // The browser downloads the file: nothing is written over a source. + #[cfg(not(target_arch = "wasm32"))] + { + let own = Own { + kind: "layer", + name: &l.name, + files: [l.gpkg.as_ref().map(|g| g.path.as_str()), l.linked_file(), l.dataset.source.as_deref()].into_iter().flatten().collect(), + table: l.gpkg.as_ref().map(|g| g.table.as_str()).or_else(|| l.linked_table()), + }; + refuse_own_source(s, &path, &gpkg, download.is_some(), &own)?; + } Ok(Box::new(move || { let note = boxes.export_notes(map, &l)?; let mut wrote = write_layer(&l, &path, asked, project, gpkg, download)?; diff --git a/crates/engine/src/cmd/share/table.rs b/crates/engine/src/cmd/share/table.rs index ffdde528c5..98c3c29be7 100644 --- a/crates/engine/src/cmd/share/table.rs +++ b/crates/engine/src/cmd/share/table.rs @@ -154,6 +154,12 @@ pub(in crate::cmd) fn table_work(s: &Session, p: &Value) -> Result let mut ds = s.project.tables.get(s.table_index(p)?).ok_or("no such table")?.dataset.clone(); let (sort, limit) = options(&ds, p)?; let download = s.download_room()?; + // The browser downloads the file: nothing is written over a source. + #[cfg(not(target_arch = "wasm32"))] + { + let own = super::Own { kind: "table", name: &ds.name, files: ds.source.as_deref().into_iter().collect(), table: None }; + super::refuse_own_source(s, &path, &gpkg, download.is_some(), &own)?; + } Ok(Box::new(move || { let omitted = ordered(&mut ds, &sort, limit)?; let default = ds.name.clone(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 5b5bdeee44..8d64c74993 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3,6 +3,9 @@ use serde_json::{Value, json}; use crate::{Project, Session, sample}; +#[cfg(not(target_arch = "wasm32"))] +#[path = "tests/export_own_source.rs"] +mod export_own_source; #[path = "tests/formats_out.rs"] mod formats_out; #[path = "tests/graphics_frames.rs"] @@ -32992,8 +32995,9 @@ fn dropped_z_values_are_said_on_import_and_export() { #[test] fn exporting_a_table_says_its_dropped_z_values() { let dir = std::env::temp_dir().join(format!("rustgis-engine-table-zm-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let src = dir.join("wells.geojson"); + // The source apart from the exports: an export over the table's own file is refused. + std::fs::create_dir_all(dir.join("source")).unwrap(); + let src = dir.join("source").join("wells.geojson"); std::fs::write( &src, r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"depth":30},"geometry":{"type":"Point","coordinates":[1,2,30]}}]}"#, @@ -33040,11 +33044,11 @@ fn exporting_a_table_says_its_dropped_z_values() { assert!(said(&s, mark).is_empty(), "{:?}", s.notices_since(mark)); // A table read without Z: no notice. std::fs::write( - dir.join("flat.geojson"), + dir.join("source").join("flat.geojson"), r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"depth":30},"geometry":{"type":"Point","coordinates":[1,2]}}]}"#, ) .unwrap(); - let (flat, _) = rustgis_data::io::read_path(&dir.join("flat.geojson")).unwrap(); + let (flat, _) = rustgis_data::io::read_path(&dir.join("source").join("flat.geojson")).unwrap(); assert!(!flat.zm_dropped, "premise"); s.project.add_table(flat); for ext in ["geojson", "shp"] { diff --git a/crates/engine/src/tests/export_own_source.rs b/crates/engine/src/tests/export_own_source.rs new file mode 100644 index 0000000000..96e24dfc68 --- /dev/null +++ b/crates/engine/src/tests/export_own_source.rs @@ -0,0 +1,137 @@ +//! Feature and table exports refuse to write over the file a layer or table was read from (#3567), +//! as tool outputs already do: a row limit or a definition query would cut the source itself. + +use crate::{Project, Session}; +use serde_json::json; + +/// A folder removed however the test ends. +struct Dir(std::path::PathBuf); +impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn dir(name: &str) -> Dir { + let d = std::env::temp_dir().join(format!("rustgis-export-own-source-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + Dir(d) +} + +const ROWS: &str = "code,name,value\n1,Alpha,10\n2,Beta,20\n3,Gamma,30\n"; +const POINTS: &str = r#"{"type":"FeatureCollection","features":[ +{"type":"Feature","properties":{"n":1},"geometry":{"type":"Point","coordinates":[1,1]}}, +{"type":"Feature","properties":{"n":2},"geometry":{"type":"Point","coordinates":[2,2]}}]}"#; + +#[test] +fn export_table_refuses_its_own_csv_and_writes_another() { + let d = dir("table"); + let source = d.0.join("origem.csv"); + std::fs::write(&source, ROWS).unwrap(); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": source})).unwrap(); + assert!(s.project.tables.iter().any(|t| t.dataset.name == "origem")); + + let error = s.run("share.exportTable", &json!({"table": "origem", "path": source, "limit": 1})).unwrap_err(); + assert!(error.contains("destination is the source of table 'origem'; choose a different output file"), "{error}"); + assert_eq!(std::fs::read_to_string(&source).unwrap(), ROWS); + + let other = d.0.join("first.csv"); + s.run("share.exportTable", &json!({"table": "origem", "path": other, "limit": 1})).unwrap(); + assert_eq!(std::fs::read_to_string(&other).unwrap().lines().count(), 2); + assert_eq!(std::fs::read_to_string(&source).unwrap(), ROWS); +} + +#[test] +fn export_layer_refuses_its_own_geojson_and_writes_another() { + let d = dir("layer"); + let source = d.0.join("pontos.geojson"); + std::fs::write(&source, POINTS).unwrap(); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": source})).unwrap(); + s.run("layer.definitionQuery", &json!({"layer": "pontos", "where": "n = 1"})).unwrap(); + + let error = s.run("share.exportLayer", &json!({"layer": "pontos", "path": source})).unwrap_err(); + assert!(error.contains("destination is the source of layer 'pontos'; choose a different output file"), "{error}"); + assert_eq!(std::fs::read_to_string(&source).unwrap(), POINTS); + + let other = d.0.join("one.geojson"); + s.run("share.exportLayer", &json!({"layer": "pontos", "path": other})).unwrap(); + let written: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&other).unwrap()).unwrap(); + assert_eq!(written["features"].as_array().unwrap().len(), 1); +} + +/// The rows of `table` in GeoPackage `path`, read apart from the session. +fn rows(path: &std::path::Path, table: &str) -> i64 { + let db = rusqlite::Connection::open(path).unwrap(); + db.query_row(&format!("SELECT count(*) FROM \"{table}\""), [], |r| r.get(0)).unwrap() +} + +/// In a GeoPackage a layer was read from, a new file and the layer's own table replaced are +/// refused; a table added beside it, or another table replaced, leaves its rows alone. A layer +/// read whole doesn't keep its table's name: any table it replaces there is refused. +#[test] +fn export_layer_into_its_own_geopackage_keeps_its_table() { + let d = dir("gpkg"); + let geojson = d.0.join("pontos.geojson"); + std::fs::write(&geojson, POINTS).unwrap(); + let source = d.0.join("pontos.gpkg"); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": geojson})).unwrap(); + s.run("share.exportLayer", &json!({"layer": "pontos", "path": source})).unwrap(); + s.run("layer.addData", &json!({"path": source, "name": "Whole"})).unwrap(); + s.run("layer.addData", &json!({"path": source, "layer": "pontos", "stream": true, "name": "Streamed"})).unwrap(); + for layer in ["Whole", "Streamed"] { + s.run("layer.definitionQuery", &json!({"layer": layer, "where": "n = 1"})).unwrap(); + } + + let error = s.run("share.exportLayer", &json!({"layer": "pontos", "path": source})).unwrap_err(); + assert!(error.contains("destination is the source of layer"), "{error}"); + for layer in ["Whole", "Streamed"] { + let own = json!({"layer": layer, "path": source, "mode": "replaceTable", "tableName": "pontos"}); + let error = s.run("share.exportLayer", &own).unwrap_err(); + assert!(error.contains(&format!("destination is the source of layer '{layer}'")), "{error}"); + } + assert_eq!(rows(&source, "pontos"), 2); + + s.run("share.exportLayer", &json!({"layer": "pontos", "path": source, "mode": "addTable", "tableName": "copia"})).unwrap(); + assert_eq!((rows(&source, "pontos"), rows(&source, "copia")), (2, 2)); + let other = json!({"layer": "Whole", "path": source, "mode": "replaceTable", "tableName": "copia"}); + assert!(s.run("share.exportLayer", &other).unwrap_err().contains("source of layer 'Whole'")); + s.run("share.exportLayer", &json!({"layer": "Streamed", "path": source, "mode": "replaceTable", "tableName": "copia"})).unwrap(); + assert_eq!((rows(&source, "pontos"), rows(&source, "copia")), (2, 1)); +} + +/// A Shapefile export writes its `.dbf` beside the `.shp`: data read from that `.dbf`, as the +/// Shapefile's layer or as a table on its own, refuses it. +#[test] +fn export_layer_to_a_shapefile_beside_a_loaded_dbf_is_refused() { + let d = dir("shp"); + let geojson = d.0.join("pontos.geojson"); + std::fs::write(&geojson, POINTS).unwrap(); + let shp = d.0.join("roads.shp"); + let dbf = shp.with_extension("dbf"); + for alone in [false, true] { + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": geojson})).unwrap(); + s.run("share.exportLayer", &json!({"layer": "pontos", "path": shp})).unwrap(); + if alone { + for ext in ["shp", "shx", "prj", "cpg"] { + let _ = std::fs::remove_file(shp.with_extension(ext)); + } + } + let before = std::fs::read(&dbf).unwrap(); + let added = s.run("layer.addData", &json!({"path": dbf})).unwrap(); + let (kind, name) = match added["table"].as_str() { + Some(table) => ("table", table.to_string()), + None => ("layer", s.map().layer(added["layer"].as_u64().unwrap_or_else(|| panic!("{added}")) as u32).unwrap().name.clone()), + }; + assert_eq!(kind, if alone { "table" } else { "layer" }, "{added}"); + s.run("layer.definitionQuery", &json!({"layer": "pontos", "where": "n = 1"})).unwrap(); + + let error = s.run("share.exportLayer", &json!({"layer": "pontos", "path": shp})).unwrap_err(); + assert!(error.contains(&format!("destination is the source of {kind} '{name}'")), "{error}"); + assert_eq!(std::fs::read(&dbf).unwrap(), before); + } +}