diff --git a/src/js/builtins.d.ts b/src/js/builtins.d.ts index 4d0a84598226..8c76eef28726 100644 --- a/src/js/builtins.d.ts +++ b/src/js/builtins.d.ts @@ -439,11 +439,13 @@ declare function $ERR_INVALID_CHAR(name, field?): TypeError; declare function $ERR_HTTP_INVALID_HEADER_VALUE(value: string, name: string): TypeError; declare function $ERR_HTTP_HEADERS_SENT(action: string): Error; declare function $ERR_INVALID_PROTOCOL(proto, expected): TypeError; +declare function $ERR_INVALID_URL_SCHEME(expected: string): TypeError; declare function $ERR_INVALID_STATE(message: string): Error; declare function $ERR_INVALID_STATE_TypeError(message: string): TypeError; declare function $ERR_INVALID_STATE_RangeError(message: string): RangeError; declare function $ERR_UNESCAPED_CHARACTERS(arg): TypeError; declare function $ERR_HTTP_INVALID_STATUS_CODE(code): RangeError; +declare function $ERR_HTTP_CONTENT_LENGTH_MISMATCH(actual: number, expected: number): Error; declare function $ERR_UNHANDLED_ERROR(err?): Error; declare function $ERR_BUFFER_OUT_OF_BOUNDS(name?: string): RangeError; declare function $ERR_CHILD_PROCESS_IPC_REQUIRED(where): Error; @@ -473,6 +475,7 @@ declare function $ERR_SOCKET_DGRAM_IS_CONNECTED(): Error; declare function $ERR_SOCKET_DGRAM_NOT_CONNECTED(): Error; declare function $ERR_SOCKET_DGRAM_NOT_RUNNING(): Error; declare function $ERR_INVALID_CURSOR_POS(): Error; +declare function $ERR_SCRIPT_EXECUTION_INTERRUPTED(): Error; declare function $ERR_MULTIPLE_CALLBACK(): Error; declare function $ERR_STREAM_PREMATURE_CLOSE(): Error; declare function $ERR_STREAM_NULL_VALUES(): TypeError; @@ -512,6 +515,7 @@ declare function $ERR_HTTP2_ALTSVC_LENGTH(): TypeError; declare function $ERR_HTTP2_PING_LENGTH(): RangeError; declare function $ERR_HTTP2_OUT_OF_STREAMS(): Error; declare function $ERR_HTTP_BODY_NOT_ALLOWED(): Error; +declare function $ERR_HTTP_TRAILER_INVALID(): Error; declare function $ERR_HTTP_SOCKET_ASSIGNED(): Error; declare function $ERR_DIR_CLOSED(): Error; declare function $ERR_SOCKET_CONNECTION_TIMEOUT(): Error; diff --git a/src/js/internal/fs/streams.ts b/src/js/internal/fs/streams.ts index 365c24987f53..ca563d52c6e4 100644 --- a/src/js/internal/fs/streams.ts +++ b/src/js/internal/fs/streams.ts @@ -163,7 +163,7 @@ function ReadStream(this: FSStream, path, options): void { this[kFs] = customFs || fs; } else if (typeof fd === "object" && fd instanceof FileHandle) { if (options.fs) { - throw $ERR_METHOD_NOT_IMPLEMENTED("fs.FileHandle with custom fs operations"); + throw $ERR_METHOD_NOT_IMPLEMENTED("FileHandle with fs"); } this[kFs] = fileHandleStreamFs(fd); this.fd = fd[kFd]; @@ -408,7 +408,7 @@ function WriteStream(this: FSStream, path: string | null, options?: any): void { this[kFs] = customFs || fs; } else if (typeof fd === "object" && fd instanceof FileHandle) { if (options.fs) { - throw $ERR_METHOD_NOT_IMPLEMENTED("fs.FileHandle with custom fs operations"); + throw $ERR_METHOD_NOT_IMPLEMENTED("FileHandle with fs"); } this[kFs] = customFs = fileHandleStreamFs(fd); fd[kRef](); diff --git a/src/js/internal/http.ts b/src/js/internal/http.ts index 7601cac41640..9631dec34b71 100644 --- a/src/js/internal/http.ts +++ b/src/js/internal/http.ts @@ -321,7 +321,7 @@ function hasServerResponseFinished(self, chunk, callback) { if (finished) { err = $ERR_STREAM_WRITE_AFTER_END(); } else if (destroyed) { - err = $ERR_STREAM_DESTROYED("Stream is destroyed"); + err = $ERR_STREAM_DESTROYED("write"); } if (!destroyed) { diff --git a/src/js/internal/repl/node-errors.js b/src/js/internal/repl/node-errors.js index 84c2c29eecc6..a9b3d5246185 100644 --- a/src/js/internal/repl/node-errors.js +++ b/src/js/internal/repl/node-errors.js @@ -18,8 +18,8 @@ function ERR_USE_AFTER_CLOSE(...args) { function ERR_INVALID_CURSOR_POS(...args) { return $ERR_INVALID_CURSOR_POS(...args); } -function ERR_SCRIPT_EXECUTION_INTERRUPTED(...args) { - return $ERR_SCRIPT_EXECUTION_INTERRUPTED(...args); +function ERR_SCRIPT_EXECUTION_INTERRUPTED() { + return $ERR_SCRIPT_EXECUTION_INTERRUPTED(); } function ERR_INVALID_STATE(...args) { return $ERR_INVALID_STATE(...args); diff --git a/src/js/node/_http_server.ts b/src/js/node/_http_server.ts index 1e0bcc316d13..5e2c41acc30b 100644 --- a/src/js/node/_http_server.ts +++ b/src/js/node/_http_server.ts @@ -2041,7 +2041,7 @@ function _writeHead(statusCode, reason, obj, response) { // header fields, regardless of the header fields present in the // message, and thus cannot contain a message body or 'trailers'. if (hasInvalidTrailer(response)) { - throw $ERR_HTTP_TRAILER_INVALID("Trailers are invalid with this transfer encoding"); + throw $ERR_HTTP_TRAILER_INVALID(); } // Headers in obj should override previous headers but still // allow explicit duplicates. To do so, we first remove any @@ -2071,7 +2071,7 @@ function _writeHead(statusCode, reason, obj, response) { // The message is not chunk-framed, so `Trailer` is the offending header; drop it // so a caller that swallows the throw cannot put it on the wire. response.removeHeader("trailer"); - throw $ERR_HTTP_TRAILER_INVALID("Trailers are invalid with this transfer encoding"); + throw $ERR_HTTP_TRAILER_INVALID(); } } } diff --git a/src/js/node/fs.promises.ts b/src/js/node/fs.promises.ts index 2c0bdf175caf..3e68fdd80ae5 100644 --- a/src/js/node/fs.promises.ts +++ b/src/js/node/fs.promises.ts @@ -1146,7 +1146,7 @@ function asyncWrap(fn: any, name: string) { if (bytesWritten === 0) { if (++retries > 5) { - throw $ERR_OPERATION_FAILED("Operation failed: write failed after retries"); + throw $ERR_OPERATION_FAILED("write failed after retries"); } } else { retries = 0; @@ -1190,7 +1190,7 @@ function asyncWrap(fn: any, name: string) { // Retry the writev as-is on a zero-byte write (up to 5 times) // instead of degrading to the concat fallback below. if (++retries > 5) { - throw $ERR_OPERATION_FAILED("Operation failed: writev failed after retries"); + throw $ERR_OPERATION_FAILED("writev failed after retries"); } continue; } @@ -1227,7 +1227,7 @@ function asyncWrap(fn: any, name: string) { const bytesWritten = fsSync.writeSync(fd, buf, offset, length, position >= 0 ? position : null) || 0; if (bytesWritten === 0) { if (++retries > 5) { - throw $ERR_OPERATION_FAILED("Operation failed: write failed after retries"); + throw $ERR_OPERATION_FAILED("write failed after retries"); } } else { retries = 0; diff --git a/src/js/node/url.ts b/src/js/node/url.ts index 470a682272a2..425b6890f230 100644 --- a/src/js/node/url.ts +++ b/src/js/node/url.ts @@ -1317,7 +1317,7 @@ function fileURLToPathBuffer(path: unknown, options?: { windows?: boolean }): Bu } const url = path as URL; if (url.protocol !== "file:") { - throw $ERR_INVALID_URL_SCHEME("The URL must be of scheme file"); + throw $ERR_INVALID_URL_SCHEME("file"); } if (windows ?? process.platform === "win32") { let pathname = url.pathname.replaceAll("/", "\\"); diff --git a/src/jsc/bindings/ErrorCode.cpp b/src/jsc/bindings/ErrorCode.cpp index 03723bfb09d4..d3afabf7d224 100644 --- a/src/jsc/bindings/ErrorCode.cpp +++ b/src/jsc/bindings/ErrorCode.cpp @@ -1895,6 +1895,7 @@ static constexpr SimpleErrorMessage simpleErrorMessages[] = { { ErrorCode::ERR_INVALID_STATE_TypeError, 1, { "Invalid state: "_s, ""_s, ""_s } }, { ErrorCode::ERR_INVALID_STATE_RangeError, 1, { "Invalid state: "_s, ""_s, ""_s } }, { ErrorCode::ERR_INVALID_PROTOCOL, 2, { "Protocol \""_s, "\" not supported. Expected \""_s, "\""_s } }, + { ErrorCode::ERR_INVALID_URL_SCHEME, 1, { "The URL must be of scheme "_s, ""_s, ""_s } }, { ErrorCode::ERR_BROTLI_INVALID_PARAM, 1, { ""_s, " is not a valid Brotli parameter"_s, ""_s } }, { ErrorCode::ERR_BUFFER_TOO_LARGE, 1, { "Cannot create a Buffer larger than "_s, " bytes"_s, ""_s } }, { ErrorCode::ERR_INVALID_THIS, 1, { "Value of \"this\" must be of type "_s, ""_s, ""_s } }, @@ -1913,6 +1914,7 @@ static constexpr SimpleErrorMessage simpleErrorMessages[] = { { ErrorCode::ERR_HTTP_HEADERS_SENT, 1, { "Cannot "_s, " headers after they are sent to the client"_s, ""_s } }, { ErrorCode::ERR_UNESCAPED_CHARACTERS, 1, { ""_s, " contains unescaped characters"_s, ""_s } }, { ErrorCode::ERR_HTTP_INVALID_STATUS_CODE, 1, { "Invalid status code: "_s, ""_s, ""_s } }, + { ErrorCode::ERR_HTTP_CONTENT_LENGTH_MISMATCH, 2, { "Response body's content-length of "_s, " byte(s) does not match the content-length of "_s, " byte(s) set in header"_s } }, { ErrorCode::ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE, 2, { "Invalid key object type "_s, ", expected "_s, "."_s } }, { ErrorCode::ERR_CRYPTO_INCOMPATIBLE_KEY, 2, { "Incompatible "_s, ": "_s, ""_s } }, { ErrorCode::ERR_CHILD_PROCESS_IPC_REQUIRED, 1, { "Forked processes must have an IPC channel, missing value 'ipc' in "_s, ""_s, ""_s } }, @@ -2321,6 +2323,8 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Bun::jsFunctionMakeErrorWithCode, __att return JSC::JSValue::encode(createError(globalObject, ErrorCode::ERR_SOCKET_DGRAM_NOT_RUNNING, "Not running"_s)); case ErrorCode::ERR_INVALID_CURSOR_POS: return JSC::JSValue::encode(createError(globalObject, ErrorCode::ERR_INVALID_CURSOR_POS, "Cannot set cursor row without setting its column"_s)); + case ErrorCode::ERR_SCRIPT_EXECUTION_INTERRUPTED: + return JSC::JSValue::encode(createError(globalObject, ErrorCode::ERR_SCRIPT_EXECUTION_INTERRUPTED, "Script execution was interrupted by `SIGINT`"_s)); case ErrorCode::ERR_INVALID_HANDLE_TYPE: return JSC::JSValue::encode(createError(globalObject, ErrorCode::ERR_INVALID_HANDLE_TYPE, "This handle type cannot be sent"_s)); case ErrorCode::ERR_MULTIPLE_CALLBACK: @@ -2426,6 +2430,8 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Bun::jsFunctionMakeErrorWithCode, __att return JSC::JSValue::encode(createError(globalObject, ErrorCode::ERR_HTTP2_GOAWAY_SESSION, "New streams cannot be created after receiving a GOAWAY"_s)); case ErrorCode::ERR_HTTP_BODY_NOT_ALLOWED: return JSC::JSValue::encode(createError(globalObject, ErrorCode::ERR_HTTP_BODY_NOT_ALLOWED, "Adding content for this request method or response status is not allowed."_s)); + case ErrorCode::ERR_HTTP_TRAILER_INVALID: + return JSC::JSValue::encode(createError(globalObject, ErrorCode::ERR_HTTP_TRAILER_INVALID, "Trailers are invalid with this transfer encoding"_s)); case ErrorCode::ERR_HTTP_SOCKET_ASSIGNED: return JSC::JSValue::encode(createError(globalObject, ErrorCode::ERR_HTTP_SOCKET_ASSIGNED, "Socket already assigned"_s)); case ErrorCode::ERR_STREAM_RELEASE_LOCK: diff --git a/src/runtime/server/NodeHTTPResponse.rs b/src/runtime/server/NodeHTTPResponse.rs index 15977391c7e4..085b2f40f843 100644 --- a/src/runtime/server/NodeHTTPResponse.rs +++ b/src/runtime/server/NodeHTTPResponse.rs @@ -287,6 +287,24 @@ fn err_throw(global: &JSGlobalObject, code: ErrorCode, msg: &'static str) -> Err(err_throw_cold(global, code, msg)) } +/// Same text as the `ERR_HTTP_CONTENT_LENGTH_MISMATCH` row of `simpleErrorMessages` in ErrorCode.cpp. +#[cold] +#[inline(never)] +fn err_throw_content_length_mismatch( + global: &JSGlobalObject, + actual: usize, + expected: u64, +) -> jsc::JsError { + global + .err( + ErrorCode::ERR_HTTP_CONTENT_LENGTH_MISMATCH, + format_args!( + "Response body's content-length of {actual} byte(s) does not match the content-length of {expected} byte(s) set in header" + ), + ) + .throw() +} + /// AnyResponse `is_ssl()` shim (upstream lacks this accessor). #[inline] fn any_response_is_ssl(r: &uws::AnyResponse) -> bool { @@ -1974,20 +1992,17 @@ impl NodeHTTPResponse { if let Some(content_length) = strict_content_length { let bytes_written = self.bytes_written.get() + bytes.len(); - if IS_END { - if bytes_written as u64 != content_length { - return err_throw( - global_object, - ErrorCode::ERR_HTTP_CONTENT_LENGTH_MISMATCH, - "Content-Length mismatch", - ); - } - } else if bytes_written as u64 > content_length { - return err_throw( + let mismatch = if IS_END { + bytes_written as u64 != content_length + } else { + bytes_written as u64 > content_length + }; + if mismatch { + return Err(err_throw_content_length_mismatch( global_object, - ErrorCode::ERR_HTTP_CONTENT_LENGTH_MISMATCH, - "Content-Length mismatch", - ); + bytes_written, + content_length, + )); } self.bytes_written.set(bytes_written); } else { diff --git a/test/js/node/errors/error-code-messages.test.ts b/test/js/node/errors/error-code-messages.test.ts index cbb3d1222d79..90073bd10c00 100644 --- a/test/js/node/errors/error-code-messages.test.ts +++ b/test/js/node/errors/error-code-messages.test.ts @@ -1,8 +1,14 @@ import { expect, test } from "bun:test"; +import { bunEnv, bunExe, tempDir } from "harness"; import child_process from "node:child_process"; +import { once } from "node:events"; +import fs from "node:fs"; import http from "node:http"; +import net, { type AddressInfo } from "node:net"; +import path from "node:path"; import { Readable } from "node:stream"; import tls from "node:tls"; +import url from "node:url"; import zlib from "node:zlib"; // Codes whose messages come from the fixed-template table behind $ERR_*. @@ -10,11 +16,15 @@ function capture(fn: () => unknown): string { try { fn(); } catch (e: any) { - return `${e.code} | ${e.name} | ${e.message}`; + return describeError(e); } return "no throw"; } +function describeError(e: any): string { + return `${e.code} | ${e.name} | ${e.message}`; +} + test("table-driven ERR_* codes keep their exact messages", () => { expect(capture(() => zlib.createBrotliCompress({ params: { 99999: 1 } }))).toBe( "ERR_BROTLI_INVALID_PARAM | RangeError | 99999 is not a valid Brotli parameter", @@ -35,3 +45,189 @@ test("table-driven ERR_* codes keep their exact messages", () => { "ERR_METHOD_NOT_IMPLEMENTED | Error | The _read() method is not implemented", ); }); + +// Every expected message below is the text node v26.3.0 gives that error. + +// Runs `handler` in a node:http request listener on 127.0.0.1 and resolves to what it returns. +async function inRequestListener(handler: (res: http.ServerResponse) => T | Promise): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + const server = http.createServer((req, res) => { + new Promise(done => done(handler(res))).then(resolve, reject).finally(() => res.destroy()); + }); + server.on("error", reject); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const socket = net.connect((server.address() as AddressInfo).port, "127.0.0.1"); + socket.on("error", reject); + socket.on("close", () => reject(new Error("the connection closed before the request listener finished"))); + socket.write("GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"); + try { + return await promise; + } finally { + socket.destroy(); + server.closeAllConnections(); + server.close(); + } +} + +// `strictContentLength` is a field of OutgoingMessage. @types/node declares it on ServerResponse only. +type ClientRequest = http.ClientRequest & { strictContentLength: boolean }; + +// Runs `fn` on a request to a node:http server on 127.0.0.1. Every `fn` here throws before the request is complete. +async function withClientRequest(options: http.RequestOptions, fn: (req: ClientRequest) => T): Promise { + const server = http.createServer((req, res) => res.end()); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const port = (server.address() as AddressInfo).port; + const req = http.request({ host: "127.0.0.1", port, agent: false, ...options }) as ClientRequest; + // destroy() below aborts the request. The abort arrives as an "error" event. + req.on("error", () => {}); + try { + return fn(req); + } finally { + req.destroy(); + server.closeAllConnections(); + server.close(); + } +} + +test("ERR_HTTP_CONTENT_LENGTH_MISMATCH names the written and the declared byte counts", async () => { + const mismatch = (actual: number) => + `ERR_HTTP_CONTENT_LENGTH_MISMATCH | Error | Response body's content-length of ${actual} byte(s) does not match the content-length of 5 byte(s) set in header`; + const post = { method: "POST", headers: { "Content-Length": 5 } }; + + expect( + await withClientRequest(post, req => { + req.strictContentLength = true; + return capture(() => req.end("abc")); + }), + ).toBe(mismatch(3)); + expect( + await withClientRequest(post, req => { + req.strictContentLength = true; + req.write("hello"); + return capture(() => req.write("a")); + }), + ).toBe(mismatch(6)); + expect( + await inRequestListener(res => { + res.strictContentLength = true; + res.setHeader("Content-Length", 5); + return capture(() => res.end("abc")); + }), + ).toBe(mismatch(3)); + expect( + await inRequestListener(res => { + res.strictContentLength = true; + res.setHeader("Content-Length", 5); + res.write("hello"); + return capture(() => res.write("a")); + }), + ).toBe(mismatch(6)); +}); + +test("ERR_HTTP_TRAILER_INVALID has node's message on a request and on a response", async () => { + const invalid = "ERR_HTTP_TRAILER_INVALID | Error | Trailers are invalid with this transfer encoding"; + + expect(await withClientRequest({ method: "GET", headers: { Trailer: "X-T" } }, req => capture(() => req.end()))).toBe( + invalid, + ); + // writeHead() checks the trailer in two places: with a raw header array, and with no headers or an object. + for (const headers of [undefined, ["X-A", "1"]]) { + expect( + await inRequestListener(res => { + res.setHeader("Trailer", "X-T"); + res.setHeader("Content-Length", 3); + return capture(() => res.writeHead(200, headers)); + }), + ).toBe(invalid); + } +}); + +test("ERR_STREAM_DESTROYED from a destroyed ServerResponse names write()", async () => { + const err = await inRequestListener(res => { + const { promise, resolve } = Promise.withResolvers(); + res.destroy(); + res.write("x", resolve); + return promise; + }); + expect(describeError(err)).toBe("ERR_STREAM_DESTROYED | Error | Cannot call write after a stream was destroyed"); +}); + +test("ERR_INVALID_URL_SCHEME names the file scheme for every fileURLToPath variant", () => { + const scheme = "ERR_INVALID_URL_SCHEME | TypeError | The URL must be of scheme file"; + for (const options of [undefined, { windows: true }, { windows: false }]) { + expect(capture(() => url.fileURLToPath("http://example.com/x", options))).toBe(scheme); + expect(capture(() => url.fileURLToPath(new URL("http://example.com/x"), options))).toBe(scheme); + expect(capture(() => url.fileURLToPathBuffer("http://example.com/x", options))).toBe(scheme); + } +}); + +test("ERR_METHOD_NOT_IMPLEMENTED for a FileHandle stream with a custom fs", async () => { + const handle = await fs.promises.open(import.meta.path); + try { + const notImplemented = "ERR_METHOD_NOT_IMPLEMENTED | Error | The FileHandle with fs method is not implemented"; + expect(capture(() => fs.createReadStream(null as any, { fd: handle, fs }))).toBe(notImplemented); + expect(capture(() => fs.createWriteStream(null as any, { fd: handle, fs }))).toBe(notImplemented); + } finally { + await handle.close(); + } +}); + +test("ERR_OPERATION_FAILED from a FileHandle writer has one prefix", async () => { + using dir = tempDir("error-code-messages", {}); + const handle = await fs.promises.open(path.join(String(dir), "out.txt"), "w"); + const writer = (handle as any).writer({ autoClose: true }); + const { writeSync } = fs; + try { + // The writer retries a write that makes no progress, then gives up. + fs.writeSync = () => 0; + expect(capture(() => writer.writeSync(Buffer.from("abc")))).toBe( + "ERR_OPERATION_FAILED | Error | Operation failed: write failed after retries", + ); + } finally { + fs.writeSync = writeSync; + writer.fail(); + } +}); + +// node:repl takes about 5 s to load on a debug build with ASAN (see test/js/bun/repl/repl.test.ts). +const replTimeout = 20_000; + +test( + "the REPL reports ERR_SCRIPT_EXECUTION_INTERRUPTED with node's message", + async () => { + // Ctrl+C while the REPL awaits a promise that never settles. The terminal delivers its input + // synchronously, like test/common/arraystream.js in node, so the keypress cannot arrive early. + const fixture = ` + const repl = require("node:repl"); + const { Stream } = require("node:stream"); + class Terminal extends Stream { + readable = true; + writable = true; + output = ""; + pause() {} + resume() {} + write(chunk) { + this.output += chunk; + } + } + const terminal = new Terminal(); + const server = repl.start({ prompt: "> ", stream: terminal, terminal: true, useColors: false, breakEvalOnSigint: true }); + terminal.emit("data", "await new Promise(() => {})\\n"); + server.write("", { ctrl: true, name: "c" }); + process.on("exit", () => process.stdout.write(terminal.output)); + `; + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", fixture], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(stdout).toContain("Script execution was interrupted by `SIGINT`"); + expect(exitCode).toBe(0); + }, + replTimeout, +); diff --git a/test/js/node/test/parallel/test-fs-read-stream-file-handle.js b/test/js/node/test/parallel/test-fs-read-stream-file-handle.js index 366f8e08cc5b..729fc4f58b70 100644 --- a/test/js/node/test/parallel/test-fs-read-stream-file-handle.js +++ b/test/js/node/test/parallel/test-fs-read-stream-file-handle.js @@ -58,7 +58,7 @@ fs.promises.open(file, 'r').then((handle) => { }, { code: 'ERR_METHOD_NOT_IMPLEMENTED', name: 'Error', - // message: 'The FileHandle with fs method is not implemented' + message: 'The FileHandle with fs method is not implemented' }); return handle.close(); }).then(common.mustCall());