From efb2a6cbc7d220032d404efcf8c0ca670d966535 Mon Sep 17 00:00:00 2001 From: faseJade Date: Thu, 5 Nov 2026 09:39:27 +0200 Subject: [PATCH] refactor: one base64 decoder, from the base64 crate paint::tile::b64_decode, plugin.install, the macOS monitor-profile reader and the font SRI helper each hand-rolled base64. The shared decoder took "====" as one zero byte and padding mid-string ("QQ==QUJD"), and plugin.install alone took unpadded input. All now use the base64 crate (already in the tree): standard alphabet, padding optional, whitespace ignored, anything else refused. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 + apps/photocraft/src/monitor_profile.rs | 56 +------------------- crates/engine/src/cmd/plugin_cmds.rs | 29 +---------- crates/engine/src/cmd/plugin_cmds/tests.rs | 13 +---- crates/paint/Cargo.toml | 2 + crates/paint/src/tile.rs | 60 ++++++++-------------- crates/text/Cargo.toml | 2 + crates/text/src/served.rs | 17 +----- 8 files changed, 31 insertions(+), 150 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b66bb8add0..b5117436d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5453,6 +5453,7 @@ dependencies = [ name = "photocraft-paint" version = "0.20.1" dependencies = [ + "base64 0.23.1", "photocraft-cms", "photocraft-color", "photocraft-geom", @@ -5545,6 +5546,7 @@ dependencies = [ name = "photocraft-text" version = "0.20.1" dependencies = [ + "base64 0.23.1", "flate2", "parley", "photocraft-color", diff --git a/apps/photocraft/src/monitor_profile.rs b/apps/photocraft/src/monitor_profile.rs index c210e096ec..cd3fa7b964 100644 --- a/apps/photocraft/src/monitor_profile.rs +++ b/apps/photocraft/src/monitor_profile.rs @@ -372,7 +372,7 @@ fn parse_reply(out: &str) -> Detection { let b64 = b64.trim(); // An ICC profile starts with its size and carries `acsp` at offset 36; anything else is // treated as no profile (the engine then says the display has none). - let icc = (!b64.is_empty()).then(|| base64_decode(b64)).flatten().filter(|b| b.len() >= 132 && b.get(36..40) == Some(b"acsp")); + let icc = (!b64.is_empty()).then(|| photocraft_engine::paint::tile::b64_decode(b64)).flatten().filter(|b| b.len() >= 132 && b.get(36..40) == Some(b"acsp")); let profile_name = Some(profile_name.trim().to_string()).filter(|n| !n.is_empty()); displays.push(Display { id, name, frame: [x, top, w, h], profile_name, icc: icc.map(std::sync::Arc::new) }); } @@ -400,51 +400,10 @@ fn display_id(s: &str) -> Option { }) } -/// Standard base64 (RFC 4648, with padding) → bytes; `None` on any invalid character. -#[cfg_attr(not(target_os = "macos"), allow(dead_code))] -fn base64_decode(s: &str) -> Option> { - let val = |c: u8| -> Option { - Some(match c { - b'A'..=b'Z' => c - b'A', - b'a'..=b'z' => c - b'a' + 26, - b'0'..=b'9' => c - b'0' + 52, - b'+' => 62, - b'/' => 63, - _ => return None, - } as u32) - }; - let s = s.trim_end_matches('=').as_bytes(); - let mut out = Vec::with_capacity(s.len() * 3 / 4); - for chunk in s.chunks(4) { - let mut acc = 0u32; - for (i, c) in chunk.iter().enumerate() { - acc |= val(*c)? << (18 - 6 * i); - } - let n = match chunk.len() { - 4 => 3, - 3 => 2, - 2 => 1, - _ => return None, - }; - out.extend_from_slice(&acc.to_be_bytes()[1..1 + n]); - } - Some(out) -} - #[cfg(test)] mod tests { use super::*; - #[test] - fn base64() { - assert_eq!(base64_decode("aGVsbG8=").as_deref(), Some(&b"hello"[..])); - assert_eq!(base64_decode("aGVsbG8h").as_deref(), Some(&b"hello!"[..])); - assert_eq!(base64_decode("aGk=").as_deref(), Some(&b"hi"[..])); - assert_eq!(base64_decode("").as_deref(), Some(&b""[..])); - assert!(base64_decode("a").is_none()); - assert!(base64_decode("a$==").is_none()); - } - #[test] fn helper_replies() { // Only the ICC signature is checked here; parsing is the engine's job. @@ -510,18 +469,7 @@ mod tests { } fn base64_encode(b: &[u8]) -> String { - const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let mut s = String::new(); - for c in b.chunks(3) { - let n = c.iter().enumerate().fold(0u32, |n, (i, v)| n | u32::from(*v) << (16 - 8 * i)); - for i in 0..=c.len() { - s.push(A[(n >> (18 - 6 * i) & 63) as usize] as char); - } - } - while !s.len().is_multiple_of(4) { - s.push('='); - } - s + photocraft_engine::paint::tile::b64_encode(b) } /// On a Mac, every display is read, and the profiles parse as RGB profiles. diff --git a/crates/engine/src/cmd/plugin_cmds.rs b/crates/engine/src/cmd/plugin_cmds.rs index 6e5ff3dff9..56d68a49d7 100644 --- a/crates/engine/src/cmd/plugin_cmds.rs +++ b/crates/engine/src/cmd/plugin_cmds.rs @@ -160,33 +160,6 @@ pub(crate) fn apply_to_surface(command: &str, params: &Value, surf: &Surface, se /// Largest base64 payload `plugin.install` accepts (the module limit, encoded). const MAX_DATA_CHARS: usize = (32 << 20) / 3 * 4 + 4; -fn b64_decode(s: &str) -> Option> { - let val = |c: u8| -> Option { - Some(u32::from(match c { - b'A'..=b'Z' => c - b'A', - b'a'..=b'z' => c - b'a' + 26, - b'0'..=b'9' => c - b'0' + 52, - b'+' | b'-' => 62, - b'/' | b'_' => 63, - _ => return None, - })) - }; - let clean: Vec = s.bytes().filter(|c| !c.is_ascii_whitespace() && *c != b'=').collect(); - if clean.len() % 4 == 1 { - return None; - } - let mut out = Vec::with_capacity(clean.len() / 4 * 3 + 2); - for chunk in clean.chunks(4) { - let mut n = 0u32; - for (i, &c) in chunk.iter().enumerate() { - n |= val(c)? << (18 - 6 * i); - } - let bytes = [(n >> 16) as u8, (n >> 8) as u8, n as u8]; - out.extend_from_slice(bytes.get(..chunk.len() - 1)?); - } - Some(out) -} - fn install(_s: &mut Session, p: &Value) -> Result { const CMD: &str = "plugin.install"; let plugin = if let Some(data) = p.get("data") { @@ -194,7 +167,7 @@ fn install(_s: &mut Session, p: &Value) -> Result { if data.len() > MAX_DATA_CHARS { return Err(bad(CMD, "`data` is larger than the module limit")); } - let bytes = b64_decode(data).ok_or_else(|| bad(CMD, "`data` is not valid base64"))?; + let bytes = photocraft_paint::tile::b64_decode(data).ok_or_else(|| bad(CMD, "`data` is not valid base64"))?; Plugin::load(&bytes, photocraft_plugins::Limits::default()).map_err(err)? } else if let Some(path) = p.get("path") { let path = path.as_str().filter(|s| !s.is_empty()).ok_or_else(|| bad(CMD, "`path` must be a file path"))?; diff --git a/crates/engine/src/cmd/plugin_cmds/tests.rs b/crates/engine/src/cmd/plugin_cmds/tests.rs index 44b129bc5c..22ad669772 100644 --- a/crates/engine/src/cmd/plugin_cmds/tests.rs +++ b/crates/engine/src/cmd/plugin_cmds/tests.rs @@ -6,15 +6,7 @@ const INVERT: &[u8] = include_bytes!("../../../../plugins/tests/fixtures/invert. const INVERT_ID: &str = "org.photocraft.example.invert"; fn b64(b: &[u8]) -> String { - const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let mut out = String::new(); - for c in b.chunks(3) { - let n = (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0)); - for i in 0..4 { - out.push(if i <= c.len() { T[(n >> (18 - 6 * i)) as usize & 63] as char } else { '=' }); - } - } - out + photocraft_paint::tile::b64_encode(b) } /// A WAT plug-in with its own `id` whose `pc_filter` body is `filter`. @@ -324,9 +316,6 @@ fn bad_params_are_errors_not_panics() { } // No document: running is disabled. assert!(Session::new().execute("plugin.run", json!({"id": "x"})).is_err()); - assert_eq!(b64_decode("aGk="), Some(b"hi".to_vec())); - assert_eq!(b64_decode("aGk"), Some(b"hi".to_vec())); - assert_eq!(b64_decode("a"), None); } #[test] diff --git a/crates/paint/Cargo.toml b/crates/paint/Cargo.toml index f07ffeefaf..62ec0ab951 100644 --- a/crates/paint/Cargo.toml +++ b/crates/paint/Cargo.toml @@ -13,6 +13,8 @@ photocraft-color = { workspace = true } photocraft-raster = { workspace = true } serde = { workspace = true } rustc-hash = { workspace = true } +# The tile serde form and commands that take file bytes as base64 text. +base64 = "0.23" # Large tips rasterize, accumulate and composite in parallel (the same pixels as serially). [target.'cfg(not(target_arch = "wasm32"))'.dependencies] diff --git a/crates/paint/src/tile.rs b/crates/paint/src/tile.rs index 8ea0e776b6..470a61c6bb 100644 --- a/crates/paint/src/tile.rs +++ b/crates/paint/src/tile.rs @@ -174,53 +174,21 @@ impl<'de> Deserialize<'de> for GrayTile { } } -const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +/// Base64 with the standard alphabet; decoding takes padded or unpadded input. +const B64: base64::engine::GeneralPurpose = base64::engine::GeneralPurpose::new( + &base64::alphabet::STANDARD, + base64::engine::GeneralPurposeConfig::new().with_decode_padding_mode(base64::engine::DecodePaddingMode::Indifferent), +); /// Standard base64 with padding (the tile serde form; commands taking file bytes). pub fn b64_encode(b: &[u8]) -> String { - let mut out = String::with_capacity(b.len().div_ceil(3) * 4); - for c in b.chunks(3) { - let n = (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0)); - out.push(B64[(n >> 18) as usize & 63] as char); - out.push(B64[(n >> 12) as usize & 63] as char); - out.push(if c.len() > 1 { B64[(n >> 6) as usize & 63] as char } else { '=' }); - out.push(if c.len() > 2 { B64[n as usize & 63] as char } else { '=' }); - } - out + base64::Engine::encode(&B64, b) } -/// Decode standard base64 (whitespace ignored); `None` on invalid input. +/// Decode standard base64, padded or not (whitespace ignored); `None` on invalid input. pub fn b64_decode(s: &str) -> Option> { - let val = |c: u8| -> Option { - Some(match c { - b'A'..=b'Z' => c - b'A', - b'a'..=b'z' => c - b'a' + 26, - b'0'..=b'9' => c - b'0' + 52, - b'+' => 62, - b'/' => 63, - _ => return None, - } as u32) - }; let s: Vec = s.bytes().filter(|c| !c.is_ascii_whitespace()).collect(); - if !s.len().is_multiple_of(4) { - return None; - } - let mut out = Vec::with_capacity(s.len() / 4 * 3); - for c in s.chunks(4) { - let pad = c.iter().rev().take_while(|&&x| x == b'=').count(); - let mut n = 0u32; - for (i, &x) in c.iter().enumerate() { - n = (n << 6) | if i >= 4 - pad { 0 } else { val(x)? }; - } - out.push((n >> 16) as u8); - if pad < 2 { - out.push((n >> 8) as u8); - } - if pad < 1 { - out.push(n as u8); - } - } - Some(out) + base64::Engine::decode(&B64, s).ok() } // ---------- sampling ---------- @@ -331,6 +299,18 @@ mod tests { } } + #[test] + fn base64_rejects_bad_padding_and_takes_unpadded() { + assert_eq!(b64_decode("aGk=").as_deref(), Some(&b"hi"[..])); + assert_eq!(b64_decode("aGk").as_deref(), Some(&b"hi"[..])); + assert_eq!(b64_decode(" aG\nk= ").as_deref(), Some(&b"hi"[..])); + assert_eq!(b64_decode("").as_deref(), Some(&b""[..])); + assert_eq!(b64_decode("===="), None); + assert_eq!(b64_decode("QQ==QUJD"), None); + assert_eq!(b64_decode("a"), None); + assert_eq!(b64_decode("a$=="), None); + } + #[test] fn tile_serde_round_trip_and_float_form() { let t = GrayTile::from_fn(5, 3, |x, y| (x + y) as f32 / 6.0); diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 88ea57c94b..335b4091cd 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -20,6 +20,8 @@ photocraft-psd = { workspace = true } parley = { version = "0.11", default-features = false, features = ["std"] } skrifa = "0.44" flate2 = { workspace = true } +# Subresource Integrity values for served fonts. +base64 = "0.23" # ICU dictionary data for Japanese word boundaries and complex-script (Thai, Lao, Khmer, Burmese) # line breaking. Native only: the CJK dictionary alone is 3.8 MB of wasm, and the web build must diff --git a/crates/text/src/served.rs b/crates/text/src/served.rs index 138a1991b0..015e3b2811 100644 --- a/crates/text/src/served.rs +++ b/crates/text/src/served.rs @@ -166,22 +166,7 @@ fn sri(hex: &str) -> Option { return None; } let bytes: Option> = (0..32).map(|i| hex.get(2 * i..2 * i + 2).and_then(|h| u8::from_str_radix(h, 16).ok())).collect(); - Some(format!("sha256-{}", base64(&bytes?))) -} - -/// Standard base64 (RFC 4648, with padding). -fn base64(data: &[u8]) -> String { - const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let mut s = String::with_capacity(data.len().div_ceil(3) * 4); - for chunk in data.chunks(3) { - let b = |i: usize| u32::from(chunk.get(i).copied().unwrap_or(0)); - let n = (b(0) << 16) | (b(1) << 8) | b(2); - for k in 0..4 { - let six = ((n >> (18 - 6 * k)) & 63) as usize; - s.push(if k <= chunk.len() { TABLE.get(six).map_or('=', |&c| char::from(c)) } else { '=' }); - } - } - s + Some(format!("sha256-{}", base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes?))) } struct State {