diff --git a/src/workerd/api/streams/common.h b/src/workerd/api/streams/common.h index e4b916f41c4..f9fee831844 100644 --- a/src/workerd/api/streams/common.h +++ b/src/workerd/api/streams/common.h @@ -1086,6 +1086,15 @@ jsg::Promise rejectedMaybeHandledPromise(jsg::Lock& js, jsg::JsValue reason, return kj::mv(prp.promise); } +// Returns a promise rejected with `reason` for one step of a pipe, marked as handled. The pipe +// machinery consumes every such promise, and the caller learns the outcome from the pipe +// promise, which is settled separately. These promises are often returned already rejected +// from a promise continuation, and V8 attaches the handler that adopts them only in a later +// microtask; left unmarked, they can be reported as unhandled rejections before then. +inline jsg::Promise rejectedPipeStep(jsg::Lock& js, jsg::JsValue reason) { + return rejectedMaybeHandledPromise(js, reason, true); +} + // Captures the current context's identity for stream objects without retaining a reference that // could be destroyed from a different thread during garbage collection. inline kj::Maybe tryGetIoContextId() { diff --git a/src/workerd/api/streams/internal.c++ b/src/workerd/api/streams/internal.c++ index 48d7caefad5..92d0c93ac38 100644 --- a/src/workerd/api/streams/internal.c++ +++ b/src/workerd/api/streams/internal.c++ @@ -915,7 +915,10 @@ kj::Maybe> ReadableStreamInternalController::read( controller.doError(js, error); } - return js.rejectedPromise(error); + // The read's promise adopts this one and carries the error to the caller. Mark it as + // handled: it is returned already rejected, and the handler that adopts it is attached + // only in a later microtask, so it could otherwise be reported as unhandled first. + return rejectedMaybeHandledPromise(js, error, true); })); } else { return js.rejectedPromise( @@ -2660,12 +2663,12 @@ jsg::Promise WritableStreamInternalController::Pipe::pipeLoop(jsg::Lock& j if (!preventAbort && parentRef.state.isActive()) { parentRef.state.whenActive( [&](IoOwn& writable) { writable->abort(js.exceptionToKj(errored)); }); - return js.rejectedPromise(errored); + return rejectedPipeStep(js, errored); } // If preventAbort was true, we're going to unlock the destination now. parentRef.writeState.transitionTo(); - return js.rejectedPromise(errored); + return rejectedPipeStep(js, errored); } auto getReadableRef = [&]() -> kj::Maybe> { @@ -2681,7 +2684,7 @@ jsg::Promise WritableStreamInternalController::Pipe::pipeLoop(jsg::Lock& j parentRef.writeState.transitionTo(); if (!preventCancel) { releaseSource(js, reason); - return js.rejectedPromise(reason); + return rejectedPipeStep(js, reason); } releaseSource(js); return js.resolvedPromise(); @@ -2727,7 +2730,7 @@ jsg::Promise WritableStreamInternalController::Pipe::pipeLoop(jsg::Lock& j releaseSource(js); } - return js.rejectedPromise(destClosed); + return rejectedPipeStep(js, destClosed); } // The read can run the source's pull algorithm, and that code can end this pipe, destroying diff --git a/src/workerd/api/streams/standard.c++ b/src/workerd/api/streams/standard.c++ index 46c2fb8a750..e79232b0921 100644 --- a/src/workerd/api/streams/standard.c++ +++ b/src/workerd/api/streams/standard.c++ @@ -21,9 +21,6 @@ namespace workerd::api { using DefaultController = jsg::Ref; using ByobController = jsg::Ref; -// Whether a pipe was started by pipeThrough(), whose pipe promise is marked as handled. -WD_STRONG_BOOL(IsPipeThrough); - namespace { struct ValueReadable; struct ByteReadable; @@ -596,25 +593,20 @@ void WritableLockImpl::visitForGc(jsg::GcVisitor& visitor) { // with `reason` once the cancel completes, or with the cancel's error if it fails. Without the // pipe_to_backward_propagation compatibility flag, the pipe rejects with `reason` right away and // the cancel's outcome is ignored. -jsg::Promise rejectAfterCancel(jsg::Lock& js, - kj::Maybe> maybeCancel, - jsg::JsValue reason, - IsPipeThrough isPipeThrough) { - bool pipeThrough = isPipeThrough.toBool(); +jsg::Promise rejectAfterCancel( + jsg::Lock& js, kj::Maybe> maybeCancel, jsg::JsValue reason) { if (!FeatureFlags::get(js).getPipeToBackwardPropagation()) { - return rejectedMaybeHandledPromise(js, reason, pipeThrough); + return rejectedPipeStep(js, reason); } KJ_IF_SOME(cancel, maybeCancel) { - auto onSuccess = - JSG_VISITABLE_LAMBDA((reason = reason.addRef(js), pipeThrough), (reason), (jsg::Lock& js) { - return rejectedMaybeHandledPromise(js, reason.getHandle(js), pipeThrough); - }); - auto onFailure = [pipeThrough](jsg::Lock& js, jsg::Value error) { - return rejectedMaybeHandledPromise(js, jsg::JsValue(error.getHandle(js)), pipeThrough); + auto onSuccess = JSG_VISITABLE_LAMBDA((reason = reason.addRef(js)), (reason), + (jsg::Lock& js) { return rejectedPipeStep(js, reason.getHandle(js)); }); + auto onFailure = [](jsg::Lock& js, jsg::Value error) { + return rejectedPipeStep(js, jsg::JsValue(error.getHandle(js))); }; return cancel.then(js, kj::mv(onSuccess), kj::mv(onFailure)); } - return rejectedMaybeHandledPromise(js, reason, pipeThrough); + return rejectedPipeStep(js, reason); } template @@ -622,7 +614,6 @@ void WritableLockImpl::PipeLocked::shutDown(jsg::Lock& js, jsg::JsVa // Copy what we need first: the source's cancel algorithm can run user JS that re-enters the // controller and releases the write-side pipe lock, destroying *this. auto pipeResolver = resolver.addRef(js); - IsPipeThrough pipeThrough(flags.pipeThrough); auto cancel = flags.preventCancel ? releaseSource(js) : releaseSource(js, reason); if (!FeatureFlags::get(js).getPipeToBackwardPropagation()) { // Without the compatibility flag, the pipe promise is left to the pipe loop, which resolves @@ -630,18 +621,18 @@ void WritableLockImpl::PipeLocked::shutDown(jsg::Lock& js, jsg::JsVa return; } // Whatever the pipe loop later produces is ignored: a promise can only be resolved once. - pipeResolver.resolve(js, rejectAfterCancel(js, kj::mv(cancel), reason, pipeThrough)); + pipeResolver.resolve(js, rejectAfterCancel(js, kj::mv(cancel), reason)); } template jsg::Promise WritableLockImpl::PipeLocked::finishAbortedPipe( jsg::Lock& js, Controller& self, jsg::JsValue reason, Flags flags) { if (!flags.preventAbort) { - return self.abort(js, reason).then(js, JSG_VISITABLE_LAMBDA((reason = reason.addRef(js), flags, ref = self.addRef()), (reason, ref), (jsg::Lock& js) { - return rejectedMaybeHandledPromise(js, reason.getHandle(js), flags.pipeThrough); + return self.abort(js, reason).then(js, JSG_VISITABLE_LAMBDA((reason = reason.addRef(js), ref = self.addRef()), (reason, ref), (jsg::Lock& js) { + return rejectedPipeStep(js, reason.getHandle(js)); })); } - return rejectedMaybeHandledPromise(js, reason, flags.pipeThrough); + return rejectedPipeStep(js, reason); } template @@ -4360,7 +4351,7 @@ jsg::Promise WritableStreamJsController::pipeLoop(jsg::Lock& js) { auto reason = isErroredOrErroring(js).orDefault( [&] { return js.typeError("This pipe's source has already been released."_kj); }); lock.releasePipeLock(); - return rejectedMaybeHandledPromise(js, reason, pipeThrough); + return rejectedPipeStep(js, reason); } // At the start of each pipe step, we check to see if either the source or @@ -4380,26 +4371,24 @@ jsg::Promise WritableStreamJsController::pipeLoop(jsg::Lock& js) { pipeLock.releaseSource(js); lock.releasePipeLock(); if (!preventAbort) { - auto onSuccess = JSG_VISITABLE_LAMBDA( - (pipeThrough, reason = errored.addRef(js)), (reason), (jsg::Lock& js) { - return rejectedMaybeHandledPromise(js, reason.getHandle(js), pipeThrough); - }); + auto onSuccess = JSG_VISITABLE_LAMBDA((reason = errored.addRef(js)), (reason), + (jsg::Lock& js) { return rejectedPipeStep(js, reason.getHandle(js)); }); return abort(js, errored).then(js, kj::mv(onSuccess)); } - return rejectedMaybeHandledPromise(js, errored, pipeThrough); + return rejectedPipeStep(js, errored); } KJ_IF_SOME(errored, state.tryGetUnsafe()) { auto reason = errored.getHandle(js); auto cancel = preventCancel ? pipeLock.releaseSource(js) : pipeLock.releaseSource(js, reason); lock.releasePipeLock(); - return rejectAfterCancel(js, kj::mv(cancel), reason, IsPipeThrough(pipeThrough)); + return rejectAfterCancel(js, kj::mv(cancel), reason); } KJ_IF_SOME(erroring, isErroring(js)) { auto cancel = preventCancel ? pipeLock.releaseSource(js) : pipeLock.releaseSource(js, erroring); lock.releasePipeLock(); - return rejectAfterCancel(js, kj::mv(cancel), erroring, IsPipeThrough(pipeThrough)); + return rejectAfterCancel(js, kj::mv(cancel), erroring); } if (pipeLock.source->isClosed()) { @@ -4419,7 +4408,7 @@ jsg::Promise WritableStreamJsController::pipeLoop(jsg::Lock& js) { auto reason = js.typeError("This destination writable stream is closed."_kj); auto cancel = preventCancel ? pipeLock.releaseSource(js) : pipeLock.releaseSource(js, reason); lock.releasePipeLock(); - return rejectAfterCancel(js, kj::mv(cancel), reason, IsPipeThrough(pipeThrough)); + return rejectAfterCancel(js, kj::mv(cancel), reason); } // Assuming we get by that, we perform a read on the source. If the read errors, @@ -4432,7 +4421,7 @@ jsg::Promise WritableStreamJsController::pipeLoop(jsg::Lock& js) { // source (again, depending on options). If the write operation is successful, // we call pipeLoop again to move on to the next iteration. - auto onSuccess = JSG_VISITABLE_LAMBDA((this, ref = addRef(), preventCancel, pipeThrough), (ref), + auto onSuccess = JSG_VISITABLE_LAMBDA((this, ref = addRef(), preventCancel), (ref), (jsg::Lock & js, ReadResult result) mutable->jsg::Promise { auto maybePipeLock = lock.tryGetPipe(); if (maybePipeLock == kj::none) return js.resolvedPromise(); @@ -4451,7 +4440,7 @@ jsg::Promise WritableStreamJsController::pipeLoop(jsg::Lock& js) { auto onSuccess = JSG_VISITABLE_LAMBDA((this, ref = addRef()),(ref) ,(jsg::Lock& js) { return pipeLoop(js); } ); - auto onFailure = JSG_VISITABLE_LAMBDA((this, ref = addRef(), preventCancel, pipeThrough),(ref) ,( + auto onFailure = JSG_VISITABLE_LAMBDA((this, ref = addRef(), preventCancel),(ref) ,( jsg::Lock& js, jsg::V8Ref exception) mutable { // The write failed. We need to release the source if the pipe lock still exists. // The write-side pipe lock is left in place; doError() cleans it up when the @@ -4461,7 +4450,7 @@ jsg::Promise WritableStreamJsController::pipeLoop(jsg::Lock& js) { KJ_IF_SOME(pipeLock, lock.tryGetPipe()) { cancel = preventCancel ? pipeLock.releaseSource(js) : pipeLock.releaseSource(js, reason); } else {} // Trailing else() to squash compiler warning - return rejectAfterCancel(js, kj::mv(cancel), reason, IsPipeThrough(pipeThrough)); + return rejectAfterCancel(js, kj::mv(cancel), reason); } ); auto promise = write(js, diff --git a/src/workerd/api/tests/BUILD.bazel b/src/workerd/api/tests/BUILD.bazel index 3b2bdff895a..e24ebec8af8 100644 --- a/src/workerd/api/tests/BUILD.bazel +++ b/src/workerd/api/tests/BUILD.bazel @@ -1261,6 +1261,11 @@ wd_test( data = ["pipe-source-error-uaf-test.js"], ) +wd_test( + src = "pipe-js-source-error-unhandled-rejection-test.wd-test", + data = ["pipe-js-source-error-unhandled-rejection-test.js"], +) + wd_test( src = "autovuln-132-test.wd-test", args = ["--experimental"], diff --git a/src/workerd/api/tests/pipe-js-source-error-unhandled-rejection-test.js b/src/workerd/api/tests/pipe-js-source-error-unhandled-rejection-test.js new file mode 100644 index 00000000000..a8e0f4d926a --- /dev/null +++ b/src/workerd/api/tests/pipe-js-source-error-unhandled-rejection-test.js @@ -0,0 +1,152 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +// Regression test: when a JavaScript-backed ReadableStream errors while it is +// piped into a WritableStream, the pipe must not report an unhandled rejection. +// The caller handles the pipeTo() promise and every other promise it can see, +// so no unhandledrejection event may fire. +// +// The pipe loops used to return promises that were already rejected from their +// promise continuations. V8 attaches the handler that adopts such a promise +// only in a later microtask, so when unhandled rejections are processed in a +// microtask (see the .wd-test's compatibility flags) the promise was reported +// first. This covers the loop for JavaScript-backed writables (DigestStream is +// one) and the loop for internal ones (IdentityTransformStream), and internal +// sources as well as JavaScript-backed ones. + +import { deepStrictEqual, rejects } from 'node:assert'; + +// A byte source that delivers one chunk and errors on the next pull, so the +// error is seen by the pipe loop after a successful read and write. +function erroringByteSource() { + let sent = false; + return new ReadableStream({ + type: 'bytes', + pull(c) { + if (sent) { + c.error(new Error('source failed')); + return; + } + sent = true; + c.enqueue(new Uint8Array(1024)); + }, + }); +} + +// Same as above, but a default (non-byte) source. +function erroringDefaultSource() { + let sent = false; + return new ReadableStream({ + pull(c) { + if (sent) { + c.error(new Error('source failed')); + return; + } + sent = true; + c.enqueue(new Uint8Array(1024)); + }, + }); +} + +function newDigestStream() { + const d = new crypto.DigestStream('MD5'); + d.digest.catch(() => {}); + return d; +} + +async function expectNoUnhandledRejection(fn) { + const reasons = []; + const handler = (event) => { + reasons.push(String(event.reason?.stack ?? event.reason)); + event.preventDefault(); + }; + addEventListener('unhandledrejection', handler); + try { + await fn(); + // Unhandled rejections are reported once the microtask queue drains, before + // the event loop's next turn, so one turn is enough. + await scheduler.wait(0); + deepStrictEqual(reasons, []); + } finally { + removeEventListener('unhandledrejection', handler); + } +} + +export const byteSourceIntoDigestStream = { + async test() { + await expectNoUnhandledRejection(async () => { + await rejects(erroringByteSource().pipeTo(newDigestStream()), { + message: 'source failed', + }); + }); + }, +}; + +export const defaultSourceIntoDigestStream = { + async test() { + await expectNoUnhandledRejection(async () => { + await rejects(erroringDefaultSource().pipeTo(newDigestStream()), { + message: 'source failed', + }); + }); + }, +}; + +export const byteSourceIntoIdentityTransformStream = { + async test() { + await expectNoUnhandledRejection(async () => { + const { readable, writable } = new IdentityTransformStream(); + const drained = readable.pipeTo(new WritableStream()).catch(() => {}); + await rejects(erroringByteSource().pipeTo(writable), { + message: 'source failed', + }); + await drained; + }); + }, +}; + +export const teedByteSourceIntoDigestStreams = { + async test() { + await expectNoUnhandledRejection(async () => { + const [a, b] = erroringByteSource().tee(); + const results = await Promise.allSettled([ + a.pipeTo(newDigestStream()), + b.pipeTo(newDigestStream()), + ]); + deepStrictEqual( + results.map((r) => r.status), + ['rejected', 'rejected'] + ); + }); + }, +}; + +// An internal (native) source that errors while piped into a JavaScript-backed +// writable: the IdentityTransformStream's writable side is aborted mid-pipe. +async function abortedNativeSourceIntoDigestStream(options) { + const { readable, writable } = new IdentityTransformStream(); + const piped = rejects(readable.pipeTo(newDigestStream(), options), { + message: 'source aborted', + }); + const writer = writable.getWriter(); + await writer.write(new Uint8Array(10)); + await writer.abort(new Error('source aborted')); + await piped; +} + +export const nativeSourceIntoDigestStream = { + async test() { + await expectNoUnhandledRejection(() => + abortedNativeSourceIntoDigestStream() + ); + }, +}; + +export const nativeSourceIntoDigestStreamPreventAbort = { + async test() { + await expectNoUnhandledRejection(() => + abortedNativeSourceIntoDigestStream({ preventAbort: true }) + ); + }, +}; diff --git a/src/workerd/api/tests/pipe-js-source-error-unhandled-rejection-test.wd-test b/src/workerd/api/tests/pipe-js-source-error-unhandled-rejection-test.wd-test new file mode 100644 index 00000000000..2f7c6111349 --- /dev/null +++ b/src/workerd/api/tests/pipe-js-source-error-unhandled-rejection-test.wd-test @@ -0,0 +1,20 @@ +using Workerd = import "/workerd/workerd.capnp"; + +const unitTests :Workerd.Config = ( + services = [ + ( name = "pipe-js-source-error-unhandled-rejection-test", + worker = ( + modules = [ + (name = "worker", esModule = embed "pipe-js-source-error-unhandled-rejection-test.js") + ], + compatibilityFlags = [ + "nodejs_compat", + "streams_enable_constructors", + # The rejections fixed here were reported only when unhandled rejections are + # processed in a microtask, which races with promise adoption. + "no_unhandled_rejection_after_microtask_checkpoint", + ], + ) + ), + ], +);