Skip to content

[web] Harden WebP and GIF header readers against truncated and malformed buffers - #196075

Merged
auto-submit[bot] merged 14 commits into
flutter:masterfrom
harryterkelsen:web-harden-webpheaderreader-and-gifheaderreader
Nov 18, 2026
Merged

auto-submit[bot] merged 14 commits into
flutter:masterfrom
harryterkelsen:web-harden-webpheaderreader-and-gifheaderreader

Conversation

@harryterkelsen

Copy link
Copy Markdown
Contributor

Hardens the WebP and GIF header readers that detectImageType uses to sniff animation, so that truncated or malformed image bytes can no longer crash image detection on the web.

detectImageType runs synchronously on every encoded image before decoding. When a buffer matched the WebP (RIFF....WEBP) or GIF (GIF87a/GIF89a) signature but was cut short (a partial network download, a corrupt asset, a small synthetic buffer), the header readers indexed past the end of the ByteData and threw an unhandled RangeError. In debug/test builds, malformed GIF blocks also tripped bare asserts. Separately, the GIF reader counted a frame even when it failed to parse the graphic block. It also treated any bytes after the first frame (comments, padding, garbage) as a second frame, so some corrupt or trailing-data single-frame GIFs were reported as animated.

This PR:

  • Adds explicit bounds checks before every read in both readers and turns the GIF asserts into checks that return false.
  • Makes the GIF block-skipping helpers return bool. A frame is only counted after its graphic block parses completely through the data sub-block terminator. The reader only reports animation when that frame is followed by the start of another graphic block (Graphic Control Extension, Plain Text Extension, or Image Descriptor).
  • Wraps each isAnimated() in a final on ArgumentError catch (which also covers RangeError), so the readers never throw.
  • Renames the library-private readers to WebpHeaderReader / GifHeaderReader, marked @visibleForTesting, so tests can drive them directly with synthetic ByteData. They are only reachable through the internal engine library, not dart:ui.
  • Adds table-driven tests for truncated WebP/GIF buffers at every structural boundary, malformed GIF blocks, trailing non-graphic data after one frame, padded subviews, and full-size color tables.

Related: #151911 (animated WebP/GIF detection)

Behavioral Changes

  • Truncated WebP (12–20 bytes, or cut off before the VP8X flags byte):
    • Before: detectImageType threw RangeError (byteOffset): ....
    • After: returns ImageType.webp.
  • Truncated GIF (header only, partial logical screen descriptor, truncated global/local color table, cut inside an extension or image data, or one frame with no trailer):
    • Before: detectImageType threw RangeError.
    • After: returns ImageType.gif.
  • Malformed GIF (reserved/unknown extension label, image separator other than 0x2c, data sub-block longer than the remaining bytes):
    • Before: AssertionError in debug builds, or a misparse in release.
    • After: returns ImageType.gif.
  • Single-frame GIF followed by comment/application extensions, padding, or garbage, with no second graphic block:
    • Before: ImageType.animatedGif.
    • After: ImageType.gif.
  • A GIF containing a reserved extension label (0xFA–0xFD) now reports as static (ImageType.gif). Before, these hit an assert in debug builds and in release were skipped as if they were Application Extensions.
  • Valid WebP and GIF files (including the full test_images corpus) are classified as before.

Where to focus

  • GIF state machine (GifHeaderReader.isAnimated / _skipGraphicBlock in image_format_detector.dart): animation now means "one fully parsed graphic block, then the start of another." The reader stops at the first bytes of frame 2 and doesn't parse it. So a GIF truncated in the middle of its second frame is still detected as animated, which is intended.
  • Failed special-purpose block skips (_maybeSkipSpecialPurposeBlocks returns bool): when a comment/application block is truncated or has a reserved label, the read position is mid-block. Every caller then bails out with false, so bytes inside the broken block (e.g. a stray 0x2c) can't be misread as a frame.
  • Conservative handling of reserved labels 0xFA–0xFD: these make the GIF report as static rather than being skipped generically as introducer + label + sub-blocks. Strictly that's safer, but it means a genuinely animated GIF with a reserved extension decodes as static. Worth a second opinion.
  • The on ArgumentError catch is a backstop: every read is already bounds-checked. It catches ArgumentError rather than RangeError because dart2js surfaces the native JS RangeError from DataView as a Dart ArgumentError.
  • Primary review files: engine/src/flutter/lib/web_ui/lib/src/engine/image_format_detector.dart, then engine/src/flutter/lib/web_ui/test/engine/image_format_detector_test.dart.

