Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/workerd/api/streams/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -1086,6 +1086,15 @@ jsg::Promise<T> 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<void> rejectedPipeStep(jsg::Lock& js, jsg::JsValue reason) {
return rejectedMaybeHandledPromise<void>(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<IoContext::Id> tryGetIoContextId() {
Expand Down
13 changes: 8 additions & 5 deletions src/workerd/api/streams/internal.c++
Original file line number Diff line number Diff line change
Expand Up @@ -915,7 +915,10 @@ kj::Maybe<jsg::Promise<ReadResult>> ReadableStreamInternalController::read(
controller.doError(js, error);
}

return js.rejectedPromise<ReadResult>(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<ReadResult>(js, error, true);
}));
} else {
return js.rejectedPromise<ReadResult>(
Expand Down Expand Up @@ -2660,12 +2663,12 @@ jsg::Promise<void> WritableStreamInternalController::Pipe::pipeLoop(jsg::Lock& j
if (!preventAbort && parentRef.state.isActive()) {
parentRef.state.whenActive(
[&](IoOwn<Writable>& writable) { writable->abort(js.exceptionToKj(errored)); });
return js.rejectedPromise<void>(errored);
return rejectedPipeStep(js, errored);
}

// If preventAbort was true, we're going to unlock the destination now.
parentRef.writeState.transitionTo<Unlocked>();
return js.rejectedPromise<void>(errored);
return rejectedPipeStep(js, errored);
}

auto getReadableRef = [&]() -> kj::Maybe<jsg::Ref<ReadableStream>> {
Expand All @@ -2681,7 +2684,7 @@ jsg::Promise<void> WritableStreamInternalController::Pipe::pipeLoop(jsg::Lock& j
parentRef.writeState.transitionTo<Unlocked>();
if (!preventCancel) {
releaseSource(js, reason);
return js.rejectedPromise<void>(reason);
return rejectedPipeStep(js, reason);
}
releaseSource(js);
return js.resolvedPromise();
Expand Down Expand Up @@ -2727,7 +2730,7 @@ jsg::Promise<void> WritableStreamInternalController::Pipe::pipeLoop(jsg::Lock& j
releaseSource(js);
}

return js.rejectedPromise<void>(destClosed);
return rejectedPipeStep(js, destClosed);
}

// The read can run the source's pull algorithm, and that code can end this pipe, destroying
Expand Down
55 changes: 22 additions & 33 deletions src/workerd/api/streams/standard.c++
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@ namespace workerd::api {
using DefaultController = jsg::Ref<ReadableStreamDefaultController>;
using ByobController = jsg::Ref<ReadableByteStreamController>;

// Whether a pipe was started by pipeThrough(), whose pipe promise is marked as handled.
WD_STRONG_BOOL(IsPipeThrough);

namespace {
struct ValueReadable;
struct ByteReadable;
Expand Down Expand Up @@ -596,52 +593,46 @@ void WritableLockImpl<Controller>::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<void> rejectAfterCancel(jsg::Lock& js,
kj::Maybe<jsg::Promise<void>> maybeCancel,
jsg::JsValue reason,
IsPipeThrough isPipeThrough) {
bool pipeThrough = isPipeThrough.toBool();
jsg::Promise<void> rejectAfterCancel(
jsg::Lock& js, kj::Maybe<jsg::Promise<void>> maybeCancel, jsg::JsValue reason) {
if (!FeatureFlags::get(js).getPipeToBackwardPropagation()) {
return rejectedMaybeHandledPromise<void>(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<void>(js, reason.getHandle(js), pipeThrough);
});
auto onFailure = [pipeThrough](jsg::Lock& js, jsg::Value error) {
return rejectedMaybeHandledPromise<void>(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<void>(js, reason, pipeThrough);
return rejectedPipeStep(js, reason);
}

template <typename Controller>
void WritableLockImpl<Controller>::PipeLocked::shutDown(jsg::Lock& js, jsg::JsValue reason) {
// 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
// it once it notices the pipe is gone (or never, if its read never completes).
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 <typename Controller>
jsg::Promise<void> WritableLockImpl<Controller>::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<void>(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<void>(js, reason, flags.pipeThrough);
return rejectedPipeStep(js, reason);
}

template <typename Controller>
Expand Down Expand Up @@ -4360,7 +4351,7 @@ jsg::Promise<void> 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<void>(js, reason, pipeThrough);
return rejectedPipeStep(js, reason);
}

// At the start of each pipe step, we check to see if either the source or
Expand All @@ -4380,26 +4371,24 @@ jsg::Promise<void> 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<void>(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<void>(js, errored, pipeThrough);
return rejectedPipeStep(js, errored);
}

KJ_IF_SOME(errored, state.tryGetUnsafe<StreamStates::Errored>()) {
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()) {
Expand All @@ -4419,7 +4408,7 @@ jsg::Promise<void> 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,
Expand All @@ -4432,7 +4421,7 @@ jsg::Promise<void> 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<void> {
auto maybePipeLock = lock.tryGetPipe();
if (maybePipeLock == kj::none) return js.resolvedPromise();
Expand All @@ -4451,7 +4440,7 @@ jsg::Promise<void> 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<v8::Value> 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
Expand All @@ -4461,7 +4450,7 @@ jsg::Promise<void> 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,
Expand Down
5 changes: 5 additions & 0 deletions src/workerd/api/tests/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
Original file line number Diff line number Diff line change
@@ -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 })
);
},
};
Original file line number Diff line number Diff line change
@@ -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",
],
)
),
],
);
Loading