diff --git a/src/adb/AdbPushProbeEvidence.test.ts b/src/adb/AdbPushProbeEvidence.test.ts index 5129ef15c6..c97d193861 100644 --- a/src/adb/AdbPushProbeEvidence.test.ts +++ b/src/adb/AdbPushProbeEvidence.test.ts @@ -1,8 +1,8 @@ import { createHash } from "node:crypto"; -import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { readFile, stat, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect, it, onTestFinished } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { AdbProvider } from "./AdbProvider.js"; const startup = @@ -43,8 +43,7 @@ else out("", "Unexpected adb fixture command", 2); it.each([false, true])( "retains startup probe evidence alongside digest observations (recognized=%s)", async (recognized) => { - const root = await mkdtemp(join(tmpdir(), "rea-adb-probe-evidence-")); - onTestFinished(() => rm(root, { recursive: true, force: true })); + const root = await createTestTempDirectory("rea-adb-probe-evidence-"); const source = join(root, "input.bin"); const bytes = Buffer.from("caller-owned bytes"); await writeFile(source, bytes); diff --git a/src/adb/AdbVersionProbe.test.ts b/src/adb/AdbVersionProbe.test.ts index 6d47fab2db..2e9aceadcc 100644 --- a/src/adb/AdbVersionProbe.test.ts +++ b/src/adb/AdbVersionProbe.test.ts @@ -1,7 +1,7 @@ -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { afterAll, expect, it, onTestFinished } from "vitest"; +import { afterAll, expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { @@ -59,8 +59,7 @@ it("reports the fixed adb version-output cap", async () => { ), ); if (process.platform !== "win32") { - const root = await mkdtemp(join(tmpdir(), "rea-adb-version-cap-")); - onTestFinished(() => rm(root, { recursive: true, force: true })); + const root = await createTestTempDirectory("rea-adb-version-cap-"); const selected = join(root, "adb"); await writeFile( selected, @@ -193,8 +192,7 @@ it.skipIf(process.platform === "win32").each([ expectedPath: () => null, }, ])("preserves the source identity for $name", async (testCase) => { - const root = await mkdtemp(join(tmpdir(), "rea-adb-version-")); - onTestFinished(() => rm(root, { recursive: true, force: true })); + const root = await createTestTempDirectory("rea-adb-version-"); const binary = join(root, testCase.fileName); const output = "Android Debug Bridge version 1.0.41\nVersion 35.0.2-stub\n" + diff --git a/src/application/AppBundleExecutable.test.ts b/src/application/AppBundleExecutable.test.ts index 1aa4074e1e..8fc3fee791 100644 --- a/src/application/AppBundleExecutable.test.ts +++ b/src/application/AppBundleExecutable.test.ts @@ -1,5 +1,4 @@ -import { mkdtemp, mkdir, rm, truncate, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, truncate, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; @@ -102,24 +101,20 @@ describe("app bundle Info.plist magic", () => { }); it("does not decode a high-bit fold of bplist as a binary Info.plist", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-bplist-fold-")); - try { - const bundle = join(root, "Fixture.app"); - const plistPath = join(bundle, "Contents", "Info.plist"); - await mkdir(join(bundle, "Contents"), { recursive: true }); - const plist = Buffer.from("bplist00"); - plist[0] = (plist[0] ?? 0) | 0x80; - await writeFile(plistPath, plist); - const result = await resolveAppleBundleExecutable(bundle); - expect(result).toMatchObject({ - ok: false, - error: { - cause: { name: "XmlPlistTextDecodeError", reason: "invalid-bytes" }, - }, - }); - } finally { - await rm(root, { recursive: true, force: true }); - } + const root = await createTestTempDirectory("rea-bplist-fold-"); + const bundle = join(root, "Fixture.app"); + const plistPath = join(bundle, "Contents", "Info.plist"); + await mkdir(join(bundle, "Contents"), { recursive: true }); + const plist = Buffer.from("bplist00"); + plist[0] = (plist[0] ?? 0) | 0x80; + await writeFile(plistPath, plist); + const result = await resolveAppleBundleExecutable(bundle); + expect(result).toMatchObject({ + ok: false, + error: { + cause: { name: "XmlPlistTextDecodeError", reason: "invalid-bytes" }, + }, + }); }); }); @@ -149,46 +144,42 @@ describe("app bundle Info.plist decode budget", () => { describe("app bundle program directory containment", () => { it("rejects an escaping programs directory before resolving its child", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-app-programs-")); - try { - const bundle = join(root, "Fixture.app"); - const programs = join(bundle, "Contents", "MacOS"); - const executable = join(programs, "Missing"); - const canonicalBundle = join(root, "Canonical.app"); - const outsidePrograms = join(root, "outside"); - const plist = - "CFBundleExecutableMissing"; - await mkdir(join(bundle, "Contents"), { recursive: true }); - await writeFile(join(bundle, "Contents", "Info.plist"), plist); - let childResolved = false; + const root = await createTestTempDirectory("rea-app-programs-"); + const bundle = join(root, "Fixture.app"); + const programs = join(bundle, "Contents", "MacOS"); + const executable = join(programs, "Missing"); + const canonicalBundle = join(root, "Canonical.app"); + const outsidePrograms = join(root, "outside"); + const plist = + "CFBundleExecutableMissing"; + await mkdir(join(bundle, "Contents"), { recursive: true }); + await writeFile(join(bundle, "Contents", "Info.plist"), plist); + let childResolved = false; - const result = await resolveAppleBundleExecutable(bundle, { - fileSystem: { - readFile: async () => Buffer.from(plist), - realpath: async (path) => { - if (path === bundle) return canonicalBundle; - if (path === programs) return outsidePrograms; - if (path === executable) { - childResolved = true; - throw Object.assign(new Error("missing executable"), { - code: "ENOENT", - }); - } - return path; - }, + const result = await resolveAppleBundleExecutable(bundle, { + fileSystem: { + readFile: async () => Buffer.from(plist), + realpath: async (path) => { + if (path === bundle) return canonicalBundle; + if (path === programs) return outsidePrograms; + if (path === executable) { + childResolved = true; + throw Object.assign(new Error("missing executable"), { + code: "ENOENT", + }); + } + return path; }, - }); + }, + }); - expect(result).toMatchObject({ - ok: false, - error: { - reason: "app program directory leaves Contents/MacOS", - }, - }); - expect(childResolved).toBe(false); - } finally { - await rm(root, { recursive: true, force: true }); - } + expect(result).toMatchObject({ + ok: false, + error: { + reason: "app program directory leaves Contents/MacOS", + }, + }); + expect(childResolved).toBe(false); }); }); diff --git a/src/application/AppBundleResourceRoot.test.ts b/src/application/AppBundleResourceRoot.test.ts index 4ab8c134ff..99a2af1854 100644 --- a/src/application/AppBundleResourceRoot.test.ts +++ b/src/application/AppBundleResourceRoot.test.ts @@ -1,16 +1,8 @@ -import { - chmod, - mkdir, - mkdtemp, - realpath, - rm, - symlink, - writeFile, -} from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, mkdir, realpath, symlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { createAnalysisExecution } from "../ports/AnalysisProvider.js"; import { createAnalysisExecutionEvidence } from "../domain/analysisObservation.js"; @@ -32,85 +24,73 @@ const target = { } satisfies BinaryTarget; it("resolves resource roots without requiring or hashing CFBundleExecutable", async () => { - const temp = await mkdtemp(join(tmpdir(), "rea-app-resource-root-")); - try { - const bundle = join(temp, "Fixture.app"); - const contents = join(bundle, "Contents"); - const alias = join(temp, "Selected.app"); - await mkdir(contents, { recursive: true }); - await writeFile(join(contents, "Info.plist"), ""); - await symlink(bundle, alias); + const temp = await createTestTempDirectory("rea-app-resource-root-"); + const bundle = join(temp, "Fixture.app"); + const contents = join(bundle, "Contents"); + const alias = join(temp, "Selected.app"); + await mkdir(contents, { recursive: true }); + await writeFile(join(contents, "Info.plist"), ""); + await symlink(bundle, alias); - const resolved = await resolveAppBundleResourceRoot(alias); + const resolved = await resolveAppBundleResourceRoot(alias); - expect(resolved).toEqual({ - ok: true, - value: { - callerPath: alias, - canonicalPath: bundle, - infoPlistPath: join(bundle, "Contents", "Info.plist"), - layout: "contents", - executableSha256: null, - }, - }); - } finally { - await rm(temp, { recursive: true, force: true }); - } + expect(resolved).toEqual({ + ok: true, + value: { + callerPath: alias, + canonicalPath: bundle, + infoPlistPath: join(bundle, "Contents", "Info.plist"), + layout: "contents", + executableSha256: null, + }, + }); }); it.skipIf(process.platform === "win32")( "preserves valid symlink-parent traversal when selecting resource roots", async () => { - const temp = await mkdtemp(join(tmpdir(), "rea-resource-parent-")); - try { - await mkdir(join(temp, "physical", "child"), { recursive: true }); - await mkdir(join(temp, "physical", "Fixture.app")); - await writeFile( - join(temp, "physical", "Fixture.app", "Info.plist"), - "", - ); - await symlink(join(temp, "physical", "child"), join(temp, "alias")); - const selected = `${temp}/alias/../Fixture.app`; - const resolved = await resolveAppBundleResourceRoot(selected); - if (!resolved.ok) throw resolved.error; - expect(resolved.value.callerPath).toBe(selected); - expect(resolved.value.canonicalPath).toBe( - await realpath(join(temp, "physical", "Fixture.app")), - ); - } finally { - await rm(temp, { recursive: true, force: true }); - } + const temp = await createTestTempDirectory("rea-resource-parent-"); + await mkdir(join(temp, "physical", "child"), { recursive: true }); + await mkdir(join(temp, "physical", "Fixture.app")); + await writeFile( + join(temp, "physical", "Fixture.app", "Info.plist"), + "", + ); + await symlink(join(temp, "physical", "child"), join(temp, "alias")); + const selected = `${temp}/alias/../Fixture.app`; + const resolved = await resolveAppBundleResourceRoot(selected); + if (!resolved.ok) throw resolved.error; + expect(resolved.value.callerPath).toBe(selected); + expect(resolved.value.canonicalPath).toBe( + await realpath(join(temp, "physical", "Fixture.app")), + ); }, ); it("resolves a flat bundle resource root without inferring executable identity", async () => { - const temp = await mkdtemp(join(tmpdir(), "rea-ios-resource-root-")); - try { - const bundle = join(temp, "Fixture.app"); - await mkdir(bundle); - await writeFile(join(bundle, "Info.plist"), ""); + const temp = await createTestTempDirectory("rea-ios-resource-root-"); + const bundle = join(temp, "Fixture.app"); + await mkdir(bundle); + await writeFile(join(bundle, "Info.plist"), ""); - const resolved = await resolveAppBundleResourceRoot(bundle); + const resolved = await resolveAppBundleResourceRoot(bundle); - expect(resolved).toMatchObject({ - ok: true, - value: { - callerPath: bundle, - canonicalPath: bundle, - infoPlistPath: join(bundle, "Info.plist"), - layout: "root", - executableSha256: null, - }, - }); - } finally { - await rm(temp, { recursive: true, force: true }); - } + expect(resolved).toMatchObject({ + ok: true, + value: { + callerPath: bundle, + canonicalPath: bundle, + infoPlistPath: join(bundle, "Info.plist"), + layout: "root", + executableSha256: null, + }, + }); }); it.skipIf(process.platform === "win32" || process.getuid?.() === 0)( "preserves the actual denied plist classification through resource-only root discovery", async () => { - const temp = await mkdtemp(join(tmpdir(), "rea-resource-read-denied-")); + const temp = await createTestTempDirectory("rea-resource-read-denied-"); const bundle = join(temp, "Fixture.app"); const contents = join(bundle, "Contents"); await mkdir(contents, { recursive: true }); @@ -139,7 +119,6 @@ it.skipIf(process.platform === "win32" || process.getuid?.() === 0)( }); } finally { await chmod(contents, 0o700); - await rm(temp, { recursive: true, force: true }); } }, ); diff --git a/src/application/Update.test.ts b/src/application/Update.test.ts index 5ffa14ac77..6e2a1756b4 100644 --- a/src/application/Update.test.ts +++ b/src/application/Update.test.ts @@ -1,16 +1,8 @@ import { join, resolve } from "node:path"; -import { - mkdtemp, - mkdir, - realpath, - rm, - stat, - symlink, - writeFile, -} from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, realpath, stat, symlink, writeFile } from "node:fs/promises"; import { describe, expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { err, ok, type Result } from "../domain/result.js"; import { @@ -458,53 +450,49 @@ describe("Bun installation ownership", () => { it.skipIf(process.platform === "win32")( "preserves native symlink traversal through detection and pins the canonical global project", async () => { - const directory = await mkdtemp(join(tmpdir(), "rea-bun-global-")); - try { - await mkdir(join(directory, "outer", "inner"), { recursive: true }); - await symlink( - join(directory, "outer", "inner"), - join(directory, "alias"), - ); - const selected = `${directory}/alias/../global`; - expect( - bunGlobalDirectory({ BUN_INSTALL: selected }, process.platform), - ).toBe(resolve(selected, "install", "global")); - expect( - bunGlobalDirectory({ XDG_CACHE_HOME: selected }, process.platform), - ).toBe(resolve(selected, ".bun", "install", "global")); - const selectedPackage = join( - directory, - "outer", - "global", - "node_modules", - "rea-agents", - ); - await mkdir(selectedPackage, { recursive: true }); - await writeFile(`${selected}/package.json`, "{}"); - // The lexical alternative is also a valid project; it must not win. - await mkdir(join(directory, "global", "node_modules", "rea-agents"), { - recursive: true, - }); - await writeFile(join(directory, "global", "package.json"), "{}"); - const installation = await detectBunInstallation( - selectedPackage, - bunGlobalDirectory( - { BUN_INSTALL_GLOBAL_DIR: selected }, - process.platform, - ), - { - canonicalPath: realpath, - isFile: async (path) => (await stat(path)).isFile(), - }, - ); - expect(installation).toEqual({ - manager: "bun", - globalDirectory: await realpath(selected), - packageRoot: await realpath(selectedPackage), - }); - } finally { - await rm(directory, { recursive: true, force: true }); - } + const directory = await createTestTempDirectory("rea-bun-global-"); + await mkdir(join(directory, "outer", "inner"), { recursive: true }); + await symlink( + join(directory, "outer", "inner"), + join(directory, "alias"), + ); + const selected = `${directory}/alias/../global`; + expect( + bunGlobalDirectory({ BUN_INSTALL: selected }, process.platform), + ).toBe(resolve(selected, "install", "global")); + expect( + bunGlobalDirectory({ XDG_CACHE_HOME: selected }, process.platform), + ).toBe(resolve(selected, ".bun", "install", "global")); + const selectedPackage = join( + directory, + "outer", + "global", + "node_modules", + "rea-agents", + ); + await mkdir(selectedPackage, { recursive: true }); + await writeFile(`${selected}/package.json`, "{}"); + // The lexical alternative is also a valid project; it must not win. + await mkdir(join(directory, "global", "node_modules", "rea-agents"), { + recursive: true, + }); + await writeFile(join(directory, "global", "package.json"), "{}"); + const installation = await detectBunInstallation( + selectedPackage, + bunGlobalDirectory( + { BUN_INSTALL_GLOBAL_DIR: selected }, + process.platform, + ), + { + canonicalPath: realpath, + isFile: async (path) => (await stat(path)).isFile(), + }, + ); + expect(installation).toEqual({ + manager: "bun", + globalDirectory: await realpath(selected), + packageRoot: await realpath(selectedPackage), + }); }, ); diff --git a/src/application/apkSignature/ApkSignatureService.test.ts b/src/application/apkSignature/ApkSignatureService.test.ts index cab6f85152..5ae66b8f27 100644 --- a/src/application/apkSignature/ApkSignatureService.test.ts +++ b/src/application/apkSignature/ApkSignatureService.test.ts @@ -1,8 +1,9 @@ -import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js"; import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; import { ApkSignatureProvider } from "../../apkSignature/ApkSignatureProvider.js"; import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js"; @@ -31,7 +32,7 @@ it("preserves pre-aborted cancellation reasons without starting the provider", a it.each([false, true])( "retains completed APK provenance with late cancellation=%s", async (cancelled) => { - const root = await mkdtemp(join(tmpdir(), "rea-apk-service-")); + const root = await createTestTempDirectory("rea-apk-service-"); const provider = new ApkSignatureProvider(); try { const path = join(root, "unsigned.apk"); @@ -86,7 +87,6 @@ it.each([false, true])( }); } finally { await provider.close(); - await rm(root, { recursive: true, force: true }); } }, ); @@ -108,7 +108,7 @@ it("refuses summary acquisition before reading when complete Evidence cannot be }); it("rejects a live provider subject path that differs from the selected APK", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-apk-subject-")); + const root = await createTestTempDirectory("rea-apk-subject-"); const provider = new ApkSignatureProvider(); try { const path = join(root, "selected.apk"); @@ -132,6 +132,5 @@ it("rejects a live provider subject path that differs from the selected APK", as }); } finally { await provider.close(); - await rm(root, { recursive: true, force: true }); } }); diff --git a/src/application/binary/BinarySessionBundleResources.test.ts b/src/application/binary/BinarySessionBundleResources.test.ts index 3bdd55b3c8..4f5807b2de 100644 --- a/src/application/binary/BinarySessionBundleResources.test.ts +++ b/src/application/binary/BinarySessionBundleResources.test.ts @@ -1,8 +1,8 @@ import { unknownTarget } from "../../domain/targetIdentity.js"; -import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, stat, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { afterEach, expect, it } from "vitest"; +import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; import { createAnalysisExecution, @@ -39,7 +39,6 @@ const binaryIdentity: ProviderIdentity = { name: "Fixture analysis provider", version: "1", }; -const temporaryDirectories: string[] = []; const expectResourceSnapshotRefusal = ( error: AnalysisError, @@ -59,19 +58,10 @@ const expectResourceSnapshotRefusal = ( }); }; -afterEach(async () => { - await Promise.all( - temporaryDirectories - .splice(0) - .map((path) => rm(path, { recursive: true, force: true })), - ); -}); - it.skipIf(process.platform === "win32")( "refuses invalid selected traversal before creating a bundle resource client", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-resource-selected-")); - temporaryDirectories.push(root); + const root = await createTestTempDirectory("rea-resource-selected-"); await mkdir(join(root, "Fixture.app")); await writeFile( join(root, "Fixture.app", "Info.plist"), @@ -97,8 +87,7 @@ it.skipIf(process.platform === "win32")( ); it("opens a resource-only bundle without executable identity and keeps snapshot operations inapplicable", async () => { - const rootPath = await mkdtemp(join(tmpdir(), "rea-resource-session-")); - temporaryDirectories.push(rootPath); + const rootPath = await createTestTempDirectory("rea-resource-session-"); await writeFile( join(rootPath, "Info.plist"), '', @@ -191,8 +180,7 @@ it("opens a resource-only bundle without executable identity and keeps snapshot }); it("keeps the exact caller reason for cancellation before resource-root resolution", async () => { - const rootPath = await mkdtemp(join(tmpdir(), "rea-resource-pre-cancel-")); - temporaryDirectories.push(rootPath); + const rootPath = await createTestTempDirectory("rea-resource-pre-cancel-"); const reason = { origin: "caller-pre-aborted" }; const controller = new AbortController(); controller.abort(reason); @@ -218,8 +206,7 @@ it("keeps the exact caller reason for cancellation before resource-root resoluti }); it("retains ownership when an unhealthy resource client cannot be closed", async () => { - const rootPath = await mkdtemp(join(tmpdir(), "rea-resource-cleanup-")); - temporaryDirectories.push(rootPath); + const rootPath = await createTestTempDirectory("rea-resource-cleanup-"); await writeFile(join(rootPath, "Info.plist"), ""); let closeAttempts = 0; const client: AnalysisClient = { @@ -250,8 +237,7 @@ it("retains ownership when an unhealthy resource client cannot be closed", async }); it("cancels a resource switch during prior-client retirement and closes its candidate", async () => { - const rootPath = await mkdtemp(join(tmpdir(), "rea-resource-cancel-switch-")); - temporaryDirectories.push(rootPath); + const rootPath = await createTestTempDirectory("rea-resource-cancel-switch-"); await writeFile(join(rootPath, "Info.plist"), ""); let closeStarted!: () => void; @@ -325,10 +311,9 @@ it("cancels a resource switch during prior-client retirement and closes its cand it.each([false, true])( "keeps cancellation primary through resource retirement retry (live cleanup: %s)", async (liveCleanup) => { - const rootPath = await mkdtemp( - join(tmpdir(), "rea-resource-cancel-close-failure-"), + const rootPath = await createTestTempDirectory( + "rea-resource-cancel-close-failure-", ); - temporaryDirectories.push(rootPath); await writeFile(join(rootPath, "Info.plist"), ""); let closeStarted!: () => void; const closing = new Promise((resolve) => { @@ -418,10 +403,9 @@ it.each([false, true])( ); it("keeps an earlier resource close failure primary when a later cleanup is cancelled", async () => { - const rootPath = await mkdtemp( - join(tmpdir(), "rea-resource-close-before-cancel-"), + const rootPath = await createTestTempDirectory( + "rea-resource-close-before-cancel-", ); - temporaryDirectories.push(rootPath); await writeFile(join(rootPath, "Info.plist"), ""); let candidateCloseStarted!: () => void; const candidateClosing = new Promise((resolve) => { @@ -492,10 +476,9 @@ it("keeps an earlier resource close failure primary when a later cleanup is canc }); it("keeps cancellation primary when binary retirement fails before opening resources", async () => { - const rootPath = await mkdtemp( - join(tmpdir(), "rea-binary-close-cancel-resource-"), + const rootPath = await createTestTempDirectory( + "rea-binary-close-cancel-resource-", ); - temporaryDirectories.push(rootPath); await writeFile(join(rootPath, "Info.plist"), ""); let closeStarted!: () => void; const closing = new Promise((resolve) => { @@ -586,10 +569,9 @@ it("keeps cancellation primary when binary retirement fails before opening resou }); it("keeps an earlier resource close failure primary when binary candidate cleanup is cancelled", async () => { - const rootPath = await mkdtemp( - join(tmpdir(), "rea-resource-close-before-binary-cancel-"), + const rootPath = await createTestTempDirectory( + "rea-resource-close-before-binary-cancel-", ); - temporaryDirectories.push(rootPath); await writeFile(join(rootPath, "Info.plist"), ""); let candidateCloseStarted!: () => void; const candidateClosing = new Promise((resolve) => { @@ -678,10 +660,9 @@ it("keeps an earlier resource close failure primary when binary candidate cleanu }); it("keeps an earlier binary close failure primary when candidate cleanup is cancelled", async () => { - const rootPath = await mkdtemp( - join(tmpdir(), "rea-binary-close-before-cancel-"), + const rootPath = await createTestTempDirectory( + "rea-binary-close-before-cancel-", ); - temporaryDirectories.push(rootPath); await writeFile(join(rootPath, "Info.plist"), ""); let candidateCloseStarted!: () => void; const candidateClosing = new Promise((resolve) => { @@ -776,8 +757,7 @@ it("keeps an earlier binary close failure primary when candidate cleanup is canc }); it("cancels a binary switch during resource retirement and retains null-subject Evidence", async () => { - const rootPath = await mkdtemp(join(tmpdir(), "rea-resource-cancel-binary-")); - temporaryDirectories.push(rootPath); + const rootPath = await createTestTempDirectory("rea-resource-cancel-binary-"); await writeFile(join(rootPath, "Info.plist"), ""); let resourceCloseStarted!: () => void; const closing = new Promise((resolve) => { @@ -881,10 +861,9 @@ it("cancels a binary switch during resource retirement and retains null-subject }); it("tracks independent pending resource owners after a failed session replacement", async () => { - const rootPath = await mkdtemp( - join(tmpdir(), "rea-resource-pending-owners-"), + const rootPath = await createTestTempDirectory( + "rea-resource-pending-owners-", ); - temporaryDirectories.push(rootPath); await writeFile(join(rootPath, "Info.plist"), ""); const failures = [ new ProviderCleanupError(identity.id, ["previous-reader"], {}), @@ -997,10 +976,9 @@ it.each([false, true])( it.each([0, 1])( "retains unknown cleanup completion alongside a retryable owner (unknown owner: %s)", async (unknownOwner) => { - const rootPath = await mkdtemp( - join(tmpdir(), "rea-resource-mixed-cleanup-"), + const rootPath = await createTestTempDirectory( + "rea-resource-mixed-cleanup-", ); - temporaryDirectories.push(rootPath); await writeFile(join(rootPath, "Info.plist"), ""); const ownedFailure = new ProviderCleanupError( identity.id, @@ -1092,8 +1070,7 @@ it.each([ if (targetKind === "binary") { expect(await session.open(process.execPath)).toMatchObject({ ok: true }); } else { - const rootPath = await mkdtemp(join(tmpdir(), "rea-resource-close-")); - temporaryDirectories.push(rootPath); + const rootPath = await createTestTempDirectory("rea-resource-close-"); await writeFile(join(rootPath, "Info.plist"), ""); expect(await session.openBundleResources(rootPath)).toMatchObject({ ok: true, @@ -1114,10 +1091,9 @@ it.each([ it.each(["health", "cancellation"] as const)( "updates early resource-open %s cleanup after its candidate retries", async (failureStage) => { - const rootPath = await mkdtemp( - join(tmpdir(), "rea-resource-early-cleanup-"), + const rootPath = await createTestTempDirectory( + "rea-resource-early-cleanup-", ); - temporaryDirectories.push(rootPath); await writeFile(join(rootPath, "Info.plist"), ""); const primary = new ProviderAdapterError(identity.id, "health"); const cleanup = new ProviderCleanupError( diff --git a/src/application/frida/FridaInstrumentationService.test.ts b/src/application/frida/FridaInstrumentationService.test.ts index b75583c015..a3996e63b5 100644 --- a/src/application/frida/FridaInstrumentationService.test.ts +++ b/src/application/frida/FridaInstrumentationService.test.ts @@ -1,8 +1,9 @@ -import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; import { FridaScriptLoadCancelledError } from "../../ports/frida/FridaInstrumentationPort.js"; import type { FridaInstrumentationPort } from "../../ports/frida/FridaInstrumentationPort.js"; @@ -1199,87 +1200,83 @@ it.each([ ); it("preserves typed load cancellation cause, safe diagnostics, and decoded source representation in partial Evidence", async () => { - const directory = await mkdtemp( - join(tmpdir(), "rea-frida-cancelled-source-"), + const directory = await createTestTempDirectory( + "rea-frida-cancelled-source-", ); const path = join(directory, "invalid-utf8.js"); await writeFile(path, Buffer.from([0x2f, 0x2f, 0x20, 0xff, 0x0a])); - try { - const controller = new AbortController(); - const abortReason = new Error("native load cancelled after decoding"); - const diagnostics = { - native_failure: "script load cancelled; transport_token=", - read_attempt: 1, - }; - const script = { - ...createScriptObservation(), - sourceKind: "file" as const, - sourcePath: path, - sourceRepresentation: { - encoding: "utf8" as const, - decoding: "replacement" as const, - loadedSourceSha256: "b".repeat(64), + const controller = new AbortController(); + const abortReason = new Error("native load cancelled after decoding"); + const diagnostics = { + native_failure: "script load cancelled; transport_token=", + read_attempt: 1, + }; + const script = { + ...createScriptObservation(), + sourceKind: "file" as const, + sourcePath: path, + sourceRepresentation: { + encoding: "utf8" as const, + decoding: "replacement" as const, + loadedSourceSha256: "b".repeat(64), + }, + messages: [{ type: "send", payload: "retained-before-cancel" }], + }; + let closes = 0; + const service = new FridaInstrumentationService( + createProvider({ + async loadScript() { + controller.abort(abortReason); + return { + ok: false, + error: new FridaScriptLoadCancelledError(script, { + cause: abortReason, + diagnostics, + }), + }; }, - messages: [{ type: "send", payload: "retained-before-cancel" }], - }; - let closes = 0; - const service = new FridaInstrumentationService( - createProvider({ - async loadScript() { - controller.abort(abortReason); - return { - ok: false, - error: new FridaScriptLoadCancelledError(script, { - cause: abortReason, - diagnostics, - }), - }; - }, - async closeSession() { - closes += 1; - return { ok: true, value: { targetResumeObserved: false } }; - }, - }), - ); + async closeSession() { + closes += 1; + return { ok: true, value: { targetResumeObserved: false } }; + }, + }), + ); - const result = await service.instrument( - { - mode: "spawn", - program: "/fixture", - source: { sourceKind: "file", path }, - durationMs: 0, - }, - controller.signal, - ); + const result = await service.instrument( + { + mode: "spawn", + program: "/fixture", + source: { sourceKind: "file", path }, + durationMs: 0, + }, + controller.signal, + ); - expect(result.ok).toBe(false); - if (result.ok) return; - expect(result.error).toBeInstanceOf(AnalysisCancelledError); - expect(result.error.cause).toBe(abortReason); - expect(result.error.diagnostics).toEqual(diagnostics); - expect(result.error.partialObservation).toMatchObject({ - normalized_result: { - source_kind: "file", - source_path: path, - source_sha256: script.sourceSha256, - messages: script.messages, - instrumentation_cleanup: "released", + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error).toBeInstanceOf(AnalysisCancelledError); + expect(result.error.cause).toBe(abortReason); + expect(result.error.diagnostics).toEqual(diagnostics); + expect(result.error.partialObservation).toMatchObject({ + normalized_result: { + source_kind: "file", + source_path: path, + source_sha256: script.sourceSha256, + messages: script.messages, + instrumentation_cleanup: "released", + }, + raw_result: { + source_representation: { + encoding: "utf8", + decoding: "replacement", + loaded_source_sha256: "b".repeat(64), }, - raw_result: { - source_representation: { - encoding: "utf8", - decoding: "replacement", - loaded_source_sha256: "b".repeat(64), - }, - }, - limitations: expect.arrayContaining([ - expect.stringContaining("Invalid UTF-8"), - ]), - }); - expect(closes).toBe(1); - } finally { - await rm(directory, { recursive: true, force: true }); - } + }, + limitations: expect.arrayContaining([ + expect.stringContaining("Invalid UTF-8"), + ]), + }); + expect(closes).toBe(1); }); it("preserves a provider-committed load when cancellation arrives during result delivery", async () => { diff --git a/src/artifacts/AsarHeaderIdentity.test.ts b/src/artifacts/AsarHeaderIdentity.test.ts index 9f28ea159f..f871712d0f 100644 --- a/src/artifacts/AsarHeaderIdentity.test.ts +++ b/src/artifacts/AsarHeaderIdentity.test.ts @@ -1,8 +1,8 @@ -import { mkdtemp, writeFile, rm } from "node:fs/promises"; +import { writeFile } from "node:fs/promises"; import { buffer } from "node:stream/consumers"; -import { tmpdir } from "node:os"; import { join } from "node:path"; import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { AsarArtifactReader } from "./AsarArtifactReader.js"; import { asarHeaderBytes } from "../../tests/fixtures/asarHeader.js"; @@ -10,7 +10,7 @@ import { asarHeaderBytes } from "../../tests/fixtures/asarHeader.js"; it.each(["close", "cancel"] as const)( "does not complete an ASAR inventory after %s while paused", async (interruption) => { - const root = await mkdtemp(join(tmpdir(), "rea-asar-paused-")); + const root = await createTestTempDirectory("rea-asar-paused-"); const path = join(root, "app.asar"); await writeFile( path, @@ -28,13 +28,12 @@ it.each(["close", "cancel"] as const)( }); } finally { await reader.close(); - await rm(root, { recursive: true, force: true }); } }, ); it("rejects malformed UTF-8 instead of inventing a replacement-character member identity", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-asar-identity-")); + const root = await createTestTempDirectory("rea-asar-identity-"); const path = join(root, "app.asar"); const reader = new AsarArtifactReader(path); const bytes = asarHeaderBytes('{"files":{"x":{"size":0,"offset":"0"}}}'); @@ -47,14 +46,13 @@ it("rejects malformed UTF-8 instead of inventing a replacement-character member }); } finally { await reader.close(); - await rm(root, { recursive: true, force: true }); } }); it.each(["�", "é", "日本語", "\uFEFFname"])( "preserves valid UTF-8 member identity %j and reads its bytes through padded framing", async (name) => { - const root = await mkdtemp(join(tmpdir(), "rea-asar-identity-")); + const root = await createTestTempDirectory("rea-asar-identity-"); const path = join(root, "app.asar"); const reader = new AsarArtifactReader(path); const content = Buffer.from("member bytes"); @@ -76,7 +74,6 @@ it.each(["�", "é", "日本語", "\uFEFFname"])( expect((await buffer(output)).equals(content)).toBe(true); } finally { await reader.close(); - await rm(root, { recursive: true, force: true }); } }, ); @@ -84,7 +81,7 @@ it.each(["�", "é", "日本語", "\uFEFFname"])( it.each(['{"files":', '\uFEFF{"files":{}}'])( "rejects invalid JSON framing %j as format failure", async (json) => { - const root = await mkdtemp(join(tmpdir(), "rea-asar-identity-")); + const root = await createTestTempDirectory("rea-asar-identity-"); const path = join(root, "app.asar"); const reader = new AsarArtifactReader(path); await writeFile(path, asarHeaderBytes(json)); @@ -94,7 +91,6 @@ it.each(['{"files":', '\uFEFF{"files":{}}'])( }); } finally { await reader.close(); - await rm(root, { recursive: true, force: true }); } }, ); diff --git a/src/browser/CdpElectronInspection.test.ts b/src/browser/CdpElectronInspection.test.ts index fb3929d696..3f2c1574ab 100644 --- a/src/browser/CdpElectronInspection.test.ts +++ b/src/browser/CdpElectronInspection.test.ts @@ -1,10 +1,10 @@ import { DEFAULT_ASAR_HEADER_ADMISSION } from "../config/asarHeaderAdmission.js"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { writeFile } from "node:fs/promises"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; -import { afterEach, describe, expect, it } from "vitest"; +import { describe, expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { fakeCdpEvents } from "../../tests/fixtures/fakeCdpEvents.js"; @@ -32,8 +32,6 @@ import { captureElectronScripts } from "./CdpElectronScripts.js"; import { inspectElectronPageInputSchema } from "../domain/javascript/electronObservation.js"; import type { ProgressReporter } from "../ports/ProgressReporter.js"; -const temporary: string[] = []; - const inspectRaceConnection = ( connection: CdpConnection, mainUrl: string, @@ -80,8 +78,7 @@ it.each([ "binds frame authorization to the tree read across file checks: %s", async (stage) => { const isAncestor = stage.endsWith("ancestor"); - const root = await mkdtemp(join(tmpdir(), "rea-frame-generation-race-")); - temporary.push(root); + const root = await createTestTempDirectory("rea-frame-generation-race-"); const main = join(root, "main.html"), child = join(root, "child.html"), script = join(root, "app.js"); @@ -228,14 +225,6 @@ it.each([ }, ); -afterEach(async () => { - await Promise.all( - temporary - .splice(0) - .map((path) => rm(path, { recursive: true, force: true })), - ); -}); - /** Raw lifecycle messages exercised by the final file-validation race. */ const documentIdentityEvent = ( kind: string, @@ -295,10 +284,9 @@ it.each([ ])( "preserves document identity through final file validation: %s", async (kind) => { - const root = await mkdtemp( - join(tmpdir(), "rea-electron-document-identity-"), + const root = await createTestTempDirectory( + "rea-electron-document-identity-", ); - temporary.push(root); const main = join(root, "main.html"), child = join(root, "child.html"), script = join(root, "app.js"); @@ -412,8 +400,7 @@ it.each([ it.each([7, null, "", "claimed-parent"])( "does not promote children when the enclosing root has a parent: %s", async (parentId) => { - const root = await mkdtemp(join(tmpdir(), "rea-electron-root-role-")); - temporary.push(root); + const root = await createTestTempDirectory("rea-electron-root-role-"); const main = join(root, "index.html"); await writeFile(main, "main"); const completeness = new CdpCaptureCompleteness(); @@ -449,8 +436,7 @@ describe("Electron frame capture", () => { it.each([7, undefined])( "classifies a malformed child frame ID as unavailable: %s", async (childId) => { - const root = await mkdtemp(join(tmpdir(), "rea-electron-frame-")); - temporary.push(root); + const root = await createTestTempDirectory("rea-electron-frame-"); const main = join(root, "index.html"); const child = join(root, "child.html"); await Promise.all([writeFile(main, "main"), writeFile(child, "child")]); @@ -491,8 +477,7 @@ describe("Electron frame capture", () => { ); it("preserves script records across context teardown and ID reuse", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-electron-script-frame-")); - temporary.push(root); + const root = await createTestTempDirectory("rea-electron-script-frame-"); const scriptPath = join(root, "app.js"); await writeFile(scriptPath, "export const app = true;"); const scripts: ElectronScriptDraft[] = []; @@ -589,8 +574,7 @@ describe("Electron frame capture", () => { }); it("admits a prefix and fitting suffix around an oversized Electron source", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-electron-source-budget-")); - temporary.push(root); + const root = await createTestTempDirectory("rea-electron-source-budget-"); const paths = await Promise.all( ["prefix.js", "oversized.js", "suffix.js"].map(async (name) => { const path = join(root, name); @@ -714,8 +698,7 @@ it.each([ ])( "detects tree-first document replacement $scope/read$stage/late=$lateEvent/changed=$changed/url=$urlChange/full=$fullReplay", async ({ scope, stage, lateEvent, changed, urlChange, fullReplay }) => { - const root = await mkdtemp(join(tmpdir(), "rea-tree-first-document-")); - temporary.push(root); + const root = await createTestTempDirectory("rea-tree-first-document-"); const main = join(root, "main.html"), child = join(root, "child.html"), script = join(root, "app.js"); @@ -838,8 +821,7 @@ it.each([ it.each([2, 3])( "refuses a tree-first main frame identity replacement at read %s", async (stage) => { - const root = await mkdtemp(join(tmpdir(), "rea-electron-root-identity-")); - temporary.push(root); + const root = await createTestTempDirectory("rea-electron-root-identity-"); const main = join(root, "main.html"); await writeFile(main, "main"); const mainUrl = pathToFileURL(main).href; @@ -886,8 +868,7 @@ it.each([ ])( "retains uncertainty when the main loader is missing at read $stage", async ({ stage, loader }) => { - const root = await mkdtemp(join(tmpdir(), "rea-electron-missing-loader-")); - temporary.push(root); + const root = await createTestTempDirectory("rea-electron-missing-loader-"); const main = join(root, "main.html"); const child = join(root, "child.html"); await Promise.all([writeFile(main, "main"), writeFile(child, "child")]); @@ -989,8 +970,7 @@ it.each([ ])( "compares later root identity with the last proven loader: $loaders", async ({ loaders, changed }) => { - const root = await mkdtemp(join(tmpdir(), "rea-electron-loader-history-")); - temporary.push(root); + const root = await createTestTempDirectory("rea-electron-loader-history-"); const main = join(root, "main.html"); await writeFile(main, "main"); const mainUrl = pathToFileURL(main).href; diff --git a/src/browser/ElectronFileScope.cleanup.test.ts b/src/browser/ElectronFileScope.cleanup.test.ts index 645cd0213b..ba506c70f9 100644 --- a/src/browser/ElectronFileScope.cleanup.test.ts +++ b/src/browser/ElectronFileScope.cleanup.test.ts @@ -1,11 +1,11 @@ import { createServer } from "node:http"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; -import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { afterEach, expect, it, vi } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; const handleState = vi.hoisted(() => ({ archive: undefined as string | undefined, @@ -82,13 +82,10 @@ import { retryElectronFileCleanup, } from "./ElectronFileScope.js"; -const roots: string[] = []; +let scopeRoot: string; afterEach(async () => { await retryElectronFileCleanup(); - await Promise.all( - roots.splice(0).map((root) => rm(root, { recursive: true, force: true })), - ); handleState.archive = undefined; handleState.failCloseCount = 0; handleState.closeController = undefined; @@ -102,10 +99,8 @@ afterEach(async () => { }); const asarPage = async (): Promise => { - const root = await realpath( - await mkdtemp(join(tmpdir(), "rea-electron-file-scope-")), - ); - roots.push(root); + const root = await createTestTempDirectory("rea-electron-file-scope-"); + scopeRoot = root; const archive = join(root, "app.asar"); const json = Buffer.from( JSON.stringify({ files: { "index.html": { size: 1, offset: "0" } } }), @@ -360,7 +355,7 @@ it.each(["completed", "read-failed", "cancelled"] as const)( "retains the completed listing prefix after ASAR finalization: %s", async (mode) => { const archiveUrl = await asarPage(); - const page = join(roots.at(-1)!, "first.html"); + const page = join(scopeRoot, "first.html"); await writeFile(page, "first"); const controller = new AbortController(); handleState.failCloseCount = 1; diff --git a/src/browser/ElectronFileScope.nodes.test.ts b/src/browser/ElectronFileScope.nodes.test.ts index cf4b094b93..db65ed4719 100644 --- a/src/browser/ElectronFileScope.nodes.test.ts +++ b/src/browser/ElectronFileScope.nodes.test.ts @@ -1,15 +1,15 @@ import { createServer } from "node:http"; -import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { writeFile } from "node:fs/promises"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { asarHeaderBytes } from "../../tests/fixtures/asarHeader.js"; import { CdpElectronProvider } from "./CdpElectronProvider.js"; it("lists only ASAR members with regular-file declarations while preserving unrelated metadata", async () => { - const root = await realpath(await mkdtemp(join(tmpdir(), "rea-asar-node-"))); + const root = await createTestTempDirectory("rea-asar-node-"); const archive = join(root, "app.asar"); const files = { "empty.html": { size: 0, offset: "0" }, @@ -98,6 +98,5 @@ it("lists only ASAR members with regular-file declarations while preserving unre error === undefined ? resolve() : reject(error), ), ); - await rm(root, { recursive: true, force: true }); } }); diff --git a/src/browser/WebBundleAnalysisWorkerServer.test.ts b/src/browser/WebBundleAnalysisWorkerServer.test.ts index 0f633d1ca0..fca779f977 100644 --- a/src/browser/WebBundleAnalysisWorkerServer.test.ts +++ b/src/browser/WebBundleAnalysisWorkerServer.test.ts @@ -2,11 +2,11 @@ import { analyzeCapturedWebScript } from "../domain/webBundleAnalyzer.js"; import { createHash, randomUUID } from "node:crypto"; import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"; import { once } from "node:events"; -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { createInterface } from "node:readline"; import { expect, it, onTestFinished } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { createWebTextArtifact } from "../domain/webContentArtifact.js"; import type { IncludedScript } from "../domain/webBundleAnalyzerState.js"; @@ -150,7 +150,7 @@ const closeServer = async ( }; it("transfers reached semantic budgets and does not retain them for the next job", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-web-worker-precision-")); + const root = await createTestTempDirectory("rea-web-worker-precision-"); let worker: ChildProcessWithoutNullStreams | undefined; try { const server = await startServer(root); @@ -198,16 +198,14 @@ it("transfers reached semantic budgets and does not retain them for the next job } } finally { if (worker !== undefined) await closeServer(worker); - await rm(root, { recursive: true, force: true }); } }); it("refuses with the allowance the parent sent and reports its limit", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-web-worker-work-")); + const root = await createTestTempDirectory("rea-web-worker-work-"); let worker: ChildProcessWithoutNullStreams | undefined; onTestFinished(async () => { if (worker !== undefined) await closeServer(worker); - await rm(root, { recursive: true, force: true }); }); const server = await startServer( root, @@ -236,11 +234,10 @@ it("refuses with the allowance the parent sent and reports its limit", async () }); const framingServer = async () => { - const root = await mkdtemp(join(tmpdir(), "rea-web-worker-framing-")); + const root = await createTestTempDirectory("rea-web-worker-framing-"); let worker: ChildProcessWithoutNullStreams | undefined; onTestFinished(async () => { if (worker !== undefined) await closeServer(worker); - await rm(root, { recursive: true, force: true }); }); const server = await startServer(root); worker = server.process; @@ -360,7 +357,7 @@ it.each([ }); it("bounds and binds per-script worker jobs, then reuses one worker for the next script", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-web-worker-server-test-")); + const root = await createTestTempDirectory("rea-web-worker-server-test-"); let worker: ChildProcessWithoutNullStreams | undefined; try { const server = await startServer(root); @@ -500,6 +497,5 @@ it("bounds and binds per-script worker jobs, then reuses one worker for the next if (worker !== undefined) { await closeServer(worker); } - await rm(root, { recursive: true, force: true }); } }); diff --git a/src/cliBundleResource.test.ts b/src/cliBundleResource.test.ts index abd3d1e509..20886c4eef 100644 --- a/src/cliBundleResource.test.ts +++ b/src/cliBundleResource.test.ts @@ -1,27 +1,16 @@ import { unknownTarget } from "./domain/targetIdentity.js"; -import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { build } from "plist"; -import { afterEach, expect, it } from "vitest"; +import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../tests/fixtures/temporaryDirectory.js"; import { createCli } from "./cli.js"; import { parseEvidence } from "./domain/evidence.js"; -const temporaryDirectories: string[] = []; - -afterEach(async () => { - await Promise.all( - temporaryDirectories - .splice(0) - .map((path) => rm(path, { recursive: true, force: true })), - ); -}); - it("inspects a keyless app bundle through the public CLI and preserves resource provenance", async () => { - const parent = await mkdtemp(join(tmpdir(), "rea-bundle-resource-cli-")); - temporaryDirectories.push(parent); + const parent = await createTestTempDirectory("rea-bundle-resource-cli-"); const bundle = join(parent, "Fixture.app"); const resources = join(bundle, "Resources"); await mkdir(resources, { recursive: true }); diff --git a/src/cliJsonPaths.test.ts b/src/cliJsonPaths.test.ts index 65e0e31b90..550dae3809 100644 --- a/src/cliJsonPaths.test.ts +++ b/src/cliJsonPaths.test.ts @@ -1,8 +1,8 @@ -import { mkdir, mkdtemp, rm, symlink } from "node:fs/promises"; +import { mkdir, symlink } from "node:fs/promises"; import { join, resolve } from "node:path"; -import { tmpdir } from "node:os"; import { describe, expect, it } from "vitest"; +import { createTestTempDirectory } from "../tests/fixtures/temporaryDirectory.js"; import { cliJsonCallerPathSchema, @@ -74,7 +74,7 @@ describe("CLI JSON path normalization", () => { it.skipIf(process.platform === "win32")( "keeps POSIX symlink-parent traversal for each selected JSON path", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-json-caller-path-")); + const root = await createTestTempDirectory("rea-json-caller-path-"); const originalCwd = process.cwd(); try { await mkdir(join(root, "real/inner"), { recursive: true }); @@ -110,7 +110,6 @@ describe("CLI JSON path normalization", () => { expect(browserInput.browser.executable_path).toBe("link/../browser"); } finally { process.chdir(originalCwd); - await rm(root, { recursive: true, force: true }); } }, ); diff --git a/src/desktop/BuildComputerController.test.ts b/src/desktop/BuildComputerController.test.ts index 7b4ec5eb4f..1cf1bde026 100644 --- a/src/desktop/BuildComputerController.test.ts +++ b/src/desktop/BuildComputerController.test.ts @@ -1,12 +1,11 @@ import { execFileSync } from "node:child_process"; import { createHash } from "node:crypto"; -import { mkdtemp, rm } from "node:fs/promises"; -import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { getHeapStatistics } from "node:v8"; import { describe, expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js"; import { guestFileAnswerBytes } from "./AgentEnvComputer.js"; @@ -303,27 +302,21 @@ describe("controller arguments", () => { ); expect(Buffer.from(piece, "utf8").toString("utf8") === piece).toBe(true); } - const root = await mkdtemp(join(tmpdir(), "rea-controller-args-")); - try { - const output = join(root, "listing.json"); - const payload = JSON.stringify({ root, output }); - const mid = Math.floor(payload.length / 2); - const script = fileURLToPath( - new URL("../../bridge/agentenv/capture.py", import.meta.url), - ); - const stdout = execFileSync( - "python3", - ["-I", "-B", script, "list", payload.slice(0, mid), payload.slice(mid)], - { encoding: "utf8" }, - ); - const answer: unknown = JSON.parse( - stdout.trim().split("\n").at(-1) ?? "", - ); - expect(answer).toMatchObject({ - listing_bytes: expect.any(Number), - }); - } finally { - await rm(root, { recursive: true, force: true }); - } + const root = await createTestTempDirectory("rea-controller-args-"); + const output = join(root, "listing.json"); + const payload = JSON.stringify({ root, output }); + const mid = Math.floor(payload.length / 2); + const script = fileURLToPath( + new URL("../../bridge/agentenv/capture.py", import.meta.url), + ); + const stdout = execFileSync( + "python3", + ["-I", "-B", script, "list", payload.slice(0, mid), payload.slice(mid)], + { encoding: "utf8" }, + ); + const answer: unknown = JSON.parse(stdout.trim().split("\n").at(-1) ?? ""); + expect(answer).toMatchObject({ + listing_bytes: expect.any(Number), + }); }); }); diff --git a/src/firmware/FirmwareSourceAdmission.test.ts b/src/firmware/FirmwareSourceAdmission.test.ts index fd17ba11db..cd488080bf 100644 --- a/src/firmware/FirmwareSourceAdmission.test.ts +++ b/src/firmware/FirmwareSourceAdmission.test.ts @@ -1,28 +1,13 @@ import { createHash } from "node:crypto"; -import { - mkdir, - mkdtemp, - readFile, - rm, - symlink, - writeFile, -} from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, readFile, symlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { afterEach, expect, it } from "vitest"; +import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { firmwareRequestSchema } from "../domain/firmware/firmwareAnalysis.js"; import { FirmwareFileAccess } from "./FirmwareFiles.js"; -const roots: string[] = []; -afterEach(async () => { - await Promise.all( - roots.splice(0).map((root) => rm(root, { recursive: true, force: true })), - ); -}); - const workspace = async () => { - const root = await mkdtemp(join(tmpdir(), "rea-firmware-source-")); - roots.push(root); + const root = await createTestTempDirectory("rea-firmware-source-"); const staging = join(root, "stage"); await mkdir(staging); return { root, staging }; diff --git a/src/ghidra/GhidraAnalysisSeeds.test.ts b/src/ghidra/GhidraAnalysisSeeds.test.ts index a5e3f0b97a..b5c558e7cf 100644 --- a/src/ghidra/GhidraAnalysisSeeds.test.ts +++ b/src/ghidra/GhidraAnalysisSeeds.test.ts @@ -1,7 +1,6 @@ import { ArtifactResourceScope } from "../resources/ArtifactResourceScope.js"; import { createHash } from "node:crypto"; import { - mkdtemp, mkdir, open, readFile, @@ -10,9 +9,9 @@ import { symlink, writeFile, } from "node:fs/promises"; -import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { parseConfig } from "../config/parseConfig.js"; import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; @@ -34,17 +33,13 @@ import { ghidraProfileInstallationHost as host } from "./GhidraInstallation.fixt import { GhidraProvider } from "./GhidraProvider.js"; import { parseGhidraSeeds } from "../domain/native/ghidraSeedFile.js"; -const directories: string[] = []; let resources = new ArtifactResourceScope(); afterEach(async () => { await resources.close(); resources = new ArtifactResourceScope(); - for (const directory of directories.splice(0)) - await rm(directory, { recursive: true, force: true }); }); const workspace = async () => { - const directory = await mkdtemp(join(tmpdir(), "rea-ghidra-seeds-")); - directories.push(directory); + const directory = await createTestTempDirectory("rea-ghidra-seeds-"); return directory; }; diff --git a/src/ghidra/GhidraCheckpoint.test.ts b/src/ghidra/GhidraCheckpoint.test.ts index e4ba3c28e9..88f9161f65 100644 --- a/src/ghidra/GhidraCheckpoint.test.ts +++ b/src/ghidra/GhidraCheckpoint.test.ts @@ -1,8 +1,8 @@ import { afterEach, expect, it, vi } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { chmod, access, - mkdtemp, mkdir, readFile, writeFile, @@ -11,7 +11,6 @@ import { symlink, type FileHandle, } from "node:fs/promises"; -import { tmpdir } from "node:os"; import { join } from "node:path"; import { ArtifactResourceScope } from "../resources/ArtifactResourceScope.js"; import { createAnalysisProfile } from "../domain/analysisProfile.js"; @@ -45,7 +44,6 @@ vi.mock("../process/OwnedLease.js", async (importOriginal) => { return { ...actual, acquireOwnedLease: vi.fn(actual.acquireOwnedLease) }; }); -const roots: string[] = []; const owners: GhidraCheckpoint[] = []; afterEach(async () => { controls.file = undefined; @@ -63,8 +61,6 @@ afterEach(async () => { vi.mocked(rm).mockReset().mockImplementation(actual.rm); vi.mocked(rename).mockReset().mockImplementation(actual.rename); for (const owner of owners.splice(0)) await owner.close(); - for (const root of roots.splice(0)) - await rm(root, { recursive: true, force: true }); }); it.skipIf(process.platform === "win32")( @@ -113,8 +109,7 @@ const profile = createAnalysisProfile( ); const target = "1".repeat(64); async function fixture() { - const root = await mkdtemp(join(tmpdir(), "rea-checkpoint-test-")); - roots.push(root); + const root = await createTestTempDirectory("rea-checkpoint-test-"); const resources = new ArtifactResourceScope(); const selection = await resolveGhidraCheckpoint( root, diff --git a/src/ghidra/GhidraLaunchFailure.test.ts b/src/ghidra/GhidraLaunchFailure.test.ts index 83b7d3fd7e..94e3033e34 100644 --- a/src/ghidra/GhidraLaunchFailure.test.ts +++ b/src/ghidra/GhidraLaunchFailure.test.ts @@ -1,8 +1,8 @@ import { createTestArtifactResourceScope } from "../../tests/fixtures/artifactResourceScope.js"; -import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { describe, expect, test } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { GhidraHeadlessLauncher, @@ -32,7 +32,7 @@ const launchSession = (runtimeRoot: string): GhidraLaunchSession => ({ /** Stand-in "java" whose LaunchSupport probe fails the way a broken JVM does. */ const failingJavaHome = async (script: string): Promise => { - const javaHome = await mkdtemp(join(tmpdir(), "rea-fake-java-")); + const javaHome = await createTestTempDirectory("rea-fake-java-"); await mkdir(join(javaHome, "bin"), { recursive: true }); await writeFile(join(javaHome, "bin", "java"), script, { mode: 0o755 }); return javaHome; @@ -68,33 +68,28 @@ describe("Ghidra launch failure diagnostics", () => { const javaHome = await failingJavaHome( "#!/bin/sh\necho 'jvm probe exploded' >&2\nexit 3\n", ); - const runtimeRoot = await mkdtemp(join(tmpdir(), "rea-ghidra-launch-")); - try { - const launched = await probeLauncher(javaHome, runtimeRoot).launch( - launchSession(runtimeRoot), - { resourceScope: createTestArtifactResourceScope() }, - ); - if (launched.ok) throw new Error("expected the launch to fail"); - expect(launched.error).toBeInstanceOf(GhidraLaunchError); - expect(launched.error.message).toBe("Ghidra headless launch failed"); - const captured = - launched.error instanceof GhidraLaunchError - ? launched.error.capturedOutput - : undefined; - expect(captured).toBeUndefined(); - const outcome = launchOutcomeOf(launched.error); - expect(outcome).toMatchObject({ - killed: false, - outputTruncated: false, - stdoutTruncated: false, - stderrTruncated: false, - stdout: "", - }); - expect(outcome?.["stderr"]).toContain("jvm probe exploded"); - } finally { - await rm(javaHome, { recursive: true, force: true }); - await rm(runtimeRoot, { recursive: true, force: true }); - } + const runtimeRoot = await createTestTempDirectory("rea-ghidra-launch-"); + const launched = await probeLauncher(javaHome, runtimeRoot).launch( + launchSession(runtimeRoot), + { resourceScope: createTestArtifactResourceScope() }, + ); + if (launched.ok) throw new Error("expected the launch to fail"); + expect(launched.error).toBeInstanceOf(GhidraLaunchError); + expect(launched.error.message).toBe("Ghidra headless launch failed"); + const captured = + launched.error instanceof GhidraLaunchError + ? launched.error.capturedOutput + : undefined; + expect(captured).toBeUndefined(); + const outcome = launchOutcomeOf(launched.error); + expect(outcome).toMatchObject({ + killed: false, + outputTruncated: false, + stdoutTruncated: false, + stderrTruncated: false, + stdout: "", + }); + expect(outcome?.["stderr"]).toContain("jvm probe exploded"); }); it("bounds projected launcher output and marks truncation explicitly", async () => { @@ -102,52 +97,42 @@ describe("Ghidra launch failure diagnostics", () => { const javaHome = await failingJavaHome( `#!/bin/sh\nprintf '%s' '${oversized}' >&2\nexit 1\n`, ); - const runtimeRoot = await mkdtemp(join(tmpdir(), "rea-ghidra-launch-")); - try { - const launched = await probeLauncher(javaHome, runtimeRoot).launch( - launchSession(runtimeRoot), - { resourceScope: createTestArtifactResourceScope() }, - ); - if (launched.ok) throw new Error("expected the launch to fail"); - const outcome = launchOutcomeOf(launched.error); - expect(outcome?.["stderrTruncated"]).toBe(true); - expect(outcome?.["outputTruncated"]).toBe(false); - expect(outcome?.["stderrBytes"]).toBe(oversized.length); - const stderr = outcome?.["stderr"]; - if (typeof stderr !== "string") - throw new Error("Expected launcher stderr"); - expect(stderr.length).toBeLessThanOrEqual(EXPECTED_OUTPUT_BOUND_BYTES); - expect(stderr).not.toContain("UNRETAINED-TAIL"); - } finally { - await rm(javaHome, { recursive: true, force: true }); - await rm(runtimeRoot, { recursive: true, force: true }); - } + const runtimeRoot = await createTestTempDirectory("rea-ghidra-launch-"); + const launched = await probeLauncher(javaHome, runtimeRoot).launch( + launchSession(runtimeRoot), + { resourceScope: createTestArtifactResourceScope() }, + ); + if (launched.ok) throw new Error("expected the launch to fail"); + const outcome = launchOutcomeOf(launched.error); + expect(outcome?.["stderrTruncated"]).toBe(true); + expect(outcome?.["outputTruncated"]).toBe(false); + expect(outcome?.["stderrBytes"]).toBe(oversized.length); + const stderr = outcome?.["stderr"]; + if (typeof stderr !== "string") throw new Error("Expected launcher stderr"); + expect(stderr.length).toBeLessThanOrEqual(EXPECTED_OUTPUT_BOUND_BYTES); + expect(stderr).not.toContain("UNRETAINED-TAIL"); }); it("leaves non-command launch failures without retained output", async () => { - const runtimeRoot = await mkdtemp(join(tmpdir(), "rea-ghidra-launch-")); - try { - const launcher = new GhidraHeadlessLauncher({ - environment: {}, - platform: "darwin", - analyzeHeadlessPath: join(runtimeRoot, "support", "analyzeHeadless"), - configurationDirectoryName: "ghidra_test_PUBLIC", - bridgeScriptPath: join(runtimeRoot, "bridge", "ReaGhidraBridge.java"), - }); - const launched = await launcher.launch(launchSession(runtimeRoot), { - resourceScope: createTestArtifactResourceScope(), - }); - if (launched.ok) throw new Error("expected the launch to fail"); - expect(launched.error).toBeInstanceOf(GhidraLaunchError); - expect(launched.error.message).toBe("Ghidra headless launch failed"); - expect( - launched.error instanceof GhidraLaunchError - ? launched.error.capturedOutput - : undefined, - ).toBeUndefined(); - expect(launchOutcomeOf(launched.error)).toBeUndefined(); - } finally { - await rm(runtimeRoot, { recursive: true, force: true }); - } + const runtimeRoot = await createTestTempDirectory("rea-ghidra-launch-"); + const launcher = new GhidraHeadlessLauncher({ + environment: {}, + platform: "darwin", + analyzeHeadlessPath: join(runtimeRoot, "support", "analyzeHeadless"), + configurationDirectoryName: "ghidra_test_PUBLIC", + bridgeScriptPath: join(runtimeRoot, "bridge", "ReaGhidraBridge.java"), + }); + const launched = await launcher.launch(launchSession(runtimeRoot), { + resourceScope: createTestArtifactResourceScope(), + }); + if (launched.ok) throw new Error("expected the launch to fail"); + expect(launched.error).toBeInstanceOf(GhidraLaunchError); + expect(launched.error.message).toBe("Ghidra headless launch failed"); + expect( + launched.error instanceof GhidraLaunchError + ? launched.error.capturedOutput + : undefined, + ).toBeUndefined(); + expect(launchOutcomeOf(launched.error)).toBeUndefined(); }); }); diff --git a/src/ghidra/extensions/GhidraExtensions.test.ts b/src/ghidra/extensions/GhidraExtensions.test.ts index 2706e643bc..c166170d49 100644 --- a/src/ghidra/extensions/GhidraExtensions.test.ts +++ b/src/ghidra/extensions/GhidraExtensions.test.ts @@ -3,10 +3,10 @@ import { execFile } from "node:child_process"; import { constants } from "node:fs"; import { promisify } from "node:util"; import { createHash } from "node:crypto"; -import { mkdtemp, open, readFile, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { open, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; +import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; import { parseConfig } from "../../config/parseConfig.js"; import { projectAnalysisError } from "../../domain/analysisErrorProjection.js"; import type { BinaryTarget } from "../../domain/binaryTargetTypes.js"; @@ -19,18 +19,13 @@ import { type GhidraExtensionResult, } from "./GhidraExtensions.js"; -const roots: string[] = []; let resources = new ArtifactResourceScope(); afterEach(async () => { await resources.close(); resources = new ArtifactResourceScope(); - await Promise.all( - roots.splice(0).map((path) => rm(path, { recursive: true, force: true })), - ); }); const root = async () => { - const path = await mkdtemp(join(tmpdir(), "rea-extension-test-")); - roots.push(path); + const path = await createTestTempDirectory("rea-extension-test-"); return path; }; const target: BinaryTarget = { diff --git a/src/hopperPaths/MacHopperPaths.test.ts b/src/hopperPaths/MacHopperPaths.test.ts index c789023331..587869646a 100644 --- a/src/hopperPaths/MacHopperPaths.test.ts +++ b/src/hopperPaths/MacHopperPaths.test.ts @@ -14,6 +14,7 @@ import { installMacHopperBundle } from "../application/MacHopper.js"; import { linuxHopperLauncherCandidates } from "./LinuxHopperPaths.js"; import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js"; import { describe, expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { localMacHopperRenamedLauncherCandidates, @@ -35,87 +36,80 @@ describe("macOS Hopper launcher paths", () => { it.skipIf(process.platform === "win32")( "preserves a selected home through symlink parent traversal", async () => { - const temporary = await mkdtemp(join(tmpdir(), "rea-hopper-home-")); - try { - await mkdir(join(temporary, "actual", "nested"), { recursive: true }); - await symlink( - join(temporary, "actual", "nested"), - join(temporary, "alias"), - ); - const home = homeDirectoryFromEnvironment( - { HOME: `${temporary}/alias/..` }, - "darwin", - ); - await mkdir( - join(temporary, "actual", "Applications", "Hopper Preview.app"), - { recursive: true }, - ); - const expected = `${home}/Applications/Hopper Preview.app/Contents/MacOS/hopper`; - expect( - [...localMacHopperRenamedLauncherCandidates(home)].filter((path) => - path.startsWith(home), - ), - ).toEqual([expected]); - expect( - (await readMacHopperRenamedLauncherCandidates(home)).filter((path) => - path.startsWith(home), - ), - ).toEqual([expected]); - expect(macHopperUserApplicationPath(home)).toBe( - `${home}/Applications/Hopper Disassembler.app`, - ); - expect(macHopperCanonicalLauncherCandidates(home)[1]).toBe( - `${home}/Applications/Hopper Disassembler.app/Contents/MacOS/hopper`, - ); - expect(linuxHopperLauncherCandidates(home)[1]).toBe( - `${home}/.local/share/rea/hopper/bin/Hopper`, - ); - const source = join(temporary, "source.app"); - await mkdir(join(source, "Contents/MacOS"), { recursive: true }); - await writeFile( - join(source, "Contents/MacOS/hopper"), - "inert launcher", - ); - const result = await installMacHopperBundle( - source, - macHopperUserApplicationPath(home), - false, - { - createStagingRoot: (parent) => - mkdtemp(`${parent}/.rea-hopper-stage-`), - copyBundle: async (from, to) => { - await mkdir(`${to}/Contents/MacOS`, { recursive: true }); - await writeFile( - `${to}/Contents/MacOS/hopper`, - await readFile(`${from}/Contents/MacOS/hopper`), - ); - }, - requireLauncher: (path) => access(path), - pathExists: async (path) => - access(path).then( - () => true, - () => false, - ), - rename, - removeStagingRoot: (path) => rm(path, { recursive: true }), + const temporary = await createTestTempDirectory("rea-hopper-home-"); + await mkdir(join(temporary, "actual", "nested"), { recursive: true }); + await symlink( + join(temporary, "actual", "nested"), + join(temporary, "alias"), + ); + const home = homeDirectoryFromEnvironment( + { HOME: `${temporary}/alias/..` }, + "darwin", + ); + await mkdir( + join(temporary, "actual", "Applications", "Hopper Preview.app"), + { recursive: true }, + ); + const expected = `${home}/Applications/Hopper Preview.app/Contents/MacOS/hopper`; + expect( + [...localMacHopperRenamedLauncherCandidates(home)].filter((path) => + path.startsWith(home), + ), + ).toEqual([expected]); + expect( + (await readMacHopperRenamedLauncherCandidates(home)).filter((path) => + path.startsWith(home), + ), + ).toEqual([expected]); + expect(macHopperUserApplicationPath(home)).toBe( + `${home}/Applications/Hopper Disassembler.app`, + ); + expect(macHopperCanonicalLauncherCandidates(home)[1]).toBe( + `${home}/Applications/Hopper Disassembler.app/Contents/MacOS/hopper`, + ); + expect(linuxHopperLauncherCandidates(home)[1]).toBe( + `${home}/.local/share/rea/hopper/bin/Hopper`, + ); + const source = join(temporary, "source.app"); + await mkdir(join(source, "Contents/MacOS"), { recursive: true }); + await writeFile(join(source, "Contents/MacOS/hopper"), "inert launcher"); + const result = await installMacHopperBundle( + source, + macHopperUserApplicationPath(home), + false, + { + createStagingRoot: (parent) => + mkdtemp(`${parent}/.rea-hopper-stage-`), + copyBundle: async (from, to) => { + await mkdir(`${to}/Contents/MacOS`, { recursive: true }); + await writeFile( + `${to}/Contents/MacOS/hopper`, + await readFile(`${from}/Contents/MacOS/hopper`), + ); }, - () => { - throw new Error("Unexpected retained cleanup"); - }, - ); - expect(result).toMatchObject({ status: "installed" }); - expect( - await readFile( - join( - temporary, - "actual/Applications/Hopper Disassembler.app/Contents/MacOS/hopper", + requireLauncher: (path) => access(path), + pathExists: async (path) => + access(path).then( + () => true, + () => false, ), - "utf8", + rename, + removeStagingRoot: (path) => rm(path, { recursive: true }), + }, + () => { + throw new Error("Unexpected retained cleanup"); + }, + ); + expect(result).toMatchObject({ status: "installed" }); + expect( + await readFile( + join( + temporary, + "actual/Applications/Hopper Disassembler.app/Contents/MacOS/hopper", ), - ).toBe("inert launcher"); - } finally { - await rm(temporary, { recursive: true, force: true }); - } + "utf8", + ), + ).toBe("inert launcher"); }, ); diff --git a/src/ida/IdaDoctor.test.ts b/src/ida/IdaDoctor.test.ts index c0625ccfa3..1bbcac9fad 100644 --- a/src/ida/IdaDoctor.test.ts +++ b/src/ida/IdaDoctor.test.ts @@ -1,7 +1,7 @@ -import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, readdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { afterEach, expect, it } from "vitest"; +import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { inspectIdaRegistration } from "./IdaDoctor.js"; import { providerRegistrationEnvironment } from "../application/SetupRegistrationEnvironment.js"; import type { RetainedResourceScope } from "../ports/AnalysisProvider.js"; @@ -11,16 +11,10 @@ const resourceScope: RetainedResourceScope = { run: (operation) => operation(), }; -const roots: string[] = []; -afterEach(async () => { - for (const root of roots.splice(0)) - await rm(root, { recursive: true, force: true }); -}); it.each([true, false])( "uses allocation filesystem resolution without creating entries (traversed directory exists=%s)", async (exists) => { - const root = await mkdtemp(join(tmpdir(), "rea-ida-workspace-parent-")); - roots.push(root); + const root = await createTestTempDirectory("rea-ida-workspace-parent-"); const path = join(root, "registration.json"); await mkdir(join(root, "existing")); const rawRoot = exists ? `${root}/existing/..` : `${root}/missing/..`; @@ -49,8 +43,7 @@ it.each([true, false])( it.skipIf(process.platform === "win32")( "rejects a non-directory intermediate component before canonicalizing readiness", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-ida-workspace-lookup-")); - roots.push(root); + const root = await createTestTempDirectory("rea-ida-workspace-lookup-"); const path = join(root, "registration.json"); const workspace = join(root, "workspace"); await mkdir(workspace); @@ -81,8 +74,7 @@ it.skipIf(process.platform === "win32")( it.skipIf(process.platform === "win32")( "marks an unusable system temporary parent unavailable when workspaceRoot is omitted", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-ida-default-parent-")); - roots.push(root); + const root = await createTestTempDirectory("rea-ida-default-parent-"); const path = join(root, "registration.json"); const unusableDefault = join(root, "not-a-directory"); await writeFile(unusableDefault, "file"); @@ -108,8 +100,7 @@ it.skipIf(process.platform === "win32")( }, ); it("keeps IDA configuration for setup without copying transport credentials or claiming runtime verification", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-ida-doctor-")); - roots.push(root); + const root = await createTestTempDirectory("rea-ida-doctor-"); const path = join(root, "registration.json"); await writeFile( path, diff --git a/src/inspector/V8InspectorProvider.closeOwnership.test.ts b/src/inspector/V8InspectorProvider.closeOwnership.test.ts index 92a241330d..12bbadb9a3 100644 --- a/src/inspector/V8InspectorProvider.closeOwnership.test.ts +++ b/src/inspector/V8InspectorProvider.closeOwnership.test.ts @@ -1,10 +1,10 @@ import { createServer } from "node:http"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { writeFile } from "node:fs/promises"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { expect, it, onTestFinished, vi } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { WebSocketServer } from "ws"; import { withVerifierCleanup, @@ -24,7 +24,7 @@ import { } from "./V8InspectorProvider.js"; const inspectorCloseFixture = async () => { - const root = await mkdtemp(join(tmpdir(), "rea-inspector-close-owner-")); + const root = await createTestTempDirectory("rea-inspector-close-owner-"); const scriptPath = join(root, "target.js"); await writeFile(scriptPath, "globalThis.fixture = true;\n"); const scriptUrl = pathToFileURL(scriptPath).href; @@ -109,7 +109,6 @@ const inspectorCloseFixture = async () => { if (server.listening) await new Promise((resolve) => server.close(() => resolve())); }, - () => rm(root, { recursive: true, force: true }), ]); }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); diff --git a/src/inspector/V8InspectorProvider.handshake.test.ts b/src/inspector/V8InspectorProvider.handshake.test.ts index 011110ed38..2f10b4cf69 100644 --- a/src/inspector/V8InspectorProvider.handshake.test.ts +++ b/src/inspector/V8InspectorProvider.handshake.test.ts @@ -1,11 +1,11 @@ import { createServer } from "node:http"; import type { Duplex } from "node:stream"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { writeFile } from "node:fs/promises"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { expect, it, onTestFinished } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { WebSocketServer } from "ws"; import { closeVerifierResources } from "../../scripts/lib/verifier-cleanup.mjs"; import { awaitAcknowledgement } from "../../tests/fixtures/lifecycleAcknowledgement.js"; @@ -26,7 +26,7 @@ const MODELED_INSPECTOR_COMMANDS = new Set([ ]); it("cancels a held inspector WebSocket handshake and admits the next observation", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-inspector-handshake-")); + const root = await createTestTempDirectory("rea-inspector-handshake-"); const scriptPath = join(root, "target.js"); await writeFile(scriptPath, "globalThis.fixture = true;\n"); let endpoint = ""; @@ -109,7 +109,6 @@ it("cancels a held inspector WebSocket handshake and admits the next observation if (server.listening) await new Promise((resolve) => server.close(() => resolve())); }, - () => rm(root, { recursive: true, force: true }), ]); }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); diff --git a/src/inspector/V8InspectorProvider.partial.test.ts b/src/inspector/V8InspectorProvider.partial.test.ts index 537b356492..772c48c1a8 100644 --- a/src/inspector/V8InspectorProvider.partial.test.ts +++ b/src/inspector/V8InspectorProvider.partial.test.ts @@ -1,10 +1,10 @@ import { createServer } from "node:http"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { writeFile } from "node:fs/promises"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { WebSocketServer } from "ws"; import { z } from "zod"; @@ -126,7 +126,7 @@ const createPartialInspectorServer = ( it.each(failureCases)( "preserves captured scripts and contexts after %s", async (failure, reason) => { - const root = await mkdtemp(join(tmpdir(), "rea-inspector-partial-")); + const root = await createTestTempDirectory("rea-inspector-partial-"); const scriptPath = join(root, "target.js"); const scriptUrl = pathToFileURL(scriptPath).href; const reportedScriptUrl = failure === "cancellation" ? "" : scriptUrl; @@ -199,7 +199,6 @@ it.each(failureCases)( } finally { await new Promise((resolve) => sockets.close(() => resolve())); await new Promise((resolve) => server.close(() => resolve())); - await rm(root, { recursive: true, force: true }); } }, ); diff --git a/src/javascript/analysis/JavaScriptAnalysisSourceTransfer.test.ts b/src/javascript/analysis/JavaScriptAnalysisSourceTransfer.test.ts index 933688692a..c36192739c 100644 --- a/src/javascript/analysis/JavaScriptAnalysisSourceTransfer.test.ts +++ b/src/javascript/analysis/JavaScriptAnalysisSourceTransfer.test.ts @@ -1,7 +1,7 @@ -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; const writeFileMock = vi.hoisted(() => vi.fn()); const windowsWriteTransientFile = vi.hoisted(() => vi.fn()); @@ -121,27 +121,23 @@ describe("writeJavaScriptAnalysisSourceTransfer", () => { return actual.writeFile(...args); }, ); - const root = await mkdtemp(join(tmpdir(), "rea-js-source-transfer-")); + const root = await createTestTempDirectory("rea-js-source-transfer-"); const path = join(root, "job.source"); - try { - await writeJavaScriptAnalysisSourceTransfer(path, "source-bytes", { + await writeJavaScriptAnalysisSourceTransfer(path, "source-bytes", { + platform: "linux", + }); + expect(await readFile(path, "utf8")).toBe("source-bytes"); + expect(writeFileMock).toHaveBeenCalledWith(path, "source-bytes", { + flag: "wx", + mode: 0o600, + signal: undefined, + }); + expect(windowsPrivateRuntime).not.toHaveBeenCalled(); + await expect( + writeJavaScriptAnalysisSourceTransfer(path, "again", { platform: "linux", - }); - expect(await readFile(path, "utf8")).toBe("source-bytes"); - expect(writeFileMock).toHaveBeenCalledWith(path, "source-bytes", { - flag: "wx", - mode: 0o600, - signal: undefined, - }); - expect(windowsPrivateRuntime).not.toHaveBeenCalled(); - await expect( - writeJavaScriptAnalysisSourceTransfer(path, "again", { - platform: "linux", - }), - ).rejects.toMatchObject({ code: "EEXIST" }); - } finally { - await rm(root, { recursive: true, force: true }); - } + }), + ).rejects.toMatchObject({ code: "EEXIST" }); }); it("surfaces EPERM from the POSIX exclusive create path", async () => { diff --git a/src/javascript/analysis/JavaScriptAnalysisWorkerServer.test.ts b/src/javascript/analysis/JavaScriptAnalysisWorkerServer.test.ts index fbf279b883..213eccadf7 100644 --- a/src/javascript/analysis/JavaScriptAnalysisWorkerServer.test.ts +++ b/src/javascript/analysis/JavaScriptAnalysisWorkerServer.test.ts @@ -1,11 +1,11 @@ import { spawn } from "node:child_process"; import { createHash, randomUUID } from "node:crypto"; import { once } from "node:events"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { writeFile } from "node:fs/promises"; import { join } from "node:path"; import { createInterface } from "node:readline"; import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; import { JAVASCRIPT_ANALYSIS_WORKER_DEFAULTS, javaScriptWorkerAdmissionSchema, @@ -23,7 +23,7 @@ const admission = (id: string) => }); const startServer = async () => { - const root = await mkdtemp(join(tmpdir(), "rea-js-server-framing-")); + const root = await createTestTempDirectory("rea-js-server-framing-"); const serverUrl = new URL( "./JavaScriptAnalysisWorkerServer.ts", import.meta.url, @@ -90,7 +90,6 @@ const startServer = async () => { if (child.exitCode === null && child.signalCode === null) child.kill(); await closed; lines.close(); - await rm(root, { recursive: true, force: true }); }, }; }; diff --git a/src/native/MachoCommandNames.test.ts b/src/native/MachoCommandNames.test.ts index c121a8388c..d738a9517d 100644 --- a/src/native/MachoCommandNames.test.ts +++ b/src/native/MachoCommandNames.test.ts @@ -1,4 +1,5 @@ import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { createHash } from "node:crypto"; import { readMachoCommandNames } from "../domain/apple/machoCommandNames.js"; import { projectMachoBinary } from "./MachoBinaryProjection.js"; @@ -578,58 +579,54 @@ it("retains UUID, entrypoint and bounded build tool records", async () => { it.skipIf(process.platform !== "darwin")( "reads an Apple linker generated multiline section from bounded ranges", async () => { - const { mkdtemp, writeFile, rm, open } = await import("node:fs/promises"); + const { writeFile, open } = await import("node:fs/promises"); const { join } = await import("node:path"); - const { tmpdir } = await import("node:os"); + const { execFileSync } = await import("node:child_process"); - const root = await mkdtemp(join(tmpdir(), "rea-macho-names-")); + const root = await createTestTempDirectory("rea-macho-names-"); + const code = join(root, "main.c"); + const payload = join(root, "payload"); + const image = join(root, "target"); + await writeFile(code, "int main(void) { return 0; }\n"); + await writeFile(payload, "data"); + execFileSync("/usr/bin/clang", [ + "-arch", + "arm64", + "-o", + image, + code, + `-Wl,-sectcreate,__DATA,x\naddr 0x1,${payload}`, + ]); + const handle = await open(image, "r"); try { - const code = join(root, "main.c"); - const payload = join(root, "payload"); - const image = join(root, "target"); - await writeFile(code, "int main(void) { return 0; }\n"); - await writeFile(payload, "data"); - execFileSync("/usr/bin/clang", [ - "-arch", - "arm64", - "-o", - image, - code, - `-Wl,-sectcreate,__DATA,x\naddr 0x1,${payload}`, - ]); - const handle = await open(image, "r"); - try { - const stat = await handle.stat(); - const result = await readMachoCommandNames( - async (offset, size) => { - const bytes = Buffer.alloc(size); - const read = await handle.read(bytes, 0, size, offset); - return bytes.subarray(0, read.bytesRead); - }, - stat.size, - 1024, - 10000, - ); - expect( - result.commands - .flatMap((command) => command.sections ?? []) - .some( - (section) => - Buffer.from(section.name).subarray(0, 10).toString() === - "x\naddr 0x1", - ), - ).toBe(true); - const parsed = projectMachoBinary(result); - expect( - parsed.segments - .flatMap((segment) => segment.sections) - .some((section) => section.name === "x\naddr 0x1"), - ).toBe(true); - } finally { - await handle.close(); - } + const stat = await handle.stat(); + const result = await readMachoCommandNames( + async (offset, size) => { + const bytes = Buffer.alloc(size); + const read = await handle.read(bytes, 0, size, offset); + return bytes.subarray(0, read.bytesRead); + }, + stat.size, + 1024, + 10000, + ); + expect( + result.commands + .flatMap((command) => command.sections ?? []) + .some( + (section) => + Buffer.from(section.name).subarray(0, 10).toString() === + "x\naddr 0x1", + ), + ).toBe(true); + const parsed = projectMachoBinary(result); + expect( + parsed.segments + .flatMap((segment) => segment.sections) + .some((section) => section.name === "x\naddr 0x1"), + ).toBe(true); } finally { - await rm(root, { recursive: true, force: true }); + await handle.close(); } }, ); diff --git a/src/native/NativeMachoOperand.test.ts b/src/native/NativeMachoOperand.test.ts index 4baa680ab2..8f7bd22eb9 100644 --- a/src/native/NativeMachoOperand.test.ts +++ b/src/native/NativeMachoOperand.test.ts @@ -1,7 +1,8 @@ import { mkdtemp, readlink, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; +import { describe, expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { NativeFixtureRunner, nativeMachoTargetForFile, @@ -12,14 +13,6 @@ import { NativeCommandFailure } from "../providers/NativeCommandRunner.js"; import { inspectMachoSchema } from "../domain/native/nativeInspection.js"; import { err, ok } from "../domain/result.js"; -const targetDirectories: string[] = []; -afterEach(async () => { - await Promise.all( - targetDirectories - .splice(0) - .map((directory) => rm(directory, { recursive: true, force: true })), - ); -}); /** A FAT container whose arm64 row matches the canned lipo fixture. */ const parenthesizedFatTarget = () => { const bytes = Buffer.alloc(40_960); @@ -45,8 +38,7 @@ const parenthesizedFatTarget = () => { return bytes; }; const parenthesizedTarget = async () => { - const directory = await mkdtemp(join(tmpdir(), "rea-macho-target-")); - targetDirectories.push(directory); + const directory = await createTestTempDirectory("rea-macho-target-"); const path = join(directory, "app(foo)"); await writeFile(path, parenthesizedFatTarget()); return { directory, target: await nativeMachoTargetForFile(path) }; @@ -102,7 +94,6 @@ describe("private otool operand lifecycle", () => { } finally { await client.close(); await rm(path, { recursive: true, force: true }); - await rm(selected.directory, { recursive: true, force: true }); } }); @@ -171,7 +162,6 @@ describe("private otool operand lifecycle", () => { } finally { await client.close(); await rm(path, { recursive: true, force: true }); - await rm(selected.directory, { recursive: true, force: true }); } }); }); diff --git a/src/native/NativeMachoSource.test.ts b/src/native/NativeMachoSource.test.ts index 7a09ab4f04..897063cd8c 100644 --- a/src/native/NativeMachoSource.test.ts +++ b/src/native/NativeMachoSource.test.ts @@ -1,8 +1,8 @@ import { createHash } from "node:crypto"; -import { mkdtemp, rename, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { rename, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, expect, it, vi } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { ArtifactResourceScope } from "../resources/ArtifactResourceScope.js"; import { ArtifactFileCleanupFailure } from "../resources/ArtifactFileOperation.js"; import { withNativeMachoSource } from "./NativeMachoSource.js"; @@ -33,7 +33,7 @@ afterEach(() => { }); const fixture = async () => { - const root = await mkdtemp(join(tmpdir(), "rea-macho-source-")); + const root = await createTestTempDirectory("rea-macho-source-"); const path = join(root, "image"); const bytes = Buffer.from("0123456789abcdef"); await writeFile(path, bytes); @@ -68,7 +68,6 @@ it("binds bounded reads and returned failures to the selected bytes", async () = expect(control.attempts).toBe(1); } finally { await scope.close(); - await rm(f.root, { recursive: true, force: true }); } }); @@ -100,7 +99,6 @@ it("refuses wrong initial digest and a changed selected file even after a return }); } finally { await scope.close(); - await rm(f.root, { recursive: true, force: true }); } }); @@ -120,7 +118,6 @@ it("refuses a path replacement during the producer callback", async () => { }); } finally { await scope.close(); - await rm(f.root, { recursive: true, force: true }); } }); @@ -150,7 +147,6 @@ it("keeps callback cancellation and retries the exact descriptor after close fai } finally { control.failClose = false; await scope.close(); - await rm(f.root, { recursive: true, force: true }); } }); @@ -176,7 +172,6 @@ it("retains the completed producer failure when cancellation prevents final veri }); } finally { await scope.close(); - await rm(f.root, { recursive: true, force: true }); } }); @@ -210,7 +205,6 @@ it("retains a returned producer failure when final descriptor close fails", asyn } finally { control.failClose = false; await scope.close(); - await rm(f.root, { recursive: true, force: true }); } }); @@ -240,7 +234,6 @@ it("rechecks source after a thrown producer failure and retains both failures", }); } finally { await scope.close(); - await rm(f.root, { recursive: true, force: true }); } }); @@ -267,6 +260,5 @@ it("retains a thrown producer failure if cancellation prevents final verificatio }); } finally { await scope.close(); - await rm(f.root, { recursive: true, force: true }); } }); diff --git a/src/native/SignatureTargetBinding.test.ts b/src/native/SignatureTargetBinding.test.ts index 1d6eb149a7..54acc4ddef 100644 --- a/src/native/SignatureTargetBinding.test.ts +++ b/src/native/SignatureTargetBinding.test.ts @@ -13,6 +13,7 @@ import { import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, expect, it, vi, onTestFinished } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { withVerifierCleanup } from "../../scripts/lib/verifier-cleanup.mjs"; import { phaseGate } from "../../tests/support/lifecycleHarness.js"; @@ -47,7 +48,6 @@ const unusedInspection = async (): Promise => { throw new Error("Inspection must not run after failed target binding"); }; const roots: string[] = []; -const targets: string[] = []; const unusedRunner: NativeCommandRunner = { async run() { throw new Error("Changed target must be rejected before a command runs"); @@ -64,20 +64,16 @@ const unusedTracer: NativeCallTracer = { afterEach(async () => { await Promise.all( - [...roots, ...targets].map((path) => - rm(path, { recursive: true, force: true }), - ), + roots.map((path) => rm(path, { recursive: true, force: true })), ); roots.length = 0; - targets.length = 0; }); const createTarget = async ( bytes: string, digest = bytes, ): Promise => { - const directory = await mkdtemp(join(tmpdir(), "rea-signature-target-")); - targets.push(directory); + const directory = await createTestTempDirectory("rea-signature-target-"); const path = join(directory, "target.bin"); await writeFile(path, bytes); return { diff --git a/src/process/LocalSocketConnection.test.ts b/src/process/LocalSocketConnection.test.ts index 6051753101..8ffbbbf8b6 100644 --- a/src/process/LocalSocketConnection.test.ts +++ b/src/process/LocalSocketConnection.test.ts @@ -1,16 +1,15 @@ import { once } from "node:events"; -import { mkdtemp, rm } from "node:fs/promises"; import { createServer, type AddressInfo } from "node:net"; -import { tmpdir } from "node:os"; import { join } from "node:path"; import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { connectLocalSocketOnce } from "./LocalSocketConnection.js"; for (const transport of ["tcp", "unix"] as const) it.skipIf(transport === "unix" && process.platform === "win32")( `connects a real local ${transport} socket and transfers ownership`, async () => { - const directory = await mkdtemp(join(tmpdir(), "rea-local-socket-")); + const directory = await createTestTempDirectory("rea-local-socket-"); const server = createServer(); const path = join(directory, "socket"); try { @@ -38,7 +37,6 @@ for (const transport of ["tcp", "unix"] as const) await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())), ); - await rm(directory, { recursive: true, force: true }); } }, ); @@ -80,18 +78,14 @@ it("cancels an outstanding connection attempt with the caller's reason", async ( it.skipIf(process.platform === "win32")( "reports a local socket connection failure", async () => { - const directory = await mkdtemp(join(tmpdir(), "rea-missing-socket-")); - try { - const result = await connectLocalSocketOnce( - { path: join(directory, "missing") }, - new AbortController().signal, - ); - expect(result).toMatchObject({ - ok: false, - error: { kind: "error", cause: { code: "ENOENT" } }, - }); - } finally { - await rm(directory, { recursive: true, force: true }); - } + const directory = await createTestTempDirectory("rea-missing-socket-"); + const result = await connectLocalSocketOnce( + { path: join(directory, "missing") }, + new AbortController().signal, + ); + expect(result).toMatchObject({ + ok: false, + error: { kind: "error", cause: { code: "ENOENT" } }, + }); }, ); diff --git a/src/process/ProcessInspectionCancellation.test.ts b/src/process/ProcessInspectionCancellation.test.ts index 6afecd5bb9..a47e7c6396 100644 --- a/src/process/ProcessInspectionCancellation.test.ts +++ b/src/process/ProcessInspectionCancellation.test.ts @@ -1,7 +1,7 @@ -import { access, mkdtemp, readFile, rm } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { access, readFile } from "node:fs/promises"; import { join } from "node:path"; import { expect, it, vi } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { AnalysisOutputError } from "../domain/analysisErrorCore.js"; import { @@ -12,22 +12,18 @@ import { systemProcessOwnershipHost } from "./ProcessOwnershipObservation.js"; import { spawnOwnedProviderProcess } from "./ProviderProcess.js"; it("does not turn a physical OS read failure into inspection cancellation when reused as the abort reason", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-inspection-origin-")); - try { - const failure = await readFile(join(root, "missing")).catch( - (cause: unknown) => cause, - ); - expect(failure).toMatchObject({ code: "ENOENT" }); - const controller = new AbortController(); - controller.abort(failure); - expect(isProcessOwnershipInspectionCancellation(failure)).toBe(false); - } finally { - await rm(root, { recursive: true, force: true }); - } + const root = await createTestTempDirectory("rea-inspection-origin-"); + const failure = await readFile(join(root, "missing")).catch( + (cause: unknown) => cause, + ); + expect(failure).toMatchObject({ code: "ENOENT" }); + const controller = new AbortController(); + controller.abort(failure); + expect(isProcessOwnershipInspectionCancellation(failure)).toBe(false); }); it("wraps an opaque non-cancellation analysis error at already-aborted spawn admission without launching", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-inspection-admission-")); + const root = await createTestTempDirectory("rea-inspection-admission-"); const marker = join(root, "launched"); const prepare = vi .spyOn(systemProcessOwnershipHost, "prepare") @@ -59,6 +55,5 @@ it("wraps an opaque non-cancellation analysis error at already-aborted spawn adm await expect(access(marker)).rejects.toMatchObject({ code: "ENOENT" }); } finally { prepare.mockRestore(); - await rm(root, { recursive: true, force: true }); } }); diff --git a/src/process/ProcessOwnership.descriptorCancellation.test.ts b/src/process/ProcessOwnership.descriptorCancellation.test.ts index 88b3374765..d24a519215 100644 --- a/src/process/ProcessOwnership.descriptorCancellation.test.ts +++ b/src/process/ProcessOwnership.descriptorCancellation.test.ts @@ -1,13 +1,7 @@ -import { - mkdtemp, - mkdir, - rm, - writeFile, - type FileHandle, -} from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, writeFile, type FileHandle } from "node:fs/promises"; import { join } from "node:path"; import { expect, it, onTestFinished, vi } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { createDeferred } from "../../tests/fixtures/binarySession.js"; import { awaitAcknowledgement } from "../../tests/fixtures/lifecycleAcknowledgement.js"; @@ -79,8 +73,7 @@ const prepare = async () => { fixture.onReadFailure = undefined; fixture.onClosed = undefined; fixture.onDeniedClose = undefined; - const root = await mkdtemp(join(tmpdir(), "rea-inspection-descriptor-")); - onTestFinished(() => rm(root, { recursive: true, force: true })); + const root = await createTestTempDirectory("rea-inspection-descriptor-"); const rows = [42, 43, 44].map((pid) => ({ pid, parentPid: 1, diff --git a/src/process/ProcessOwnership.identity.test.ts b/src/process/ProcessOwnership.identity.test.ts index bc35bddaff..d6eca10579 100644 --- a/src/process/ProcessOwnership.identity.test.ts +++ b/src/process/ProcessOwnership.identity.test.ts @@ -8,8 +8,6 @@ import { import { createSystemProcessOwnershipHost } from "./ProcessOwnershipObservation.js"; import { ProcessOwnershipEvidenceOwner } from "./ProcessOwnershipEvidence.js"; -const itOnLinux = process.platform === "linux" ? it : it.skip; - const observedIdentity = (entry: ProcessTableEntry, identity: string) => ({ state: "readable" as const, identity, @@ -232,42 +230,45 @@ it.each([undefined, "run-token"])( ); describe("Linux process start identities", () => { - itOnLinux("reads Linux process start identities from proc stat", async () => { - const host = createSystemProcessOwnershipHost("linux", {}); - expect(host.processIdentities).toBeDefined(); - expect(host.captureBaseline).toBeDefined(); - const observedProcess = { - pid: process.pid, - parentPid: process.ppid, - processGroupId: process.pid, - state: "S", - command: process.execPath, - } satisfies ProcessTableEntry; - const identities = await host.processIdentities?.( - [observedProcess], - undefined, - new Set([observedProcess.pid]), - ); - expect(identities?.get(observedProcess.pid)).toMatchObject({ - state: "readable", - identity: expect.stringMatching(/^linux-starttime:\d+$/u), - lifecycle: { state: "observed", lifecycle: "non-zombie" }, - relation: { - state: "observed", + it.runIf(process.platform === "linux")( + "reads Linux process start identities from proc stat", + async () => { + const host = createSystemProcessOwnershipHost("linux", {}); + expect(host.processIdentities).toBeDefined(); + expect(host.captureBaseline).toBeDefined(); + const observedProcess = { + pid: process.pid, parentPid: process.ppid, - processGroupId: expect.any(Number), - }, - }); - expect(identities?.get(observedProcess.pid)).toHaveProperty( - "effectiveUid", - process.geteuid!(), - ); - const baseline = await host.captureBaseline?.(); - expect(baseline).toContainEqual({ - pid: observedProcess.pid, - identity: expect.stringMatching(/^linux-starttime:\d+$/u), - }); - }); + processGroupId: process.pid, + state: "S", + command: process.execPath, + } satisfies ProcessTableEntry; + const identities = await host.processIdentities?.( + [observedProcess], + undefined, + new Set([observedProcess.pid]), + ); + expect(identities?.get(observedProcess.pid)).toMatchObject({ + state: "readable", + identity: expect.stringMatching(/^linux-starttime:\d+$/u), + lifecycle: { state: "observed", lifecycle: "non-zombie" }, + relation: { + state: "observed", + parentPid: process.ppid, + processGroupId: expect.any(Number), + }, + }); + expect(identities?.get(observedProcess.pid)).toHaveProperty( + "effectiveUid", + process.geteuid!(), + ); + const baseline = await host.captureBaseline?.(); + expect(baseline).toContainEqual({ + pid: observedProcess.pid, + identity: expect.stringMatching(/^linux-starttime:\d+$/u), + }); + }, + ); }); it("validates and cleans an exact-token owner without a capture baseline", async () => { diff --git a/src/process/ProcessOwnership.nativeExit.test.ts b/src/process/ProcessOwnership.nativeExit.test.ts index e3007a4358..18816600bd 100644 --- a/src/process/ProcessOwnership.nativeExit.test.ts +++ b/src/process/ProcessOwnership.nativeExit.test.ts @@ -256,9 +256,7 @@ it.each([ }, ); -const itOnLinux = process.platform === "linux" ? it : it.skip; - -itOnLinux( +it.runIf(process.platform === "linux")( "verifies a real child exit between the native identity and follow-up read", async () => { const child = spawn( diff --git a/src/process/capture/FilesystemSnapshot.test.ts b/src/process/capture/FilesystemSnapshot.test.ts index 09f8fb529f..41d2b907b2 100644 --- a/src/process/capture/FilesystemSnapshot.test.ts +++ b/src/process/capture/FilesystemSnapshot.test.ts @@ -1,7 +1,6 @@ import { ProcessCaptureError } from "./ProcessCaptureError.js"; import { fstatSync } from "node:fs"; import { - mkdtemp, mkdir, symlink, lstat, @@ -11,10 +10,10 @@ import { utimes, writeFile, } from "node:fs/promises"; -import { tmpdir } from "node:os"; import { join } from "node:path"; import { expect, it } from "vitest"; +import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; import { hashFile } from "./FilesystemSnapshot.js"; import { ProcessCaptureReadFailure } from "./ProcessCaptureRead.js"; @@ -42,160 +41,136 @@ const countOpenDescriptorsFor = async (path: string): Promise => { it.skipIf(process.platform === "win32")( "omits a captured regular file replaced by a symlink", async () => { - const directory = await mkdtemp(join(tmpdir(), "rea-snapshot-symlink-")); + const directory = await createTestTempDirectory("rea-snapshot-symlink-"); const selected = join(directory, "selected"); const replacement = join(directory, "replacement"); - try { - await writeFile(selected, "captured bytes"); - await writeFile(replacement, "unselected bytes"); - const expected = await lstat(selected); - await rm(selected); - await symlink(replacement, selected); - const outcome = await hashFile(selected, expected, 1_000); - expect(outcome.state).toBe("omitted"); - expect(outcome).not.toHaveProperty("sha256"); - } finally { - await rm(directory, { recursive: true, force: true }); - } + await writeFile(selected, "captured bytes"); + await writeFile(replacement, "unselected bytes"); + const expected = await lstat(selected); + await rm(selected); + await symlink(replacement, selected); + const outcome = await hashFile(selected, expected, 1_000); + expect(outcome.state).toBe("omitted"); + expect(outcome).not.toHaveProperty("sha256"); }, ); it("does not hash a replacement file using the earlier path metadata", async () => { - const directory = await mkdtemp(join(tmpdir(), "rea-snapshot-identity-")); + const directory = await createTestTempDirectory("rea-snapshot-identity-"); const path = join(directory, "observed-file"); - try { - await writeFile(path, "captured file\n"); - const expected = await lstat(path); - await rm(path); - await writeFile(path, "replacement with a different identity and size\n"); + await writeFile(path, "captured file\n"); + const expected = await lstat(path); + await rm(path); + await writeFile(path, "replacement with a different identity and size\n"); - await expect(hashFile(path, expected, 1_000)).resolves.toEqual({ - state: "omitted", - reason: "file_changed_or_short_read", - system_code: null, - }); - } finally { - await rm(directory, { recursive: true, force: true }); - } + await expect(hashFile(path, expected, 1_000)).resolves.toEqual({ + state: "omitted", + reason: "file_changed_or_short_read", + system_code: null, + }); }); it("rejects a same-size rewrite even when its modification time is restored", async () => { - const directory = await mkdtemp(join(tmpdir(), "rea-snapshot-ctime-")); + const directory = await createTestTempDirectory("rea-snapshot-ctime-"); const path = join(directory, "observed-file"); - try { - const fixedMtime = new Date("2020-01-02T03:04:05.000Z"); - await writeFile(path, "before\n"); - await utimes(path, fixedMtime, fixedMtime); - const expected = await lstat(path); - await expect - .poll(async () => { - await writeFile(path, "after!\n"); - await utimes(path, fixedMtime, fixedMtime); - return (await lstat(path)).ctimeMs; - }) - .not.toBe(expected.ctimeMs); - const rewritten = await lstat(path); + const fixedMtime = new Date("2020-01-02T03:04:05.000Z"); + await writeFile(path, "before\n"); + await utimes(path, fixedMtime, fixedMtime); + const expected = await lstat(path); + await expect + .poll(async () => { + await writeFile(path, "after!\n"); + await utimes(path, fixedMtime, fixedMtime); + return (await lstat(path)).ctimeMs; + }) + .not.toBe(expected.ctimeMs); + const rewritten = await lstat(path); - expect(rewritten).toMatchObject({ - dev: expected.dev, - ino: expected.ino, - mode: expected.mode, - size: expected.size, - mtimeMs: expected.mtimeMs, - }); - expect(rewritten.ctimeMs).not.toBe(expected.ctimeMs); + expect(rewritten).toMatchObject({ + dev: expected.dev, + ino: expected.ino, + mode: expected.mode, + size: expected.size, + mtimeMs: expected.mtimeMs, + }); + expect(rewritten.ctimeMs).not.toBe(expected.ctimeMs); - await expect(hashFile(path, expected, 1_000)).resolves.toMatchObject({ - state: "omitted", - reason: "file_changed_or_short_read", - system_code: null, - }); - } finally { - await rm(directory, { recursive: true, force: true }); - } + await expect(hashFile(path, expected, 1_000)).resolves.toMatchObject({ + state: "omitted", + reason: "file_changed_or_short_read", + system_code: null, + }); }); it("reports a file removed between metadata observation and open", async () => { - const directory = await mkdtemp(join(tmpdir(), "rea-snapshot-open-race-")); + const directory = await createTestTempDirectory("rea-snapshot-open-race-"); const path = join(directory, "observed-file"); - try { - await writeFile(path, "captured file\n"); - const expected = await lstat(path); - await rm(path); + await writeFile(path, "captured file\n"); + const expected = await lstat(path); + await rm(path); - await expect(hashFile(path, expected, 1_000)).resolves.toEqual({ - state: "omitted", - reason: "file_unavailable", - system_code: "ENOENT", - }); - } finally { - await rm(directory, { recursive: true, force: true }); - } + await expect(hashFile(path, expected, 1_000)).resolves.toEqual({ + state: "omitted", + reason: "file_unavailable", + system_code: "ENOENT", + }); }); it("rejects cancellation for an empty file before returning its digest", async () => { - const directory = await mkdtemp(join(tmpdir(), "rea-snapshot-empty-cancel-")); + const directory = await createTestTempDirectory("rea-snapshot-empty-cancel-"); const path = join(directory, "observed-file"); - try { - await writeFile(path, ""); - const expected = await lstat(path); - const controller = new AbortController(); - controller.abort(); + await writeFile(path, ""); + const expected = await lstat(path); + const controller = new AbortController(); + controller.abort(); - const failure: unknown = await hashFile( - path, - expected, - 1_000, - controller.signal, - ).catch((cause: unknown) => cause); - expect(failure).toBeInstanceOf(ProcessCaptureError); - if (!(failure instanceof ProcessCaptureError)) - throw new Error("Expected cancellation from the capture checkpoint"); - expect(failure.reason).toBe("cancelled"); - expect(failure.cause).toBe(controller.signal.reason); - } finally { - await rm(directory, { recursive: true, force: true }); - } + const failure: unknown = await hashFile( + path, + expected, + 1_000, + controller.signal, + ).catch((cause: unknown) => cause); + expect(failure).toBeInstanceOf(ProcessCaptureError); + if (!(failure instanceof ProcessCaptureError)) + throw new Error("Expected cancellation from the capture checkpoint"); + expect(failure.reason).toBe("cancelled"); + expect(failure.cause).toBe(controller.signal.reason); }); it.skipIf(process.platform === "win32")( "closes the opened file when cancellation arrives during open", async () => { - const directory = await mkdtemp(join(tmpdir(), "rea-snapshot-cancel-")); + const directory = await createTestTempDirectory("rea-snapshot-cancel-"); const path = join(directory, "observed-file"); - try { - await writeFile(path, "captured file\n"); - const expected = await lstat(path); - const controller = new AbortController(); - const held = await open(path, "r"); - expect(await countOpenDescriptorsFor(path)).toBe(1); - await held.close(); - expect(await countOpenDescriptorsFor(path)).toBe(0); - const hashing = hashFile(path, expected, 1_000, controller.signal); - // hashFile reaches `open` synchronously before its first suspension, so - // this abort is observed after the descriptor is acquired and is handled - // by the `finally` close path. - const reason = Object.assign(new Error("cancelled while opening"), { - code: "EACCES", - }); - controller.abort(reason); + await writeFile(path, "captured file\n"); + const expected = await lstat(path); + const controller = new AbortController(); + const held = await open(path, "r"); + expect(await countOpenDescriptorsFor(path)).toBe(1); + await held.close(); + expect(await countOpenDescriptorsFor(path)).toBe(0); + const hashing = hashFile(path, expected, 1_000, controller.signal); + // hashFile reaches `open` synchronously before its first suspension, so + // this abort is observed after the descriptor is acquired and is handled + // by the `finally` close path. + const reason = Object.assign(new Error("cancelled while opening"), { + code: "EACCES", + }); + controller.abort(reason); - let failure: unknown; - try { - await hashing; - } catch (cause: unknown) { - failure = cause; - } - expect(failure).toBeInstanceOf(ProcessCaptureReadFailure); - expect(failure).toMatchObject({ - cause: reason, - userCategory: "cancelled", - outcome: { kind: "failed" }, - }); - expect(await countOpenDescriptorsFor(path)).toBe(0); - } finally { - await rm(directory, { recursive: true, force: true }); + let failure: unknown; + try { + await hashing; + } catch (cause: unknown) { + failure = cause; } + expect(failure).toBeInstanceOf(ProcessCaptureReadFailure); + expect(failure).toMatchObject({ + cause: reason, + userCategory: "cancelled", + outcome: { kind: "failed" }, + }); + expect(await countOpenDescriptorsFor(path)).toBe(0); }, ); @@ -208,33 +183,29 @@ for (const variant of [ it.runIf(process.platform === "win32")( `hashes only the captured Windows file through ${variant}`, async () => { - const directory = await mkdtemp(join(tmpdir(), "rea-snapshot-windows-")); - try { - const original = join(directory, "original"); - const replacement = join(directory, "replacement"); - await mkdir(original); - await mkdir(replacement); - await writeFile(join(original, "TestFile.txt"), "captured bytes"); - await writeFile(join(replacement, "TestFile.txt"), "replaced bytes"); - const alias = join(directory, "alias"); - if (variant === "ancestor-junction" || variant === "replaced-junction") - await symlink(original, alias, "junction"); - const path = join( - variant.includes("junction") ? alias : original, - variant === "case-alias" ? "testfile.txt" : "TestFile.txt", - ); - const expected = await lstat(path); - if (variant === "replaced-junction") { - await rm(alias); - await symlink(replacement, alias, "junction"); - } - const result = await hashFile(path, expected, 1_000); - expect(result.state).toBe( - variant === "replaced-junction" ? "omitted" : "hashed", - ); - } finally { - await rm(directory, { recursive: true, force: true }); + const directory = await createTestTempDirectory("rea-snapshot-windows-"); + const original = join(directory, "original"); + const replacement = join(directory, "replacement"); + await mkdir(original); + await mkdir(replacement); + await writeFile(join(original, "TestFile.txt"), "captured bytes"); + await writeFile(join(replacement, "TestFile.txt"), "replaced bytes"); + const alias = join(directory, "alias"); + if (variant === "ancestor-junction" || variant === "replaced-junction") + await symlink(original, alias, "junction"); + const path = join( + variant.includes("junction") ? alias : original, + variant === "case-alias" ? "testfile.txt" : "TestFile.txt", + ); + const expected = await lstat(path); + if (variant === "replaced-junction") { + await rm(alias); + await symlink(replacement, alias, "junction"); } + const result = await hashFile(path, expected, 1_000); + expect(result.state).toBe( + variant === "replaced-junction" ? "omitted" : "hashed", + ); }, ); } diff --git a/src/process/capture/ProcessScenarioRuntimeValidation.test.ts b/src/process/capture/ProcessScenarioRuntimeValidation.test.ts index e3c370c340..7a3a43ae57 100644 --- a/src/process/capture/ProcessScenarioRuntimeValidation.test.ts +++ b/src/process/capture/ProcessScenarioRuntimeValidation.test.ts @@ -2,13 +2,11 @@ import { execFileSync } from "node:child_process"; import { chmod, mkdir, - mkdtemp, rm, realpath, symlink, writeFile, } from "node:fs/promises"; -import { tmpdir } from "node:os"; import { delimiter, join } from "node:path"; import { expect, it } from "vitest"; @@ -46,79 +44,67 @@ it.skipIf(process.platform === "win32")( it.skipIf(process.platform === "win32")( "preserves the caller-selected executable symlink for process invocation", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-process-executable-alias-")); - try { - const alias = join(root, "chosen-node"); - await symlink(process.execPath, alias); + const root = await createTestTempDirectory("rea-process-executable-alias-"); + const alias = join(root, "chosen-node"); + await symlink(process.execPath, alias); - const resolved = await resolveProcessScenarioRuntimePaths( - processScenarioSchema.parse({ - executable: alias, - working_directory: root, - environment: { PATH: "" }, - }), - process.env, - process.platform, - ); - expect(resolved.executable).toBe(alias); - } finally { - await rm(root, { recursive: true, force: true }); - } + const resolved = await resolveProcessScenarioRuntimePaths( + processScenarioSchema.parse({ + executable: alias, + working_directory: root, + environment: { PATH: "" }, + }), + process.env, + process.platform, + ); + expect(resolved.executable).toBe(alias); }, ); it("resolves a Windows executable through the canonical PATH spelling", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-process-path-")); - try { - const selected = join(root, "selected"); - const ambient = join(root, "ambient"); - await mkdir(selected); - await mkdir(ambient); - await writeFile(join(selected, "tool.exe"), ""); - await chmod(join(selected, "tool.exe"), 0o755); - const scenario = processScenarioSchema.parse({ - executable: "tool.exe", - working_directory: root, - environment: { Path: selected }, - }); - const candidate = join(selected, "tool.exe"); - const resolved = await resolveProcessScenarioRuntimePaths( - scenario, - { PATH: ambient }, - "win32", - ); - expect(resolved.executable).toBe(candidate); - } finally { - await rm(root, { recursive: true, force: true }); - } + const root = await createTestTempDirectory("rea-process-path-"); + const selected = join(root, "selected"); + const ambient = join(root, "ambient"); + await mkdir(selected); + await mkdir(ambient); + await writeFile(join(selected, "tool.exe"), ""); + await chmod(join(selected, "tool.exe"), 0o755); + const scenario = processScenarioSchema.parse({ + executable: "tool.exe", + working_directory: root, + environment: { Path: selected }, + }); + const candidate = join(selected, "tool.exe"); + const resolved = await resolveProcessScenarioRuntimePaths( + scenario, + { PATH: ambient }, + "win32", + ); + expect(resolved.executable).toBe(candidate); }); it("reports a working-directory file as invalid input", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-process-invalid-cwd-")); + const root = await createTestTempDirectory("rea-process-invalid-cwd-"); const selectedFile = join(root, "selected-file"); await writeFile(selectedFile, "not a directory"); - try { - const failure = await runtimePathFailure({ - executable: process.execPath, - working_directory: selectedFile, - }); - expect(failure.issues[0]?.message).toContain("not a directory"); - expect(projectAnalysisError(failure)).toMatchObject({ - code: "invalid_request", - details: { - operation: "capture_process_scenario", - issues: [ - { - path: ["working_directory"], - reason: "invalid_value", - message: expect.stringContaining(selectedFile), - }, - ], - }, - }); - } finally { - await rm(root, { recursive: true, force: true }); - } + const failure = await runtimePathFailure({ + executable: process.execPath, + working_directory: selectedFile, + }); + expect(failure.issues[0]?.message).toContain("not a directory"); + expect(projectAnalysisError(failure)).toMatchObject({ + code: "invalid_request", + details: { + operation: "capture_process_scenario", + issues: [ + { + path: ["working_directory"], + reason: "invalid_value", + message: expect.stringContaining(selectedFile), + }, + ], + }, + }); }); it.skipIf(process.platform === "win32")( @@ -151,60 +137,52 @@ it.skipIf(process.platform === "win32")( ); it("reports an executable directory as invalid input", async () => { - const root = await mkdtemp( - join(tmpdir(), "rea-process-executable-directory-"), + const root = await createTestTempDirectory( + "rea-process-executable-directory-", ); const directory = join(root, "tool-directory"); - try { - await mkdir(directory); - const directoryFailure = await runtimePathFailure({ - executable: directory, - working_directory: root, - }); - expect(directoryFailure.issues[0]?.message).toContain("not a regular file"); - expect(projectAnalysisError(directoryFailure)).toMatchObject({ - code: "invalid_request", - details: { - issues: [ - { - path: ["executable"], - message: expect.stringContaining(directory), - }, - ], - }, - }); - } finally { - await rm(root, { recursive: true, force: true }); - } + await mkdir(directory); + const directoryFailure = await runtimePathFailure({ + executable: directory, + working_directory: root, + }); + expect(directoryFailure.issues[0]?.message).toContain("not a regular file"); + expect(projectAnalysisError(directoryFailure)).toMatchObject({ + code: "invalid_request", + details: { + issues: [ + { + path: ["executable"], + message: expect.stringContaining(directory), + }, + ], + }, + }); }); it.skipIf(process.platform === "win32")( "reports a non-executable regular file as invalid input", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-process-non-executable-")); + const root = await createTestTempDirectory("rea-process-non-executable-"); const selected = join(root, "not-executable"); - try { - await writeFile(selected, "not executable"); - await chmod(selected, 0o644); - const failure = await runtimePathFailure({ - executable: selected, - working_directory: root, - }); - expect(failure.issues[0]?.message).toContain("EACCES"); - expect(projectAnalysisError(failure)).toMatchObject({ - code: "invalid_request", - details: { - issues: [ - { - path: ["executable"], - message: expect.stringContaining(selected), - }, - ], - }, - }); - } finally { - await rm(root, { recursive: true, force: true }); - } + await writeFile(selected, "not executable"); + await chmod(selected, 0o644); + const failure = await runtimePathFailure({ + executable: selected, + working_directory: root, + }); + expect(failure.issues[0]?.message).toContain("EACCES"); + expect(projectAnalysisError(failure)).toMatchObject({ + code: "invalid_request", + details: { + issues: [ + { + path: ["executable"], + message: expect.stringContaining(selected), + }, + ], + }, + }); }, ); diff --git a/src/process/capture/TerminalRenderer.test.ts b/src/process/capture/TerminalRenderer.test.ts index e670054868..79f4bae189 100644 --- a/src/process/capture/TerminalRenderer.test.ts +++ b/src/process/capture/TerminalRenderer.test.ts @@ -3,6 +3,7 @@ import { mkdtemp, rm, stat } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { expect, it, vi } from "vitest"; +import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; import { TerminalRenderer } from "./TerminalRenderer.js"; import { ProcessCaptureResourceScope } from "./ProcessCaptureLifecycle.js"; @@ -229,7 +230,7 @@ it("retains disposal failures for a later cleanup retry", async () => { normalize: boundedNormalize((value) => value), }); const scope = new ProcessCaptureResourceScope(); - const temporaryRoot = await mkdtemp(join(tmpdir(), "rea-terminal-retry-")); + const temporaryRoot = await createTestTempDirectory("rea-terminal-retry-"); try { const cleanup = await scope.release({ timers: new Set(), @@ -251,7 +252,6 @@ it("retains disposal failures for a later cleanup retry", async () => { await scope.close(); } finally { terminalDispose.mockRestore(); - await rm(temporaryRoot, { recursive: true, force: true }); } } }); diff --git a/src/setupEnvironment.test.ts b/src/setupEnvironment.test.ts index 65f6aff9ab..cc87ff8002 100644 --- a/src/setupEnvironment.test.ts +++ b/src/setupEnvironment.test.ts @@ -4,11 +4,10 @@ import { withoutPackageRunnerIdentity, } from "./application/ClientRegistrationIdentity.js"; import { UpdateCommandRunner } from "./application/UpdateCommandRunner.js"; -import { mkdtemp, rm } from "node:fs/promises"; -import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { createTestTempDirectory } from "../tests/fixtures/temporaryDirectory.js"; import { createDoctorHostFixture } from "./application/Doctor.fixture.js"; import * as macHopperInstaller from "./application/MacHopper.js"; @@ -47,7 +46,7 @@ it.each([undefined, "/caller/tools with spaces/ilspycmd"])( ); it("plans setup and uninstall against selected home and client overrides", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-selected-setup-")); + const root = await createTestTempDirectory("rea-selected-setup-"); const environment = { HOME: join(root, "selected-home"), USERPROFILE: join(root, "selected-home"), @@ -57,51 +56,47 @@ it("plans setup and uninstall against selected home and client overrides", async vi.stubEnv("HOME", join(root, "ambient-home")); vi.stubEnv("CODEX_HOME", join(root, "ambient-codex")); vi.stubEnv("npm_command", "other"); - try { - const doctor = createDoctorHostFixture({ homeDirectory: environment.HOME }); - const host = systemSetupHost(doctor, environment); - const result = await runSetup( - { - ...options(false), - dryRun: true, - clientIds: ["codex"], - installSkill: true, - }, - host, - ); - expect(result.status).toBe("planned"); - expect(result.plannedActions).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - id: "configure_client:codex", - target: join(environment.CODEX_HOME, "config.toml"), - }), - expect.objectContaining({ - id: "install_skill", - target: join( - environment.HOME, - ".agents/skills", - PRODUCT_IDENTITY.skillName, - ), - }), - ]), - ); - expect(host.registrationCommand).toEqual( - currentClientRegistrationCommand({ platform: "win32", environment }), - ); - const clients = await systemUninstallHost( - environment.HOME, - undefined, - environment, - doctor.platform, - ).clients(); - expect(clients.find(({ name }) => name === "codex")?.configPath).toBe( - join(environment.CODEX_HOME, "config.toml"), - ); - expect(JSON.stringify(result)).not.toContain("ambient-"); - } finally { - await rm(root, { recursive: true, force: true }); - } + const doctor = createDoctorHostFixture({ homeDirectory: environment.HOME }); + const host = systemSetupHost(doctor, environment); + const result = await runSetup( + { + ...options(false), + dryRun: true, + clientIds: ["codex"], + installSkill: true, + }, + host, + ); + expect(result.status).toBe("planned"); + expect(result.plannedActions).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + id: "configure_client:codex", + target: join(environment.CODEX_HOME, "config.toml"), + }), + expect.objectContaining({ + id: "install_skill", + target: join( + environment.HOME, + ".agents/skills", + PRODUCT_IDENTITY.skillName, + ), + }), + ]), + ); + expect(host.registrationCommand).toEqual( + currentClientRegistrationCommand({ platform: "win32", environment }), + ); + const clients = await systemUninstallHost( + environment.HOME, + undefined, + environment, + doctor.platform, + ).clients(); + expect(clients.find(({ name }) => name === "codex")?.configPath).toBe( + join(environment.CODEX_HOME, "config.toml"), + ); + expect(JSON.stringify(result)).not.toContain("ambient-"); }); it("composes provider diagnostics from selected configuration rather than ambient configuration", async () => { @@ -151,7 +146,7 @@ it("includes the macOS Hopper installer diagnostic in setup remediation", async }); it("preserves a validated selected JEB endpoint in setup registrations without claiming live readiness", async () => { - const root = await mkdtemp(join(tmpdir(), "rea-jeb-setup-")); + const root = await createTestTempDirectory("rea-jeb-setup-"); const endpoint = "http://127.0.0.1:8425/mcp/"; const ambientEndpoint = "http://127.0.0.1:8426/mcp"; vi.stubEnv("REA_JEB_MCP_URL", ambientEndpoint); @@ -186,7 +181,6 @@ it("preserves a validated selected JEB endpoint in setup registrations without c ); } finally { vi.unstubAllEnvs(); - await rm(root, { recursive: true, force: true }); } }); diff --git a/src/windows/WindowsHandleClose.test.ts b/src/windows/WindowsHandleClose.test.ts index b51c7ab1cf..b94652e3e1 100644 --- a/src/windows/WindowsHandleClose.test.ts +++ b/src/windows/WindowsHandleClose.test.ts @@ -1,10 +1,9 @@ import { execFile, spawnSync } from "node:child_process"; -import { mkdtemp, rm } from "node:fs/promises"; -import { tmpdir } from "node:os"; import { join } from "node:path"; import { promisify } from "node:util"; import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; const run = promisify(execFile); const compilerProbe = spawnSync("g++", ["--version"], { stdio: "ignore" }); @@ -22,32 +21,28 @@ describe.skipIf(process.platform === "win32" && compilerMissing)( new URL("../../native/windows/src/", import.meta.url), ); const source = join(include, "handle_close_test.cc"); - const directory = await mkdtemp(join(tmpdir(), "rea-handle-close-")); + const directory = await createTestTempDirectory("rea-handle-close-"); const binary = join(directory, "handle-close-test"); - try { - await run( - "g++", - [ - "-std=c++17", - "-Wall", - "-Wextra", - "-Werror", - `-I${include}`, - source, - "-o", - binary, - ], - { encoding: "utf8", timeout: 60_000 }, - ); - const result = await run(binary, [], { - encoding: "utf8", - timeout: 30_000, - }); - expect(result.stdout).toBe(""); - expect(result.stderr).toBe(""); - } finally { - await rm(directory, { recursive: true, force: true }); - } + await run( + "g++", + [ + "-std=c++17", + "-Wall", + "-Wextra", + "-Werror", + `-I${include}`, + source, + "-o", + binary, + ], + { encoding: "utf8", timeout: 60_000 }, + ); + const result = await run(binary, [], { + encoding: "utf8", + timeout: 30_000, + }); + expect(result.stdout).toBe(""); + expect(result.stderr).toBe(""); }); }, );