Pre-launch Checklist

If you need help, consider asking for advice on the #hackers-new channel on Discord.

If this change needs to override an active code freeze, provide a comment explaining why. The code freeze workflow can be overridden by code reviewers. See pinned issues for any active code freezes with guidance.

Note: The Flutter team is currently trialing the use of Gemini Code Assist for GitHub. Comments from the gemini-code-assist bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed.

@harryterkelsen harryterkelsen added engine flutter/engine related. See also e: labels. platform-web Web applications specifically team-web Owned by Web platform team CICD Run CI/CD labels Nov 5, 2026
@harryterkelsen
harryterkelsen marked this pull request as ready for review November 5, 2026 23:16

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request modifies the image format detector to handle truncated and malformed WebP and GIF buffers gracefully by introducing bounds checks and error handling instead of throwing exceptions. It also exposes the header reader classes as public for testing and adds comprehensive unit tests. Review feedback suggests adding documentation comments to the newly public members of WebpHeaderReader and GifHeaderReader to comply with the style guide, and simplifying the loop in GifHeaderReader.isAnimated by removing a redundant block-skipping check.

Every GIF extension is the introducer, the label and data sub-blocks, so
skip any extension that is not part of a graphic block instead of only
Comment and Application Extensions. An animated GIF with a reserved or
unknown extension between frames is detected as animated again, as it
was before the bounds checks were added.

The frame loop never counted past one frame, so replace it with skipping
the first frame and checking whether a second graphic block starts.
mdebbar
mdebbar previously approved these changes Nov 7, 2026

@mdebbar mdebbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM with one final suggestion!

harryterkelsen and others added 2 commits November 6, 2026 17:42
An animated GIF whose graphic control extension declares a block size
other than 4 was misparsed and reported as static. Skip the extension
the same way as other extensions so its data sub-blocks are walked by
their declared sizes.
mdebbar
mdebbar previously approved these changes Nov 7, 2026

@mdebbar mdebbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still LGTM!

@reidbaker

Copy link
Copy Markdown
Member

@harryterkelsen I am having my agent give both an adversarial review and a review using personas of different current and previous teammates. It will add comments to this pr. Feel free to ignore it as a human. It is intended to comment for your agent to consume.

@reidbaker-agent reidbaker-agent left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The bounds checks look right to me: every read is guarded, both skip loops always advance or exit, and trailing non-graphic data after one frame no longer counts as animation. A few parts of the PR description no longer match the code after the later commits:

  • It says each isAnimated() is wrapped in an on ArgumentError catch, and lists that catch under the places to focus. There is no try/catch left in image_format_detector.dart.
  • It says reserved GIF labels 0xFA–0xFD make the GIF report as static. _checkForSpecialPurposeBlock now treats every label other than 0xF9 and 0x01 as a skippable extension, and the tests expect animatedGif for 0xFA/0xFD between two frames.
  • The "Malformed GIF" bullet lists reserved or unknown extension labels as returning gif. As far as I can tell that only happens now when the extension is truncated.

Could you update the description to match? Inline comments below are smaller suggestions.

Drop the up-front buffer length checks, which repeat the per-read bounds
checks, rename the non-graphic extension helpers to match what they
match, and use backticks for literals in doc comments.

@mdebbar mdebbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

Can we update the PR description before landing? It still mentions the on ArgumentError catch, and it says reserved labels 0xFA–0xFD make the GIF report as static. Neither matches the code anymore.

