diff --git a/src/application/javascript/JavaScriptSemanticGraphResourceProjection.ts b/src/application/javascript/JavaScriptSemanticGraphResourceProjection.ts index fd0954d4bb0..140912b4a83 100644 --- a/src/application/javascript/JavaScriptSemanticGraphResourceProjection.ts +++ b/src/application/javascript/JavaScriptSemanticGraphResourceProjection.ts @@ -24,14 +24,30 @@ export const projectSemanticResources = ( }), ); for (const operation of context.ir.resourceOperations) - if (operation.kind === "acquire") + if (operation.kind === "acquire") { + const callSite = context.callSiteAt(operation.location); + const resource = resourceNodes.get(operation.resourceId); addSemanticGraphRelation(context.state, { - source: context.callSiteAt(operation.location), - target: resourceNodes.get(operation.resourceId), + source: callSite, + target: resource, relation: "acquires", - ...builtinSemanticRelation(context.file, operation, "resolved"), + ...builtinSemanticRelation( + context.file, + operation, + operation.resolution === "complete" ? "resolved" : "candidate", + ), }); - else projectRelease(context, operation, resourceNodes); + if (operation.resolution === "partial") + addSemanticGraphUnknown(context.state, { + node_id: callSite?.node_id ?? null, + family: "resource-lifecycle", + relation_kinds: ["acquires"], + reason: "ambiguous-target", + detail: `Static ${operation.method} resource acquisition is uncertain.`, + candidate_node_ids: resource === undefined ? [] : [resource.node_id], + evidence: unknownSemanticEvidence(context.file, operation.location), + }); + } else projectRelease(context, operation, resourceNodes); }; const addResourceNode = ( diff --git a/src/application/javascript/JavaScriptSemanticGraphResources.test.ts b/src/application/javascript/JavaScriptSemanticGraphResources.test.ts index c643f586842..d9673da6440 100644 --- a/src/application/javascript/JavaScriptSemanticGraphResources.test.ts +++ b/src/application/javascript/JavaScriptSemanticGraphResources.test.ts @@ -9,6 +9,39 @@ import { resolveJavaScriptSemanticEvidence } from "../../../tests/support/javasc const SHA256 = "a".repeat(64); const GRAPH_ID = `jag_${"b".repeat(64)}`; +it("retains an uncertain stream acquisition and release as candidates", () => { + const graph = graphFor(` + const fs = require("node:fs"); + Object.defineProperty(fs, "ReadStream", { value: Custom }); + const stream = fs.createReadStream("input", { start: -1 }); + stream.close(); + `); + expect(graph.relations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + relation: "acquires", + resolution: "candidate", + }), + expect.objectContaining({ + relation: "releases", + resolution: "candidate", + }), + ]), + ); + expect(graph.unknowns).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + family: "resource-lifecycle", + relation_kinds: ["acquires"], + }), + expect.objectContaining({ + family: "resource-lifecycle", + relation_kinds: ["releases"], + }), + ]), + ); +}); + it("keeps literal event links and dynamic event uncertainty", () => { const graph = graphFor(` function run(bus, dynamicName) { diff --git a/src/domain/javascript/javascriptSemanticAnalysis.open_flag_literal.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.open_flag_literal.test.ts index b48b4836bab..f66906e5339 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.open_flag_literal.test.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.open_flag_literal.test.ts @@ -1,5 +1,6 @@ import { expect, it } from "vitest"; +import { graphForJavaScript } from "../../../tests/fixtures/javascriptSemanticGraph.js"; import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js"; /** @@ -417,3 +418,1169 @@ it.each([ { kind: "acquire", method: "openSync" }, ]); }); +/** + * `fs.createReadStream` and `fs.createWriteStream` validate their options object + * before constructing the stream, so a refused member throws and no handle exists. + * + * Measured on Node 24.22.1, per member: + * + * start / end -1, 1.5, NaN, Infinity -> THREW ERR_OUT_OF_RANGE + * "10", null, true, 1n -> THREW ERR_INVALID_ARG_TYPE + * -0, 0, undefined -> stream + * fd -1, 1.5 -> THREW ERR_OUT_OF_RANGE + * "x" -> THREW ERR_INVALID_ARG_TYPE + * null, 0 -> stream + * highWaterMark -1, 1.5, "x" -> THREW ERR_INVALID_ARG_VALUE + * null, 0 -> stream + * encoding "nope", 1, true -> THREW ERR_INVALID_ARG_VALUE + * "utf8", "", null, 0, false -> stream + * start > end -> THREW ERR_OUT_OF_RANGE + * createWriteStream ignores `end` -> stream even for `{end: -1}` + * flags / mode / autoClose are not validated eagerly + */ +const streamRelationsFor = (options: string) => + graphForJavaScript( + `const fs = require("node:fs"); const s = fs.createReadStream("i", ${options});`, + ).relations.map( + ({ relation, resolution }) => `${relation}/${resolution ?? ""}`, + ); + +const streamAcquisitionsFor = (call: string) => + analyzeJavaScriptSemantics( + `import fs from "node:fs";\nfunction g(p, opts, n) { ${call}; }`, + ).resourceOperations.map(({ kind, method }) => ({ kind, method })); + +/** + * A unary operator over a BigInt literal is still a BigInt, and `import.meta` is + * always an object, so Node refuses both in these members before a handle exists + * — which is what separates them from a genuinely undecided member: + * + * createReadStream(p, { start: -1n }) -> THREW ERR_INVALID_ARG_TYPE + * createReadStream(p, { start: import.meta }) -> THREW ERR_INVALID_ARG_TYPE + * createReadStream(p, { start: opts }) -> stream, acquisition retained + */ +it.each([ + ["a negated BigInt start", `{ start: -1n }`], + ["a unary-plus BigInt end", `{ end: +1n }`], + ["an import.meta start", `{ start: import.meta }`], +] as const)("emits no stream acquisition for %s", (_name, options) => { + // A refused member throws before the handle exists, so no acquisition — not even + // a candidate — survives. A candidate here would be the undecided path. + expect(streamRelationsFor(options)).not.toContain("acquires/candidate"); + expect(streamRelationsFor(options)).not.toContain("acquires/resolved"); +}); + +it("keeps an undecided member as a candidate", () => { + // The control: an unreadable member must not be dropped, or the check above + // could pass by simply emitting nothing. + expect(streamRelationsFor("{ start: opts }")).toContain("acquires/candidate"); +}); + +it.each(["createReadStream", "createWriteStream"] as const)( + "retains %s and its release when Object.prototype may intercept option copying", + (method) => { + const operations = analyzeJavaScriptSemantics(` + import fs from "node:fs"; + Object.defineProperty(Object.prototype, "start", { set(value) {}, configurable: true }); + const stream = fs.${method}("input", { start: -1 }); + stream.close(); + `).resourceOperations; + expect(operations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ kind: "acquire", method }), + expect.objectContaining({ kind: "release", method: "close" }), + ]), + ); + }, +); + +it.each([ + ["createReadStream", "Readable"], + ["createWriteStream", "Writable"], +] as const)( + "retains %s when a shared Stream ancestor member is installed", + (method, ancestor) => { + // `Readable` and `Writable` both extend `Stream`, so a member installed on that + // shared ancestor is inherited by the stream Node builds. Measured on Node + // 24.22.1: with `Stream.prototype.start` defined as a getter returning 0, + // `createReadStream(p, {start:-1})` returns a handle while the unmutated call + // throws `ERR_OUT_OF_RANGE`. + const operations = analyzeJavaScriptSemantics(` + const { Stream } = require("node:stream"); + const fs = require("node:fs"); + Object.defineProperty(Stream.prototype, "start", { + get() { return 0; }, + set() {}, + configurable: true, + }); + const stream = fs.${method}("input", { start: -1 }); + stream.close(); + `).resourceOperations; + expect(operations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + kind: "acquire", + method, + resolution: "partial", + }), + expect.objectContaining({ + kind: "release", + method: "close", + resolution: "partial", + }), + ]), + ); + expect(ancestor.length).toBeGreaterThan(0); + }, +); + +it("retains a read stream when Array.prototype is set to a FileHandle", () => { + // An array literal is normally not a valid `fd`, but `Object.setPrototypeOf` on + // `Array.prototype` makes it `instanceof FileHandle`. Measured on Node 24.22.1 with a + // real `FileHandle` as that prototype, `createReadStream(p, {fd: []})` constructs a + // stream and reads from the descriptor. + const operations = analyzeJavaScriptSemantics(` + const fs = require("node:fs"); + const handle = fs.openSync("input", "r"); + Object.setPrototypeOf(Array.prototype, handle); + const stream = fs.createReadStream("input", { fd: [] }); + stream.close(); + `).resourceOperations; + expect( + operations.filter( + ({ kind, method }) => kind === "acquire" && method === "createReadStream", + ), + ).toHaveLength(1); +}); + +it("retains a read stream when RegExp.prototype is set to a FileHandle", () => { + // A regular-expression literal is not a valid `fd`, but `Object.setPrototypeOf` on + // `RegExp.prototype` makes it `instanceof FileHandle`. Measured on Node 24.22.1 with a + // real `FileHandle` as that prototype, `createReadStream(p, {fd: /x/})` constructs a + // stream and reads from the descriptor. + const operations = analyzeJavaScriptSemantics(` + const fs = require("node:fs"); + const handle = fs.openSync("input", "r"); + function seed() {} + Object.setPrototypeOf(RegExp.prototype, handle); + const stream = fs.createReadStream("input", { fd: /x/ }); + stream.close(); + `).resourceOperations; + expect( + operations.filter( + ({ kind, method }) => kind === "acquire" && method === "createReadStream", + ), + ).toHaveLength(1); +}); + +it("still rejects an fd regexp when RegExp.prototype is untouched", () => { + const operations = analyzeJavaScriptSemantics(` + const fs = require("node:fs"); + function seed() {} + fs.createReadStream("input", { fd: /x/ }); + `).resourceOperations; + expect(operations.filter(({ kind }) => kind === "acquire")).toEqual([]); +}); +it("still rejects an fd array when Array.prototype is untouched", () => { + const operations = analyzeJavaScriptSemantics(` + const fs = require("node:fs"); + fs.createReadStream("input", { fd: [] }); + `).resourceOperations; + expect(operations.filter(({ kind }) => kind === "acquire")).toEqual([]); +}); +it.each([ + [ + "a default import", + `import sd from "node:string_decoder"; + sd.StringDecoder = class { write(c) { return String(c); } end() { return ""; } };`, + ], + [ + "a named StringDecoder import", + `import { StringDecoder } from "node:string_decoder"; + StringDecoder.extra = 1;`, + ], +] as const)( + "retains a read stream when the decoder is replaced through %s", + (_label, setup) => { + // `fs.createReadStream` builds its `StringDecoder` from this module at first use. + // Measured on Node 24.22.1 with an admitting `Buffer.isEncoding`, replacing the + // export through an ESM default import constructs a handle from `{encoding:"nope"}`. + const operations = analyzeJavaScriptSemantics(` + ${setup} + import fs from "node:fs"; + Buffer.isEncoding = () => true; + const stream = fs.createReadStream("input", { encoding: "nope" }); + stream.close(); + `).resourceOperations; + expect(operations.filter(({ kind }) => kind === "acquire")).toHaveLength(1); + }, +); +it("retains a read stream mutated through the stream root export", () => { + // The CommonJS root export of `node:stream` *is* the constructor, so + // `const Stream = require("node:stream")` records its mutation at `["prototype", …]` + // rather than under the named slot. Measured on Node 24.22.1, both spellings construct + // a handle from `{start:-1}` while the unmutated call throws `ERR_OUT_OF_RANGE`. + const operations = analyzeJavaScriptSemantics(` + const Stream = require("node:stream"); + const fs = require("node:fs"); + Object.defineProperty(Stream.prototype, "start", { + get() { return 0; }, + set() {}, + configurable: true, + }); + const stream = fs.createReadStream("input", { start: -1 }); + stream.close(); + `).resourceOperations; + expect(operations.filter(({ kind }) => kind === "acquire")).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + method: "createReadStream", + resolution: "partial", + }), + ]), + ); +}); +it("retains a read stream mutated through the events root export", () => { + // The CommonJS root export of `node:events` *is* the constructor, so + // `const EventEmitter = require("node:events")` records its mutation at + // `["prototype", …]` rather than under the named slot. Measured on Node 24.22.1, both + // spellings construct a handle from `{start:-1}`. + const operations = analyzeJavaScriptSemantics(` + const EventEmitter = require("node:events"); + const fs = require("node:fs"); + Object.defineProperty(EventEmitter.prototype, "start", { + get() { return 0; }, + set() {}, + configurable: true, + }); + const stream = fs.createReadStream("input", { start: -1 }); + stream.close(); + `).resourceOperations; + expect(operations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + kind: "acquire", + method: "createReadStream", + resolution: "partial", + }), + expect.objectContaining({ kind: "release", method: "close" }), + ]), + ); +}); + +it.each([ + [ + "a replaced StringDecoder and an admitting Buffer.isEncoding", + `const sd = require("node:string_decoder"); + sd.StringDecoder = class { write(c) { return String(c); } end() { return ""; } }; + Buffer.isEncoding = () => true;`, + true, + ], + [ + "an admitting Buffer.isEncoding only", + "Buffer.isEncoding = () => true;", + false, + ], + [ + "a replaced StringDecoder only", + `const sd = require("node:string_decoder"); + sd.StringDecoder = class { write(c) { return String(c); } end() { return ""; } };`, + false, + ], +] as const)( + "read stream encoding acceptance with %s", + (_label, setup, expectKept) => { + // Measured on Node 24.22.1: a read stream throws from whichever gate runs first, so + // it still rejects while either the decoder or `Buffer.isEncoding` is Node's own. + // Only replacing both lifts the rejection. + const operations = analyzeJavaScriptSemantics(` + ${setup} + const fs = require("node:fs"); + const stream = fs.createReadStream("input", { encoding: "nope" }); + stream.close(); + `).resourceOperations; + const acquisitions = operations.filter(({ kind }) => kind === "acquire"); + expect(acquisitions).toHaveLength(expectKept ? 1 : 0); + }, +); +it.each([ + ["a named Stream import", `import { Stream } from "node:stream";`, "Stream"], + [ + "a named EventEmitter import", + `import { EventEmitter } from "node:events";`, + "EventEmitter", + ], +] as const)( + "retains a read stream mutated through %s", + (_label, importLine, ancestor) => { + // `Readable` and `Writable` extend `Stream`, which extends `EventEmitter`, so a + // member installed on either ancestor is inherited by the stream Node builds. + // Measured on Node 24.22.1, defining `start` on either prototype makes + // `createReadStream(p, {start:-1})` return a handle while the unmutated call + // throws `ERR_OUT_OF_RANGE`. + const operations = analyzeJavaScriptSemantics(` + ${importLine} + import fs from "node:fs"; + Object.defineProperty(${ancestor}.prototype, "start", { + get() { return 0; }, + set() {}, + configurable: true, + }); + const stream = fs.createReadStream("input", { start: -1 }); + stream.close(); + `).resourceOperations; + expect(operations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + kind: "acquire", + method: "createReadStream", + resolution: "partial", + }), + expect.objectContaining({ kind: "release", method: "close" }), + ]), + ); + }, +); +it("retains a write stream when Buffer is mutated through its prototype constructor", () => { + // `Buffer.prototype.constructor` is `Buffer`, so a write through that route replaces + // the same predicate the encoding check calls. Measured on Node 24.22.1, with a named + // `Buffer as B` import, `B.prototype.constructor.isEncoding = () => true` makes + // `createWriteStream(p, {encoding:"nope"})` return a handle. The stream itself is + // real, so only the acquisition and its release are asserted, as the neighbouring + // validator-mutation cases do. + const operations = analyzeJavaScriptSemantics(` + const { Buffer: B } = require("node:buffer"); + const fs = require("node:fs"); + B.prototype.constructor.isEncoding = () => true; + const stream = fs.createWriteStream("input", { encoding: "nope" }); + stream.close(); + `).resourceOperations; + expect(operations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + kind: "acquire", + method: "createWriteStream", + }), + expect.objectContaining({ kind: "release", method: "close" }), + ]), + ); +}); +it("keeps native rejection when the other stream prototype changes or the change is later", () => { + for (const setup of [ + 'Object.defineProperty(fs.WriteStream.prototype, "start", { set(value) {} }); fs.createReadStream("input", { start: -1 });', + 'fs.createReadStream("input", { start: -1 }); Object.defineProperty(fs.ReadStream.prototype, "start", { set(value) {} });', + ]) { + const operations = analyzeJavaScriptSemantics( + `const fs = require("node:fs"); ${setup}`, + ).resourceOperations; + expect(operations.filter(({ kind }) => kind === "acquire")).toEqual([]); + } +}); + +it.each([ + ["createReadStream", "ReadStream"], + ["createWriteStream", "WriteStream"], +] as const)( + "retains %s when its constructor may be replaced", + (method, constructor) => { + const operations = analyzeJavaScriptSemantics(` + import fs from "node:fs"; + const Native = fs.${constructor}; + fs.${constructor} = class extends Native { constructor(p, opts) { super(p, { ...opts, start: 0 }); } }; + const stream = fs.${method}("input", { start: -1 }); + stream.close(); + `).resourceOperations; + expect(operations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + kind: "acquire", + method, + resolution: "partial", + }), + expect.objectContaining({ + kind: "release", + method: "close", + resolution: "partial", + }), + ]), + ); + }, +); + +it("still rejects a bad read option when only the write constructor changed", () => { + const operations = analyzeJavaScriptSemantics(` + import fs from "node:fs"; + fs.WriteStream = Custom; + fs.createReadStream("input", { start: -1 }); + `).resourceOperations; + expect(operations.filter(({ kind }) => kind === "acquire")).toEqual([]); +}); + +it.each([ + ["ReadStream", "createReadStream"], + ["WriteStream", "createWriteStream"], +] as const)( + "retains %s prototype effects through named imports", + (constructor, method) => { + const operations = analyzeJavaScriptSemantics(` + import fs, { ${constructor} } from "node:fs"; + Object.defineProperty(${constructor}.prototype, "start", { get() { return 0; }, set(value) {} }); + const stream = fs.${method}("input", { start: -1 }); + stream.close(); + `).resourceOperations; + expect(operations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + kind: "acquire", + method, + resolution: "partial", + }), + expect.objectContaining({ + kind: "release", + method: "close", + resolution: "partial", + }), + ]), + ); + }, +); + +it.each([ + ["ReadStream", "createReadStream", "FileReadStream", "Readable"], + ["WriteStream", "createWriteStream", "FileWriteStream", "Writable"], +] as const)( + "retains %s after shared constructor escapes or inherited mutations", + (constructor, method, alias, parent) => { + for (const setup of [ + `import { ${constructor} } from "node:fs"; configure(${constructor});`, + `Object.defineProperty(fs.${alias}.prototype, "start", { get() { return 0; }, set(value) {} });`, + `Object.defineProperty(require("node:stream").${parent}.prototype, "start", { get() { return 0; }, set(value) {} });`, + `import { ${parent} } from "node:stream"; Object.defineProperty(${parent}.prototype, "start", { get() { return 0; }, set(value) {} });`, + ]) { + const preamble = setup.includes('require("node:stream")') + ? 'const fs = require("node:fs");' + : 'import fs from "node:fs";'; + const operations = analyzeJavaScriptSemantics( + `${preamble} ${setup} const stream = fs.${method}("input", { start: -1 }); stream.close();`, + ).resourceOperations; + expect(operations, setup).toEqual( + expect.arrayContaining([ + expect.objectContaining({ kind: "acquire", method }), + expect.objectContaining({ kind: "release", method: "close" }), + ]), + ); + } + }, +); + +it.each([ + ["Readable", "createReadStream"], + ["Writable", "createWriteStream"], +] as const)( + "retains %s when its export is replaced before stream initialization", + (parent, method) => { + const operations = analyzeJavaScriptSemantics(` + const stream = require("node:stream"); + stream.${parent} = wrapper; + const fs = require("node:fs"); + const handle = fs.${method}("input", { highWaterMark: -1 }); + handle.close(); + `).resourceOperations; + expect(operations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ kind: "acquire", method }), + expect.objectContaining({ kind: "release", method: "close" }), + ]), + ); + }, +); + +it("retains write streams when the named Buffer constructor escapes", () => { + const operations = analyzeJavaScriptSemantics( + `import fs from "node:fs"; import { Buffer as B } from "node:buffer"; configure(B); const stream = fs.createWriteStream("input", { encoding: "nope" }); stream.close();`, + ).resourceOperations; + expect(operations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ kind: "acquire", method: "createWriteStream" }), + expect.objectContaining({ kind: "release", method: "close" }), + ]), + ); +}); + +it("keeps native rejection after unrelated prototype or local binding changes", () => { + for (const setup of [ + 'const { Writable } = require("node:stream"); Object.defineProperty(Writable.prototype, "start", { set(value) {} });', + 'let { ReadStream } = require("node:fs"); ReadStream = Custom;', + "fs.FileReadStream = Custom;", + ]) { + const operations = analyzeJavaScriptSemantics( + `const fs = require("node:fs"); ${setup} fs.createReadStream("input", { start: -1 });`, + ).resourceOperations; + expect( + operations.filter(({ kind }) => kind === "acquire"), + setup, + ).toEqual([]); + } +}); + +it.each([ + "Buffer.isEncoding = () => true", + "globalThis.Buffer.isEncoding = () => true", + "const { Buffer: B } = require('node:buffer'); B.isEncoding = () => true", + "import { Buffer as B } from 'node:buffer'; B.isEncoding = () => true", + "import * as b from 'node:buffer'; b.Buffer.isEncoding = () => true", +])("retains write streams after validator mutation: %s", (setup) => { + const operations = analyzeJavaScriptSemantics(` + ${setup.startsWith("import") ? 'import fs from "node:fs";' : 'const fs = require("node:fs");'} ${setup}; + const stream = fs.createWriteStream("input", { encoding: "nope" }); + stream.close(); + `).resourceOperations; + expect(operations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ kind: "acquire", method: "createWriteStream" }), + expect.objectContaining({ kind: "release", method: "close" }), + ]), + ); +}); + +it.each([ + "Buffer.isEncoding = () => true", + "globalThis.Buffer.isEncoding = () => true", + "const { Buffer: B } = require('node:buffer'); B.isEncoding = () => true", + "import { Buffer as B } from 'node:buffer'; B.isEncoding = () => true", +])( + "retains read streams with a boxed encoding after validator mutation: %s", + (setup) => { + const operations = analyzeJavaScriptSemantics(` + ${setup.startsWith("import") ? 'import fs from "node:fs";' : 'const fs = require("node:fs");'} ${setup}; + const stream = fs.createReadStream("input", { encoding: new String("utf8") }); + stream.close(); + `).resourceOperations; + expect(operations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + kind: "acquire", + method: "createReadStream", + }), + expect.objectContaining({ kind: "release", method: "close" }), + ]), + ); + }, +); + +it("keeps independent rejection and later or unrelated validator writes precise", () => { + for (const body of [ + 'fs.createWriteStream("input", { encoding: "nope" }); Buffer.isEncoding = () => true;', + 'Buffer.other = 1; fs.createWriteStream("input", { encoding: "nope" });', + 'Buffer.isEncoding = () => true; fs.createWriteStream("input", { start: -1, encoding: "nope" });', + 'Buffer.isEncoding = () => true; fs.createReadStream("input", { encoding: "nope" });', + ]) { + const operations = analyzeJavaScriptSemantics( + `const fs = require("node:fs"); ${body}`, + ).resourceOperations; + expect(operations.filter(({ kind }) => kind === "acquire")).toEqual([]); + } +}); + +it.each([ + ["ReadStream", "createReadStream"], + ["WriteStream", "createWriteStream"], +] as const)( + "retains %s acquisition and release when its prototype intercepts start", + (constructor, method) => { + const operations = analyzeJavaScriptSemantics(` + const fs = require("node:fs"); + Object.defineProperty(fs.${constructor}.prototype, "start", { get() { return 0; }, set(value) {} }); + const stream = fs.${method}("input", { start: -1 }); + stream.close(); + `).resourceOperations; + expect(operations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + kind: "acquire", + method, + resolution: "partial", + }), + expect.objectContaining({ + kind: "release", + method: "close", + resolution: "partial", + }), + ]), + ); + }, +); + +it.each(["createReadStream", "createWriteStream"] as const)( + "does not attribute %s to fs after mutating the result of defineProperty", + (method) => { + const operations = analyzeJavaScriptSemantics(` + const fs = require("node:fs"); + const alias = Object.defineProperty(fs, "tag", { value: 1 }); + alias.${method} = () => null; + const stream = fs.${method}("input"); + stream.close(); + `).resourceOperations; + expect(operations.filter(({ kind }) => kind === "acquire")).toEqual([]); + }, +); + +it.each(["createReadStream", "createWriteStream"] as const)( + "keeps descriptor-installed accessors conservative for %s", + (method) => { + for (const [descriptor, use] of [ + [`get: function () { this.${method} = () => null; }`, "fs.tag;"], + [`set: function (_) { this.${method} = () => null; }`, "fs.tag = 1;"], + ]) { + const operations = analyzeJavaScriptSemantics(` + const fs = require("node:fs"); + Object.defineProperty(fs, "tag", { ${descriptor} }); + ${use} + const stream = fs.${method}("input"); + stream.close(); + `).resourceOperations; + expect(operations.filter(({ kind }) => kind === "acquire")).toEqual([]); + } + }, +); + +it("checks the constructor at the factory call even when the factory was saved earlier", () => { + const operations = analyzeJavaScriptSemantics(` + const fs = require("node:fs"); + const read = fs.createReadStream; + fs.ReadStream = Custom; + const stream = read("input", { start: -1 }); + stream.close(); + `).resourceOperations; + expect(operations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ kind: "acquire", method: "createReadStream" }), + expect.objectContaining({ kind: "release", method: "close" }), + ]), + ); +}); + +it("still rejects a bad option when the matching constructor changes afterward", () => { + const operations = analyzeJavaScriptSemantics(` + const fs = require("node:fs"); + fs.createReadStream("input", { start: -1 }); + fs.ReadStream = Custom; + `).resourceOperations; + expect(operations.filter(({ kind }) => kind === "acquire")).toEqual([]); +}); + +it("retains a stream when its constructor is replaced through a module alias", () => { + const operations = analyzeJavaScriptSemantics(` + const fs = require("fs"); + const alias = require("node:fs"); + alias.ReadStream = Custom; + fs.createReadStream("input", { start: -1 }); + `).resourceOperations; + expect(operations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ kind: "acquire", method: "createReadStream" }), + ]), + ); +}); + +it("retains a stream when Object.defineProperty replaces its constructor through a module alias", () => { + const operations = analyzeJavaScriptSemantics(` + const fs = require("fs"); + const alias = require("node:fs"); + Object.defineProperty(alias, "ReadStream", { value: Custom }); + const stream = fs.createReadStream("input", { start: -1 }); + stream.close(); + `).resourceOperations; + expect(operations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + kind: "acquire", + method: "createReadStream", + resolution: "partial", + }), + expect.objectContaining({ + kind: "release", + method: "close", + resolution: "partial", + }), + ]), + ); +}); + +it("keeps native rejection when Object.defineProperty changes an unrelated fs slot", () => { + const operations = analyzeJavaScriptSemantics(` + const fs = require("node:fs"); + Object.defineProperty(fs, "WriteStream", { value: Custom }); + fs.createReadStream("input", { start: -1 }); + `).resourceOperations; + expect(operations.filter(({ kind }) => kind === "acquire")).toEqual([]); +}); + +it("does not trust a replaced Object.defineProperty as a confined mutation", () => { + const operations = analyzeJavaScriptSemantics(` + const fs = require("node:fs"); + Object.defineProperty = patched; + Object.defineProperty(fs, "WriteStream", { value: Custom }); + fs.createReadStream("input", { start: -1 }); + `).resourceOperations; + expect(operations.filter(({ kind }) => kind === "acquire")).toEqual([]); +}); + +it("does not attribute a redefined factory to the native built-in", () => { + const operations = analyzeJavaScriptSemantics(` + const fs = require("node:fs"); + Object.defineProperty(fs, "createReadStream", { value: Custom }); + fs.createReadStream("input", { start: 0 }); + `).resourceOperations; + expect(operations.filter(({ kind }) => kind === "acquire")).toEqual([]); +}); + +it("still rejects a bad option when a prototype change is definitely later", () => { + const operations = analyzeJavaScriptSemantics(` + import fs from "node:fs"; + fs.createReadStream("input", { start: -1 }); + Object.defineProperty(Object.prototype, "start", { set(value) {}, configurable: true }); + `).resourceOperations; + expect(operations.filter(({ kind }) => kind === "acquire")).toEqual([]); +}); + +it("retains a bad option when prototype mutation timing crosses a callable", () => { + const operations = analyzeJavaScriptSemantics(` + import fs from "node:fs"; + function configure() { Object.defineProperty(Object.prototype, "start", { set(value) {}, configurable: true }); } + function open() { return fs.createReadStream("input", { start: -1 }); } + `).resourceOperations; + expect(operations.filter(({ kind }) => kind === "acquire")).toHaveLength(1); +}); + +it.each(["createReadStream", "createWriteStream"] as const)( + "rejects boxed numeric and encoding values for %s while leaving constructed fd unknown", + (method) => { + for (const member of [ + "start: new Number(0)", + "highWaterMark: new Number(0)", + "encoding: new String('utf8')", + ]) + expect(streamAcquisitionsFor(`fs.${method}(p, { ${member} })`)).toEqual( + [], + ); + expect( + streamAcquisitionsFor(`fs.${method}(p, { end: new Number(0) })`), + ).toHaveLength(method === "createReadStream" ? 0 : 1); + expect( + streamAcquisitionsFor(`fs.${method}(p, { fd: new Handle() })`), + ).toHaveLength(1); + }, +); + +it.each(["createReadStream", "createWriteStream"] as const)( + "keeps %s and its close when delete may evaluate to false", + (method) => { + const operations = analyzeJavaScriptSemantics(` + const fs = require("node:fs"); + function open(p) { + const o = {}; + Object.defineProperty(o, "x", { value: 1 }); + const stream = fs.${method}(p, { encoding: delete o.x }); + stream.close(); + } + `).resourceOperations; + const acquire = operations.find( + (operation) => operation.kind === "acquire", + ); + const release = operations.find( + (operation) => operation.kind === "release", + ); + expect(acquire).toMatchObject({ kind: "acquire", method }); + expect(release).toMatchObject({ kind: "release", method: "close" }); + expect(release?.linkedResourceIds).toContain(acquire?.resourceId); + }, +); + +it.each([ + ["a negative start", `fs.createReadStream(p, {start: -1})`], + ["a fractional start", `fs.createReadStream(p, {start: 1.5})`], + ["a NaN start", `fs.createReadStream(p, {start: NaN})`], + ["an Infinity start", `fs.createReadStream(p, {start: Infinity})`], + ["a string start", `fs.createReadStream(p, {start: "10"})`], + ["a null start", `fs.createReadStream(p, {start: null})`], + ["a boolean start", `fs.createReadStream(p, {start: true})`], + ["a BigInt start", `fs.createReadStream(p, {start: 1n})`], + ["a negative end", `fs.createReadStream(p, {end: -1})`], + ["a fractional end", `fs.createReadStream(p, {end: 1.5})`], + ["a string end", `fs.createReadStream(p, {end: "x"})`], + ["a null end", `fs.createReadStream(p, {end: null})`], + ["a start above the end", `fs.createReadStream(p, {start: 10, end: 2})`], + ["a negative fd", `fs.createReadStream(p, {fd: -1})`], + ["a fractional fd", `fs.createReadStream(p, {fd: 1.5})`], + ["a string fd", `fs.createReadStream(p, {fd: "x"})`], + ["a negative high-water mark", `fs.createReadStream(p, {highWaterMark: -1})`], + [ + "a fractional high-water mark", + `fs.createReadStream(p, {highWaterMark: 1.5})`, + ], + ["a string high-water mark", `fs.createReadStream(p, {highWaterMark: "x"})`], + ["an unknown encoding", `fs.createReadStream(p, {encoding: "nope"})`], + ["a numeric encoding", `fs.createReadStream(p, {encoding: 5})`], + ["a truthy boolean encoding", `fs.createReadStream(p, {encoding: true})`], + ["a write-stream negative start", `fs.createWriteStream(p, {start: -1})`], + ["a write-stream fractional start", `fs.createWriteStream(p, {start: 1.5})`], + ["a write-stream string start", `fs.createWriteStream(p, {start: "x"})`], + ["a write-stream negative fd", `fs.createWriteStream(p, {fd: -1})`], + [ + "a write-stream negative high-water mark", + `fs.createWriteStream(p, {highWaterMark: -1})`, + ], + ["a write-stream numeric encoding", `fs.createWriteStream(p, {encoding: 5})`], +] as const)("emits no stream acquisition for %s", (_name, call) => { + expect(streamAcquisitionsFor(call)).toEqual([]); +}); + +it.each([ + [ + "a descriptor with an unknown prototype", + `fs.createReadStream(p, {fd: {__proto__: opts}})`, + ], + [ + "a copied prototype setter", + `fs.createReadStream(p, {["__proto__"]: {set start(v) {}}, start: -1})`, + ], + [ + "a spread that may supply a prototype setter", + `fs.createReadStream(p, {...opts, start: -1})`, + ], + [ + "a computed key that may be a prototype setter", + `fs.createWriteStream(p, {[n]: opts, start: -1})`, + ], + ["a zero start", `fs.createReadStream(p, {start: 0})`], + ["a negative zero start", `fs.createReadStream(p, {start: -0})`], + ["an undefined start", `fs.createReadStream(p, {start: undefined})`], + ["a zero end", `fs.createReadStream(p, {end: 0})`], + ["an end equal to the start", `fs.createReadStream(p, {start: 2, end: 2})`], + ["an end above the start", `fs.createReadStream(p, {start: 2, end: 10})`], + ["a null fd", `fs.createReadStream(p, {fd: null})`], + ["a null high-water mark", `fs.createReadStream(p, {highWaterMark: null})`], + ["a known encoding", `fs.createReadStream(p, {encoding: "utf8"})`], + [ + "an upper-case known encoding", + `fs.createReadStream(p, {encoding: "UTF8"})`, + ], + ["an empty encoding", `fs.createReadStream(p, {encoding: ""})`], + ["a null encoding", `fs.createReadStream(p, {encoding: null})`], + ["a zero encoding", `fs.createReadStream(p, {encoding: 0})`], + ["a false encoding", `fs.createReadStream(p, {encoding: false})`], + ["an unvalidated flags value", `fs.createReadStream(p, {flags: 123})`], + ["an unvalidated mode value", `fs.createReadStream(p, {mode: -1})`], + ["an ignored end on a write stream", `fs.createWriteStream(p, {end: -1})`], + ["an unreadable start", `fs.createReadStream(p, {start: n})`], + ["no options object", `fs.createReadStream(p)`], +] as const)("keeps the stream acquisition for %s", (_name, call) => { + expect(streamAcquisitionsFor(call)).toEqual([ + { + kind: "acquire", + method: call.includes("createWriteStream") + ? "createWriteStream" + : "createReadStream", + }, + ]); +}); +/** + * Five shapes where the stream-option filter disagreed with Node 24.22.1: + * + * 1. A write stream ignores `end`, so neither its own check nor the `start > end` + * ordering applies: `createWriteStream(p, {start: 10, end: 2})` creates a handle. + * 2. `end: Infinity` is a valid unlimited end on a read stream, while `start: Infinity` + * is out of range and `end: -Infinity` and `end: NaN` throw. + * 3. A unary member is not always `+`: `~0` is `-1` and throws, `~-1` is `0` and does + * not, and `!0`, `!1` and `typeof 1` yield a boolean or a string Node refuses. + * 4. Each integer member has its own upper bound: `start` and `end` stop at + * `Number.MAX_SAFE_INTEGER`, `fd` at `2_147_483_647`, and `highWaterMark` has none + * (`1e21` is accepted, `Infinity` is not). + * 5. An object, array, function or regular expression member throws + * `ERR_INVALID_ARG_TYPE`. + */ +it.each([ + [`fs.createReadStream(p, {start: 10, end: 2})`], + [`fs.createReadStream(p, {start: Infinity})`], + [`fs.createReadStream(p, {end: -Infinity})`], + [`fs.createReadStream(p, {end: NaN})`], + [`fs.createReadStream(p, {start: ~0})`], + [`fs.createReadStream(p, {end: ~0})`], + [`fs.createReadStream(p, {start: !0})`], + [`fs.createReadStream(p, {start: !1})`], + [`fs.createReadStream(p, {start: typeof 1})`], + [`fs.createReadStream(p, {start: 9007199254740992})`], + [`fs.createReadStream(p, {end: 9007199254740992})`], + [`fs.createReadStream(p, {fd: 2147483648})`], + [`fs.createReadStream(p, {fd: -2147483648})`], + [`fs.createWriteStream(p, {fd: 2147483648})`], + [`fs.createReadStream(p, {highWaterMark: Infinity})`], + [`fs.createReadStream(p, {highWaterMark: NaN})`], + [`fs.createReadStream(p, {start: []})`], + [`fs.createReadStream(p, {start: {}})`], + [`fs.createReadStream(p, {start: () => {}})`], + [`fs.createReadStream(p, {start: /x/})`], +] as const)("emits no stream acquisition for %s", (call) => { + expect(streamAcquisitionsFor(call)).toEqual([]); +}); + +it.each([ + [ + "a write stream ignoring end", + `fs.createWriteStream(p, {start: 10, end: 2})`, + ], + [ + "a write stream ignoring a negative end", + `fs.createWriteStream(p, {end: -1})`, + ], + [ + "a write stream ignoring an infinite end", + `fs.createWriteStream(p, {end: Infinity})`, + ], + ["an infinite end", `fs.createReadStream(p, {end: Infinity})`], + ["an overflowing end", `fs.createReadStream(p, {end: 1e400})`], + [ + "an infinite end above a start", + `fs.createReadStream(p, {start: 5, end: Infinity})`, + ], + ["a complemented minus one", `fs.createReadStream(p, {start: ~-1})`], + ["a complemented uint32 max", `fs.createReadStream(p, {start: ~4294967295})`], + ["a void start", `fs.createReadStream(p, {start: void 0})`], + [ + "an offset at the safe-integer ceiling", + `fs.createReadStream(p, {start: 9007199254740991})`, + ], + ["a descriptor at int32 max", `fs.createReadStream(p, {fd: 2147483647})`], + [ + "a descriptor above int32 on a write stream", + `fs.createWriteStream(p, {fd: 2147483647})`, + ], + [ + "a high-water mark above int32", + `fs.createReadStream(p, {highWaterMark: 2147483648})`, + ], + [ + "a high-water mark of 1e21", + `fs.createReadStream(p, {highWaterMark: 1e21})`, + ], +] as const)("keeps the stream acquisition for %s", (_name, call) => { + expect(streamAcquisitionsFor(call)).toHaveLength(1); +}); +/** + * A getter in the options literal runs while Node enumerates and copies the object, so + * it can replace another member before that member is read. Measured on Node 24.22.1: + * + * createReadStream(p, {get reset(){this.start=0}, start:-1}) -> stream + * createReadStream(p, {get reset(){}, start:-1}) -> stream + * createReadStream(p, {set x(v){}, start:-1}) -> THREW + * createReadStream(p, {reset(){this.start=0}, start:-1}) -> THREW (methods are not invoked) + * createReadStream(p, {start:-1, get z(){}}) -> THREW (the getter runs after) + * + * A `set` accessor and a plain method do not run during the copy, so a bad member there + * is still decided. + */ +it.each([ + [`fs.createReadStream(p, {get reset(){this.start=0}, start:-1})`], + [`fs.createReadStream(p, {get reset(){}, start:-1})`], + [`fs.createReadStream(p, {start:-1, get z(){}})`], + [`fs.createReadStream(p, {get z(){this.highWaterMark=-1}, highWaterMark:0})`], + [`fs.createWriteStream(p, {get reset(){this.start=0}, start:-1})`], +] as const)("leaves a getter-bearing options literal undecided: %s", (call) => { + expect(streamAcquisitionsFor(call)).toHaveLength(1); +}); + +it.each([ + [`fs.createReadStream(p, {set x(v){}, start:-1})`], + [`fs.createReadStream(p, {reset(){this.start=0}, start:-1})`], + [`fs.createReadStream(p, {start:-1})`], +] as const)( + "still decides a literal whose accessors do not run: %s", + (call) => { + expect(streamAcquisitionsFor(call)).toEqual([]); + }, +); +/** + * A computed string key does not stop a getter from running while Node copies the + * literal. Measured on Node 24.22.1: + * + * createReadStream(p, {get ["reset"](){this.start=0}, start:-1}) -> stream + * createReadStream(p, {get ["reset"](){}, start:-1}) -> stream + */ +it("treats a computed string-key getter as eager", () => { + expect( + streamAcquisitionsFor( + `fs.createReadStream(p, {get ["reset"](){this.start=0}, start:-1})`, + ), + ).toHaveLength(1); + expect( + streamAcquisitionsFor( + `fs.createReadStream(p, {get ["reset"](){}, start:-1})`, + ), + ).toHaveLength(1); +}); + +/** + * A method written in shorthand reaches the reader as an `ObjectMethod`, and a class + * expression has the same runtime type as a function. Measured on Node 24.22.1, all of + * `{start(){}}`, `{start: function(){}}`, `{start: class{}}` and `{start: function*(){}}` + * throw `ERR_INVALID_ARG_TYPE`, and `{encoding(){}}` throws `ERR_INVALID_ARG_VALUE`. + */ +it.each([ + [`fs.createReadStream(p, {start(){}})`], + [`fs.createReadStream(p, {end(){}})`], + [`fs.createReadStream(p, {fd(){}})`], + [`fs.createReadStream(p, {highWaterMark(){}})`], + [`fs.createReadStream(p, {start: class{}})`], + [`fs.createReadStream(p, {start: function*(){}})`], + [`fs.createReadStream(p, {encoding(){}})`], +] as const)("emits no acquisition for a method-valued member: %s", (call) => { + expect(streamAcquisitionsFor(call)).toEqual([]); +}); + +/** + * Any truthy non-string `encoding` reaches Node's check and is refused; a falsy one is + * skipped first. Measured on Node 24.22.1: `-1`, `1.5`, `Infinity`, `-Infinity`, `{}` + * and `[]` throw `ERR_INVALID_ARG_VALUE`, while `0`, `-0`, `""`, `false`, `0n` and `NaN` + * all construct a stream. + */ +it.each([ + [`fs.createReadStream(p, {encoding: -1})`], + [`fs.createReadStream(p, {encoding: 1.5})`], + [`fs.createReadStream(p, {encoding: Infinity})`], + [`fs.createReadStream(p, {encoding: -Infinity})`], + [`fs.createReadStream(p, {encoding: {}})`], + [`fs.createReadStream(p, {encoding: []})`], +] as const)( + "emits no acquisition for a truthy non-string encoding: %s", + (call) => { + expect(streamAcquisitionsFor(call)).toEqual([]); + }, +); + +it.each([ + [`fs.createReadStream(p, {encoding: NaN})`], + [`fs.createReadStream(p, {encoding: -0})`], + [`fs.createReadStream(p, {encoding: 0})`], + [`fs.createReadStream(p, {encoding: ""})`], + [`fs.createReadStream(p, {encoding: false})`], +] as const)("keeps the acquisition for a falsy encoding: %s", (call) => { + expect(streamAcquisitionsFor(call)).toHaveLength(1); +}); +/** + * `encoding` truthiness is a separate question from the numeric bounds. Measured on + * Node 24.22.1: + * + * {encoding: !1} -> false, skipped -> stream + * {encoding: !0} -> true, refused -> THREW ERR_INVALID_ARG_VALUE + * {encoding: ~-1} -> 0, skipped -> stream + * {encoding: ~0} -> -1, refused -> THREW + * {encoding: typeof 1} -> "number", refused -> THREW + * {encoding: `utf8`} -> stream + * {encoding: `ut${"f8"}`} -> stream (interpolated, undecided) + * {encoding: `nope${"x"}`} -> THREW, but undecided here + */ +it.each([ + [`fs.createReadStream(p, {encoding: !1})`], + [`fs.createReadStream(p, {encoding: ~-1})`], + [`fs.createReadStream(p, {encoding: \`utf8\`})`], + [`fs.createReadStream(p, {encoding: \`ut\${"f8"}\`})`], + [`fs.createReadStream(p, {encoding: \`nope\${"x"}\`})`], +] as const)( + "keeps the acquisition for a skipped or undecided encoding: %s", + (call) => { + expect(streamAcquisitionsFor(call)).toHaveLength(1); + }, +); + +it.each([ + [`fs.createReadStream(p, {encoding: !0})`], + [`fs.createReadStream(p, {encoding: ~0})`], + [`fs.createReadStream(p, {encoding: typeof 1})`], + // A regular expression is an object at runtime, and Node refuses it as an encoding. + [`fs.createReadStream(p, {encoding: /x/})`], + [`fs.createWriteStream(p, {encoding: /x/})`], +] as const)( + "emits no acquisition for a truthy non-string encoding: %s", + (call) => { + expect(streamAcquisitionsFor(call)).toEqual([]); + }, +); + +/** + * `import.meta` is an object, so the member decides: + * + * createReadStream(p, { encoding: import.meta }) -> THREW ERR_INVALID_ARG_VALUE + * createReadStream(p, { start: import.meta }) -> THREW ERR_INVALID_ARG_TYPE + * + * Both throw before a handle exists, so neither retains an acquisition. + */ +it.each([ + ["an import.meta encoding", `{ encoding: import.meta }`], + ["an import.meta start", `{ start: import.meta }`], +] as const)("emits no stream acquisition for %s", (_name, options) => { + expect(streamRelationsFor(options)).not.toContain("acquires/candidate"); +}); + +/** + * A `+`/`-` chain over a BigInt literal is still a BigInt, so it is refused wherever a + * Number is required, and it is truthy for `encoding` unless it is zero: + * + * createReadStream(p, { start: -(-1n) }) -> THREW ERR_INVALID_ARG_TYPE + * createReadStream(p, { encoding: -1n }) -> THREW ERR_INVALID_ARG_VALUE + * createReadStream(p, { encoding: -0n }) -> accepted as "not given" + */ +it.each([ + ["a nested unary BigInt start", `{ start: -(-1n) }`], + ["a nested unary BigInt end", `{ end: +(+2n) }`], + ["a BigInt encoding", `{ encoding: -1n }`], +] as const)("emits no stream acquisition for %s", (_name, options) => { + expect(streamRelationsFor(options)).not.toContain("acquires/candidate"); +}); + +it("keeps a zero BigInt encoding as not given", () => { + // `-0n` is falsy, so Node skips the member and the stream is constructed. The graph + // fixtures report that as a candidate acquisition, the same as a valid literal option. + expect( + streamRelationsFor(`{ encoding: -0n }`).some((relation) => + relation.startsWith("acquires/"), + ), + ).toBe(true); +}); + +/** + * The chain is evaluated, not just read: `~0n` is `-1n` (truthy, refused for `encoding`) + * and `~-1n` is `0n` (falsy, so the member is skipped). Unary `+` on a BigInt throws. + */ +it.each([ + ["a bitwise-not zero encoding", `{ encoding: ~0n }`], + ["a bitwise-not minus-one start", `{ start: ~-1n }`], + ["a unary-plus BigInt encoding", `{ encoding: +1n }`], +] as const)("emits no stream acquisition for %s", (_name, options) => { + expect(streamRelationsFor(options)).not.toContain("acquires/candidate"); +}); + +it("keeps a bitwise-not minus-one encoding, which evaluates to zero", () => { + expect( + streamRelationsFor(`{ encoding: ~-1n }`).some((relation) => + relation.startsWith("acquires/"), + ), + ).toBe(true); +}); + +/** + * `fd` is the member where an object is legal, and `import.meta` is directly + * re-prototypable: + * + * Object.setPrototypeOf(import.meta, handle); + * fs.createReadStream(p, { fd: import.meta, autoClose: false }) -> constructs and reads + * + * That mutation names `import.meta`, not `Object.prototype`, so the member stays undecided. + */ +it("keeps an fd supplied through import.meta", () => { + expect( + streamRelationsFor(`{ fd: import.meta, autoClose: false }`).some( + (relation) => relation.startsWith("acquires/"), + ), + ).toBe(true); +}); diff --git a/src/domain/javascript/javascriptSemanticDataEffectHelpers.ts b/src/domain/javascript/javascriptSemanticDataEffectHelpers.ts index 40e5a6964ee..b20d9eb5cf4 100644 --- a/src/domain/javascript/javascriptSemanticDataEffectHelpers.ts +++ b/src/domain/javascript/javascriptSemanticDataEffectHelpers.ts @@ -878,6 +878,8 @@ export const requiredModuleChanged = ( allowCandidate = false, ignoreCandidateEffects = false, snapshotObjectRoot?: "env" | "argv", + descendantsMatter = false, + ignoreRootSlotWrite = false, ): boolean => { const identity = semanticRequireExportsIdentity(specifier, selected); return builtinModuleEffects(identity.specifier, state, allowCandidate).some( @@ -889,6 +891,12 @@ export const requiredModuleChanged = ( path.length === 1 && path[0] === snapshotObjectRoot ) && + !( + ignoreRootSlotWrite && + kind === "write" && + path.length === 1 && + path[0] === identity.path[0] + ) && !( savedObjectCapture !== undefined && path.length < identity.path.length && @@ -898,7 +906,12 @@ export const requiredModuleChanged = ( state.parentsByNode, ) ) && - affectsBuiltinPath(path, identity.path) && + (affectsBuiltinPath(path, identity.path) || + (descendantsMatter && + path.length > identity.path.length && + identity.path.every((key, index) => + semanticPropertyPathKeyMatches(path[index]!, key), + ))) && !semanticTopLevelEffectFollowsCapture( capture, node, @@ -910,6 +923,56 @@ export const requiredModuleChanged = ( ); }; +/** Whether a built-in export can still be relied on at this use site. */ +export const builtinModuleSlotUnmodified = ( + specifier: string, + path: readonly string[], + use: t.Node, + state: JavaScriptSemanticAnalysisState, +): boolean => + !requiredModuleChanged(specifier, path, use, state, false, undefined, true); + +/** Whether a built-in object and its descendants retain their known behavior. */ +export const builtinModuleSubtreeUnmodified = ( + specifier: string, + path: readonly string[], + use: t.Node, + state: JavaScriptSemanticAnalysisState, +): boolean => + !requiredModuleChanged( + specifier, + path, + use, + state, + false, + undefined, + true, + false, + undefined, + true, + ); + +/** A saved constructor's shared prototype survives reassignment of its export slot. */ +export const builtinSharedPrototypeUnmodified = ( + specifier: string, + path: readonly string[], + use: t.Node, + state: JavaScriptSemanticAnalysisState, +): boolean => + !requiredModuleChanged( + specifier, + path, + use, + state, + false, + undefined, + true, + false, + undefined, + true, + true, + ); + /** Calling an unchanged built-in as a member is not an escape to unknown code. */ const originalBuiltinReceiver = ( node: t.Node | undefined, diff --git a/src/domain/javascript/javascriptSemanticMemberMutations.ts b/src/domain/javascript/javascriptSemanticMemberMutations.ts index 1867a84bc75..7dcf24c696b 100644 --- a/src/domain/javascript/javascriptSemanticMemberMutations.ts +++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts @@ -6,6 +6,7 @@ import { createGlobalPathReader, retainSemanticAmbientEffect, } from "./javascriptSemanticAmbientWrites.js"; +import { isUnmodifiedGlobalReference } from "./javascriptSemanticGlobalReference.js"; import { isIntrinsicMapLookup } from "./javascriptSemanticIntrinsicInstances.js"; import { JavaScriptSemanticWorkMeter } from "./javascriptSemanticWorkAllowance.js"; import { @@ -19,6 +20,7 @@ import { semanticEffectMayReachOriginalGlobalProcess, semanticMutableBuiltinOrigin, semanticRequireExportsIdentity, + semanticRequireOrigin, semanticRequireOriginCandidate, semanticRequireLoaderAt, hasSemanticCreateRequireFactoryOrigin, @@ -911,6 +913,7 @@ export function* collectSemanticMemberMutationsSteps( iterableReferences.push(reference); }; const ambientPaths = createAmbientPathResolver(state, true); + const propertyDefinitions = new WeakSet(); // One query's alias states. Exact paths are affordable for almost every // query; a query that outgrows this budget is answered again by escaping // whole objects, so one dense alias cluster cannot spend the source's @@ -1388,6 +1391,7 @@ export function* collectSemanticMemberMutationsSteps( // Preserve the explicit target write separately; deleting never invokes it. if ( effect === "write" && + (mutation === undefined || !propertyDefinitions.has(mutation)) && !t.isUnaryExpression(mutation, { operator: "delete" }) ) { const selectedPath = path; @@ -1434,7 +1438,11 @@ export function* collectSemanticMemberMutationsSteps( let retainsInitializers = true; if (!primitiveWrite) { for (const origin of origins.directOrigins) { - const shared = semanticMutableBuiltinOrigin(origin, path); + const shared = semanticMutableBuiltinOrigin( + origin, + path, + effect === "escape", + ); if (shared !== undefined) recordRequiredEffect( shared.specifier, @@ -1998,8 +2006,85 @@ export function* collectSemanticMemberMutationsSteps( ); else if (node.init != null) markEscaped(node.init, exit); }; + /** + * `Object.defineProperty(fs, "x", {value, writable, enumerable, configurable})` + * defines one known property of a mutable built-in and returns its target. When + * the result is discarded the target never escapes, so the call is not an escape + * either; a retained result is returned so the caller can step over it. + */ + const markBuiltinPropertyDefinition = ( + node: t.CallExpression | t.OptionalCallExpression | t.NewExpression, + parent: t.Node | null, + ): t.Node | undefined => { + if (t.isNewExpression(node)) return undefined; + const callTarget = unwrapJavaScriptExpression(node.callee).node; + if ( + (!t.isMemberExpression(callTarget) && + !t.isOptionalMemberExpression(callTarget)) || + semanticStaticPropertyKey(callTarget.property, callTarget.computed) !== + "defineProperty" || + !isUnmodifiedGlobalReference(node.callee, state, [ + "Object", + "defineProperty", + ]) + ) + return undefined; + const [target, key, descriptor] = node.arguments; + if ( + target === undefined || + t.isSpreadElement(target) || + t.isArgumentPlaceholder(target) || + (!t.isStringLiteral(key) && !t.isNumericLiteral(key)) || + !t.isObjectExpression(descriptor) || + !descriptor.properties.every( + (property) => + t.isObjectProperty(property) && + !property.computed && + ["value", "writable", "enumerable", "configurable"].includes( + semanticStaticPropertyKey(property.key, false) ?? "", + ), + ) + ) + return undefined; + const value = unwrapJavaScriptExpression(target).node; + const required = semanticRequireOriginCandidate(value, state); + const binding = t.isIdentifier(value) + ? resolveSemanticBindingState(state, value, value.name) + : undefined; + const provenance = + binding === undefined + ? undefined + : evaluateSemanticExpressionProvenance(value, state); + // A single candidate origin is still the module this call mutates, which is + // the same allowance `semanticExpressionModuleOrigin` makes. + const origin = + required?.origin ?? + (provenance?.status === "module" + ? provenance.origins[0] + : provenance?.status === "ambiguous" && + provenance.origins.length === 1 && + provenance.origins[0]?.loaderAuthority === "candidate" + ? provenance.origins[0] + : undefined); + const module = + origin === undefined + ? undefined + : semanticMutableBuiltinOrigin(origin, []); + if ( + module === undefined || + module.specifier.replace(/^node:/u, "") !== "fs" || + module.path.length !== 0 + ) + return undefined; + propertyDefinitions.add(node); + markValue(target, [String(key.value)], new Set(), "write", node); + return parent !== null && t.isExpressionStatement(parent) + ? target + : undefined; + }; const markInvocation = ( node: t.CallExpression | t.OptionalCallExpression | t.NewExpression, + definedTarget?: t.Node, ): void => { for (const source of returnedReferences(node.callee).references) markEscaped(source.node, node, source.projection); @@ -2018,7 +2103,7 @@ export function* collectSemanticMemberMutationsSteps( mutation: node, originAt: node, }); - else markEscaped(argument, node); + else if (argument !== definedTarget) markEscaped(argument, node); // Constructing a member does not pass its container as `this`. if (!t.isNewExpression(node)) { const mapLookup = isIntrinsicMapLookup(node, state); @@ -2123,7 +2208,7 @@ export function* collectSemanticMemberMutationsSteps( t.isOptionalCallExpression(node) || t.isNewExpression(node) ) - markInvocation(node); + markInvocation(node, markBuiltinPropertyDefinition(node, parent)); break; case "tagged-template": if (t.isTaggedTemplateExpression(node)) { diff --git a/src/domain/javascript/javascriptSemanticRequireOrigin.ts b/src/domain/javascript/javascriptSemanticRequireOrigin.ts index 993dcace1e4..d5ac977ef26 100644 --- a/src/domain/javascript/javascriptSemanticRequireOrigin.ts +++ b/src/domain/javascript/javascriptSemanticRequireOrigin.ts @@ -2139,12 +2139,25 @@ const MUTABLE_BUILTIN_DEFAULTS = new Set([ "path/posix", "path/win32", "url", + "buffer", + "stream", + // `Stream` extends `EventEmitter`, so a member installed on that ancestor is inherited + // by every fs stream. Measured on Node 24.22.1, defining `start` on + // `EventEmitter.prototype` makes `createReadStream(p, {start:-1})` return a handle + // while the unmutated call throws `ERR_OUT_OF_RANGE`. + "events", + // `fs.createReadStream` builds its `StringDecoder` from this module at first use, so a + // replaced export changes which encodings a read stream accepts. Measured on Node + // 24.22.1 with an admitting `Buffer.isEncoding`, replacing `StringDecoder` through the + // default export constructs a handle from `{encoding:"nope"}`. + "string_decoder", ]); /** Mutable default/object selections share CommonJS identity; namespace slots do not. */ export const semanticMutableBuiltinOrigin = ( origin: JavaScriptModuleOrigin, selected: readonly Key[] = [], + escaped = false, ): | { readonly specifier: string; readonly path: readonly (Key | string)[] } | undefined => { @@ -2154,7 +2167,29 @@ export const semanticMutableBuiltinOrigin = ( const specifier = origin.specifier.replace(/^node:/u, ""); if (!MUTABLE_BUILTIN_DEFAULTS.has(specifier)) return undefined; if (path[0] === "default") return { specifier, path: path.slice(1) }; - if (specifier === "events" && path[0] === "EventEmitter" && path.length > 1) + // Named imports cannot replace their namespace slots, but their exported + // constructor objects still share identity with the CommonJS built-in. + if ( + (selected.length > 0 || escaped) && + ((specifier === "fs" && + (path[0] === "ReadStream" || + path[0] === "WriteStream" || + path[0] === "FileReadStream" || + path[0] === "FileWriteStream")) || + (specifier === "buffer" && path[0] === "Buffer") || + // `Stream` is the ancestor both fs stream classes extend, so a member installed + // through a named `Stream` import reaches them. Measured on Node 24.22.1, the + // named-import form constructs a handle from `{start:-1}` exactly like the + // CommonJS form. + (specifier === "stream" && + (path[0] === "Readable" || + path[0] === "Writable" || + path[0] === "Stream")) || + (specifier === "events" && path[0] === "EventEmitter") || + // The default-import form is handled by the `default` arm above; this covers a + // named `StringDecoder` import, whose binding is the same constructor object. + (specifier === "string_decoder" && path[0] === "StringDecoder")) + ) return { specifier, path }; if (specifier === "process" && (path[0] === "env" || path[0] === "argv")) return { specifier, path }; diff --git a/src/domain/javascript/javascriptSemanticResources.ts b/src/domain/javascript/javascriptSemanticResources.ts index ebd4fb1610d..c68e97e54fc 100644 --- a/src/domain/javascript/javascriptSemanticResources.ts +++ b/src/domain/javascript/javascriptSemanticResources.ts @@ -14,10 +14,12 @@ import type { } from "./javascriptSemanticIr.js"; import { readExactJavaScriptLiteral, + isNullishJavaScriptSyntax, isObjectPrototypeSetter, primitiveOwnKeys, semanticStaticPropertyName, staticJavaScriptTruthiness, + staticObjectProperty, staticObjectPropertyReader, staticObjectCopyPropertyReader, unwrapJavaScriptExpression, @@ -26,10 +28,12 @@ import { isUnmodifiedGlobalReference } from "./javascriptSemanticGlobalReference import { bindingEffectsConfinedToReceiverCalls, bindingMethodMayHaveChanged, + ambientPathMayObserveAt, opaqueCodeMayRebindBinding, prototypeMutationMayPrecede, } from "./javascriptSemanticEffectLog.js"; import { semanticBindingAtRead } from "./javascriptSemanticMutationInitializers.js"; +import { semanticPropertyPathKeyMatches } from "./javascriptSemanticPropertyPaths.js"; import { resolveSemanticBindingState, type JavaScriptSemanticAnalysisState, @@ -38,13 +42,20 @@ import { } from "./javascriptSemanticState.js"; import { builtinDataEffectIdentity, + builtinModuleSlotUnmodified, + builtinModuleSubtreeUnmodified, + builtinSharedPrototypeUnmodified, dataEffectMemberCallee, outerDataEffectBinding, requiredModuleChanged, traverseDataEffects, type DataEffectTraversalContext, } from "./javascriptSemanticDataEffectHelpers.js"; -import { FS_OPEN_FLAGS, range } from "./javascriptStaticAnalysisHelpers.js"; +import { + BUFFER_ENCODINGS, + FS_OPEN_FLAGS, + range, +} from "./javascriptStaticAnalysisHelpers.js"; const RELEASE_METHODS = ["close", "destroy", "end"] as const; @@ -57,6 +68,7 @@ interface ResourceCandidate { readonly resultBindingId: string | null; /** The initial result is the opening Promise; later writes may replace it. */ readonly resultIsPromise: boolean; + readonly constructorUncertain?: true; } /** Recover built-in filesystem/network acquisition and local release handles. */ @@ -71,25 +83,123 @@ export const collectJavaScriptSemanticResources = ( callableStack: [], ancestors: [], }; - const acquisitions = collectAcquisitions(program, context).filter( - (candidate) => - !socketPortInFirstArgument(candidate) || - (!rejectsSocketLiteralArguments( + const acquisitions = collectAcquisitions(program, context) + .map((candidate): ResourceCandidate => + streamOptionsInSecondArgument(candidate) && + (!builtinModuleSlotUnmodified( + "fs", + [ + candidate.method === "createReadStream" + ? "ReadStream" + : "WriteStream", + ], candidate.node, - candidate.specifier, - context, - ) && - !rejectsTlsProtocolVersionLiteral( + state, + ) || + !builtinSharedPrototypeUnmodified( + "fs", + [ + candidate.method === "createReadStream" + ? "FileReadStream" + : "FileWriteStream", + "prototype", + ], + candidate.node, + state, + ) || + !builtinModuleSubtreeUnmodified( + "fs", + [ + candidate.method === "createReadStream" + ? "ReadStream" + : "WriteStream", + "prototype", + ], + candidate.node, + state, + ) || + // Node lazily captures the stream superclass when fs streams initialize. + // A replacement before that point can change constructor validation. + !builtinModuleSubtreeUnmodified( + "stream", + [ + candidate.method === "createReadStream" ? "Readable" : "Writable", + "prototype", + ], + candidate.node, + state, + ) || + // `Readable` and `Writable` both extend `Stream`, so a member installed on + // that shared ancestor is inherited by the stream Node builds. Measured on + // Node 24.22.1: with `Stream.prototype.start` defined as a getter returning 0, + // `createReadStream(p, {start:-1})` returns a handle while the unmutated call + // throws `ERR_OUT_OF_RANGE`. + !builtinModuleSubtreeUnmodified( + "stream", + ["Stream", "prototype"], + candidate.node, + state, + ) || + // The CommonJS root export *is* the constructor, so + // `const Stream = require("node:stream")` records its mutation at + // `["prototype", …]` rather than under the named slot. Measured on Node + // 24.22.1, both spellings construct a handle from `{start:-1}`. + !builtinModuleSubtreeUnmodified( + "stream", + ["prototype"], + candidate.node, + state, + ) || + // `Stream` itself extends `EventEmitter`, so a member installed there is + // inherited too. Node exposes that constructor at two identities, and the + // CommonJS root export *is* the constructor, so + // `const EventEmitter = require("node:events")` records its mutation at + // `["prototype", …]` rather than under the named slot. Measured on Node + // 24.22.1, both spellings construct a handle from `{start:-1}`. + !builtinModuleSubtreeUnmodified( + "events", + ["EventEmitter", "prototype"], + candidate.node, + state, + ) || + !builtinModuleSubtreeUnmodified( + "events", + ["prototype"], + candidate.node, + state, + )) + ? { ...candidate, constructorUncertain: true } + : candidate, + ) + .filter( + (candidate) => + !socketPortInFirstArgument(candidate) || + (!rejectsSocketLiteralArguments( candidate.node, candidate.specifier, - context.state, + context, ) && - !rejectsSocketHostMember( + !rejectsTlsProtocolVersionLiteral( + candidate.node, + candidate.specifier, + context.state, + ) && + !rejectsSocketHostMember( + candidate.node, + candidate.specifier, + context.state, + )), + ) + .filter( + (candidate) => + !streamOptionsInSecondArgument(candidate) || + candidate.constructorUncertain === true || + !rejectsStreamOptionsLiteral( candidate.node, - candidate.specifier, - context.state, - )), - ); + candidate.method === "createReadStream", + context, + ), + ); return [ ...acquisitions.map(immutableAcquisition), ...collectReleases(program, context, acquisitions), @@ -116,6 +226,466 @@ const rejectsFlagOrModeLiteral = (value: t.Node): boolean => { ); }; +/** + * `fs.createReadStream` and `fs.createWriteStream` take their options object in slot 1. + * + * Node validates `start`, `end`, `fd`, `highWaterMark` and `encoding` there before it + * constructs the stream, so a value it rejects throws synchronously and no handle + * exists. Being a stream, that handle is what the release facts attach to, so a + * wrongly retained acquisition also invents a teardown. + */ +const streamOptionsInSecondArgument = ( + candidate: Pick, +): boolean => + candidate.specifier === "fs" && + (candidate.method === "createReadStream" || + candidate.method === "createWriteStream"); + +/** + * The number a stream-option member evaluates to, or a marker for the shapes that are + * not numbers at all. + * + * `absent` is a member Node skips; `refused` is a present value whose type Node + * rejects with `ERR_INVALID_ARG_TYPE`. `undefined` is a value this reader cannot price. + * + * The unary arm reuses `unaryOperandNumber`, which already resolves `-`, `+` and `~` + * chains exactly, so `~0` is `-1` and `~-1` is `0` rather than the operand's magnitude. + * `!`, `typeof` and `delete` yield a boolean or a string, which Node refuses. + */ +type StreamMemberValue = + | { readonly kind: "absent" } + | { readonly kind: "refused" } + | { readonly kind: "number"; readonly value: number } + | undefined; + +/** + * The BigInt literal a `+`/`-`/`~` chain ends at, or `undefined`. + * + * `-(-1n)` and `~0n` are still BigInts, so a member that accepts only numbers refuses + * them just as it refuses `-1n`. `unaryOperandNumber` cannot price that operand, which is + * why the chain is read here instead of only its immediate argument. + */ +const unaryBigIntOperand = ( + value: t.UnaryExpression, +): bigint | "throws" | undefined => { + // Walk to the innermost caller before applying the operators outward, because `~0n` is + // `-1n` and `~-1n` is `0n`: reading only the literal's digits swaps truthy for falsy. + const chain: t.UnaryExpression[] = []; + let current: t.Node = value; + let literal: t.BigIntLiteral | undefined; + for (let depth = 0; depth < 8; depth += 1) { + const node: t.Node = unwrapJavaScriptExpression(current).node; + if (t.isBigIntLiteral(node)) { + literal = node; + break; + } + if (!t.isUnaryExpression(node) || !["+", "-", "~"].includes(node.operator)) + return undefined; + chain.push(node); + current = node.argument; + } + if (literal === undefined) return undefined; + let result = BigInt(String(literal.value).replace(/_/gu, "")); + for (const operator of chain.reverse()) { + // Unary `+` on a BigInt throws a TypeError, so the call never reaches a handle. + if (operator.operator === "+") return "throws"; + result = operator.operator === "-" ? -result : ~result; + } + return result; +}; + +const streamMemberValue = ( + value: t.Node, + context: DataEffectTraversalContext, +): StreamMemberValue => { + if (isAbsentOptionValue(value, context.state)) return { kind: "absent" }; + if (t.isNumericLiteral(value)) return { kind: "number", value: value.value }; + if (t.isUnaryExpression(value)) { + if ( + value.operator === "!" || + value.operator === "typeof" || + value.operator === "delete" + ) + return { kind: "refused" }; + // A unary operator over a BigInt literal is still a BigInt, which Node refuses + // before a handle exists. `unaryOperandNumber` cannot read that operand, so + // without this the member would stay undecided and keep the acquisition. + if (unaryBigIntOperand(value) !== undefined) return { kind: "refused" }; + const number = unaryOperandNumber(value, context, 0); + return number === undefined ? undefined : { kind: "number", value: number }; + } + if ( + t.isIdentifier(value) && + (value.name === "NaN" || value.name === "Infinity") + ) + return isUnmodifiedGlobalReference(value, context.state, value.name) + ? { + kind: "number", + value: value.name === "NaN" ? Number.NaN : Number.POSITIVE_INFINITY, + } + : undefined; + // Every remaining exactly readable value is a type Node refuses for these members. + // A method written in shorthand reaches this reader as an `ObjectMethod`, and a class + // expression has the same runtime type as a function: measured on Node 24.22.1, + // `createReadStream(p, {start(){}})`, `{start: function(){}}` and `{start: class{}}` + // all throw `ERR_INVALID_ARG_TYPE`. + if ( + t.isStringLiteral(value) || + t.isTemplateLiteral(value) || + t.isBooleanLiteral(value) || + t.isBigIntLiteral(value) || + t.isObjectExpression(value) || + t.isNewExpression(value) || + t.isObjectMethod(value) || + t.isArrayExpression(value) || + t.isFunctionExpression(value) || + t.isArrowFunctionExpression(value) || + t.isClassExpression(value) || + t.isRegExpLiteral(value) || + // `import.meta` is always an object in a module, so a numeric member rejects it just + // as it rejects a literal object. `fd` is the exception and is handled by its caller. + (t.isMetaProperty(value) && value.meta.name === "import") + ) + return { kind: "refused" }; + return undefined; +}; + +/** + * Whether an options literal has a member that runs code when Node copies it. + * + * Node enumerates the literal's own keys and copies them in declaration order, so a + * getter listed before a plain member can replace that member's value before it is + * read. Measured on Node 24.22.1, `createReadStream(p, {get reset(){this.start=0}, + * start:-1})` constructs a stream while the same literal without the getter throws + * `ERR_OUT_OF_RANGE`, so the getter's presence makes every other member undecided. + * + * A computed string key does not help: `{get ["reset"](){this.start=0}, start:-1}` + * also constructs a stream, because the key is materialised when the literal is + * created and then enumerated like any other. So every getter counts, computed or not. + * + * A `set` accessor is not read during the copy and a plain method is not invoked, so + * neither affects a later member. + */ +const optionsHasEagerAccessor = (object: t.ObjectExpression): boolean => + object.properties.some( + (property) => t.isObjectMethod(property) && property.kind === "get", + ); + +/** + * Whether a stream's options object provably throws before the handle exists. + * + * Measured on Node 24.22.1. Each member has its own check, and the bounds differ: + * + * - `start`: an integer in `[0, Number.MAX_SAFE_INTEGER]`, so `Infinity` is out of + * range here. `-0` is zero, so the sign alone does not decide. + * - `end`: the same range plus `Infinity`, which Node reads as "read to the end". A + * write stream ignores `end` entirely, so `createWriteStream(p, {end: -1})` still + * creates a handle and the `start > end` ordering check does not apply there. + * - `fd`: an integer in `[0, 2_147_483_647]`, the signed 32-bit range. + * - `highWaterMark`: a non-negative integer with no upper bound — `1e21` is accepted + * while `Infinity` is not. + * - `encoding`: a nullish or otherwise falsy value is skipped, so only a truthy + * literal is decided, and a string must be one `Buffer` accepts. + * + * For `start`, `end` and `fd`, a string, boolean, BigInt, object, array, function or + * regular expression throws `ERR_INVALID_ARG_TYPE`; `null` is present there while + * `fd` and `highWaterMark` treat it as absent. A member this reader cannot price, and + * an options expression that is not an object literal, leave the call undecided. + */ +const rejectsStreamOptionsLiteral = ( + node: t.CallExpression | t.OptionalCallExpression, + readStream: boolean, + context: DataEffectTraversalContext, +): boolean => { + // A spread before the options slot shifts the runtime position, so slot 1 is not + // provably the options object. + if (t.isSpreadElement(node.arguments[0])) return false; + const options = node.arguments[1]; + if (options === undefined || t.isSpreadElement(options)) return false; + const value = unwrapJavaScriptExpression(options).node; + if (!t.isObjectExpression(value)) return false; + // A getter anywhere in the literal can replace another member before Node reads it, + // so no member's declared value is what Node sees. + if (optionsHasEagerAccessor(value)) return false; + // Node copies into an ordinary object. An inherited setter may intercept a + // copied value, so a source-visible prototype change before (or possibly + // before) this call makes the copied members uncertain. + if (prototypeMutationMayPrecede(context.state, "Object", node)) return false; + // Node copies own enumerable keys by assignment. An own __proto__ key, including + // one supplied by a spread or dynamic key, can install setters on the copy before + // a later option is assigned. The literal's values then do not prove a rejection. + if (staticObjectProperty(value, "__proto__").status !== "missing") + return false; + const member = (name: string): StreamMemberValue => { + const read = staticObjectProperty(value, name); + if (read.status !== "explicit") return undefined; + const memberValue = unwrapJavaScriptExpression(read.value as t.Node).node; + if (name === "fd" && t.isNewExpression(memberValue)) return undefined; + // `import.meta` is the one object `fd` accepts: measured on Node 24.22.1, after + // `Object.setPrototypeOf(import.meta, handle)` with a real `FileHandle`, + // `createReadStream(p, {fd: import.meta, autoClose: false})` constructs and reads. That + // mutation names `import.meta` itself rather than `Object.prototype`, so the recorded + // object-prototype question cannot see it; the member stays undecided instead of being + // priced as refused. + if (name === "fd" && t.isMetaProperty(memberValue)) return undefined; + // A FileHandle can be the prototype of an object literal, so the literal's + // shape alone does not prove that Node rejects it as a descriptor. + if ( + name === "fd" && + t.isObjectExpression(memberValue) && + staticObjectProperty(memberValue, "__proto__").status !== "missing" + ) + return undefined; + // An array or regular-expression literal is normally not a descriptor, but + // `Object.setPrototypeOf` on `Array.prototype` or `RegExp.prototype` can make it + // `instanceof FileHandle`. Measured on Node 24.22.1 with a real `FileHandle` as + // either prototype, `createReadStream(p, {fd: []})` and + // `createReadStream(p, {fd: /x/})` construct a stream and read from the descriptor. + if ( + name === "fd" && + (t.isArrayExpression(memberValue) || t.isRegExpLiteral(memberValue)) + ) { + const owner = t.isArrayExpression(memberValue) ? "Array" : "RegExp"; + if (prototypeMutationMayPrecede(context.state, owner, node)) + return undefined; + } + return streamMemberValue(memberValue, context); + }; + const rejectsIndex = ( + name: string, + max: number, + nullIsAbsent: boolean, + unlimited: boolean, + ): boolean => { + const read = staticObjectProperty(value, name); + if (read.status !== "explicit") return false; + if (t.isNullLiteral(unwrapJavaScriptExpression(read.value as t.Node).node)) + return !nullIsAbsent; + const found = member(name); + if (found === undefined || found.kind === "absent") return false; + if (found.kind === "refused") return true; + const number = found.value; + if (unlimited && number === Number.POSITIVE_INFINITY) return false; + return !Number.isInteger(number) || number < 0 || number > max; + }; + // `start` and `fd` share the safe-integer range; `end` additionally admits + // `Infinity`, and only a read stream looks at it at all. + if (rejectsIndex("start", Number.MAX_SAFE_INTEGER, false, false)) return true; + if (readStream && rejectsIndex("end", Number.MAX_SAFE_INTEGER, false, true)) + return true; + if (rejectsIndex("fd", 2_147_483_647, true, false)) return true; + // No upper bound for a buffer budget, but `Infinity` and a fraction still throw. + if (rejectsIndex("highWaterMark", Number.POSITIVE_INFINITY, true, false)) + return true; + // `start` above `end` throws `ERR_OUT_OF_RANGE`. Only a read stream has an `end`, + // and `Infinity` there is above every readable `start`, so it never trips this. + if (readStream) { + const start = member("start"); + const end = member("end"); + if ( + start !== undefined && + end !== undefined && + start.kind === "number" && + end.kind === "number" && + Number.isFinite(start.value) && + Number.isFinite(end.value) && + start.value > end.value + ) + return true; + } + if ( + rejectsStreamEncoding( + value, + context, + readStream, + streamEncodingValidatorUnmodified(node, context.state), + streamEncodingDecoderUnmodified(node, context.state), + ) + ) + return true; + return false; +}; + +/** + * Whether the lazily loaded read-side decoder still resolves to Node's own export. + * + * `fs.createReadStream` constructs a `StringDecoder` for the encoding, and the class it + * captures comes from the `string_decoder` module at first use. Measured on Node 24.22.1 + * with a replaced `StringDecoder` and an admitting `Buffer.isEncoding`, + * `createReadStream(p, {encoding:"nope"})` returns a handle, while either replacement + * alone still throws. + */ +const streamEncodingDecoderUnmodified = ( + node: t.Node, + state: JavaScriptSemanticAnalysisState, +): boolean => + builtinModuleSlotUnmodified( + "string_decoder", + ["StringDecoder"], + node, + state, + ) && + builtinModuleSubtreeUnmodified( + "string_decoder", + ["StringDecoder"], + node, + state, + ); + +/** + * Stream option admission consults the mutable Buffer predicate. + * + * `Buffer.prototype.constructor` is `Buffer` itself, so a write through that route + * replaces the same predicate the encoding check calls. Measured on Node 24.22.1, with a + * named `Buffer as B` import, `B.prototype.constructor.isEncoding = () => true` makes + * `createWriteStream(p, {encoding:"nope"})` return a handle while the unmutated call + * throws `ERR_INVALID_ARG_VALUE`. The recorded mutation path is + * `["Buffer","prototype","constructor","isEncoding"]`, which a prefix-only slot query for + * `["Buffer","isEncoding"]` never matches, so both routes are consulted. + */ +const streamEncodingValidatorUnmodified = ( + node: t.Node, + state: JavaScriptSemanticAnalysisState, +): boolean => { + const selected = ["global", "Buffer", "isEncoding"]; + const changed = ambientPathMayObserveAt(state, node, selected, "contents"); + return ( + !changed && + builtinModuleSlotUnmodified( + "buffer", + ["Buffer", "isEncoding"], + node, + state, + ) && + builtinModuleSubtreeUnmodified( + "buffer", + ["Buffer", "prototype", "constructor", "isEncoding"], + node, + state, + ) + ); +}; + +/** + * Truthiness of a stream-option value, including forms the shared reader leaves open. + * + * `staticJavaScriptTruthiness` covers literals, but a unary result is also exactly + * readable here: measured on Node 24.22.1, `!1` is `false` and `~-1` is `0`, both + * skipped, while `!0`, `~0` and `typeof 1` are truthy and refused. An unshadowed + * `Infinity` is truthy and `NaN` is falsy, matching their values. + */ +const encodingTruthiness = ( + value: t.Node, + context: DataEffectTraversalContext, +): boolean | undefined => { + const shared = staticJavaScriptTruthiness(value); + if (shared !== undefined) return shared; + // A shorthand method, a class expression and a regular expression are all objects at + // runtime, so they are truthy like the function and object literals the shared reader + // already covers. Measured on Node 24.22.1, `{encoding: /x/}` throws + // `ERR_INVALID_ARG_VALUE` for both stream methods. + if ( + t.isObjectMethod(value) || + t.isClassExpression(value) || + t.isRegExpLiteral(value) || + t.isNewExpression(value) || + // `import.meta` is always an object in a module. Measured on Node 24.22.1, + // `createReadStream(p, {encoding: import.meta})` throws `ERR_INVALID_ARG_VALUE`. + (t.isMetaProperty(value) && value.meta.name === "import") + ) + return true; + if ( + t.isIdentifier(value) && + (value.name === "NaN" || value.name === "Infinity") + ) + return isUnmodifiedGlobalReference(value, context.state, value.name) + ? value.name === "Infinity" + : undefined; + if (!t.isUnaryExpression(value)) return undefined; + // `typeof` is a non-empty string and `void` is `undefined`. A `delete` + // expression can return either boolean, so its truthiness is unknown. + if (value.operator === "typeof") return true; + if (value.operator === "delete") return undefined; + if (value.operator === "void") return false; + // `!` over an exactly readable operand is the negation of its truthiness. + if (value.operator === "!") { + const operand = encodingTruthiness( + unwrapJavaScriptExpression(value.argument).node, + context, + ); + return operand === undefined ? undefined : !operand; + } + // `-`, `+` and `~` chains resolve to a number exactly, so `~0` is `-1` and truthy + // while `~-1` is `0` and falsy. A non-finite result is truthy except for `NaN`. + // A `+`/`-` chain over a BigInt literal is a BigInt: `-0n` is falsy like `0n`, and any + // other value is truthy. Measured on Node 24.22.1, `{encoding: -1n}` throws + // `ERR_INVALID_ARG_VALUE` while `{encoding: -0n}` is accepted as "not given". + const bigint = unaryBigIntOperand(value); + // A unary `+` on a BigInt throws before the member is read, so nothing is constructed; + // the truthy branch refuses it, which is the same verdict by the other route. + if (bigint === "throws") return true; + if (bigint !== undefined) return bigint !== 0n; + const number = unaryOperandNumber(value, context, 0); + if (number === undefined) return undefined; + return number !== 0 && !Number.isNaN(number); +}; + +/** + * Whether a stream `encoding` member is one Node's `Buffer` refuses. + * + * Node skips the member when it is falsy and otherwise requires a string `Buffer` + * accepts. Truthiness and the string check are separate questions from the numeric + * bounds the other members use, so this reads them separately instead of reusing the + * index rules — a boolean or a unary result can be falsy and therefore skipped. + * + * Measured on Node 24.22.1: `0`, `-0`, `""`, `false`, `0n`, `NaN`, `!1` (which is + * `false`), `~-1` (which is `0`) and a `void` member are all skipped, while `-1`, `1.5`, + * `Infinity`, `-Infinity`, `{}`, `[]`, `!0`, `typeof 1` and a method all throw + * `ERR_INVALID_ARG_VALUE`. + * + * An interpolated template stays undecided: `` `ut${"f8"}` `` produces a valid encoding, + * so its shape alone does not prove a throw. + */ +const rejectsStreamEncoding = ( + options: t.ObjectExpression, + context: DataEffectTraversalContext, + readStream: boolean, + validatorUnmodified: boolean, + decoderUnmodified: boolean, +): boolean => { + const read = staticObjectProperty(options, "encoding"); + if (read.status !== "explicit") return false; + const value = unwrapJavaScriptExpression(read.value as t.Node).node; + if (isAbsentOptionValue(value, context.state)) return false; + const text = t.isStringLiteral(value) + ? value.value + : t.isTemplateLiteral(value) && value.expressions.length === 0 + ? value.quasis[0]?.value.cooked + : undefined; + if (text !== undefined && text !== null) { + if (text.length === 0 || BUFFER_ENCODINGS.has(text.toLowerCase())) + return false; + // An unknown encoding throws from whichever gate runs first. A write stream has + // only the `Buffer.isEncoding` check, so replacing that predicate lifts it. A read + // stream also builds a `StringDecoder`, so it still throws while that decoder is + // Node's own. Measured on Node 24.22.1: replaced `Buffer.isEncoding` alone still + // throws `ERR_UNKNOWN_ENCODING` for a read stream, and only both replacements + // together construct a handle. + return readStream + ? validatorUnmodified || decoderUnmodified + : validatorUnmodified; + } + // Fail-closed for the truthy shapes below whenever either gate may have changed. + if (!validatorUnmodified) return false; + const truthiness = encodingTruthiness(value, context); + if (truthiness === undefined) return false; + // A falsy member never reaches Node's check, whatever its type. + if (!truthiness) return false; + // A truthy string was decided by the encoding set above; only a truthy non-string + // reaches here, and Node refuses every one of those. + return !t.isStringLiteral(value) && !t.isTemplateLiteral(value); +}; + /** * `fs.open`/`fs.openSync` validate the flag before touching the filesystem, so * a flag Node rejects at the call site throws synchronously and no descriptor @@ -589,6 +1159,8 @@ const collectReleases = ( ), ) && (binding.kind !== "parameter" || receiver.hasDefiniteInitializer) && + linked.length === 1 && + linked[0]?.constructorUncertain !== true && holdsOnlyAcquisitions(binding, linked, context.state), "resource release resolution partial", ), @@ -701,6 +1273,22 @@ const isNullishPlaceholder = ( t.isUnaryExpression(value, { operator: "void" }) || isUnmodifiedGlobalReference(value, state, "undefined"); +/** + * Whether a member value is absent, which Node reads as "this option was not passed". + * + * `null` and `void …` are absent by syntax. The bare `undefined` name is absent only + * while nothing has rebound it: under `const undefined = false` the member carries + * `false`, so the option is present. + */ +const isAbsentOptionValue = ( + value: t.Node, + state: JavaScriptSemanticAnalysisState, +): boolean => + isNullishJavaScriptSyntax(value) || + (t.isIdentifier(value) && + value.name === "undefined" && + isUnmodifiedGlobalReference(value, state, "undefined")); + const immutableAcquisition = ( candidate: ResourceCandidate, ): JavaScriptSemanticResourceOperation => ({ @@ -714,7 +1302,10 @@ const immutableAcquisition = ( ownerCallableId: candidate.ownerCallableId, resultBindingId: candidate.resultBindingId, linkedResourceIds: [], - resolution: "complete", + resolution: knownCoverage( + candidate.constructorUncertain !== true, + "the constructor that produced this acquisition is not certain", + ), }); interface AcquisitionReference { diff --git a/src/domain/javascript/javascriptStaticAnalysisHelpers.ts b/src/domain/javascript/javascriptStaticAnalysisHelpers.ts index 335602a0315..0ab4ccecb12 100644 --- a/src/domain/javascript/javascriptStaticAnalysisHelpers.ts +++ b/src/domain/javascript/javascriptStaticAnalysisHelpers.ts @@ -545,6 +545,28 @@ export const FS_OPEN_FLAGS: ReadonlySet = new Set([ "xw+", ]); +/** + * Encodings Node's `Buffer` accepts, so an `encoding` stream option can be decided. + * + * `Buffer.isEncoding` is the authority, but this module is the pure domain layer and + * does not reach for Node globals. The set is the documented list; a value outside it + * is one Node rejects at the call site. + */ +export const BUFFER_ENCODINGS: ReadonlySet = new Set([ + "ascii", + "base64", + "base64url", + "binary", + "hex", + "latin1", + "ucs-2", + "ucs2", + "utf-16le", + "utf8", + "utf-8", + "utf16le", +]); + /** Reserved browsing-context names (ASCII case-insensitive). */ const BROWSING_CONTEXT_KEYWORDS = new Set([ "_blank", diff --git a/tests/acceptance/applications/javascriptBuiltinDefaultsCli.test.ts b/tests/acceptance/applications/javascriptBuiltinDefaultsCli.test.ts index ab8352944a3..f3cd4ce2675 100644 --- a/tests/acceptance/applications/javascriptBuiltinDefaultsCli.test.ts +++ b/tests/acceptance/applications/javascriptBuiltinDefaultsCli.test.ts @@ -12,6 +12,129 @@ import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; const execute = promisify(execFile); +it("retains streams with an undecidable delete encoding through CLI and MCP", async () => { + const root = await createTestTempDirectory("rea-stream-delete-"); + await writeFile( + join(root, "app.cjs"), + `throw new Error("parse only"); + const fs = require("node:fs"); + const o = {}; Object.defineProperty(o, "x", { value: 1 }); + const read = fs.createReadStream("input", { encoding: delete o.x }); + const write = fs.createWriteStream("output", { encoding: delete o.x }); + read.close(); write.close();`, + ); + const { stdout } = await execute( + process.execPath, + ["scripts/rea.mjs", "analyze-javascript-application", root, "--json"], + { cwd: process.cwd(), maxBuffer: 16 * 1024 * 1024 }, + ); + const evidence = parseEvidence(JSON.parse(stdout)); + const result = javascriptApplicationAnalysisResultSchema.parse( + evidence.normalized_result, + ); + expect( + result.semantic_graph.nodes.filter(({ kind }) => kind === "resource"), + ).toHaveLength(2); + expect( + result.semantic_graph.relations.filter( + ({ relation }) => relation === "releases", + ), + ).toHaveLength(2); + const { client, call } = await connectLocalToolsMcp(); + const response = await call("analyze_javascript_application", { + input_path: root, + format: "auto", + }); + expect(response.isError, JSON.stringify(response)).not.toBe(true); + expect(response.structuredContent).toEqual(evidence); + await client.ping(); +}, 60000); + +it("keeps prototype-intercepted streams and rejects boxed options through CLI and MCP", async () => { + const root = await createTestTempDirectory("rea-stream-option-ownership-"); + await writeFile( + join(root, "prototype.cjs"), + ` + const fs = require("node:fs"); + Object.defineProperty(Object.prototype, "start", { set(value) {}, configurable: true }); + const read = fs.createReadStream("input", { start: -1 }); + const write = fs.createWriteStream("output", { start: -1 }); + read.close(); write.close(); + `, + ); + await writeFile( + join(root, "boxed.cjs"), + ` + const fs = require("node:fs"); + fs.createReadStream("input", { start: new Number(0) }); + fs.createWriteStream("output", { encoding: new String("utf8") }); + fs.createReadStream("input", { fd: new Handle() }); + `, + ); + await writeFile( + join(root, "validator.cjs"), + ` + const fs = require("node:fs"); + fs.createReadStream("before", { encoding: new String("utf8") }); + Buffer.isEncoding = () => true; + const read = fs.createReadStream("input", { encoding: new String("utf8") }); + read.close(); + fs.createReadStream("invalid", { encoding: "nope" }); + `, + ); + await writeFile( + join(root, "superclass.cjs"), + ` + const stream = require("node:stream"); + stream.Readable = wrapRead; + stream.Writable = wrapWrite; + const fs = require("node:fs"); + const read = fs.createReadStream("input", { highWaterMark: -1 }); + const write = fs.createWriteStream("output", { highWaterMark: -1 }); + read.close(); write.close(); + `, + ); + const { stdout } = await execute( + process.execPath, + ["scripts/rea.mjs", "analyze-javascript-application", root, "--json"], + { cwd: process.cwd(), maxBuffer: 16 * 1024 * 1024 }, + ); + const evidence = parseEvidence(JSON.parse(stdout)); + const graph = javascriptApplicationAnalysisResultSchema.parse( + evidence.normalized_result, + ).semantic_graph; + const resources = graph.nodes.filter(({ kind }) => kind === "resource"); + expect( + resources.filter( + ({ identity }) => identity.module_path === "prototype.cjs", + ), + ).toHaveLength(2); + expect( + resources.filter(({ identity }) => identity.module_path === "boxed.cjs"), + ).toHaveLength(1); + expect( + resources.filter( + ({ identity }) => identity.module_path === "validator.cjs", + ), + ).toHaveLength(1); + expect( + resources.filter( + ({ identity }) => identity.module_path === "superclass.cjs", + ), + ).toHaveLength(2); + expect( + graph.relations.filter(({ relation }) => relation === "releases"), + ).toHaveLength(5); + const { client, call } = await connectLocalToolsMcp(); + const response = await call("analyze_javascript_application", { + input_path: root, + format: "auto", + }); + expect(response.isError, JSON.stringify(response)).not.toBe(true); + expect(response.structuredContent).toEqual(evidence); + await client.ping(); +}, 60000); + it("preserves earlier and sibling effects without inventing replaced cached-module or process effects", async () => { const root = await createTestTempDirectory("rea-builtin-identity-"); await writeFile( diff --git a/tests/boundary/cli/javascriptApplicationJsonOutput.test.ts b/tests/boundary/cli/javascriptApplicationJsonOutput.test.ts index 651a9095cda..f7327394243 100644 --- a/tests/boundary/cli/javascriptApplicationJsonOutput.test.ts +++ b/tests/boundary/cli/javascriptApplicationJsonOutput.test.ts @@ -11,6 +11,132 @@ import { cliTest } from "../../support/cli/cliFixture.js"; const filter = "evidence_id,normalized_result.graph.nodes[0,1].node_id"; +cliTest( + "reports a replaced stream constructor as an uncertain resource", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-js-stream-constructor-"); + await writeFile( + join(root, "main.js"), + ` + const fs = require("node:fs"); + Object.defineProperty(fs, "ReadStream", { value: Custom }); + const stream = fs.createReadStream("input", { start: -1 }); + stream.close(); + `, + ); + const output = await cli.run({ + arguments: ["analyze-javascript-application", root, "--json"], + }); + expect(output.exitCode).toBe(0); + const data = z + .object({ normalized_result: javascriptApplicationAnalysisResultSchema }) + .parse(output.json).normalized_result; + expect(data.semantic_graph.relations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + relation: "acquires", + resolution: "candidate", + }), + expect.objectContaining({ + relation: "releases", + resolution: "candidate", + }), + ]), + ); + expect(data.semantic_graph.unknowns).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + family: "resource-lifecycle", + relation_kinds: ["acquires"], + }), + ]), + ); + }, +); + +cliTest( + "retains stream resources after named constructor and validator mutations", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-js-stream-named-import-"); + await writeFile( + join(root, "main.mjs"), + ` + import fs, { ReadStream } from "node:fs"; + import { Buffer as B } from "node:buffer"; + Object.defineProperty(ReadStream.prototype, "start", { get() { return 0; }, set(value) {} }); + B.isEncoding = () => true; + const reader = fs.createReadStream("input", { start: -1 }); + reader.close(); + const writer = fs.createWriteStream("output", { encoding: "nope" }); + writer.close(); + `, + ); + const output = await cli.run({ + arguments: ["analyze-javascript-application", root, "--json"], + }); + expect(output.exitCode).toBe(0); + const data = z + .object({ normalized_result: javascriptApplicationAnalysisResultSchema }) + .parse(output.json).normalized_result; + expect( + data.semantic_graph.relations.filter( + ({ relation }) => relation === "acquires", + ), + ).toHaveLength(2); + expect( + data.semantic_graph.relations.filter( + ({ relation }) => relation === "releases", + ), + ).toHaveLength(2); + expect(data.semantic_graph.relations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + relation: "acquires", + resolution: "candidate", + }), + expect.objectContaining({ + relation: "releases", + resolution: "candidate", + }), + ]), + ); + }, +); + +cliTest( + "retains stream resources after inherited prototype mutations and constructor escapes", + async ({ cli }) => { + const root = await createTestTempDirectory( + "rea-js-stream-shared-prototype-", + ); + await writeFile( + join(root, "main.mjs"), + ` + import fs, { ReadStream } from "node:fs"; + import { Writable } from "node:stream"; + import { Buffer as B } from "node:buffer"; + configure(ReadStream); configure(B); + Object.defineProperty(Writable.prototype, "start", { get() { return 0; }, set(value) {} }); + const reader = fs.createReadStream("input", { start: -1 }); reader.close(); + const writer = fs.createWriteStream("output", { start: -1 }); writer.close(); + `, + ); + const output = await cli.run({ + arguments: ["analyze-javascript-application", root, "--json"], + }); + expect(output.exitCode).toBe(0); + const graph = z + .object({ normalized_result: javascriptApplicationAnalysisResultSchema }) + .parse(output.json).normalized_result.semantic_graph; + expect( + graph.relations.filter(({ relation }) => relation === "acquires"), + ).toHaveLength(2); + expect( + graph.relations.filter(({ relation }) => relation === "releases"), + ).toHaveLength(2); + }, +); + for (const scenario of [ { command: "analyze-javascript-application",