Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(fonts): validate binary FontFace payloads after descriptor conversion
ldm0c884fe059bc2
diff --git a/moli-core/tests/fetch_behaviors.rs b/moli-core/tests/fetch_behaviors.rsindex fc21683ec..cc18e39b3 100644--- a/moli-core/tests/fetch_behaviors.rs+++ b/moli-core/tests/fetch_behaviors.rs@@ -15,6 +15,9 @@ mod preload_lifecycle;#[path = "fetch_behaviors/preload_as.rs"]mod preload_as;+#[path = "fetch_behaviors/font_binary.rs"]+mod font_binary;+fn diagnostic_global<'a>(page: &'a Page, name: &str) -> Option<&'a JsValueSnapshot> {page.script_execution().global(name)}diff --git a/moli-core/tests/fetch_behaviors/font_binary.rs b/moli-core/tests/fetch_behaviors/font_binary.rsnew file mode 100644index 000000000..93e3a37b4--- /dev/null+++ b/moli-core/tests/fetch_behaviors/font_binary.rs@@ -0,0 +1,29 @@+use super::*;++#[tokio::test(flavor = "multi_thread")]+async fn font_face_binary_sources_validate_payloads_and_buffer_conversion_order() -> Result<()> {+ let fonts = serde_json::json!({+ "ttf": include_bytes!("../../../moli-layout/tests/fixtures/moli-ahem.ttf").as_slice(),+ "woff": include_bytes!("../../../moli-layout/tests/fixtures/moli-ahem.woff").as_slice(),+ "woff2": include_bytes!("../../../moli-layout/tests/fixtures/moli-ahem.woff2").as_slice(),+ });+ let server = FixtureServer::spawn().await?;+ let browser = Browser::new(AppConfig::default())?;+ let mut page = browser.fetch(&server.url("/static")).await?;+ let probe = include_str!("../fixtures/font-binary.js");+ let expression = format!("({probe})({fonts}).then(JSON.stringify)");+ let result = tokio::time::timeout(+ Duration::from_secs(30),+ page.evaluate_runtime_expression_with_await_async(&expression, true),+ )+ .await??;+ let value: serde_json::Value = serde_json::from_str(+ result["value"]+ .as_str()+ .context("binary FontFace results")?,+ )?;+ assert_eq!(value["failures"], serde_json::json!([]), "{value}");+ assert_eq!(value["rows"].as_array().unwrap().len(), 52, "{value}");+ server.shutdown().await;+ Ok(())+}diff --git a/moli-core/tests/fixtures/font-binary.js b/moli-core/tests/fixtures/font-binary.jsnew file mode 100644index 000000000..9815383d4--- /dev/null+++ b/moli-core/tests/fixtures/font-binary.js@@ -0,0 +1,90 @@+async function(fontBytes) {+ const rows = [], failures = [];+ const bytes = format => Uint8Array.from(fontBytes[format]);+ const check = (name, actual, expected) => {+ rows.push({name, actual});+ if (JSON.stringify(actual) !== JSON.stringify(expected)) failures.push({name, actual, expected});+ };+ async function probe(name, make, expected) {+ let conversions = 0, descriptors = 0;+ const source = make();+ try {+ source[Symbol.toPrimitive] = () => { conversions++; return 'url(font.woff2)'; };+ const face = new FontFace(name, source, {get style() { descriptors++; return 'normal'; }});+ const loaded = face.loaded;+ const outcome = await face.load().then(value => value === face ? 'loaded' : 'wrong value', e => e.name);+ check(name, [outcome, face.status, loaded === face.loaded, loaded === face.load(), conversions, descriptors],+ [expected, expected === 'loaded' ? 'loaded' : 'error', true, true, 0, 1]);+ } catch (error) {+ check(name, [error.name, conversions, descriptors], [expected, 0, 0]);+ }+ }+ for (const format of ['ttf', 'woff', 'woff2']) {+ const data = bytes(format);+ for (const kind of ['buffer', 'view', 'offset-view', 'data-view']) {+ await probe(format + '-' + kind, () => {+ const padded = new Uint8Array(data.length + 20); padded.set(data, 8);+ return kind === 'buffer' ? data.slice().buffer : kind === 'view' ? data.slice() :+ kind === 'offset-view' ? padded.subarray(8, 8 + data.length) : new DataView(padded.buffer, 8, data.length);+ }, 'loaded');+ }+ for (const size of [0, 4, 8, 12, 44, 48, data.length - 10]) {+ await probe(format + '-truncated-' + size, () => data.slice(0, size), 'SyntaxError');+ }+ }+ for (const magic of ['OTTO', 'ttcf', 'true', 'typ1']) {+ await probe('magic-' + magic, () => new TextEncoder().encode(magic), 'SyntaxError');+ }+ for (const kind of ['buffer', 'view', 'data-view']) {+ await probe('detached-' + kind, () => {+ const buffer = bytes('ttf').buffer;+ const source = kind === 'buffer' ? buffer : kind === 'view' ? new Uint8Array(buffer) : new DataView(buffer);+ structuredClone(buffer, {transfer: [buffer]}); return source;+ }, 'SyntaxError');+ await probe('resizable-' + kind, () => {+ const data = bytes('ttf'), buffer = new ArrayBuffer(data.length, {maxByteLength: data.length * 2});+ new Uint8Array(buffer).set(data);+ return kind === 'buffer' ? buffer : kind === 'view' ? new Uint8Array(buffer) : new DataView(buffer);+ }, 'TypeError');+ await probe('shared-' + kind, () => {+ const data = bytes('ttf'), buffer = new WebAssembly.Memory({initial: 1, maximum: 1, shared: true}).buffer;+ new Uint8Array(buffer).set(data);+ return kind === 'buffer' ? buffer : kind === 'view' ? new Uint8Array(buffer, 0, data.length) : new DataView(buffer, 0, data.length);+ }, 'TypeError');+ }++ const mutable = bytes('ttf');+ const copied = new FontFace('Copied', mutable, {get style() { mutable.fill(0); return 'normal'; }});+ check('descriptor-mutation-before-copy', [await copied.loaded.catch(e => e.name), copied.status, mutable[1]], ['SyntaxError', 'error', 0]);+ const detached = bytes('ttf');+ const detachedFace = new FontFace('Detached', detached, {get style() {+ structuredClone(detached.buffer, {transfer: [detached.buffer]}); return 'normal';+ }});+ check('descriptor-detachment-before-copy', await detachedFace.loaded.catch(e => e.name), 'SyntaxError');+ const repaired = new Uint8Array(fontBytes.ttf.length);+ const repairedFace = new FontFace('Repaired', repaired, {get style() { repaired.set(bytes('ttf')); return 'normal'; }});+ check('descriptor-repair-before-copy', await repairedFace.loaded === repairedFace, true);+ const transferred = bytes('ttf');+ const retained = new FontFace('Retained', transferred);+ structuredClone(transferred.buffer, {transfer: [transferred.buffer]});+ check('retained-after-transfer', [await retained.load() === retained, retained.status], [true, 'loaded']);+ await probe('whole-padded-buffer', () => {+ const data = bytes('ttf'), padded = new Uint8Array(data.length + 20); padded.set(data, 8); return padded;+ }, 'SyntaxError');++ const iframe = document.createElement('iframe');+ const ready = new Promise(resolve => iframe.onload = resolve);+ document.body.append(iframe); await ready;+ const other = iframe.contentWindow;+ const valid = new other.FontFace('Foreign', bytes('ttf'));+ const load = FontFace.prototype.load.call(valid);+ const invalid = new other.FontFace('Invalid', new Uint8Array([0, 1, 0, 0]));+ const rejection = await invalid.loaded.catch(e => [e.name, e instanceof other.DOMException]);+ let thrown;+ try { new other.FontFace('Resizable', new ArrayBuffer(8, {maxByteLength: 16})); }+ catch (e) { thrown = [e instanceof other.TypeError, e instanceof TypeError]; }+ check('cross-realm', [load instanceof other.Promise, await load === valid, rejection, thrown],+ [true, true, ['SyntaxError', true], [true, false]]);+ iframe.remove();+ return {rows, failures};+}diff --git a/moli-layout/src/lib.rs b/moli-layout/src/lib.rsindex 72db0713a..e3ffb52d1 100644--- a/moli-layout/src/lib.rs+++ b/moli-layout/src/lib.rs@@ -101,6 +101,7 @@ pub use style::{pub use text::{DocumentLayoutServices, SystemFontPolicy, WebFontFace, WebFontRegistration,WebFontRegistrationError, WebFontRegistrationOutcome, WebFontStyle, WebFontUnicodeRange,+ validate_web_font_bytes,};pub use world::{LayoutAnonymousReason, LayoutBox, LayoutBoxId, LayoutBoxKind, LayoutCapabilityDiagnostic,diff --git a/moli-layout/src/text.rs b/moli-layout/src/text.rsindex e5c03cf94..4c94c6cde 100644--- a/moli-layout/src/text.rs+++ b/moli-layout/src/text.rs@@ -954,6 +954,11 @@ fn validate_registered_font(.ok_or(WebFontRegistrationError::UnsupportedPayload)}+/// Validate font bytes without registering them in a document's layout.+pub fn validate_web_font_bytes(bytes: &[u8]) -> Result<(), WebFontRegistrationError> {+ validate_registered_font(&WebFontFace::new("FontFace"), decode_web_font_bytes(bytes)?)+}+fn decode_web_font_bytes(bytes: &[u8]) -> Result<Arc<[u8]>, WebFontRegistrationError> {let decoded = match bytes.get(..4) {Some(b"wOFF") => wuff::decompress_woff1(bytes)diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rsindex 943a964f7..c736147a1 100644--- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs@@ -183,16 +183,16 @@ struct FontFacePrototypeAccessorsDeclaration {#[derive(webidl::WebIdlArgs)]#[webidl(prefix = "FontFace")]-struct FontFaceConstructorArgs {+struct FontFaceConstructorArgs<'s> {#[webidl(required)]family: String,#[webidl(required, with = font_face_constructor_source_arg)]- source: FontFaceConstructorSource,+ source: FontFaceConstructorSource<'s>,}-enum FontFaceConstructorSource {+enum FontFaceConstructorSource<'s> {Css(String),- Binary(Vec<u8>),+ Binary(v8::Local<'s, v8::Value>),}pub(in crate::context_bootstrap) fn install_font_face_template_accessors<'s>(@@ -322,19 +322,34 @@ pub(in crate::context_bootstrap) fn font_face_constructor_callback<'s>(let loaded = resolved_promise(scope, this.into());(source, "loaded", loaded)}- FontFaceConstructorSource::Binary(bytes)- if moli_web_mime::sniff_font_mime_type(&bytes).is_some() =>- {- let loaded = resolved_promise(scope, this.into());- (String::new(), "loaded", loaded)- }- FontFaceConstructorSource::Binary(_) => {- let loaded = super::query::make_rejected_dom_exception_promise(+ FontFaceConstructorSource::Binary(value) => {+ // Retain the native buffer during union conversion. Descriptor+ // getters may mutate or detach it before the operation copies it.+ let bytes = match webidl::convert::<webidl::BufferSource>(scope,- "SyntaxError",- "Invalid font data in ArrayBuffer.",- );- (String::new(), "error", Some(loaded))+ value,+ webidl::Context::argument("FontFace", 2),+ ) {+ Ok(bytes) => bytes.into_bytes(),+ Err(error) => {+ webidl::throw_error(scope, &error);+ return;+ }+ };+ if moli_layout::validate_web_font_bytes(&bytes).is_ok() {+ let backing = v8::ArrayBuffer::new_backing_store_from_vec(bytes).make_shared();+ let data = v8::ArrayBuffer::with_backing_store(scope, &backing);+ set_private_value(scope, this, "__moliFontFaceData", data.into());+ let loaded = resolved_promise(scope, this.into());+ (String::new(), "loaded", loaded)+ } else {+ let loaded = super::query::make_rejected_dom_exception_promise(+ scope,+ "SyntaxError",+ "Invalid font data in ArrayBuffer.",+ );+ (String::new(), "error", Some(loaded))+ }}}};@@ -365,7 +380,7 @@ fn font_face_constructor_source_arg<'s>(scope: &mut v8::PinScope<'s, '_>,args: &v8::FunctionCallbackArguments<'s>,index: i32,-) -> Result<FontFaceConstructorSource, webidl::WebIdlError> {+) -> Result<FontFaceConstructorSource<'s>, webidl::WebIdlError> {if args.length() <= index {return Err(webidl::WebIdlError::custom_message("Failed to construct 'FontFace': 2 arguments required, but only 1 present.",@@ -373,11 +388,18 @@ fn font_face_constructor_source_arg<'s>(}let value = args.get(index);let context = webidl::Context::argument("FontFace", (index + 1) as usize);+ // The BufferSource alternative has neither AllowShared nor AllowResizable.+ if value.is_shared_array_buffer()+ || crate::blob::buffer_source_has_shared_or_resizable_backing_store(value)+ {+ return Err(webidl::WebIdlError::custom_message(+ "Failed to construct 'FontFace': shared and resizable buffers are not allowed.",+ ));+ }if v8::Local::<v8::ArrayBuffer>::try_from(value).is_ok()|| v8::Local::<v8::ArrayBufferView>::try_from(value).is_ok(){- return webidl::convert::<webidl::BufferSource>(scope, value, context)- .map(|source| FontFaceConstructorSource::Binary(source.into_bytes()));+ return Ok(FontFaceConstructorSource::Binary(value));}webidl::convert::<webidl::DomString>(scope, value, context).map(|source| FontFaceConstructorSource::Css(source.into()))