@harryterkelsen harryterkelsen added the autosubmit Merge PR when tree becomes green via auto submit App label Nov 17, 2026
@auto-submit auto-submit Bot removed the autosubmit Merge PR when tree becomes green via auto submit App label Nov 17, 2026
@auto-submit

auto-submit Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

autosubmit label was removed for flutter/flutter/196075, because - The status or check suite Presubmit has failed. Please fix the issues identified (or deflake) before re-applying this label.

@harryterkelsen harryterkelsen added the autosubmit Merge PR when tree becomes green via auto submit App label Nov 18, 2026
@auto-submit
auto-submit Bot added this pull request to the merge queue Nov 18, 2026
Merged via the queue into flutter:master with commit ef20079 Nov 18, 2026
22 checks passed
@flutter-dashboard flutter-dashboard Bot removed the autosubmit Merge PR when tree becomes green via auto submit App label Nov 18, 2026
LouiseHsu pushed a commit to flutter/packages that referenced this pull request Nov 18, 2026
flutter/flutter@2f09f96...06f32f8

2026-11-18 [email protected] Move macOS
desktop builds to ThinLTO (flutter/flutter#196804)
2026-11-18 [email protected] Roll Dart SDK from
5ed55b4b2ebc to 753488ede427 (2 revisions) (flutter/flutter#196893)
2026-11-18 [email protected] Roll Packages from
9af69be to dca2e58 (7 revisions) (flutter/flutter#196892)
2026-11-18 [email protected] Roll Skia from 503a380ebecc
to 81ee7327e81c (29 revisions) (flutter/flutter#196889)
2026-11-18 [email protected] Roll Dart SDK from
26e38955d9d4 to 5ed55b4b2ebc (4 revisions) (flutter/flutter#196843)
2026-11-18 [email protected] Fix permissions for action updates
(flutter/flutter#196791)
2026-11-18 [email protected] iOS: Apply platform view mutators from
FlutterPlatformViewLayer (flutter/flutter#196753)
2026-11-18 [email protected] [flutter_tools] Remove ambient Doctor,
FeatureFlags, and device getters (flutter/flutter#196572)
2026-11-18 [email protected] Fix
RelativeRect.lerp crash when b is null (flutter/flutter#196655)
2026-11-18 [email protected] [web] Harden
WebP and GIF header readers against truncated and malformed buffers
(flutter/flutter#196075)
2026-11-17 [email protected] Enable apps to
control focus behavior during app lifecycle changes via
`FocusLifecyclePolicy` (flutter/flutter#190570)
2026-11-17 [email protected] Don't re-run the code freeze check
on label changes (flutter/flutter#196745)
2026-11-17 [email protected] Android: Report
FlutterView as a text editor while a text input client is attached
(flutter/flutter#193074)
2026-11-17 [email protected] Roll Packages from
4c6a7d3 to 9af69be (5 revisions) (flutter/flutter#196812)
2026-11-17 [email protected] [flutter_tools] Handle target VM filesystem
errors in DevFS.create (flutter/flutter#196234)
2026-11-17 [email protected] [flutter_tools] Clarify analytics reporting
status when on a feature branch (flutter/flutter#194496)
2026-11-17 [email protected] [web] Recover
CanvasKit surfaces from WebGL failures without per-frame null crashes
(flutter/flutter#196257)
2026-11-17 [email protected] [devicelab] Trigger navigation tap via
Flutter Driver in service_extensions_test (flutter/flutter#194456)

If this roll has caused a breakage, revert this CL and set the roller
to dry run mode using the controls here:
https://autoroll.skia.org/r/flutter-packages
Please CC [email protected],[email protected] on the revert to
ensure that a human
is aware of the problem.

To file a bug in Packages:
https://github.com/flutter/flutter/issues/new/choose

To report a problem with the AutoRoller itself, please file a bug:
https://issues.skia.org/issues/new?component=1389291&template=1850622

Documentation for the AutoRoller is here:
https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CICD Run CI/CD engine flutter/engine related. See also e: labels. platform-web Web applications specifically team-web Owned by Web platform team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants