PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Slice, layer comp and type style ids out of u32 range are rejected, not wrapped onto a real item (#914) (#930)
Brandon Thomase694208a06a7
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex d1fd213b4..e43f96817 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -134,6 +134,17 @@ pub(crate) fn int_i32(cmd: &str, p: &Value, key: &str) -> Result<Option<i32>> {}}+/// An id (layer comp, slice, style…) from a JSON value: a bad-params error unless it is a whole+/// number in `u32` range. `as u32` would wrap `2^32 + 1` to `1` and target a real item.+pub(crate) fn u32_id(cmd: &str, key: &str, v: &Value) -> Result<u32> {+ v.as_u64().and_then(|n| u32::try_from(n).ok()).ok_or_else(|| bad(cmd, format!("`{key}` = {v} is not a valid id (0..={})", u32::MAX)))+}++/// [`u32_id`] of `p[key]`: `None` when absent.+pub(crate) fn u32_id_param(cmd: &str, p: &Value, key: &str) -> Result<Option<u32>> {+ p.get(key).map(|v| u32_id(cmd, key, v)).transpose()+}+fn f32_or(p: &Value, key: &str, default: f32) -> f32 {p.get(key).and_then(Value::as_f64).map(|v| v as f32).unwrap_or(default)}diff --git a/crates/engine/src/comps_cmds.rs b/crates/engine/src/comps_cmds.rsindex 55c4bcd29..57d8fa010 100644--- a/crates/engine/src/comps_cmds.rs+++ b/crates/engine/src/comps_cmds.rs@@ -40,8 +40,8 @@ fn export_comps(s: &Session) -> std::result::Result<(), String> {/// The comp a command acts on: `"comp"` as an id or a name, else the last applied comp.fn comp_param(doc: &Document, p: &Value, cmd: &str) -> Result<u32> {match p.get("comp") {- Some(Value::Number(n)) => {- let id = n.as_u64().ok_or_else(|| bad(cmd, "\"comp\" must be a comp id or name"))? as u32;+ Some(v @ Value::Number(_)) => {+ let id = crate::commands::u32_id(cmd, "comp", v)?;doc.comp(id).map(|c| c.id).ok_or_else(|| bad(cmd, format!("no layer comp with id {id}")))}Some(Value::String(name)) => {@@ -351,7 +351,7 @@ fn comps_to_files(s: &mut Session, p: &Value) -> Result<Value> {let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name));let doc = d.doc.clone();let chosen: Vec<u32> = match p.get("comps") {- Some(Value::Array(a)) => a.iter().filter_map(Value::as_u64).map(|v| v as u32).collect(),+ Some(Value::Array(a)) => a.iter().map(|v| crate::commands::u32_id(cmd, "comps", v)).collect::<Result<Vec<_>>>()?,_ if flag(p, "selectedOnly", false) => vec![comp_param(&doc, &json!({}), cmd)?],_ => doc.layer_comps.iter().map(|c| c.id).collect(),};diff --git a/crates/engine/src/comps_cmds/tests.rs b/crates/engine/src/comps_cmds/tests.rsindex 1f578859f..fd33b3daa 100644--- a/crates/engine/src/comps_cmds/tests.rs+++ b/crates/engine/src/comps_cmds/tests.rs@@ -207,3 +207,21 @@ fn export_comps_to_files_naming() {assert_eq!(r["files"].as_array().unwrap().len(), 1);let _ = std::fs::remove_dir_all(&dir);}++#[test]+fn out_of_range_comp_ids_are_rejected_not_wrapped() {+ // #914: 2^32 + id used to wrap to a real comp.+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 16, "height": 16})).unwrap();+ let c = s.execute("layerComp.new", json!({"name": "Start"})).unwrap()["comp"].as_u64().unwrap();+ let wrapped = (1u64 << 32) + c;+ assert!(s.execute("layerComp.delete", json!({"comp": wrapped})).is_err());+ assert!(s.execute("layerComp.setOptions", json!({"comp": wrapped, "name": "renamed"})).is_err());+ let doc = &s.active().unwrap().doc;+ assert_eq!(doc.layer_comps.len(), 1);+ assert_eq!(doc.layer_comps[0].name, "Start");+ let dir = std::env::temp_dir().join(format!("photocraft-comps-wrap-{}", std::process::id()));+ let r = s.execute("file.export.layerCompsToFiles", json!({"dir": dir.to_string_lossy(), "comps": [wrapped]}));+ assert!(r.is_err());+ let _ = std::fs::remove_dir_all(dir);+}diff --git a/crates/engine/src/slice_cmds.rs b/crates/engine/src/slice_cmds.rsindex 96c5b7f68..8854e4383 100644--- a/crates/engine/src/slice_cmds.rs+++ b/crates/engine/src/slice_cmds.rs@@ -204,8 +204,8 @@ enum Target {fn find(s: &Session, p: &Value, cmd: &str) -> Result<Target> {let d = s.active().ok_or(EngineError::NoDocument)?;- if let Some(id) = crate::commands::int(p, "slice").filter(|v| *v >= 0).map(|v| v as u64) {- return d.doc.slices.get(id as u32).map(|sl| Target::Stored(sl.id)).ok_or_else(|| bad(cmd, format!("no slice with id {id}")));+ if let Some(id) = crate::commands::u32_id_param(cmd, p, "slice")? {+ return d.doc.slices.get(id).map(|sl| Target::Stored(sl.id)).ok_or_else(|| bad(cmd, format!("no slice with id {id}")));}let n = crate::commands::int(p, "number").filter(|v| *v > 0).ok_or_else(|| bad(cmd, "give \"slice\" (id) or \"number\""))? as usize;let r = slices::resolve(&d.doc).into_iter().find(|r| r.number == n).ok_or_else(|| bad(cmd, format!("no slice number {n}")))?;@@ -358,7 +358,8 @@ fn promote(s: &mut Session, p: &Value) -> Result<Value> {fn ids_param(s: &mut Session, p: &Value, cmd: &str) -> Result<Vec<u32>> {if let Some(a) = p.get("slices").and_then(Value::as_array) {let d = s.active().ok_or(EngineError::NoDocument)?;- let ids: Vec<u32> = a.iter().filter_map(Value::as_u64).map(|v| v as u32).filter(|id| d.doc.slices.get(*id).is_some()).collect();+ let ids: Vec<u32> = a.iter().map(|v| crate::commands::u32_id(cmd, "slices", v)).collect::<Result<Vec<_>>>()?;+ let ids: Vec<u32> = ids.into_iter().filter(|id| d.doc.slices.get(*id).is_some()).collect();if ids.is_empty() {return Err(bad(cmd, "none of the slices exist"));}diff --git a/crates/engine/src/slice_cmds/tests.rs b/crates/engine/src/slice_cmds/tests.rsindex aa4d760f0..cee4ef529 100644--- a/crates/engine/src/slice_cmds/tests.rs+++ b/crates/engine/src/slice_cmds/tests.rs@@ -243,3 +243,18 @@ fn slice_options_after_an_explicit_promote_is_its_own_step() {assert!(s.undo());assert!(doc(&s).slices.is_empty());}++#[test]+fn out_of_range_slice_ids_are_rejected_not_wrapped() {+ // #914: 2^32 + 1 used to wrap to slice 1 and delete it.+ let mut s = session(8);+ let id = s.execute("slice.new", json!({"rect": [0, 0, 10, 10]})).unwrap()["slice"].as_u64().unwrap();+ assert_eq!(id, 1);+ let wrapped = (1u64 << 32) + 1;+ assert!(s.execute("slice.delete", json!({"slice": wrapped})).is_err());+ assert!(s.execute("slice.delete", json!({"slices": [wrapped]})).is_err());+ assert!(s.execute("slice.set", json!({"slice": wrapped, "name": "x"})).is_err());+ assert!(s.execute("slice.delete", json!({"slice": -1})).is_err());+ assert_eq!(doc(&s).slices.list.len(), 1);+ assert_eq!(doc(&s).slices.list[0].name, "");+}diff --git a/crates/engine/src/type_styles_cmds.rs b/crates/engine/src/type_styles_cmds.rsindex 64ba6d87a..363bccf47 100644--- a/crates/engine/src/type_styles_cmds.rs+++ b/crates/engine/src/type_styles_cmds.rs@@ -75,8 +75,8 @@ fn range_of(text: &str, p: &Value) -> (usize, usize) {}}-fn id_param(p: &Value) -> Option<u32> {- p.get("id").and_then(Value::as_u64).map(|v| v as u32)+fn id_param(cmd: &str, p: &Value) -> Result<Option<u32>> {+ crate::commands::u32_id_param(cmd, p, "id")}// ---------- attribute parameters ----------@@ -467,7 +467,7 @@ fn new_style(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {}fn lookup_id(cmd: &str, st: &TextStyles, p: &Value, paragraph: bool, allow_default: bool) -> Result<u32> {- let id = id_param(p).ok_or_else(|| bad(cmd, "missing `id`"))?;+ let id = id_param(cmd, p)?.ok_or_else(|| bad(cmd, "missing `id`"))?;let ok = if paragraph { st.para_style(id).is_some() } else { st.char_style(id).is_some() };if !(ok || (allow_default && id == 0)) {return Err(bad(cmd, format!("no style with id {id}")));@@ -638,7 +638,7 @@ fn redefine(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {let cmd = if paragraph { "type.paragraphStyle.redefine" } else { "type.characterStyle.redefine" };let mut st = styles(s)?;let (run, para, layer, span) = sample(s, p).ok_or_else(|| bad(cmd, "select type to redefine the style from"))?;- let id = match id_param(p) {+ let id = match id_param(cmd, p)? {Some(_) => lookup_id(cmd, &st, p, paragraph, paragraph)?,None if paragraph => para.style_sheet.unwrap_or(0),None => run.style_sheet.ok_or_else(|| bad(cmd, "the selected text has no character style"))?,