From 3ffbe25cb11fffc14d1d7a0c9f2e1756d1976b91 Mon Sep 17 00:00:00 2001 From: ldm0 Date: Sun, 18 Oct 2026 13:57:18 +0800 Subject: [PATCH] fix(fetch): transfer Request bodies through native streams --- .../src/network_host/body_source.rs | 71 ++++++- .../src/network_host/fetch_surface.rs | 114 +++++------ .../src/network_host/request/bindings.rs | 2 +- .../src/network_host/request/input.rs | 6 +- .../src/runtime/page_vm/tests/mod.rs | 2 + .../page_vm/tests/request_body_transfer.rs | 182 ++++++++++++++++++ .../webidl_interfaces_and_url_params.rs | 12 +- .../lifecycle/fetch_events_and_messages.rs | 9 +- .../tests/fixtures/request-body-transfer.js | 151 +++++++++++++++ 9 files changed, 464 insertions(+), 85 deletions(-) create mode 100644 moli-renderer-v8/src/runtime/page_vm/tests/request_body_transfer.rs create mode 100644 moli-renderer-v8/tests/fixtures/request-body-transfer.js diff --git a/moli-renderer-v8/src/network_host/body_source.rs b/moli-renderer-v8/src/network_host/body_source.rs index cf55f0ff6d4..83ce7771286 100644 --- a/moli-renderer-v8/src/network_host/body_source.rs +++ b/moli-renderer-v8/src/network_host/body_source.rs @@ -35,6 +35,8 @@ use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt}; const BODY_SOURCE_KIND_BYTES: &str = "bytes"; const BODY_SOURCE_KIND_BLOB: &str = "blob"; const BODY_SOURCE_BLOB_SLOT: &str = "__lmNetworkBodySourceBlob"; +const BODY_SOURCE_KIND_STREAM: &str = "stream"; +const BODY_SOURCE_ORIGINAL_SLOT: &str = "__lmNetworkBodySourceOriginal"; const BODY_SOURCE_KIND_REGISTRY_BYTES: &str = "registry-bytes"; const BODY_SOURCE_KIND_SUBRESOURCE_BODY: &str = "subresource-body"; const BODY_SOURCE_KIND_PENDING_STREAM: &str = "pending-stream"; @@ -69,6 +71,15 @@ struct BlobNetworkBodySourceDeclaration<'scope> { blob: v8::Local<'scope, v8::Object>, } +#[derive(WebApiObject)] +#[webapi(plain)] +struct StreamNetworkBodySourceDeclaration<'scope> { + #[webapi(slot = NETWORK_BODY_SOURCE_KIND_SLOT)] + kind: &'static str, + #[webapi(slot = BODY_SOURCE_ORIGINAL_SLOT)] + original: v8::Local<'scope, v8::Object>, +} + #[derive(WebApiObject)] #[webapi(plain)] struct RegisteredNetworkBodySourceDeclaration<'scope> { @@ -553,13 +564,53 @@ pub(in crate::network_host) fn set_network_body_blob_source<'s>( set_network_body_source_object(scope, object, source); } -pub(in crate::network_host) fn body_uses_blob_stream<'s>( +/// Keep immutable replay data when a body starts using a transferred stream. +/// Reading this body must follow that stream, including its cancellation and +/// errors, even when the original source bytes are already available. +pub(in crate::network_host) fn set_network_body_stream_source<'s>( scope: &mut v8::PinScope<'s, '_>, object: v8::Local<'s, v8::Object>, + original: v8::Local<'s, v8::Object>, +) { + // Each wrapper points directly to the replay source. Repeated Request + // transfers must not grow a recursive chain of metadata carriers. + let original = if network_body_source_kind(scope, original).as_deref() + == Some(BODY_SOURCE_KIND_STREAM) + { + stream_body_original_source(scope, original).expect("stream body replay source must exist") + } else { + original + }; + let source = StreamNetworkBodySourceDeclaration::new(BODY_SOURCE_KIND_STREAM, original) + .bind(scope) + .expect("stream body source declaration should bind"); + set_network_body_source_object(scope, object, source); +} + +fn stream_body_original_source<'s>( + scope: &mut v8::PinScope<'s, '_>, + source: v8::Local<'s, v8::Object>, +) -> Option> { + network_body_source_slot_value(scope, source, BODY_SOURCE_ORIGINAL_SLOT) + .and_then(|value| v8::Local::::try_from(value).ok()) +} + +fn network_body_source_uses_stream<'s>( + scope: &mut v8::PinScope<'s, '_>, + source: v8::Local<'s, v8::Object>, ) -> bool { - network_body_source_from_object(scope, object).is_some_and(|source| { - network_body_source_kind(scope, source).as_deref() == Some(BODY_SOURCE_KIND_BLOB) - }) + matches!( + network_body_source_kind(scope, source).as_deref(), + Some(BODY_SOURCE_KIND_BLOB | BODY_SOURCE_KIND_STREAM) + ) +} + +pub(in crate::network_host) fn body_uses_readable_stream<'s>( + scope: &mut v8::PinScope<'s, '_>, + object: v8::Local<'s, v8::Object>, +) -> bool { + network_body_source_from_object(scope, object) + .is_some_and(|source| network_body_source_uses_stream(scope, source)) } fn set_network_body_response_body<'s>( @@ -1185,6 +1236,12 @@ fn try_network_body_bytes_from_storage<'s>( ) -> Result>, String> { let source_kind = network_body_source_kind(scope, object); match source_kind.as_deref() { + Some(BODY_SOURCE_KIND_STREAM) => { + let Some(original) = stream_body_original_source(scope, object) else { + return Ok(None); + }; + return try_network_body_bytes_from_storage(scope, original, consume_registry_body); + } Some(BODY_SOURCE_KIND_BLOB) => { let blob = network_body_source_slot_value(scope, object, BODY_SOURCE_BLOB_SLOT) .and_then(|value| v8::Local::::try_from(value).ok()) @@ -1572,7 +1629,7 @@ fn consume_network_body_value_from_source_inner<'s>( let pending_stream = network_body_source_kind(scope, source).as_deref() == Some(BODY_SOURCE_KIND_PENDING_STREAM); let uses_reader = explicit_source.is_none() - || body_uses_blob_stream(scope, object) + || body_uses_readable_stream(scope, object) || pending_stream && chunk_callback.is_some(); if !uses_reader && let Some(stream) = body_stream_object(scope, object) @@ -1668,9 +1725,7 @@ fn consume_network_body_value_from_source_inner<'s>( return (NetworkBodyConsumption::Pending(promise), None); } - if (explicit_source.is_none() || body_uses_blob_stream(scope, object)) - && let Some(stream) = readable_body_stream_from_object(scope, object) - { + if uses_reader && let Some(stream) = readable_body_stream_from_object(scope, object) { return consume_readable_body_stream( scope, object, diff --git a/moli-renderer-v8/src/network_host/fetch_surface.rs b/moli-renderer-v8/src/network_host/fetch_surface.rs index aa655e8ca3f..b89b66f71a2 100644 --- a/moli-renderer-v8/src/network_host/fetch_surface.rs +++ b/moli-renderer-v8/src/network_host/fetch_surface.rs @@ -805,51 +805,53 @@ fn request_clone_callback<'s>( ); return; } - if (network_body_source_from_object(scope, this).is_none() - || body_source::body_uses_blob_stream(scope, this)) - && let Some(stream) = body_stream_object(scope, this) - { - let clone = RequestCloneShellDeclaration::new() - .bind(scope) - .expect("Request clone shell declaration should bind"); - for slot in [ - REQUEST_METHOD_SLOT, - REQUEST_URL_SLOT, - REQUEST_DESTINATION_SLOT, - REQUEST_REFERRER_SLOT, - REQUEST_REFERRER_POLICY_SLOT, - REQUEST_MODE_SLOT, - REQUEST_CREDENTIALS_SLOT, - REQUEST_CACHE_SLOT, - REQUEST_REDIRECT_SLOT, - REQUEST_INTEGRITY_SLOT, - REQUEST_KEEPALIVE_SLOT, - REQUEST_PRIORITY_SLOT, - REQUEST_DUPLEX_SLOT, - REQUEST_IS_HISTORY_NAVIGATION_SLOT, - REQUEST_IS_RELOAD_NAVIGATION_SLOT, - ] { - if let Some(value) = request_slot_value(scope, this, slot) { - set_request_slot_value(scope, clone, slot, value); - } + let Some(realm) = this.get_creation_context(scope) else { + return; + }; + let scope = &mut v8::ContextScope::new(scope, realm); + let clone = RequestCloneShellDeclaration::new() + .bind(scope) + .expect("Request clone shell declaration should bind"); + for slot in [ + REQUEST_METHOD_SLOT, + REQUEST_URL_SLOT, + REQUEST_DESTINATION_SLOT, + REQUEST_REFERRER_SLOT, + REQUEST_REFERRER_POLICY_SLOT, + REQUEST_MODE_SLOT, + REQUEST_CREDENTIALS_SLOT, + REQUEST_CACHE_SLOT, + REQUEST_REDIRECT_SLOT, + REQUEST_INTEGRITY_SLOT, + REQUEST_KEEPALIVE_SLOT, + REQUEST_PRIORITY_SLOT, + REQUEST_DUPLEX_SLOT, + REQUEST_IS_HISTORY_NAVIGATION_SLOT, + REQUEST_IS_RELOAD_NAVIGATION_SLOT, + ] { + if let Some(value) = request_slot_value(scope, this, slot) { + set_request_slot_value(scope, clone, slot, value); } - let entries = request_slot_object(scope, this, REQUEST_HEADERS_SLOT) - .map(|headers| headers_entries(scope, headers)) - .unwrap_or_default(); - let guard = - if request_slot_string(scope, this, REQUEST_MODE_SLOT).as_deref() == Some("no-cors") { - HeadersGuard::RequestNoCors - } else { - HeadersGuard::Request - }; - let headers = - super::headers::build_headers_object_with_state(scope, &entries, guard, false); - set_request_slot_value(scope, clone, REQUEST_HEADERS_SLOT, headers.into()); - let signal_source = request_slot_object(scope, this, REQUEST_SIGNAL_SLOT); - let Some(signal) = new_abort_signal_for_request_with_source(scope, signal_source) else { - return; - }; - set_request_slot_value(scope, clone, REQUEST_SIGNAL_SLOT, signal); + } + let entries = request_slot_object(scope, this, REQUEST_HEADERS_SLOT) + .map(|headers| headers_list(scope, headers)) + .unwrap_or_default(); + let guard = if request_slot_string(scope, this, REQUEST_MODE_SLOT).as_deref() == Some("no-cors") + { + HeadersGuard::RequestNoCors + } else { + HeadersGuard::Request + }; + let headers = super::headers::build_headers_object_with_state(scope, &entries, guard, false); + set_request_slot_value(scope, clone, REQUEST_HEADERS_SLOT, headers.into()); + let signal_source = request_slot_object(scope, this, REQUEST_SIGNAL_SLOT); + let Some(signal) = new_abort_signal_for_request_with_source(scope, signal_source) else { + return; + }; + set_request_slot_value(scope, clone, REQUEST_SIGNAL_SLOT, signal); + let null_body = v8::null(scope).into(); + set_request_slot_value(scope, clone, REQUEST_BODY_SLOT, null_body); + if let Some(stream) = body_stream_object(scope, this) { let Some(branches) = crate::context_bootstrap::tee_fetch_body_stream(scope, stream) else { return; }; @@ -862,26 +864,12 @@ fn request_clone_callback<'s>( set_request_slot_value(scope, this, REQUEST_BODY_SLOT, original_body); set_request_slot_value(scope, clone, REQUEST_BODY_SLOT, clone_body); if let Some(source) = network_body_source_from_object(scope, this) { - body_source::set_network_body_source_object(scope, clone, source); + body_source::set_network_body_stream_source(scope, this, source); + body_source::set_network_body_stream_source(scope, clone, source); } - mark_request_object(scope, clone); - rv.set(clone.into()); - return; - } - let global = scope.get_current_context().global(scope); - let Some(ctor) = global.get(scope, v8str(scope, "Request").into()) else { - rv.set_undefined(); - return; - }; - let Ok(ctor) = v8::Local::::try_from(ctor) else { - rv.set_undefined(); - return; - }; - if let Some(clone) = ctor.new_instance(scope, &[this.into()]) { - rv.set(clone.into()); - } else { - rv.set_undefined(); } + mark_request_object(scope, clone); + rv.set(clone.into()); } fn response_clone_callback<'s>( @@ -923,7 +911,7 @@ fn response_clone_callback<'s>( .bind(scope) .expect("Response clone init declaration should bind"); - if body_source::body_uses_blob_stream(scope, this) + if body_source::body_uses_readable_stream(scope, this) && let Some(stream) = body_stream_object(scope, this) { let clone = ResponseCloneShellDeclaration::new(None) diff --git a/moli-renderer-v8/src/network_host/request/bindings.rs b/moli-renderer-v8/src/network_host/request/bindings.rs index d94d01d3cfd..8a95db1889b 100644 --- a/moli-renderer-v8/src/network_host/request/bindings.rs +++ b/moli-renderer-v8/src/network_host/request/bindings.rs @@ -128,7 +128,7 @@ pub(crate) fn request_constructor_callback<'s>( }; if let Some(source) = state.inherited_body_source { let source = v8::Local::new(scope, source); - body_source::set_network_body_source_object(scope, obj, source); + body_source::set_network_body_stream_source(scope, obj, source); } stream.into() } else { diff --git a/moli-renderer-v8/src/network_host/request/input.rs b/moli-renderer-v8/src/network_host/request/input.rs index bd6c0aa7181..dac91eff9ad 100644 --- a/moli-renderer-v8/src/network_host/request/input.rs +++ b/moli-renderer-v8/src/network_host/request/input.rs @@ -278,11 +278,9 @@ fn request_input_snapshot_from_private_slots<'s>( if body_unusable && !for_constructor { return Err(request_body_already_used_error()); } - // Constructing from a Blob-backed Request transfers its current stream; + // Constructing from a Request transfers its current stream; // copying its immutable source bytes would bypass pending reads and tee. - let body = if body_unusable - || for_constructor && body_source::body_uses_blob_stream(scope, object) - { + let body = if body_unusable || for_constructor { None } else { try_network_body_bytes_from_object(scope, object) diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs index 21abb7e13fd..acd390edfcf 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs @@ -2270,3 +2270,5 @@ mod blob_text; mod blob_reading; mod blob_support; + +mod request_body_transfer; diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/request_body_transfer.rs b/moli-renderer-v8/src/runtime/page_vm/tests/request_body_transfer.rs new file mode 100644 index 00000000000..b053aeae542 --- /dev/null +++ b/moli-renderer-v8/src/runtime/page_vm/tests/request_body_transfer.rs @@ -0,0 +1,182 @@ +use super::blob_support::run_blob_fixture; +use super::*; + +#[tokio::test(flavor = "current_thread")] +async fn request_clone_uses_receiver_realm_and_native_construction_for_every_body_source() { + run_blob_fixture( + r#" +(async () => { + const checks = []; + const frame = document.createElement('iframe');document.body.appendChild(frame); + const child = frame.contentWindow; + const cloneMethod = Request.prototype.clone, savedRequest = Request; + try { + globalThis.Request = function() {throw Error('author Request constructor called');}; + for (const kind of ['none','text','blob','stream']) { + const controller = new child.AbortController(); + const body = kind === 'none' ? undefined : kind === 'text' ? 'data' + : kind === 'blob' ? new child.Blob(['data']) : new child.ReadableStream({start(c) { + c.enqueue(new child.Uint8Array([100,97,116,97]));c.close(); + }}); + const input = new child.Request(location.href,{method:kind === 'none' ? 'GET' : 'POST',body, + signal:controller.signal,...(kind === 'stream' ? {duplex:'half'} : {})}); + const original = input.body; + const clone = cloneMethod.call(input); + checks.push({name:`${kind}/clone realm`,passed:Object.getPrototypeOf(clone) === child.Request.prototype}); + checks.push({name:`${kind}/header realm`,passed:clone.headers instanceof child.Headers}); + checks.push({name:`${kind}/signal realm and identity`,passed:clone.signal instanceof child.AbortSignal && clone.signal !== input.signal}); + checks.push({name:`${kind}/both bodies unused`,passed:!input.bodyUsed && !clone.bodyUsed}); + checks.push({name:`${kind}/null or tee body`,passed:kind === 'none' ? clone.body === null : original.locked && input.body !== original && clone.body !== input.body}); + const values = await Promise.all([input.text(),clone.text()]); + checks.push({name:`${kind}/both preserve data`,passed:values.every(value=>value === (kind === 'none' ? '' : 'data'))}); + checks.push({name:`${kind}/bodyUsed follows body presence`,passed:input.bodyUsed === (kind !== 'none') && clone.bodyUsed === (kind !== 'none')}); + const reason = {};controller.abort(reason); + checks.push({name:`${kind}/dependent abort signal`,passed:input.signal.aborted && clone.signal.aborted && clone.signal.reason === reason}); + } + } finally {globalThis.Request = savedRequest;frame.remove();} + globalThis.__uiEventResults = {checks}; +})().catch(error => { + globalThis.__uiEventResults = {checks:[{name:'clone completion',passed:false,detail:String(error.stack || error)}]}; +}); +"#, + "'borrowed Request clone'", + "https://request-clone-receiver-realm.test/", + 32, + ) + .await; +} + +#[tokio::test(flavor = "current_thread")] +async fn request_body_transfer_preserves_sources_realms_cancellation_and_validation() { + run_blob_fixture( + include_str!("../../../../tests/fixtures/request-body-transfer.js"), + "JSON.stringify(__blobReadingProgress)", + "https://request-body-transfer.test/", + 3310, + ) + .await; +} + +#[tokio::test(flavor = "current_thread")] +async fn request_body_transfer_drains_the_proxy_before_native_completion() { + run_page_vm_async_test(async move { + let loader = + crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader"); + let (mut page, _resource_source, _owner_wake) = + page_vm_with_bound_task_sources_and_owner_wake( + &loader, + Url::parse("https://request-transfer-native-completion.test/")?, + ); + page.vm_mut().eval( + r#" +globalThis.events = []; +const input = new Request(location.href, {method:'POST',body:'source'}); +const original = input.body; +const transferred = new Request(input); +globalThis.transferState = [input.bodyUsed, original.locked, transferred.bodyUsed]; +transferred.text().then(value => events.push(value)); +"#, + )?; + assert_eq!( + page.vm_mut() + .eval_without_microtask_checkpoint_for_test("JSON.stringify(transferState)")?, + "[true,true,false]", + ); + assert_eq!( + page.vm_mut() + .eval_without_microtask_checkpoint_for_test("JSON.stringify(events)")?, + "[]", + ); + // Fully reading the proxy releases the pipe's input reader. Returning + // cached bytes without reading the proxy would leave this lock held. + assert_eq!( + page.vm_mut() + .eval_without_microtask_checkpoint_for_test("original.locked")?, + "false", + ); + let Some(crate::page_task_queue::RendererPageReadyDescriptor::Timer { + deadline, + selection, + }) = page.due_page_timer_ready_descriptor( + crate::page_task_queue::RendererPageTimerSelection::AnyReady, + ) + else { + anyhow::bail!("public Body completion must queue its native Networking callback"); + }; + page.apply_selected_page_scheduler_task_on_owner_lane_for_test( + crate::page_task_queue::RendererPageSchedulerTask::Timer { + deadline, + selection, + }, + loader.clone(), + ) + .await?; + assert_eq!( + page.vm_mut() + .eval_without_microtask_checkpoint_for_test("JSON.stringify(events)")?, + r#"["source"]"#, + ); + Ok::<_, anyhow::Error>(()) + }) + .await + .expect("Request transfer consumes its proxy and keeps public completion on a native task"); +} + +#[tokio::test(flavor = "current_thread")] +async fn request_body_transfer_chain_keeps_replay_metadata_and_releases_input_readers() { + run_blob_fixture( + r#" +(async () => { + const checks = []; + const first = new Request(location.href, {method:'POST',body:'data',mode:'no-cors',keepalive:true}); + const inputs = []; + let current = first; + for (let i = 0; i < 64; i++) { + const input = current; + current = new Request(input); + inputs.push(input); + checks.push({name:`transfer ${i} locks and disturbs input`,passed:input.bodyUsed && input.body.locked}); + checks.push({name:`transfer ${i} keeps non-null source permissions`,passed:current.mode === 'no-cors' && current.keepalive}); + } + checks.push({name:'final data survives chain',passed:await current.text() === 'data'}); + checks.push({name:'all upstream readers released',passed:inputs.every(input => !input.body.locked && input.bodyUsed)}); + globalThis.__uiEventResults = {checks}; +})().catch(error => { + globalThis.__uiEventResults = {checks:[{name:'chain completion',passed:false,detail:String(error.stack || error)}]}; +}); +"#, + "'request transfer chain'", + "https://request-transfer-chain.test/", + 130, + ) + .await; +} + +#[tokio::test(flavor = "current_thread")] +async fn request_body_transfer_uses_native_slots_under_public_property_poisoning() { + run_blob_fixture( + r#" +(async () => { + const input = new Request(location.href, {method:'POST',body:'data'}); + const original = input.body; + for (const key of ['body','bodyUsed','headers','method','signal','url']) { + Object.defineProperty(input,key,{get() {throw Error(`public ${key} read`);}}); + } + const transferred = new Request(input); + globalThis.__uiEventResults = {checks:[ + {name:'native body stream transferred',passed:original.locked}, + {name:'native method copied',passed:transferred.method === 'POST'}, + {name:'native MIME copied',passed:transferred.headers.get('content-type') === 'text/plain;charset=UTF-8'}, + {name:'native body consumed',passed:await transferred.text() === 'data'}, + {name:'original native reader released',passed:!original.locked}, + ]}; +})().catch(error => { + globalThis.__uiEventResults = {checks:[{name:'poisoning completion',passed:false,detail:String(error.stack || error)}]}; +}); +"#, + "'native Request slot poisoning'", + "https://request-transfer-native-slots.test/", + 5, + ) + .await; +} diff --git a/moli-renderer-v8/src/script_vm/tests/webidl_fetch/webidl_interfaces_and_url_params.rs b/moli-renderer-v8/src/script_vm/tests/webidl_fetch/webidl_interfaces_and_url_params.rs index 2d2f940e792..8722555b215 100644 --- a/moli-renderer-v8/src/script_vm/tests/webidl_fetch/webidl_interfaces_and_url_params.rs +++ b/moli-renderer-v8/src/script_vm/tests/webidl_fetch/webidl_interfaces_and_url_params.rs @@ -1239,8 +1239,8 @@ async fn request_backing_slots_ignore_reflection_and_spoofing() { }); } - const inherited = new Request(request); const clone = request.clone(); + const inherited = new Request(request); const inheritedSurface = [ inherited.method, inherited.url, @@ -1298,7 +1298,7 @@ async fn request_backing_slots_ignore_reflection_and_spoofing() { fakeBodyMethods: null }; Promise.all([ - request.text(), + request.text().then(value => `resolve:${value}`, error => `reject:${error && error.name}`), clone.text(), inherited.text(), fetch(fetchRequest).then((response) => response.text()) @@ -1342,7 +1342,7 @@ async fn request_backing_slots_ignore_reflection_and_spoofing() { assert_eq!( result, - r#"{"initial":"||POST|https://request-slots.test/source|1|reload|include|manual|false","inheritedSurface":"POST|https://request-slots.test/source|1|null|reload|include|manual|false","cloneSurface":"POST|https://request-slots.test/source|1|null|reload|include|manual|false","fakeSurface":"throw:TypeError|throw:TypeError|throw:TypeError|throw:TypeError","consumed":"payload|payload|payload|fetch-ok|true|true|true|throw:TypeError","fakeBodyMethods":"rejected:true:TypeError|rejected:true:TypeError|rejected:true:TypeError|rejected:true:TypeError|rejected:true:TypeError|rejected:true:TypeError"}"# + r#"{"initial":"||POST|https://request-slots.test/source|1|reload|include|manual|false","inheritedSurface":"POST|https://request-slots.test/source|1|null|reload|include|manual|false","cloneSurface":"POST|https://request-slots.test/source|1|null|reload|include|manual|false","fakeSurface":"throw:TypeError|throw:TypeError|throw:TypeError|throw:TypeError","consumed":"reject:TypeError|payload|payload|fetch-ok|true|true|true|throw:TypeError","fakeBodyMethods":"rejected:true:TypeError|rejected:true:TypeError|rejected:true:TypeError|rejected:true:TypeError|rejected:true:TypeError|rejected:true:TypeError"}"# ); } @@ -1368,9 +1368,9 @@ async fn request_constructor_rejects_used_or_locked_inherited_body() { duplex: "half" }); const cloneBefore = request.clone(); - const inheritedBefore = new Request(request); const locked = request.clone(); locked.body.getReader(); + const inheritedBefore = new Request(request); globalThis.__requestBodyUsedProbe = { bodyIsStream: request.body instanceof ReadableStream, @@ -1381,7 +1381,7 @@ async fn request_constructor_rejects_used_or_locked_inherited_body() { }; Promise.all([ - request.text(), + request.text().then(value => `resolve:${value}`, error => `reject:${error && error.name}`), cloneBefore.text(), inheritedBefore.text(), request.text().then( @@ -1428,7 +1428,7 @@ async fn request_constructor_rejects_used_or_locked_inherited_body() { assert_eq!( result, - r#"{"bodyIsStream":true,"bodyUsedBefore":false,"lockedNew":"throw:TypeError","lockedClone":"throw:TypeError","done":"ok","requestText":"payload","cloneText":"payload","inheritedText":"payload","secondRead":"reject:TypeError","bodyUsedAfter":true,"afterReplacement":"false","afterNew":"throw:TypeError","afterClone":"throw:TypeError"}"# + r#"{"bodyIsStream":true,"bodyUsedBefore":true,"lockedNew":"throw:TypeError","lockedClone":"throw:TypeError","done":"ok","requestText":"reject:TypeError","cloneText":"payload","inheritedText":"payload","secondRead":"reject:TypeError","bodyUsedAfter":true,"afterReplacement":"false","afterNew":"throw:TypeError","afterClone":"throw:TypeError"}"# ); } diff --git a/moli-renderer-v8/src/worker/thread/tests/lifecycle/fetch_events_and_messages.rs b/moli-renderer-v8/src/worker/thread/tests/lifecycle/fetch_events_and_messages.rs index 31ad359fdfc..83f6b9ba0db 100644 --- a/moli-renderer-v8/src/worker/thread/tests/lifecycle/fetch_events_and_messages.rs +++ b/moli-renderer-v8/src/worker/thread/tests/lifecycle/fetch_events_and_messages.rs @@ -984,13 +984,16 @@ async fn service_worker_fetch_event_request_body_used_guards_inherited_body() { } }; const cloneBefore = request.clone(); - const inheritedBefore = new Request(request); const locked = request.clone(); locked.body.getReader(); + const inheritedBefore = new Request(request); const lockedNew = probe(() => new Request(locked)); const lockedClone = probe(() => locked.clone()); - const requestText = await request.text(); + const requestText = await request.text().then( + value => `resolve:${value}`, + error => `reject:${error && error.name}` + ); const cloneText = await cloneBefore.text(); const inheritedText = await inheritedBefore.text(); const secondRead = await request.text().then( @@ -1043,7 +1046,7 @@ async fn service_worker_fetch_event_request_body_used_guards_inherited_body() { assert_eq!(response.status, 200); assert_eq!( String::from_utf8(response.body).unwrap(), - r#"{"bodyIsStream":true,"bodyUsedAfter":true,"lockedNew":"throw:TypeError","lockedClone":"throw:TypeError","requestText":"fetch-body","cloneText":"fetch-body","inheritedText":"fetch-body","secondRead":"reject:TypeError","afterReplacement":"false","afterNew":"throw:TypeError","afterClone":"throw:TypeError"}"# + r#"{"bodyIsStream":true,"bodyUsedAfter":true,"lockedNew":"throw:TypeError","lockedClone":"throw:TypeError","requestText":"reject:TypeError","cloneText":"fetch-body","inheritedText":"fetch-body","secondRead":"reject:TypeError","afterReplacement":"false","afterNew":"throw:TypeError","afterClone":"throw:TypeError"}"# ); handle.terminate_and_join(); } diff --git a/moli-renderer-v8/tests/fixtures/request-body-transfer.js b/moli-renderer-v8/tests/fixtures/request-body-transfer.js new file mode 100644 index 00000000000..18b7d01dd54 --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/request-body-transfer.js @@ -0,0 +1,151 @@ +(async () => { + globalThis.__blobReadingProgress = {stage: 'setup', checks: [], rows: []}; + async function exercise(source, target, url, prefix) { + const checks = [], rows = []; + const check = (name, passed, detail = '') => checks.push({name: `${prefix}/${name}`, passed: !!passed, detail}); + const fence = async () => {for (let i = 0; i < 16; i++) await Promise.resolve();}; + const decode = value => new TextDecoder().decode(value); + const create = (kind, options = {}) => { + let body, text = 'data'; + if (kind === 'Text') {body = '\uD800data';text = '\uFFFDdata';} + else if (kind === 'EmptyText') {body = '';text = '';} + else if (kind === 'ArrayBuffer') body = new source.Uint8Array([100,97,116,97]).buffer; + else if (kind === 'Uint8Array') body = new source.Uint8Array([0,100,97,116,97,0]).subarray(1,5); + else if (kind === 'DataView') body = new source.DataView(new source.Uint8Array([0,100,97,116,97,0]).buffer,1,4); + else if (kind === 'URLSearchParams') {body = new source.URLSearchParams({a:'before'});text = 'a=before';} + else if (kind === 'FormData') {body = new source.FormData();body.set('a','before');text = null;} + else if (kind === 'Blob') body = new source.Blob(['data'], {type:'text/plain'}); + else if (kind === 'File') body = new source.File(['data'],'body.txt',{type:'text/plain'}); + else body = new source.ReadableStream({start(c) {c.enqueue(new source.Uint8Array([100,97,116,97]));c.close();}}); + const input = new source.Request(url, {method:'POST',body,...(kind === 'ReadableStream' ? {duplex:'half'} : {}),...options}); + if (kind === 'URLSearchParams' || kind === 'FormData') body.set('a','after'); + else if (kind === 'Uint8Array') body.fill(0); + else if (kind === 'ArrayBuffer') new source.Uint8Array(body).fill(0); + else if (kind === 'DataView') new source.Uint8Array(body.buffer).fill(0); + const valid = value => text === null ? /name="a"\r\n\r\nbefore\r\n/.test(value) && !value.includes('after') : value === text; + return {input, valid}; + }; + const kinds = ['Text','EmptyText','ArrayBuffer','Uint8Array','DataView','URLSearchParams','FormData','Blob','File','ReadableStream']; + for (const kind of kinds) { + for (const method of ['text','arrayBuffer','bytes','blob']) { + const label = `${kind}/${method}`; + const {input,valid} = create(kind), original = input.body, mime = input.headers.get('content-type'); + const transferred = new target.Request(input), stream = transferred.body; + check(`${label}/input stream locked`, original.locked); + check(`${label}/input disturbed`, input.bodyUsed); + check(`${label}/new body unused`, !transferred.bodyUsed && !stream.locked); + check(`${label}/new stream identity and realm`, stream !== original && Object.getPrototypeOf(stream) === target.ReadableStream.prototype); + check(`${label}/native MIME retained`, transferred.headers.get('content-type') === mime); + let byobError = false; + try {const reader = stream.getReader({mode:'byob'});reader.releaseLock();} + catch (error) {byobError = error instanceof target.TypeError;} + check(`${label}/proxy has default reader semantics`, byobError); + let originalError = false; + try {await input.text();} catch (error) {originalError = error instanceof source.TypeError;} + check(`${label}/input cannot be consumed again`, originalError); + const pending = transferred[method](); + check(`${label}/promise in method realm`, Object.getPrototypeOf(pending) === target.Promise.prototype); + let settled = false; + pending.then(() => {settled = true;},() => {settled = true;}); + await fence(); + check(`${label}/public completion uses a native task`, !settled); + const result = await pending; + const value = method === 'text' ? result : method === 'blob' ? await result.text() : decode(result); + check(`${label}/consumes original immutable data`, valid(value)); + check(`${label}/body used and locked after consumption`, transferred.bodyUsed && stream.locked); + rows.push({label,inputLocked:original.locked,inputUsed:input.bodyUsed,defaultReaderProxy:byobError}); + } + { + const {input,valid} = create(kind); + const transferred = new target.Request(input), original = transferred.body; + const clone = transferred.clone(); + check(`${kind}/clone/locks transferred stream`, original.locked); + check(`${kind}/clone/replaces branch identities`, transferred.body !== original && clone.body !== transferred.body); + check(`${kind}/clone/input remains disturbed`, input.bodyUsed); + const values = await Promise.all([transferred.text(),clone.text()]); + check(`${kind}/clone/both preserve data`, values.every(valid)); + check(`${kind}/clone/both consumed`, transferred.bodyUsed && clone.bodyUsed); + } + { + const {input,valid} = create(kind); + const middle = new target.Request(input), last = new source.Request(middle); + check(`${kind}/chain/first disturbed`, input.bodyUsed); + check(`${kind}/chain/middle disturbed`, middle.bodyUsed && middle.body.locked); + check(`${kind}/chain/preserves data`, valid(await last.text())); + check(`${kind}/chain/last consumed`, last.bodyUsed); + } + { + const {input,valid} = create(kind);let error; + try {new target.Request(input,{method:'GET'});} catch (value) {error = value;} + check(`${kind}/failure/GET throws`, error instanceof target.TypeError); + check(`${kind}/failure/GET preserves body state`, !input.bodyUsed && !input.body.locked); + const sentinel = {}; + try {new target.Request(input,{get headers() {throw sentinel;}});} catch (value) {error = value;} + check(`${kind}/failure/conversion exception identity`, error === sentinel); + check(`${kind}/failure/conversion preserves body state`, !input.bodyUsed && !input.body.locked); + const replacement = new target.Request(input,{body:'replacement'}); + check(`${kind}/override/does not disturb input`, !input.bodyUsed && !input.body.locked); + check(`${kind}/override/uses new body`, await replacement.text() === 'replacement'); + let originalValue, originalFailure; + try {originalValue = await input.text();} catch (error) {originalFailure = String(error);} + check(`${kind}/override/original remains usable`, originalFailure === undefined && valid(originalValue), originalFailure || ''); + } + { + const {input,valid} = create(kind); + const transferred = new target.Request(input,{body:null}); + check(`${kind}/null/inherits body state`, input.bodyUsed && input.body.locked); + check(`${kind}/null/inherits data`, valid(await transferred.text())); + } + if (kind !== 'ReadableStream') { + const {input,valid} = create(kind,{mode:'no-cors',keepalive:true}); + const transferred = new target.Request(input); + check(`${kind}/permissions/keeps no-cors`, transferred.mode === 'no-cors'); + check(`${kind}/permissions/keeps keepalive`, transferred.keepalive); + check(`${kind}/permissions/transfers stream`, input.bodyUsed && input.body.locked); + check(`${kind}/permissions/retains original data`, valid(await transferred.text())); + } + } + { + const reason = {cancel:'identity'}, seen = []; + const stream = new source.ReadableStream({cancel(value) {seen.push(value);}}); + const input = new source.Request(url,{method:'POST',body:stream,duplex:'half'}); + const transferred = new target.Request(input), reader = transferred.body.getReader(); + const pending = reader.read(); + await reader.cancel(reason); + check('cancel/pending read closes',(await pending).done); + check('cancel/reaches original source once',seen.length === 1); + check('cancel/preserves reason identity',seen[0] === reason); + check('cancel/both bodies used',input.bodyUsed && transferred.bodyUsed); + reader.releaseLock(); + } + { + const reason = {error:'identity'}; + const stream = new source.ReadableStream({start(c) {c.error(reason);}}); + const input = new source.Request(url,{method:'POST',body:stream,duplex:'half'}); + const transferred = new target.Request(input);let error; + try {await transferred.bytes();} catch (value) {error = value;} + check('error/preserves source error',error === reason); + check('error/both bodies used',input.bodyUsed && transferred.bodyUsed); + } + return {checks,rows}; + } + const frame = document.createElement('iframe');document.body.appendChild(frame); + const realms = [['top',window],['child',frame.contentWindow]]; + for (const [a,source] of realms) for (const [b,target] of realms) { + __blobReadingProgress.stage = `${a}/${b}`; + const result = await exercise(source,target,location.href,`${a}/${b}`); + __blobReadingProgress.checks.push(...result.checks);__blobReadingProgress.rows.push(...result.rows); + } + frame.remove(); + __blobReadingProgress.stage = 'worker'; + const code = `(${exercise.toString()})(self,self,${JSON.stringify(location.href)},'worker').then(result=>{postMessage(result);close();},error=>{postMessage({checks:[{name:'worker completion',passed:false,detail:String(error.stack||error)}],rows:[]});close();});`; + const url = URL.createObjectURL(new Blob([code],{type:'text/javascript'})),worker = new Worker(url); + try { + const result = await new Promise((resolve,reject)=>{worker.onmessage=e=>resolve(e.data);worker.onerror=e=>reject(Error(e.message));}); + __blobReadingProgress.checks.push(...result.checks);__blobReadingProgress.rows.push(...result.rows); + } finally {worker.terminate();URL.revokeObjectURL(url);} + globalThis.__uiEventResults = {checks:__blobReadingProgress.checks,rows:__blobReadingProgress.rows}; +})().catch(error => { + __blobReadingProgress.checks.push({name:'fixture completion',passed:false,detail:String(error.stack||error)}); + globalThis.__uiEventResults = {checks:__blobReadingProgress.checks,rows:__blobReadingProgress.rows}; +});