diff --git a/Cargo.lock b/Cargo.lock index a34ffa1dc2..3e3059cda6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5763,6 +5763,7 @@ dependencies = [ name = "photocraft-paint" version = "0.23.1" dependencies = [ + "base64 0.23.1", "craft-cms", "photocraft-color", "photocraft-geom", @@ -5847,6 +5848,7 @@ dependencies = [ name = "photocraft-text" version = "0.23.1" dependencies = [ + "base64 0.23.1", "craft-psd", "flate2", "parley", diff --git a/apps/photocraft/src/monitor_profile.rs b/apps/photocraft/src/monitor_profile.rs index 5672f88c6d..68e19b4f48 100644 --- a/apps/photocraft/src/monitor_profile.rs +++ b/apps/photocraft/src/monitor_profile.rs @@ -372,7 +372,8 @@ 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 +401,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 +470,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..9cdf456935 100644 --- a/crates/engine/src/cmd/plugin_cmds.rs +++ b/crates/engine/src/cmd/plugin_cmds.rs @@ -161,30 +161,9 @@ pub(crate) fn apply_to_surface(command: &str, params: &Value, surf: &Surface, se 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) + // plugin.install historically accepts both alphabet variants, including mixed input. + // Keep that input policy while the library validates padding and decodes the bytes. + photocraft_paint::tile::b64_decode(&s.replace('-', "+").replace('_', "/")) } fn install(_s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/plugin_cmds/tests.rs b/crates/engine/src/cmd/plugin_cmds/tests.rs index 677e5ae351..c949326f3f 100644 --- a/crates/engine/src/cmd/plugin_cmds/tests.rs +++ b/crates/engine/src/cmd/plugin_cmds/tests.rs @@ -5,16 +5,19 @@ use photocraft_geom::Rect; const INVERT: &[u8] = include_bytes!("../../../../plugins/tests/fixtures/invert.wasm"); 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 { '=' }); - } +#[test] +fn plugin_base64_keeps_standard_urlsafe_and_mixed_alphabets() { + for data in ["+/8=", "-_8=", "+_8=", "-/8=", "-_8"] { + assert_eq!(b64_decode(data), Some(vec![251, 255]), "{data}"); } - out + 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); + assert_eq!(b64_decode("QQ==QUJD"), None); +} + +fn b64(b: &[u8]) -> String { + photocraft_paint::tile::b64_encode(b) } /// A WAT plug-in with its own `id` whose `pc_filter` body is `filter`. @@ -324,9 +327,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 42d71e5317..45a36be7eb 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 08c16fb541..1eda523461 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 ---------- @@ -442,6 +410,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 bf77cdbeb7..7ee4618f12 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -20,6 +20,8 @@ craft-psd = { workspace = true } parley = { version = "0.11", default-features = false, features = ["std"] } skrifa = "0.47" 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 952f43cb25..1069e29841 100644 --- a/crates/text/src/served.rs +++ b/crates/text/src/served.rs @@ -168,22 +168,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 {