Repository navigation
fix(engine): task.import refuses a task file that needs a capability this RustGIS doesn't know (#2818) #2867
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
430e2f1
722dc97
c143e59
c390936
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -385,7 +385,9 @@ fn document(kind: Document, v: &Value, depth: usize, report: &mut Report) -> Opt | |
| let Some(text) = v.as_str().filter(|s| s.len() as u64 <= crate::project::max_bytes()) else { return invalid(v, report) }; | ||
| // One this RustGIS wouldn't read, or would rewrite without what it doesn't know, stays as | ||
| // written. Only project and map readers read format 2 and refuse a document for what it | ||
| // requires; the others keep format 1's bound and don't look at `requires`. | ||
| // requires; for the others it is a format past `FORMAT` (also 2 now). A task's and a model's | ||
| // readers do look at `requires`, so their cleaned copies keep it (`task_document` puts it and | ||
| // `format` back; `model_document` keeps its envelope). | ||
| if crate::project::kept_as_written(text, matches!(kind, Document::Project | Document::Map)) { | ||
| report.unchecked = report.unchecked.saturating_add(1); | ||
| return None; | ||
|
|
@@ -399,7 +401,7 @@ fn document(kind: Document, v: &Value, depth: usize, report: &mut Report) -> Opt | |
| text_document::<rustgis_map::Map>(text, depth) | ||
| } | ||
| } | ||
| Document::Task => text_document::<crate::project::Task>(text, depth), | ||
| Document::Task => task_document(text, depth), | ||
| Document::Presentation => text_document::<rustgis_map::presentation::Presentation>(text, depth), | ||
| Document::Notebook => crate::cmd::notebook::durable_document(text, depth), | ||
| Document::Model => model_document(text, depth), | ||
|
|
@@ -422,6 +424,34 @@ fn text_document<T: DeserializeOwned + Serialize + Durable>(text: &str, depth: u | |
| }) | ||
| } | ||
|
|
||
| /// A task document is cleaned through the typed task, as it always was (a key the task doesn't | ||
| /// have is not kept), and then `format` and `requires` are put back from the document: `task.import` | ||
| /// reads them (it refuses a newer format and what `requires` lists that this RustGIS doesn't know), | ||
| /// and the typed copy has neither. Neither is a place for a credential, so a document whose header | ||
| /// holds one is withheld whole (`[parameters withheld]`, which no replay reads as a task), as a | ||
| /// document that doesn't read is; dropping only the header would let a replay skip the check. | ||
| fn task_document(text: &str, depth: usize) -> Result<(String, Report), String> { | ||
| let original: Value = serde_json::from_str(text).map_err(|e| e.to_string())?; | ||
| let header = ["format", "requires"]; | ||
| if header.iter().filter_map(|key| original.get(key)).any(suspicious) { | ||
| let report = Report { withheld: 1, ..Report::default() }; | ||
| return Ok((WITHHELD.into(), report)); | ||
| } | ||
| let (clean, report) = text_document::<crate::project::Task>(text, depth)?; | ||
| if clean == text { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. When the typed This predates the PR, but the new doc comment on Possible fix: when the original has keys outside Category: security |
||
| return Ok((clean, report)); | ||
| } | ||
| let mut rewritten: Value = serde_json::from_str(&clean).map_err(|e| e.to_string())?; | ||
| if let (Some(from), Some(to)) = (original.as_object(), rewritten.as_object_mut()) { | ||
| for key in header { | ||
| if let Some(value) = from.get(key) { | ||
| to.insert(key.into(), value.clone()); | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| } | ||
| } | ||
| } | ||
| Ok((rewritten.to_string(), report)) | ||
| } | ||
|
|
||
| /// Model import has two envelopes; keeps the envelope's other fields and cleans only its model. | ||
| fn model_document(text: &str, depth: usize) -> Result<(String, Report), String> { | ||
| let mut v: Value = serde_json::from_str(text).map_err(|e| e.to_string())?; | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,225 @@ | ||
| //! Task files (`.rgistask`) are read with the project's header check, so an older RustGIS than the | ||
| //! file refuses what it can't keep, naming it (#2818). | ||
|
|
||
| use crate::{Project, Session}; | ||
| use serde_json::{Value, json}; | ||
|
|
||
| /// A task file as every release so far writes it: no `format`, no `requires`. | ||
| fn bare() -> Value { | ||
| json!({"name": "Lesson", "description": "", "steps": [{"title": "Zoom", "instructions": "", "command": "map.zoomIn", "params": {}}]}) | ||
| } | ||
|
|
||
| /// `bare` with `key` set to `value`. | ||
| fn with(key: &str, value: Value) -> String { | ||
| let mut v = bare(); | ||
| v[key] = value; | ||
| v.to_string() | ||
| } | ||
|
|
||
| /// A file removed when the test ends, whether or not an assertion failed first. | ||
| struct TempFile(std::path::PathBuf); | ||
|
|
||
| impl Drop for TempFile { | ||
| fn drop(&mut self) { | ||
| let _ = std::fs::remove_file(&self.0); | ||
| } | ||
| } | ||
|
|
||
| fn import(s: &mut Session, text: &str) -> Result<Value, String> { | ||
| s.run("task.import", &json!({"text": text})) | ||
| } | ||
|
|
||
| /// What the project's own reader says for the same header, said of a task. | ||
| fn as_a_project_says(text: &str) -> String { | ||
| crate::project::check_format(text, "project").unwrap_err().replace("this project", "this task") | ||
| } | ||
|
|
||
| #[test] | ||
| fn a_task_file_needing_an_unknown_capability_is_refused_by_name() { | ||
| let mut s = Session::new(Project::default()); | ||
| let text = with("requires", json!(["label-weight", "future-step-key", "future-step-key"])); | ||
| let err = import(&mut s, &text).unwrap_err(); | ||
| assert_eq!(err, "this task needs what this RustGIS can't read: future-step-key. Update RustGIS to open it."); | ||
| assert_eq!(err, as_a_project_says(&text)); | ||
| assert!(s.project.tasks.is_empty(), "nothing imported"); | ||
|
|
||
| // Read from a path and from a base64 file, as from text. | ||
| let file = TempFile(std::env::temp_dir().join(format!("task-requires-2818-{}.rgistask", std::process::id()))); | ||
| std::fs::write(&file.0, &text).unwrap(); | ||
| let from_path = s.run("task.import", &json!({"path": file.0.to_string_lossy()})).unwrap_err(); | ||
| assert_eq!(from_path, err); | ||
| use base64::Engine; | ||
| let data = base64::engine::general_purpose::STANDARD.encode(&text); | ||
| assert_eq!(s.run("task.import", &json!({"data": data})).unwrap_err(), err); | ||
| assert!(s.project.tasks.is_empty(), "nothing imported"); | ||
|
|
||
| // Told to update, not that a step is forbidden, when the file is both. | ||
| let mut both = bare(); | ||
| both["requires"] = json!(["future-step-key"]); | ||
| both["steps"] = json!([{"title": "Add", "command": "layer.addData", "params": {"path": "/data/roads.geojson"}}]); | ||
| let err = import(&mut s, &both.to_string()).unwrap_err(); | ||
| assert!(err.contains("future-step-key") && !err.contains("reads or writes files"), "{err}"); | ||
| } | ||
|
|
||
| #[test] | ||
| fn a_task_file_of_a_newer_format_is_refused() { | ||
| let mut s = Session::new(Project::default()); | ||
| let text = with("format", json!(crate::project::READ_FORMAT + 1)); | ||
| let err = import(&mut s, &text).unwrap_err(); | ||
| assert_eq!(err, "this task was saved by a newer RustGIS (format 3). Update RustGIS to open it."); | ||
| assert!(s.project.tasks.is_empty(), "nothing imported"); | ||
| } | ||
|
|
||
| #[test] | ||
| fn a_task_file_with_a_hostile_requires_is_refused_as_a_project_is() { | ||
| let mut s = Session::new(Project::default()); | ||
| let many: Vec<String> = (0..=crate::project::MAX_REQUIRES).map(|i| format!("future-{i}")).collect(); | ||
| for requires in [ | ||
| json!(5), | ||
| json!("label-weight"), | ||
| json!({"a": 1}), | ||
| json!(["label-weight", 1]), | ||
| json!([["nested"]]), | ||
| json!(many), | ||
| json!(["x".repeat(1 << 20)]), | ||
| json!(["line\nbreak\u{202e}name"]), | ||
| ] { | ||
| let text = with("requires", requires.clone()); | ||
| let err = import(&mut s, &text).unwrap_err(); | ||
| assert_eq!(err, as_a_project_says(&text), "{}", err.chars().take(120).collect::<String>()); | ||
| assert!(err.len() < 1024, "the refusal stays short for a huge name: {} bytes", err.len()); | ||
| assert!(!err.contains('\n') && !err.contains('\u{202e}'), "{err}"); | ||
| } | ||
| assert!(s.project.tasks.is_empty(), "nothing imported"); | ||
| } | ||
|
|
||
| /// Not text at all, or a list, is still `not a RustGIS task`, as before. | ||
| #[test] | ||
| fn a_task_file_that_is_no_task_is_still_said_so() { | ||
| let mut s = Session::new(Project::default()); | ||
| for text in ["[]", "5", "{}", "{\"name\": \"x\"}", "not json"] { | ||
| let err = import(&mut s, text).unwrap_err(); | ||
| assert!(err.starts_with("not a RustGIS task"), "{text}: {err}"); | ||
| } | ||
| // A `format` that isn't a whole number is read as the project reader reads it (it used to be | ||
| // ignored here, as a task file never had one): not a task this RustGIS can read. | ||
| for format in [json!("2"), json!(2.5), json!(-1), json!(null), json!([2])] { | ||
| let text = with("format", format.clone()); | ||
| let err = import(&mut s, &text).unwrap_err(); | ||
| assert!(err.starts_with("not a RustGIS task"), "{format}: {err}"); | ||
| assert_eq!(err, crate::project::check_format(&text, "task").unwrap_err()); | ||
| } | ||
| assert!(s.project.tasks.is_empty(), "nothing imported"); | ||
| } | ||
|
|
||
| #[test] | ||
| fn task_files_without_a_header_or_with_known_capabilities_import() { | ||
| let mut s = Session::new(Project::default()); | ||
| // A file as every release so far writes it. | ||
| import(&mut s, &bare().to_string()).unwrap(); | ||
| // A header listing nothing, and one listing what this RustGIS knows. | ||
| import(&mut s, &with("requires", json!([]))).unwrap(); | ||
| import(&mut s, &with("requires", json!(["label-weight", "dggs-system", "table-export-order"]))).unwrap(); | ||
| import(&mut s, &with("format", json!(crate::project::READ_FORMAT))).unwrap(); | ||
| assert_eq!(s.project.tasks.len(), 4); | ||
| assert!(s.project.tasks.iter().all(|t| t.steps.len() == 1 && t.steps[0].command == "map.zoomIn")); | ||
| } | ||
|
|
||
| /// A recorded `task.import` keeps the document's header when its text is cleaned of credentials, | ||
| /// so replaying it refuses what the first run would have (`roles::document`). | ||
| #[test] | ||
| fn a_recorded_task_import_keeps_the_check_when_its_text_is_cleaned() { | ||
| const SECRET: &str = "RGSYNTH_task_requires_20261124"; | ||
| let mut task = bare(); | ||
| task["requires"] = json!(["future-step-key"]); | ||
| task["steps"] = | ||
| json!([{"title": "Add", "command": "layer.addUrl", "params": {"url": format!("https://h.invalid/a.geojson?token={SECRET}")}}]); | ||
| let text = task.to_string(); | ||
| let (clean, report) = crate::roles::command("task.import", &json!({"text": text}), 0); | ||
| let clean = clean.expect("the credential is cleaned out of the text"); | ||
| let cleaned = clean["text"].as_str().unwrap(); | ||
| assert!(!cleaned.contains(SECRET), "{cleaned}"); | ||
| assert_eq!(report.unchecked, 0); | ||
| let kept: Value = serde_json::from_str(cleaned).unwrap(); | ||
| assert_eq!(kept["requires"], json!(["future-step-key"]), "{cleaned}"); | ||
| assert_eq!((kept["name"].as_str(), kept["steps"].as_array().map(Vec::len)), (Some("Lesson"), Some(1))); | ||
| let mut s = Session::new(Project::default()); | ||
| let err = import(&mut s, cleaned).unwrap_err(); | ||
| assert!(err.contains("future-step-key"), "{err}"); | ||
|
|
||
| // A text that needs no cleaning is kept as written. | ||
| let (clean, report) = crate::roles::command("task.import", &json!({"text": bare().to_string()}), 0); | ||
| assert!(clean.is_none() && report.unchecked == 0); | ||
| } | ||
|
|
||
| /// A recorded `task.import` is cleaned through the typed task as it always was: a key the task | ||
| /// doesn't have, with a credential in it, isn't kept beside the cleaned steps. Only `format` and | ||
| /// `requires` are put back from the document. | ||
| #[test] | ||
| fn a_recorded_task_import_keeps_only_its_envelope_beside_the_typed_clean() { | ||
| const SECRET: &str = "RGSYNTH_stray_key_20261124"; | ||
| let mut task = bare(); | ||
| task["requires"] = json!(["label-weight"]); | ||
| task["format"] = json!(crate::project::READ_FORMAT); | ||
| task["token"] = json!(SECRET); | ||
| task["extra"] = json!({"password": SECRET}); | ||
| // A credential in a step makes the document change, so it is written again from the typed task. | ||
| task["steps"] = | ||
| json!([{"title": "Add", "command": "layer.addUrl", "params": {"url": format!("https://h.invalid/a.geojson?token={SECRET}")}}]); | ||
| let (clean, report) = crate::roles::command("task.import", &json!({"text": task.to_string()}), 0); | ||
| let cleaned = clean.expect("the credential is cleaned out of the text"); | ||
| let cleaned = cleaned["text"].as_str().unwrap(); | ||
| assert!(!cleaned.contains(SECRET), "{cleaned}"); | ||
| assert_eq!(report.unchecked, 0); | ||
| let kept: Value = serde_json::from_str(cleaned).unwrap(); | ||
| let mut keys: Vec<&String> = kept.as_object().unwrap().keys().collect(); | ||
| keys.sort(); | ||
| assert_eq!(keys, ["description", "format", "name", "requires", "steps"], "{cleaned}"); | ||
| assert_eq!(kept["requires"], json!(["label-weight"])); | ||
| assert_eq!(kept["format"], json!(crate::project::READ_FORMAT)); | ||
| } | ||
|
|
||
| /// What a recorded `task.import` keeps of `requires` and `format` is only what carries no credential: | ||
| /// one that does is withheld with the whole text, which replays as no task, so a replay can't skip | ||
| /// the capability check by losing the list. A clean list is still kept, rewritten or not. | ||
| #[test] | ||
| fn a_recorded_task_import_keeps_its_requires_only_when_it_carries_no_credential() { | ||
| const SECRET: &str = "RGSYNTH_requires_20261124"; | ||
| let secret_step = | ||
| json!([{"title": "Add", "command": "layer.addUrl", "params": {"url": format!("https://h.invalid/a.geojson?token={SECRET}")}}]); | ||
| let clean_step = bare()["steps"].clone(); | ||
| for (key, value) in [ | ||
| ("requires", json!(["future-step-key", format!("https://h.invalid/x?token={SECRET}")])), | ||
| ("requires", json!({"token": SECRET})), | ||
| ("requires", json!([{"headers": {"Authorization": format!("Bearer {SECRET}")}}])), | ||
| ("format", json!({"token": SECRET})), | ||
| ] { | ||
| // Rewritten (a credential in a step) and kept as written (none). | ||
| for steps in [&secret_step, &clean_step] { | ||
| let mut task = bare(); | ||
| task[key] = value.clone(); | ||
| task["steps"] = steps.clone(); | ||
| let (clean, report) = crate::roles::command("task.import", &json!({"text": task.to_string()}), 0); | ||
| let params = clean.unwrap_or_else(|| panic!("{key} {value}: kept as written, credential and all")); | ||
| let cleaned = params["text"].as_str().unwrap(); | ||
| assert!(!cleaned.contains(SECRET), "{key} {value}: {cleaned}"); | ||
| assert_eq!(report.withheld, 1, "{key} {value}"); | ||
| // The replay is refused: nothing is imported without the check. | ||
| let mut s = Session::new(Project::default()); | ||
| assert!(import(&mut s, cleaned).is_err(), "{key} {value}: {cleaned}"); | ||
| assert!(s.project.tasks.is_empty()); | ||
| } | ||
| } | ||
| // A clean list is kept, so the replay is checked. | ||
| for steps in [&secret_step, &clean_step] { | ||
| let mut task = bare(); | ||
| task["requires"] = json!(["future-step-key"]); | ||
| task["steps"] = steps.clone(); | ||
| let (clean, report) = crate::roles::command("task.import", &json!({"text": task.to_string()}), 0); | ||
| let kept = clean.map_or(task.to_string(), |p| p["text"].as_str().unwrap().to_string()); | ||
| assert_eq!(serde_json::from_str::<Value>(&kept).unwrap()["requires"], json!(["future-step-key"]), "{kept}"); | ||
| assert_eq!(report.withheld, 0); | ||
| let mut s = Session::new(Project::default()); | ||
| assert!(import(&mut s, &kept).unwrap_err().contains("future-step-key")); | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The "(also 2 now)" reads as if
FORMATchanged, but this PR leavesFORMATat 2 (project.rs:66), so the bound was already 2 for these kinds. Dropping the parenthetical avoids implying a change that isn't there.Category: quality