diff --git a/moli-benchmark/wpt-cross-current/passed-cases.txt b/moli-benchmark/wpt-cross-current/passed-cases.txt index 2c6ba03415c..ad7ad3b018d 100644 --- a/moli-benchmark/wpt-cross-current/passed-cases.txt +++ b/moli-benchmark/wpt-cross-current/passed-cases.txt @@ -5721,7 +5721,19 @@ fetch/api/request/url-encoding.html fetch/api/response/many-empty-chunks-crash.html fetch/api/response/multi-globals/url-parsing.html fetch/api/response/response-body-read-task-handling.html +fetch/api/response/response-error-from-stream.any.js?moli-wpt-any=dedicatedworker +fetch/api/response/response-error-from-stream.any.js?moli-wpt-any=window fetch/api/response/response-form-data.html +fetch/api/response/response-from-stream.any.js?moli-wpt-any=dedicatedworker +fetch/api/response/response-from-stream.any.js?moli-wpt-any=window +fetch/api/response/response-stream-disturbed-2.any.js?moli-wpt-any=dedicatedworker +fetch/api/response/response-stream-disturbed-2.any.js?moli-wpt-any=window +fetch/api/response/response-stream-disturbed-3.any.js?moli-wpt-any=dedicatedworker +fetch/api/response/response-stream-disturbed-3.any.js?moli-wpt-any=window +fetch/api/response/response-stream-disturbed-4.any.js?moli-wpt-any=dedicatedworker +fetch/api/response/response-stream-disturbed-4.any.js?moli-wpt-any=window +fetch/api/response/response-stream-disturbed-5.any.js?moli-wpt-any=dedicatedworker +fetch/api/response/response-stream-disturbed-5.any.js?moli-wpt-any=window fetch/content-length/content-length.html fetch/nosniff/importscripts.html fetch/security/dangling-markup/media.html diff --git a/moli-core/tests/fixtures/runtime/body_consumption_state.js b/moli-core/tests/fixtures/runtime/body_consumption_state.js new file mode 100644 index 00000000000..57729b6a575 --- /dev/null +++ b/moli-core/tests/fixtures/runtime/body_consumption_state.js @@ -0,0 +1,159 @@ +async function runBodyConsumptionStateProbe(scenario, url) { + const errors = []; + const check = (value, label) => { if (!value) errors.push(label); }; + const throwsTypeError = (callback, label) => { + try { callback(); errors.push(label + ': accepted'); } + catch (error) { check(error instanceof TypeError, label + ': wrong error ' + error); } + }; + const rejectsTypeError = async (callback, label) => { + let promise; + try { promise = callback(); } + catch (error) { errors.push(label + ': synchronous throw ' + error); return; } + try { await promise; errors.push(label + ': fulfilled'); } + catch (error) { check(error instanceof TypeError, label + ': wrong rejection ' + error); } + }; + const methods = ['text', 'json', 'arrayBuffer', 'bytes', 'blob', 'formData']; + const streamFrom = value => new ReadableStream({ + start(controller) { controller.enqueue(new TextEncoder().encode(value)); controller.close(); } + }); + const makeBody = async (source, method = 'text') => { + const text = method === 'formData' ? 'name=value' : '{"value":1}'; + const headers = {'Content-Type': method === 'formData' + ? 'application/x-www-form-urlencoded' : 'application/json'}; + if (source === 'request') return new Request(url, {method: 'POST', body: text, headers}); + if (source === 'response') return new Response(text, {headers}); + if (source === 'stream') return new Response(streamFrom(text), {headers}); + return fetch(url); + }; + const sources = ['request', 'response', 'stream', 'fetch']; + + if (scenario === 'null') { + const bodies = [new Request(url), new Response(), new Response(null, {status: 204}), + Response.error(), Response.redirect(url)]; + for (const [index, body] of bodies.entries()) { + check(body.body === null, index + ': null body'); + for (const method of methods) { + for (let repeat = 0; repeat < 2; ++repeat) { + try { await body[method](); } catch (error) { + check(error instanceof TypeError || error instanceof SyntaxError, index + ': empty conversion error'); + } + check(!body.bodyUsed, index + ': ' + method + ' must not disturb a null body'); + } + } + try { check(await body.text() === '', index + ': null body remains readable'); } + catch (error) { errors.push(index + ': null body became unusable ' + error); } + try { check(body.clone().body === null, index + ': null clone'); } + catch (error) { errors.push(index + ': cannot clone null body ' + error); } + } + } else if (scenario === 'locked') { + for (const source of sources) { + for (const method of methods) { + const body = await makeBody(source, method); + const reader = body.body.getReader(); + check(!body.bodyUsed, source + ': locking alone does not disturb'); + throwsTypeError(() => body.clone(), source + ': locked clone'); + await rejectsTypeError(() => body[method](), source + ': locked ' + method); + check(!body.bodyUsed, source + ': failed ' + method + ' must not disturb'); + reader.releaseLock(); + try { await body.text(); } + catch (error) { errors.push(source + ': released unused body cannot be consumed ' + error); } + } + } + } else if (scenario === 'consumed') { + for (const source of sources) { + for (const method of methods) { + const body = await makeBody(source, method); + const original = body.body; + const pending = body[method](); + check(body.bodyUsed, source + ': ' + method + ' disturbs immediately'); + check(original.locked, source + ': ' + method + ' locks immediately'); + throwsTypeError(() => original.getReader(), source + ': reader during ' + method); + try { await pending; } catch {} + check(body.body === original && body.bodyUsed, source + ': stable used body'); + check(original.locked, source + ': ' + method + ' keeps the reader lock'); + throwsTypeError(() => body.clone(), source + ': consumed clone'); + await rejectsTypeError(() => body.text(), source + ': repeated consume'); + } + } + } else if (scenario === 'disturbed') { + const controller = new AbortController(); + controller.abort({unexpected: 'abort must not hide unusable body'}); + for (const source of sources) { + for (const action of ['read', 'cancel']) { + const body = await makeBody(source); + const stream = body.body; + if (action === 'read') { + const reader = stream.getReader(); + await reader.read(); + reader.releaseLock(); + } else { + await stream.cancel(); + } + check(!stream.locked && body.bodyUsed, source + ': ' + action + ' disturbed after release'); + throwsTypeError(() => body.clone(), source + ': disturbed clone'); + throwsTypeError(() => new Response(stream), source + ': disturbed Response input'); + throwsTypeError(() => new Request(url, {method: 'POST', body: stream, duplex: 'half'}), + source + ': disturbed RequestInit body'); + if (source === 'request') throwsTypeError(() => new Request(body), 'disturbed Request input'); + await rejectsTypeError(() => fetch(url, {method: 'POST', body: stream, duplex: 'half', + signal: controller.signal}), source + ': disturbed fetch body precedes abort'); + for (const method of methods) { + await rejectsTypeError(() => body[method](), source + ': disturbed ' + method); + } + } + } + } else if (scenario === 'errors') { + const reason = {stream: 'failed'}; + const stream = new ReadableStream({start(controller) { controller.error(reason); }}); + const response = new Response(stream); + check(!response.bodyUsed, 'unread errored body is not disturbed'); + try { await response.text(); errors.push('errored body fulfilled'); } + catch (error) { check(error === reason, 'original stream error identity'); } + check(response.bodyUsed && stream.locked, 'errored read retains used/locked state'); + await rejectsTypeError(() => response.text(), 'errored body cannot be read twice'); + let pulls = 0; + const invalidMime = new Response(new ReadableStream({pull(controller) { + ++pulls; controller.enqueue(new Uint8Array([1])); controller.close(); + }}), {headers: {'Content-Type': 'text/plain'}}); + await rejectsTypeError(() => invalidMime.formData(), 'unsupported MIME conversion'); + check(pulls === 1 && invalidMime.bodyUsed && invalidMime.body.locked, + 'conversion failure still fully consumes and locks body'); + const invalidJSON = new Response('{invalid'); + try { await invalidJSON.json(); errors.push('invalid JSON fulfilled'); } + catch (error) { check(error instanceof SyntaxError, 'JSON parse failure rejects with SyntaxError'); } + check(invalidJSON.bodyUsed && invalidJSON.body.locked, 'JSON failure consumes body'); + } else if (scenario === 'poison') { + let reads = 0; + const poison = () => { ++reads; throw new Error('public stream member consulted'); }; + const stream = streamFrom('intrinsic reader'); + Object.defineProperty(stream, 'locked', {get: poison}); + Object.defineProperty(stream, 'getReader', {get: poison}); + const response = new Response(stream); + const readDescriptor = Object.getOwnPropertyDescriptor(ReadableStreamDefaultReader.prototype, 'read'); + Object.defineProperty(ReadableStreamDefaultReader.prototype, 'read', {configurable: true, get: poison}); + try { check(await response.text() === 'intrinsic reader', 'intrinsic reader reads body'); } + finally { Object.defineProperty(ReadableStreamDefaultReader.prototype, 'read', readDescriptor); } + check(reads === 0, 'body operations ignore public stream member overrides'); + const parse = JSON.parse; + JSON.parse = poison; + try { + for (const source of ['request', 'response', 'stream']) { + const body = await makeBody(source, 'json'); + check((await body.json()).value === 1, source + ': intrinsic JSON parser'); + } + } finally { JSON.parse = parse; } + check(reads === 0, 'body JSON parsing ignores public JSON.parse'); + for (const source of ['request', 'response']) { + const body = await makeBody(source); + const reader = body.body.getReader(); + Object.defineProperty(body.body, 'locked', {value: false}); + throwsTypeError(() => body.clone(), source + ': forged unlocked stream cannot clone'); + await rejectsTypeError(() => body.text(), source + ': forged unlocked stream cannot consume'); + check(!body.bodyUsed, source + ': rejected forged lock does not disturb'); + reader.releaseLock(); + } + } else { + throw new Error('unknown body scenario ' + scenario); + } + return {errors}; +} diff --git a/moli-core/tests/web_apis.rs b/moli-core/tests/web_apis.rs index 19c0bf2cc05..3ac7cb10e73 100644 --- a/moli-core/tests/web_apis.rs +++ b/moli-core/tests/web_apis.rs @@ -30,6 +30,8 @@ use tokio::time::Duration; #[path = "web_apis/abort_signal.rs"] mod abort_signal; +#[path = "web_apis/body_state.rs"] +mod body_state; #[path = "web_apis/callback_cleanup.rs"] mod callback_cleanup; #[path = "web_apis/event_dispatch.rs"] diff --git a/moli-core/tests/web_apis/body_state.rs b/moli-core/tests/web_apis/body_state.rs new file mode 100644 index 00000000000..1889775f0fe --- /dev/null +++ b/moli-core/tests/web_apis/body_state.rs @@ -0,0 +1,56 @@ +use super::*; + +async fn assert_body_consumption_state(scenario: &str) -> Result<()> { + let server = FixtureServer::spawn().await?; + let browser = Browser::new(AppConfig::default())?; + let source = format!( + "{}\nrunBodyConsumptionStateProbe({}, {}).then(finish, error => finish({{error: String(error)}}));", + include_str!("../fixtures/runtime/body_consumption_state.js"), + serde_json::to_string(scenario)?, + serde_json::to_string(&server.url("/compat/child-dynamic-markup-document"))?, + ); + for target in ["window", "child", "worker"] { + let observed = tokio::time::timeout( + Duration::from_secs(20), + super::event_dispatch::run_probe(&browser, &server, target, &source), + ) + .await??; + assert_eq!( + observed, + serde_json::json!({"errors": []}), + "{scenario}/{target}" + ); + } + server.shutdown().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn null_bodies_remain_unused_and_allow_repeated_consumption_and_cloning() -> Result<()> { + assert_body_consumption_state("null").await +} + +#[tokio::test(flavor = "multi_thread")] +async fn locked_bodies_reject_consumption_and_clone_without_becoming_disturbed() -> Result<()> { + assert_body_consumption_state("locked").await +} + +#[tokio::test(flavor = "multi_thread")] +async fn body_consumption_locks_and_disturbs_both_buffered_and_streaming_bodies() -> Result<()> { + assert_body_consumption_state("consumed").await +} + +#[tokio::test(flavor = "multi_thread")] +async fn disturbed_body_streams_remain_unusable_after_readers_release_their_locks() -> Result<()> { + assert_body_consumption_state("disturbed").await +} + +#[tokio::test(flavor = "multi_thread")] +async fn body_read_and_conversion_errors_preserve_consumption_state() -> Result<()> { + assert_body_consumption_state("errors").await +} + +#[tokio::test(flavor = "multi_thread")] +async fn body_state_checks_and_stream_reads_ignore_public_member_overrides() -> Result<()> { + assert_body_consumption_state("poison").await +} diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs index 7bccdea92af..71915460b64 100644 --- a/moli-renderer-v8/src/context_bootstrap.rs +++ b/moli-renderer-v8/src/context_bootstrap.rs @@ -468,12 +468,14 @@ pub use self::storage_buckets::{ storage_bucket_indexed_db_storage_key, }; pub(crate) use self::stream_adapter::{ - cancel_readable_stream, close_stream, enqueue_byte_chunk, error_stream, - readable_stream_disturbed, readable_stream_error, readable_stream_has_pipe_owner, + begin_readable_stream_body_consumption, cancel_readable_stream, close_stream, + enqueue_byte_chunk, error_stream, readable_stream_disturbed, readable_stream_error, + readable_stream_has_pipe_owner, readable_stream_locked, require_internal_stream_value, }; pub(crate) use self::streams::{ ReadableStreamClonePayload, TransformStreamClonePayload, WritableStreamClonePayload, + body_stream_reader_operations, build_readable_stream_clone_shell, build_transform_stream_clone_shell, build_writable_stream_clone_shell, initialize_readable_stream_clone_shell, initialize_transform_stream_clone_shell, initialize_writable_stream_clone_shell, diff --git a/moli-renderer-v8/src/context_bootstrap/stream_adapter.rs b/moli-renderer-v8/src/context_bootstrap/stream_adapter.rs index 4873a03697c..8787c812344 100644 --- a/moli-renderer-v8/src/context_bootstrap/stream_adapter.rs +++ b/moli-renderer-v8/src/context_bootstrap/stream_adapter.rs @@ -97,12 +97,14 @@ pub(in crate::context_bootstrap) use readable_byte::{ reset_byte_stream_pending_pull_intos, respond_byte_stream_with_new_view, }; pub(in crate::context_bootstrap) use readable_state::EnqueueChunkError; -pub(crate) use readable_state::readable_stream_disturbed; pub(in crate::context_bootstrap) use readable_state::{ apply_readable_stream_access_transition, disturb_readable_stream, finish_readable_stream_close_if_requested_and_queue_empty, lock_readable_stream, readable_stream_access_snapshot, readable_stream_is_byte_stream, unlock_readable_stream, }; +pub(crate) use readable_state::{ + begin_readable_stream_body_consumption, readable_stream_disturbed, readable_stream_locked, +}; pub(crate) use readable_state::{close_stream, enqueue_chunk, error_stream, readable_stream_error}; pub(super) use readable_state::{ readable_stream_closed, reject_pending_read_requests, remove_pending_closed_promise, diff --git a/moli-renderer-v8/src/context_bootstrap/stream_adapter/readable_state.rs b/moli-renderer-v8/src/context_bootstrap/stream_adapter/readable_state.rs index 212b24f8e42..961430ecf65 100644 --- a/moli-renderer-v8/src/context_bootstrap/stream_adapter/readable_state.rs +++ b/moli-renderer-v8/src/context_bootstrap/stream_adapter/readable_state.rs @@ -583,6 +583,19 @@ pub(crate) fn readable_stream_disturbed<'s>( readable_stream_access_snapshot(scope, stream).disturbed() } +// Fetch can consume buffered/native body storage without running a JS reader. +// Commit the same access state as acquiring a reader and starting its read. +pub(crate) fn begin_readable_stream_body_consumption<'s>( + scope: &mut v8::PinScope<'s, '_>, + stream: v8::Local<'s, v8::Object>, +) -> bool { + if !lock_readable_stream(scope, stream) { + return false; + } + disturb_readable_stream(scope, stream); + true +} + pub(in crate::context_bootstrap) fn readable_stream_access_snapshot<'s>( scope: &mut v8::PinScope<'s, '_>, stream: v8::Local<'s, v8::Object>, diff --git a/moli-renderer-v8/src/context_bootstrap/streams.rs b/moli-renderer-v8/src/context_bootstrap/streams.rs index 5c627907944..07d86fd31cc 100644 --- a/moli-renderer-v8/src/context_bootstrap/streams.rs +++ b/moli-renderer-v8/src/context_bootstrap/streams.rs @@ -32,6 +32,17 @@ mod readable; mod transferable; mod writable; +pub(crate) fn body_stream_reader_operations<'s>( + scope: &mut v8::PinScope<'s, '_>, +) -> Option<[v8::Local<'s, v8::Function>; 2]> { + // Fetch keeps intrinsic reader operations without eagerly materializing + // the public ReadableStream and reader interfaces during realm bootstrap. + Some([ + v8::Function::new(scope, readable_stream_get_reader_callback)?, + v8::Function::new(scope, readable_stream_reader_read_callback)?, + ]) +} + #[derive(Clone, Copy)] enum StreamPrototypeInstaller { ReadableStream, diff --git a/moli-renderer-v8/src/network_host.rs b/moli-renderer-v8/src/network_host.rs index 5e62d949686..329c8daa038 100644 --- a/moli-renderer-v8/src/network_host.rs +++ b/moli-renderer-v8/src/network_host.rs @@ -36,21 +36,21 @@ pub(crate) use self::async_fetch::{ pub(crate) use self::beacon::{navigator_send_beacon_callback, send_link_audit_ping}; pub(super) use self::bindings::install_window_network_bindings; pub(in crate::network_host) use self::body::{ - PreparedBodyInit, body_init, body_stream_object, readable_body_stream_unusable, + PreparedBodyInit, body_init, body_is_unusable, body_is_used, body_stream_object, + readable_body_stream_unusable, }; pub(crate) use self::body::{append_default_body_content_type, has_header}; #[cfg(test)] pub(crate) use self::body_source::pending_network_body_source_buffered_len_for_test; pub(in crate::network_host) use self::body_source::{ - BODY_FORM_DATA_UNSUPPORTED_CONTENT_TYPE_ERROR_TEXT, NetworkBodyConsumption, - NetworkBodyConsumptionKind, clone_filtered_response_internal_body_source, - clone_pending_network_body_stream, consume_filtered_response_internal_body_value_from_object, + NetworkBodyConsumption, NetworkBodyConsumptionKind, + clone_filtered_response_internal_body_source, clone_pending_network_body_stream, + consume_filtered_response_internal_body_value_from_object, consume_filtered_response_internal_body_value_from_object_with_chunk_callback, consume_network_body_value_from_object, consume_network_body_value_from_object_with_chunk_callback, network_body_source_from_object, network_body_source_object_from_bytes, network_body_stream_from_response_body, - network_body_stream_from_subresource_body, network_body_value_is_pending_stream, - set_filtered_response_internal_body_from_bytes, + network_body_stream_from_subresource_body, set_filtered_response_internal_body_from_bytes, set_filtered_response_internal_body_from_pending_stream, set_filtered_response_internal_body_from_response_body, set_filtered_response_internal_body_from_subresource_body, set_network_body_owned_bytes, diff --git a/moli-renderer-v8/src/network_host/body.rs b/moli-renderer-v8/src/network_host/body.rs index 9010646b094..8b9627fa464 100644 --- a/moli-renderer-v8/src/network_host/body.rs +++ b/moli-renderer-v8/src/network_host/body.rs @@ -27,6 +27,22 @@ pub(in crate::network_host) fn readable_body_stream_unusable<'s>( || crate::context_bootstrap::readable_stream_disturbed(scope, stream) } +pub(in crate::network_host) fn body_is_used<'s>( + scope: &mut v8::PinScope<'s, '_>, + object: v8::Local<'s, v8::Object>, +) -> bool { + body_stream_object(scope, object) + .is_some_and(|stream| crate::context_bootstrap::readable_stream_disturbed(scope, stream)) +} + +pub(in crate::network_host) fn body_is_unusable<'s>( + scope: &mut v8::PinScope<'s, '_>, + object: v8::Local<'s, v8::Object>, +) -> bool { + body_stream_object(scope, object) + .is_some_and(|stream| readable_body_stream_unusable(scope, stream)) +} + #[derive(Debug, Clone)] pub(in crate::network_host) struct PreparedBodyInit { pub(in crate::network_host) bytes: bytes::Bytes, @@ -69,6 +85,11 @@ pub(in crate::network_host) fn body_init<'s>( return Ok(Some(PreparedBodyInit::new(bytes, content_type))); } if web_api_interfaces::ReadableStream::is_instance(scope, object) { + if readable_body_stream_unusable(scope, object) { + return Err(webidl::WebIdlError::custom_message( + "BodyInit ReadableStream is locked or disturbed", + )); + } return Ok(Some(PreparedBodyInit::new(Vec::new(), None))); } } diff --git a/moli-renderer-v8/src/network_host/body_source.rs b/moli-renderer-v8/src/network_host/body_source.rs index 13f9fdde9ba..7de153f75eb 100644 --- a/moli-renderer-v8/src/network_host/body_source.rs +++ b/moli-renderer-v8/src/network_host/body_source.rs @@ -1266,16 +1266,6 @@ pub(in crate::network_host) fn consume_network_body_value_from_object_with_chunk consume_network_body_value_from_object_inner(scope, object, kind, Some(chunk_callback)) } -pub(in crate::network_host) fn network_body_value_is_pending_stream<'s>( - scope: &mut v8::PinScope<'s, '_>, - object: v8::Local<'s, v8::Object>, -) -> bool { - network_body_source_from_object(scope, object) - .and_then(|source| network_body_source_kind(scope, source)) - .as_deref() - == Some(BODY_SOURCE_KIND_PENDING_STREAM) -} - pub(in crate::network_host) fn consume_filtered_response_internal_body_value_from_object<'s>( scope: &mut v8::PinScope<'s, '_>, object: v8::Local<'s, v8::Object>, @@ -1337,7 +1327,19 @@ fn consume_network_body_value_from_source_inner<'s>( chunk_callback: Option>, ) -> (NetworkBodyConsumption<'s>, Option>) { let source = explicit_source.unwrap_or(object); - if network_body_source_kind(scope, source).as_deref() == Some(BODY_SOURCE_KIND_PENDING_STREAM) { + let pending_stream = + network_body_source_kind(scope, source).as_deref() == Some(BODY_SOURCE_KIND_PENDING_STREAM); + // Native storage consumers bypass a JS reader. Public body streams still + // acquire the same permanent lock and disturbed state as fully reading. + let uses_reader = explicit_source.is_none() || pending_stream && chunk_callback.is_some(); + if !uses_reader + && let Some(stream) = body_stream_object(scope, object) + && !crate::context_bootstrap::begin_readable_stream_body_consumption(scope, stream) + { + let error = v8::Exception::type_error(scope, v8str(scope, "Body stream is locked")); + return (NetworkBodyConsumption::Rejected(error), None); + } + if pending_stream { if let Some(chunk_callback) = chunk_callback && let Some(stream) = readable_body_stream_from_object(scope, object) { @@ -1893,10 +1895,15 @@ fn body_materialization_value<'s>( } PendingBodyMaterializationKind::Json => { let text = encoding_rs::UTF_8.decode_with_bom_removal(bytes).0; - v8_json_parse(scope, &text).ok_or_else(|| { - v8_string(scope, "SyntaxError: JSON parse error") - .map(|message| v8::Exception::syntax_error(scope, message)) - .unwrap_or_else(|| v8::undefined(scope).into()) + let Some(text) = v8_string(scope, &text) else { + return Err(v8::undefined(scope).into()); + }; + let try_catch = std::pin::pin!(v8::TryCatch::new(scope)); + let scope = try_catch.init(); + v8::json::parse(&scope, text).ok_or_else(|| { + scope + .exception() + .unwrap_or_else(|| v8::undefined(&scope).into()) }) } PendingBodyMaterializationKind::ArrayBuffer => { diff --git a/moli-renderer-v8/src/network_host/fetch_surface.rs b/moli-renderer-v8/src/network_host/fetch_surface.rs index 5830986b793..58c0b508506 100644 --- a/moli-renderer-v8/src/network_host/fetch_surface.rs +++ b/moli-renderer-v8/src/network_host/fetch_surface.rs @@ -2,6 +2,7 @@ use super::headers::{build_headers_object, headers_entries, headers_list, mark_h use super::response::{ParsedResponseInit, install_response_body_methods}; use super::*; use crate::context_bootstrap::readable_stream_disturbed; +pub(in crate::network_host) use crate::util::constructor_prototype; use crate::util::{ callback_data_index_value, callback_data_item, get_private_value, set_private_value, throw_range_error, v8_string, @@ -414,7 +415,7 @@ pub(crate) fn consume_webassembly_streaming_response_value<'s>( ); return None; } - if body_already_used(scope, response, RESPONSE_BODY_USED_SLOT) { + if body_is_unusable(scope, response) { throw_type_error( scope, "Cannot compile WebAssembly.Module from an already read Response", @@ -479,8 +480,7 @@ fn request_slot_attribute_getter_callback<'s>( return; }; if slot == REQUEST_BODY_USED_SLOT { - let body_used = request_slot_bool(scope, this, slot) - || body_stream_is_disturbed(scope, this, REQUEST_BODY_SLOT, false); + let body_used = body_is_used(scope, this); rv.set(v8::Boolean::new(scope, body_used).into()); return; } @@ -503,8 +503,7 @@ fn response_slot_attribute_getter_callback<'s>( return; }; if slot == RESPONSE_BODY_USED_SLOT { - let body_used = response_slot_bool(scope, this, slot) - || body_stream_is_disturbed(scope, this, RESPONSE_BODY_SLOT, true); + let body_used = body_is_used(scope, this); rv.set(v8::Boolean::new(scope, body_used).into()); return; } @@ -788,10 +787,7 @@ fn request_clone_callback<'s>( let Some(this) = require_request_receiver(scope, args.this()) else { return; }; - if body_already_used(scope, this, REQUEST_BODY_USED_SLOT) - || body_stream_object(scope, this) - .is_some_and(|stream| readable_body_stream_unusable(scope, stream)) - { + if body_is_unusable(scope, this) { throw_type_error( scope, "Failed to execute 'clone' on 'Request': body stream already used", @@ -822,10 +818,7 @@ fn response_clone_callback<'s>( let Some(this) = require_response_receiver(scope, args.this()) else { return; }; - if body_already_used(scope, this, RESPONSE_BODY_USED_SLOT) - || body_stream_object(scope, this) - .is_some_and(|stream| readable_body_stream_unusable(scope, stream)) - { + if body_is_unusable(scope, this) { throw_type_error( scope, "Failed to execute 'clone' on 'Response': body stream already used", @@ -945,7 +938,7 @@ fn clone_response_readable_stream_body<'s>( if !web_api_interfaces::ReadableStream::is_instance(scope, stream) { return Ok(None); } - if readable_stream_locked(scope, stream) { + if readable_body_stream_unusable(scope, stream) { return Err(()); } let global = scope.get_current_context().global(scope); @@ -971,16 +964,6 @@ fn clone_response_readable_stream_body<'s>( Ok(Some(clone_branch)) } -fn readable_stream_locked( - scope: &mut v8::PinScope<'_, '_>, - stream: v8::Local<'_, v8::Object>, -) -> bool { - stream - .get(scope, v8str(scope, "locked").into()) - .map(|value| value.boolean_value(scope)) - .unwrap_or(false) -} - pub(in crate::network_host) fn new_abort_signal_for_request<'s>( scope: &mut v8::PinScope<'s, '_>, ) -> Option> { @@ -1031,7 +1014,7 @@ pub(crate) fn install_response_bindings<'s>( } const BODY_STREAM_CONSUMER_RUNTIME_SOURCE: &str = r#" -(() => { +((getReader, read) => { const consumerName = "__lmConsumeReadableStreamBody"; const teeName = "__lmTeeReadableStreamBody"; if ( @@ -1040,6 +1023,7 @@ const BODY_STREAM_CONSUMER_RUNTIME_SOURCE: &str = r#" ) { return; } + const parseJSON = JSON.parse; function uint8ArrayChunkBytes(chunk) { if (Object.prototype.toString.call(chunk) !== "[object Uint8Array]") { @@ -1049,22 +1033,16 @@ const BODY_STREAM_CONSUMER_RUNTIME_SOURCE: &str = r#" } async function consumeReadableStreamBody(stream, kind, mimeType, onChunk) { - const reader = stream.getReader(); + const reader = getReader.call(stream); const chunks = []; let total = 0; - try { - for (;;) { - const result = await reader.read(); - if (result.done) break; - const chunk = uint8ArrayChunkBytes(result.value); - if (typeof onChunk === "function") onChunk(chunk); - chunks.push(chunk); - total += chunk.byteLength; - } - } finally { - try { - reader.releaseLock(); - } catch (_) {} + for (;;) { + const result = await read.call(reader); + if (result.done) break; + const chunk = uint8ArrayChunkBytes(result.value); + if (typeof onChunk === "function") onChunk(chunk); + chunks.push(chunk); + total += chunk.byteLength; } const bytes = new Uint8Array(total); @@ -1077,7 +1055,7 @@ const BODY_STREAM_CONSUMER_RUNTIME_SOURCE: &str = r#" if (kind === "arrayBuffer") return bytes.buffer; if (kind === "bytes") return bytes; if (kind === "text") return new TextDecoder().decode(bytes); - if (kind === "json") return JSON.parse(new TextDecoder().decode(bytes)); + if (kind === "json") return parseJSON(new TextDecoder().decode(bytes)); if (kind === "blob") return new Blob([bytes], { type: mimeType || "" }); if (kind === "formData") { return new Response(bytes, { @@ -1176,7 +1154,7 @@ const BODY_STREAM_CONSUMER_RUNTIME_SOURCE: &str = r#" value: teeReadableStreamBody, configurable: true }); -})(); +}) "#; pub(crate) fn initialize_fetch_realm_helpers( @@ -1186,55 +1164,22 @@ pub(crate) fn initialize_fetch_realm_helpers( } fn install_body_stream_consumer_runtime(scope: &mut v8::PinScope<'_, '_>) -> anyhow::Result<()> { + let [get_reader, read] = crate::context_bootstrap::body_stream_reader_operations(scope) + .ok_or_else(|| anyhow::anyhow!("failed to allocate Fetch body reader operations"))?; let Some(source) = v8_string(scope, BODY_STREAM_CONSUMER_RUNTIME_SOURCE) else { anyhow::bail!("failed to allocate Fetch body stream consumer runtime source"); }; let script = v8::Script::compile(scope, source, None) .ok_or_else(|| anyhow::anyhow!("failed to compile Fetch body stream consumer runtime"))?; - crate::script_execution::execute_compiled_script(scope, script) - .ok_or_else(|| anyhow::anyhow!("failed to run Fetch body stream consumer runtime"))?; + let initializer = crate::script_execution::execute_compiled_script(scope, script) + .and_then(|value| v8::Local::::try_from(value).ok()) + .ok_or_else(|| anyhow::anyhow!("failed to create Fetch body stream consumer runtime"))?; + crate::script_execution::call_function( + scope, + initializer, + v8::undefined(scope).into(), + &[get_reader.into(), read.into()], + ) + .ok_or_else(|| anyhow::anyhow!("failed to initialize Fetch body stream consumer runtime"))?; Ok(()) } - -fn body_already_used<'s>( - scope: &mut v8::PinScope<'s, '_>, - object: v8::Local<'s, v8::Object>, - slot: &str, -) -> bool { - if is_response_slot(slot) { - return response_slot_bool(scope, object, slot) - || body_stream_is_disturbed(scope, object, RESPONSE_BODY_SLOT, true); - } - request_slot_bool(scope, object, slot) - || body_stream_is_disturbed(scope, object, REQUEST_BODY_SLOT, false) -} - -fn body_stream_is_disturbed<'s>( - scope: &mut v8::PinScope<'s, '_>, - object: v8::Local<'s, v8::Object>, - body_slot: &'static str, - response: bool, -) -> bool { - let body = if response { - response_slot_object(scope, object, body_slot) - } else { - request_slot_object(scope, object, body_slot) - }; - body.is_some_and(|stream| readable_stream_disturbed(scope, stream)) -} - -fn is_response_slot(slot: &str) -> bool { - matches!( - slot, - RESPONSE_TYPE_SLOT - | RESPONSE_URL_SLOT - | RESPONSE_INTERNAL_URL_SLOT - | RESPONSE_REDIRECTED_SLOT - | RESPONSE_STATUS_SLOT - | RESPONSE_OK_SLOT - | RESPONSE_STATUS_TEXT_SLOT - | RESPONSE_HEADERS_SLOT - | RESPONSE_BODY_SLOT - | RESPONSE_BODY_USED_SLOT - ) -} diff --git a/moli-renderer-v8/src/network_host/request/input.rs b/moli-renderer-v8/src/network_host/request/input.rs index 70c9fba8492..79d1cfa8377 100644 --- a/moli-renderer-v8/src/network_host/request/input.rs +++ b/moli-renderer-v8/src/network_host/request/input.rs @@ -112,6 +112,9 @@ pub(crate) fn mark_request_input_body_used_for_fetch<'s>( let has_body = request_slot_value(scope, object, REQUEST_BODY_SLOT) .is_some_and(|body| !body.is_null_or_undefined()); if has_body { + if let Some(stream) = body_stream_object(scope, object) { + crate::context_bootstrap::begin_readable_stream_body_consumption(scope, stream); + } set_request_slot_bool(scope, object, REQUEST_BODY_USED_SLOT, true); } } @@ -271,30 +274,7 @@ fn request_body_unusable<'s>( scope: &mut v8::PinScope<'s, '_>, object: v8::Local<'s, v8::Object>, ) -> bool { - let Some(body) = request_slot_value(scope, object, REQUEST_BODY_SLOT) else { - return false; - }; - if body.is_null_or_undefined() { - return false; - } - request_slot_bool(scope, object, REQUEST_BODY_USED_SLOT) - || request_body_stream_locked(scope, body) -} - -fn request_body_stream_locked<'s>( - scope: &mut v8::PinScope<'s, '_>, - body: v8::Local<'s, v8::Value>, -) -> bool { - let Ok(stream) = v8::Local::::try_from(body) else { - return false; - }; - if !web_api_interfaces::ReadableStream::is_instance(scope, stream) { - return false; - } - stream - .get(scope, v8str(scope, "locked").into()) - .map(|value| value.boolean_value(scope)) - .unwrap_or(false) + body_is_unusable(scope, object) } fn request_signal_snapshot_from_property<'s>( diff --git a/moli-renderer-v8/src/network_host/response/bindings.rs b/moli-renderer-v8/src/network_host/response/bindings.rs index 9c932737099..1a24ea82a56 100644 --- a/moli-renderer-v8/src/network_host/response/bindings.rs +++ b/moli-renderer-v8/src/network_host/response/bindings.rs @@ -45,10 +45,10 @@ pub(crate) fn response_constructor_callback<'s>( let obj = args.this(); let body_arg = args.get(0); let body_stream = readable_stream_body_arg(scope, body_arg); - if body_stream.is_some_and(|stream| readable_stream_body_locked(scope, stream)) { + if body_stream.is_some_and(|stream| readable_body_stream_unusable(scope, stream)) { throw_type_error( scope, - "Failed to construct 'Response': ReadableStream body is locked.", + "Failed to construct 'Response': ReadableStream body is locked or disturbed.", ); return; } @@ -126,16 +126,6 @@ fn readable_stream_body_arg<'s>( web_api_interfaces::ReadableStream::is_instance(scope, object).then_some(object) } -fn readable_stream_body_locked( - scope: &mut v8::PinScope<'_, '_>, - stream: v8::Local<'_, v8::Object>, -) -> bool { - stream - .get(scope, v8str(scope, "locked").into()) - .map(|value| value.boolean_value(scope)) - .unwrap_or(false) -} - fn is_valid_response_status_text(value: &str) -> bool { value.chars().all(|ch| { let code = ch as u32; diff --git a/moli-renderer-v8/src/network_host/response/body_methods.rs b/moli-renderer-v8/src/network_host/response/body_methods.rs index 0807d8aa0da..7d6e3a555b0 100644 --- a/moli-renderer-v8/src/network_host/response/body_methods.rs +++ b/moli-renderer-v8/src/network_host/response/body_methods.rs @@ -5,9 +5,7 @@ use super::super::fetch_surface::{ REQUEST_BODY_USED_SLOT, REQUEST_HEADERS_SLOT, RESPONSE_BODY_USED_SLOT, RESPONSE_HEADERS_SLOT, }; use super::*; -use moli_web_mime::{ - extract_response_mime_type, is_form_urlencoded_mime, multipart_form_data_boundary, -}; +use moli_web_mime::extract_response_mime_type; use self::binary::{ response_array_buffer_callback, response_blob_callback, response_bytes_callback, @@ -54,20 +52,6 @@ fn response_form_data_callback<'s>( }; let content_type = body_mime_type(scope, &consumption); - let multipart_boundary = multipart_form_data_boundary(&content_type); - if !is_urlencoded_content_type(&content_type) - && multipart_boundary.is_none() - && !network_body_value_is_pending_stream(scope, consumption.object) - { - reject_body_form_data( - scope, - consumption.resolver, - BODY_FORM_DATA_UNSUPPORTED_CONTENT_TYPE_ERROR_TEXT, - ); - rv.set(consumption.promise.into()); - return; - } - finish_body_consumption( scope, &mut rv, @@ -153,14 +137,6 @@ fn reject_body_already_used<'s>( ); } -fn reject_body_form_data<'s>( - scope: &mut v8::PinScope<'s, '_>, - resolver: v8::Local<'s, v8::PromiseResolver>, - message: &str, -) { - reject_body_type_error(scope, resolver, message); -} - fn body_headers<'s>( scope: &mut v8::PinScope<'s, '_>, object: v8::Local<'s, v8::Object>, @@ -177,10 +153,6 @@ fn body_headers<'s>( }) } -fn is_urlencoded_content_type(content_type: &str) -> bool { - is_form_urlencoded_mime(content_type) -} - fn body_mime_type<'s>( scope: &mut v8::PinScope<'s, '_>, consumption: &BodyConsumptionPromise<'s>, @@ -197,25 +169,19 @@ fn begin_body_consumption<'s>( object: v8::Local<'s, v8::Object>, receiver: BodyReceiver, ) -> bool { - let Some(body) = body_stream_object(scope, object) else { - // Consuming a null body performs the empty conversion without disturbing it. + let Some(stream) = body_stream_object(scope, object) else { + // Consuming a null body does not disturb it. return true; }; - if readable_body_stream_unusable(scope, body) { + if readable_body_stream_unusable(scope, stream) { return false; } match receiver { BodyReceiver::Response => { - if response_slot_bool(scope, object, RESPONSE_BODY_USED_SLOT) { - return false; - } set_response_slot_bool(scope, object, RESPONSE_BODY_USED_SLOT, true); true } BodyReceiver::Request => { - if request_slot_bool(scope, object, REQUEST_BODY_USED_SLOT) { - return false; - } set_request_slot_bool(scope, object, REQUEST_BODY_USED_SLOT, true); true } diff --git a/moli-renderer-v8/src/network_host/response/materialize.rs b/moli-renderer-v8/src/network_host/response/materialize.rs index 14c2f10efb6..f3e2ebc045b 100644 --- a/moli-renderer-v8/src/network_host/response/materialize.rs +++ b/moli-renderer-v8/src/network_host/response/materialize.rs @@ -548,6 +548,9 @@ pub(crate) fn materialize_response_object<'s>( } Err(error) => return Err(error), }; + if let Some(stream) = body_stream_object(scope, response) { + crate::context_bootstrap::begin_readable_stream_body_consumption(scope, stream); + } set_response_slot_bool(scope, response, RESPONSE_BODY_USED_SLOT, true); Ok(head.with_body(body)) } @@ -567,16 +570,16 @@ pub(crate) fn materialize_response_object_head<'s>( if response_type == "error" { return Err(format!("{context} rejected an error Response.")); } + if body_is_used(scope, response) { + return Err(format!( + "{context} rejected a Response whose body is already used." + )); + } if response_body_locked(scope, response) { return Err(format!( "{context} rejected a Response whose body is locked." )); } - if response_slot_bool(scope, response, RESPONSE_BODY_USED_SLOT) { - return Err(format!( - "{context} rejected a Response whose body is already used." - )); - } let status = response_slot_value(scope, response, RESPONSE_STATUS_SLOT) .and_then(|value| value.number_value(scope)) .ok_or_else(|| format!("{context} requires a Response."))?; @@ -747,19 +750,6 @@ fn response_body_locked<'s>( scope: &mut v8::PinScope<'s, '_>, response: v8::Local<'s, v8::Object>, ) -> bool { - let Some(body) = response_slot_value(scope, response, RESPONSE_BODY_SLOT) else { - return false; - }; - if body.is_null_or_undefined() { - return false; - } - let Ok(stream) = v8::Local::::try_from(body) else { - return false; - }; - if !web_api_interfaces::ReadableStream::is_instance(scope, stream) { - return false; - } - stream - .get(scope, crate::util::v8str(scope, "locked").into()) - .is_some_and(move |value| value.boolean_value(scope)) + body_stream_object(scope, response) + .is_some_and(|stream| crate::context_bootstrap::readable_stream_locked(scope, stream)) } diff --git a/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs b/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs index 5cfa89fc6df..2e19ad85a64 100644 --- a/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs +++ b/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs @@ -154,7 +154,9 @@ const DIRECT_V8_CALL_ALLOWLIST: &[AllowedDirectCallFile] = &[ ), allowed( "network_host/fetch_surface.rs", - 2, + // Includes the Fetch bootstrap closure receiving native reader + // operations; the closure is compiled from browser-owned source. + 3, DirectCallOwner::BrowserAlgorithm, ), allowed(