icons: gate image dimensions before decoding (H3)

decode() reads the container header and refuses anything over 1024x1024 before gdk::Texture::from_bytes allocates it; preview_icon no longer caches a pre-consent texture.
This commit is contained in:
raucao committed 2026-11-30 10:31:00 +04:00
1 parent 55f069e978
commit 890f934e4a
3 files changed
+188 -5

No files matched your search

+13 -3
View File
@@ -853,13 +853,23 @@ UI lives in `data/resources/ui/*.blp` (Blueprint) and is compiled to `.ui` by
`Send`). A cached `.img` may be decoded synchronously on the first paint
(`AppState::hydrate_icon`), bounded by the byte cap; `IconStore` memoises the
sidecar URL and the one-shot hydration so the per-ping path does no disk I/O.
- **Image dimensions are read before decoding.** `sniff_dimensions` parses the
container header (PNG IHDR / GIF screen / JPEG SOF / WebP VP8/VP8L/VP8X) and
anything over `MAX_ICON_DIMENSION` (1024², since icons render at 32 px) is
refused **before** `gdk::Texture::from_bytes` — a sub-1 MiB PNG can describe a
30,000² canvas, and the decode would allocate the full RGBA before any
post-decode check could run. A header that cannot be parsed is refused (fail
closed).
- **No fetch before consent — now a preference, not a rule.** For an
already-approved app the dialog shows the cached icon. For a first pairing it
shows the client's declared icon too, but **only when `load-app-icons` is on**,
fetched through `AppState::preview_icon`, which is **memory only**: no disk cache
is written for an unapproved app, so a denial leaves nothing behind. With the
preference off there is no request and the dialog shows the generic avatar and
the shortened npub. (M9's no-client-text *notification* bodies remain strict.)
is written for an unapproved app **and the texture is not put in
`IconStore.textures`** (it is handed only to the dialog's `apply` closure), so a
denial leaves nothing behind and repeated pairing prompts cannot leak textures.
With the preference off there is no request and the dialog shows the generic
avatar and the shortened npub. (M9's no-client-text *notification* bodies remain
strict.)
- **A metadata-less client is labelled by its key.** When an app declares no usable
`name`, the approval dialog and the Apps row show `plain::shorten_npub` and build
the `AdwAvatar` with `show_initials(false)` (libadwaita's generic glyph) — never
+4 -1
View File
@@ -403,7 +403,10 @@ impl AppState {
icons.end_preview(&key, &url);
if let Ok(bytes) = result {
if let Ok(texture) = crate::store::icons::decode(&bytes) {
icons.set_texture(&key, texture.clone());
// Deliberately **not** cached: this is a pre-consent
// fetch for an unapproved client, so a denial must leave
// no texture behind (and repeated prompts must not leak
// memory). The texture lives only as long as the dialog.
apply(texture);
}
}
+171 -1
View File
@@ -5,7 +5,8 @@
//! a bounded body, and raster formats only. A refused or undecodable icon simply
//! falls back to the initials an `AdwAvatar` draws.
//!
//! Cache layout (`glib::user_cache_dir()/<app id>/icons/`, the directory 0700),
//! Cache layout (`glib::user_cache_dir()/<app id>/icons/`; the directory is
//! created with the process umask, the files are mode 0600),
//! keyed by the client's public key:
//!
//! - `<hex>.img` — the bytes that decoded, mode 0600.
@@ -37,6 +38,11 @@ const MAX_REDIRECTS: usize = 3;
/// Decoded textures larger than this are dropped. A backstop only: the byte cap
/// and the raster allow-list are the real limits.
const MAX_DIMENSION: i32 = 4096;
/// The largest canvas an icon or avatar may declare. Icons render at 32 px, so
/// this is generous — and it is checked from the *header* before decoding, which
/// is what stops a sub-1 MiB file describing a 30,000×30,000 canvas from
/// allocating gigabytes of RGBA on the main thread.
const MAX_ICON_DIMENSION: u32 = 1024;
const TIMEOUT: Duration = Duration::from_secs(5);
const CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
@@ -289,11 +295,118 @@ fn decode_data_url(rest: &str) -> Result<Vec<u8>> {
Ok(bytes)
}
/// Read an image's pixel dimensions from its container header, **without
/// decoding any pixels**.
///
/// `None` means the header could not be read (truncated, or a variant we do not
/// parse); the caller fails closed. This is the gate that stops a decompression
/// bomb: a small file can describe a huge canvas, and `gdk::Texture::from_bytes`
/// allocates the full uncompressed image before any post-decode check runs.
fn sniff_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
if bytes.starts_with(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]) {
// IHDR is the first chunk: length(4) "IHDR"(4) width(4) height(4), BE.
let width = u32::from_be_bytes(bytes.get(16..20)?.try_into().ok()?);
let height = u32::from_be_bytes(bytes.get(20..24)?.try_into().ok()?);
return Some((width, height));
}
if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
// Logical screen width/height, little-endian.
let width = u16::from_le_bytes(bytes.get(6..8)?.try_into().ok()?) as u32;
let height = u16::from_le_bytes(bytes.get(8..10)?.try_into().ok()?) as u32;
return Some((width, height));
}
if bytes.starts_with(&[0xff, 0xd8, 0xff]) {
return jpeg_dimensions(bytes);
}
if bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP") {
return webp_dimensions(bytes);
}
None
}
/// Walk the JPEG segments to the first Start-Of-Frame marker.
fn jpeg_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
let mut i = 2;
while i + 4 <= bytes.len() {
if bytes[i] != 0xff {
i += 1;
continue;
}
let marker = bytes[i + 1];
if marker == 0xff {
// A fill byte.
i += 1;
continue;
}
// Standalone markers carry no length.
if marker == 0x01 || (0xd0..=0xd7).contains(&marker) {
i += 2;
continue;
}
let length = u16::from_be_bytes([bytes[i + 2], bytes[i + 3]]) as usize;
// Every SOF variant carries the frame size — excluding DHT (C4),
// JPG (C8) and DAC (CC), which are not SOF.
if (0xc0..=0xcf).contains(&marker) && !matches!(marker, 0xc4 | 0xc8 | 0xcc) {
// FF Cx, length(2), precision(1), height(2), width(2).
let height = u16::from_be_bytes([*bytes.get(i + 5)?, *bytes.get(i + 6)?]) as u32;
let width = u16::from_be_bytes([*bytes.get(i + 7)?, *bytes.get(i + 8)?]) as u32;
return Some((width, height));
}
if length < 2 {
return None;
}
i += 2 + length;
}
None
}
/// Read a WebP canvas size from its first chunk (`VP8 `, `VP8L` or `VP8X`).
fn webp_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
match bytes.get(12..16)? {
b"VP8 " => {
// Lossy: 3-byte frame tag, start code 9d 01 2a, then 14-bit
// width/height, little-endian.
let p = bytes.get(20..30)?;
if p[3..6] != [0x9d, 0x01, 0x2a] {
return None;
}
let width = (u16::from_le_bytes([p[6], p[7]]) & 0x3fff) as u32;
let height = (u16::from_le_bytes([p[8], p[9]]) & 0x3fff) as u32;
Some((width, height))
}
b"VP8L" => {
// Lossless: signature 0x2f, then 14-bit (width-1) and (height-1).
let p = bytes.get(20..25)?;
if p[0] != 0x2f {
return None;
}
let bits = u32::from_le_bytes([p[1], p[2], p[3], p[4]]);
Some(((bits & 0x3fff) + 1, ((bits >> 14) & 0x3fff) + 1))
}
b"VP8X" => {
// Extended: 4 flag/reserved bytes, then 24-bit (width-1) and
// (height-1), little-endian.
let p = bytes.get(24..30)?;
let width = u32::from_le_bytes([p[0], p[1], p[2], 0]) + 1;
let height = u32::from_le_bytes([p[3], p[4], p[5], 0]) + 1;
Some((width, height))
}
_ => None,
}
}
/// Turn icon bytes into a `GdkTexture`.
///
/// Must run on the main thread (`gdk::Texture` is not `Send`); the caller does
/// this in a `runtime::spawn` `then`, or while painting a cached icon.
pub fn decode(bytes: &[u8]) -> Result<gdk::Texture> {
// Gate on the header first: `from_bytes` allocates the whole uncompressed
// image, so the dimension check has to happen before it, not after.
let (width, height) =
sniff_dimensions(bytes).ok_or("could not read the image dimensions".to_string())?;
if width > MAX_ICON_DIMENSION || height > MAX_ICON_DIMENSION {
return Err(format!("the icon is {width}×{height}, too large to render"));
}
let bytes = glib::Bytes::from(bytes);
let texture = gdk::Texture::from_bytes(&bytes)
.map_err(|error| format!("could not decode the icon: {error}"))?;
@@ -777,4 +890,61 @@ mod tests {
assert!(!store.needs_fetch("short", "https://x/i.png"));
assert!(!dir.exists(), "no directory is created for an invalid key");
}
/// A PNG header carrying a 30,000×30,000 canvas: `decode` must refuse it
/// from the header, before `gdk::Texture::from_bytes` allocates gigabytes.
fn png_header(width: u32, height: u32) -> Vec<u8> {
let mut bytes = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
bytes.extend_from_slice(&[0, 0, 0, 13]); // IHDR length
bytes.extend_from_slice(b"IHDR");
bytes.extend_from_slice(&width.to_be_bytes());
bytes.extend_from_slice(&height.to_be_bytes());
bytes.extend_from_slice(&[8, 6, 0, 0, 0]); // bit depth, colour, …
bytes
}
#[test]
fn dimensions_are_read_from_each_format_header() {
assert_eq!(sniff_dimensions(&png_header(1200, 800)), Some((1200, 800)));
let mut gif = b"GIF89a".to_vec();
gif.extend_from_slice(&300u16.to_le_bytes());
gif.extend_from_slice(&200u16.to_le_bytes());
gif.extend_from_slice(&[0; 4]);
assert_eq!(sniff_dimensions(&gif), Some((300, 200)));
// JPEG: SOI, an APP0 segment, then SOF0 with height 100, width 150.
let mut jpeg = vec![0xff, 0xd8];
jpeg.extend_from_slice(&[0xff, 0xe0, 0x00, 0x10]); // APP0, length 16
jpeg.extend_from_slice(&[0; 14]);
jpeg.extend_from_slice(&[0xff, 0xc0, 0x00, 0x11, 0x08]); // SOF0, length 17, precision 8
jpeg.extend_from_slice(&100u16.to_be_bytes()); // height
jpeg.extend_from_slice(&150u16.to_be_bytes()); // width
jpeg.extend_from_slice(&[0; 6]);
assert_eq!(sniff_dimensions(&jpeg), Some((150, 100)));
// WebP lossy (VP8): RIFF/WEBP, a 10-byte VP8 payload.
let mut webp = b"RIFF".to_vec();
webp.extend_from_slice(&0u32.to_le_bytes());
webp.extend_from_slice(b"WEBP");
webp.extend_from_slice(b"VP8 ");
webp.extend_from_slice(&0u32.to_le_bytes());
webp.extend_from_slice(&[0, 0, 0]); // frame tag
webp.extend_from_slice(&[0x9d, 0x01, 0x2a]);
webp.extend_from_slice(&320u16.to_le_bytes());
webp.extend_from_slice(&240u16.to_le_bytes());
assert_eq!(sniff_dimensions(&webp), Some((320, 240)));
assert_eq!(sniff_dimensions(&[0x89, b'P', b'N', b'G']), None);
}
/// A huge declared canvas is refused, and a truncated header is refused too
/// (fail closed) — without either reaching the decoder.
#[test]
fn a_decompression_bomb_is_refused_before_decoding() {
let bomb = png_header(30_000, 30_000);
let error = decode(&bomb).expect_err("a 30,000² header must be refused");
assert!(error.contains("too large"), "{error}");
assert!(decode(&[0x89, b'P', b'N', b'G']).is_err());
}
}