PhotoCraft: An open-source, photo editor written by scratch in pure Rust
gradient.fill.stop rejects an out-of-range index with BadParams instead of overflowing (#958) (#1000)
yang533c46f7d861
diff --git a/crates/engine/src/gradient_fill_cmds.rs b/crates/engine/src/gradient_fill_cmds.rsindex e5a9a0bbe..09c18f7d5 100644--- a/crates/engine/src/gradient_fill_cmds.rs+++ b/crates/engine/src/gradient_fill_cmds.rs@@ -376,8 +376,16 @@ pub fn apply_stop(f: &Fill, p: &Value, fg: [f32; 4], bg: [f32; 4]) -> Result<Fil"opacity" => true,o => return Err(bad(CMD, format!("unknown kind `{o}` (color|opacity)"))),};- let index = || -> Result<usize> {- p.get("index").and_then(Value::as_u64).and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad(CMD, "missing `index` (a stop number from 0)"))+ // The `index` param, checked against the `len` entries it can address (`what`, e.g.+ // "colour stop" or "segment") before any arithmetic on it: an index is untrusted and can be as+ // large as the integer type, so `i + 1` on it would overflow (#958).+ let index = |len: usize, what: &str| -> Result<usize> {+ let i =+ p.get("index").and_then(Value::as_u64).and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad(CMD, "missing `index` (a stop number from 0)"))?;+ if i >= len {+ return Err(bad(CMD, format!("no {what} {i} (there are {len})")));+ }+ Ok(i)};let location = || num(p, "location").map(|v| v.clamp(0.0, 1.0)).ok_or_else(|| bad(CMD, "missing `location` (0..1)"));let ramp = gf::Ramp::new(f).ok_or_else(|| bad(CMD, "not a gradient fill"))?;@@ -396,22 +404,19 @@ pub fn apply_stop(f: &Fill, p: &Value, fg: [f32; 4], bg: [f32; 4]) -> Result<Filos.push((t, a.clamp(0.0, 1.0)));}"move" => {- let i = index()?;+ let i = index(os.len(), "opacity stop")?;let t = location()?;os.get_mut(i).ok_or_else(|| bad(CMD, format!("no opacity stop {i}")))?.0 = t;}"delete" => {- let i = index()?;- if i >= os.len() {- return Err(bad(CMD, format!("no opacity stop {i}")));- }+ let i = index(os.len(), "opacity stop")?;if os.len() <= 2 {return Err(bad(CMD, "a gradient keeps at least 2 opacity stops"));}os.remove(i);}"opacity" => {- let i = index()?;+ let i = index(os.len(), "opacity stop")?;let a = opacity()?;os.get_mut(i).ok_or_else(|| bad(CMD, format!("no opacity stop {i}")))?.1 = a;}@@ -446,34 +451,27 @@ pub fn apply_stop(f: &Fill, p: &Value, fg: [f32; 4], bg: [f32; 4]) -> Result<Fil}}"move" => {- let i = index()?;+ let i = index(v.len(), "colour stop")?;let t = location()?;v.get_mut(i).ok_or_else(|| bad(CMD, format!("no colour stop {i}")))?.0 = t;}"delete" => {- let i = index()?;- if i >= v.len() {- return Err(bad(CMD, format!("no colour stop {i}")));- }+ let i = index(v.len(), "colour stop")?;if v.len() <= 2 {return Err(bad(CMD, "a gradient keeps at least 2 colour stops"));}v.remove(i);}"color" => {- let i = index()?;+ let i = index(v.len(), "colour stop")?;let c = p.get("color").and_then(|c| parse_color(c, fg, bg)).ok_or_else(|| bad(CMD, "missing or bad `color`"))?;v.get_mut(i).ok_or_else(|| bad(CMD, format!("no colour stop {i}")))?.1 = c;}"midpoint" => {- let i = index()?;+ // Segment `i` runs from stop `i` to stop `i + 1`, so there is one fewer than stops.+ let i = index(v.len().saturating_sub(1), "segment")?;let m = num(p, "location").ok_or_else(|| bad(CMD, "missing `location` (0..1 of the segment)"))?.clamp(0.05, 0.95);- if i + 1 >= v.len() {- return Err(bad(CMD, format!("no segment {i} (there are {})", v.len().saturating_sub(1))));- }- if let Some(s) = v.get_mut(i) {- s.2 = m;- }+ v.get_mut(i).ok_or_else(|| bad(CMD, format!("no segment {i}")))?.2 = m;}o => return Err(bad(CMD, format!("unknown action `{o}` (add|move|delete|color|midpoint)"))),}diff --git a/crates/engine/src/gradient_fill_cmds/tests.rs b/crates/engine/src/gradient_fill_cmds/tests.rsindex f8a6fa77b..4d16838d3 100644--- a/crates/engine/src/gradient_fill_cmds/tests.rs+++ b/crates/engine/src/gradient_fill_cmds/tests.rs@@ -323,3 +323,38 @@ fn a_clamped_handle_drag_leaves_the_other_handle_alone() {}}}++/// Issue #958: a stop or segment index far past the end (up to the largest integer) is a+/// `BadParams` error for every action and kind, never an overflow panic, and leaves the gradient+/// and the history as they were.+#[test]+fn stop_rejects_huge_indices_without_panicking() {+ let mut s = session(8, "white");+ s.execute(CREATE, json!({"from": [0, 0], "to": [8, 8], "stops": [[0, "#000000"], [1, "#ffffff"]]})).unwrap();+ let before = active_fill(&s);+ let h = s.active().unwrap().history.past_len();+ for index in [u64::MAX, usize::MAX as u64, u64::MAX - 1, 1 << 32, 2] {+ for p in [+ json!({"action": "midpoint", "index": index, "location": 0.5}),+ json!({"action": "move", "index": index, "location": 0.5}),+ json!({"action": "delete", "index": index}),+ json!({"action": "color", "index": index, "color": "#ff0000"}),+ json!({"action": "move", "kind": "opacity", "index": index, "location": 0.5}),+ json!({"action": "delete", "kind": "opacity", "index": index}),+ json!({"action": "opacity", "kind": "opacity", "index": index, "opacity": 50}),+ ] {+ let r = s.execute(STOP, p.clone());+ assert!(matches!(r, Err(EngineError::BadParams { .. })), "{p}: {r:?}");+ assert_eq!(active_fill(&s), before, "{p} changed the gradient");+ assert_eq!(s.active().unwrap().history.past_len(), h, "{p} added a history step");+ }+ }+ // The last segment of a two-stop gradient is 0; segment 1 does not exist.+ let r = s.execute(STOP, json!({"action": "midpoint", "index": 1, "location": 0.5}));+ assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains("no segment 1 (there are 1)")), "{r:?}");+ // Control: a valid midpoint edit still applies as one undo step.+ s.execute(STOP, json!({"action": "midpoint", "index": 0, "location": 0.25})).unwrap();+ let Fill::Gradient { midpoints, .. } = active_fill(&s) else { panic!("not a gradient fill") };+ assert_eq!(midpoints, vec![0.25]);+ assert_eq!(s.active().unwrap().history.past_len(), h + 1);+}