diff --git a/src/application/desktop/DesktopBuildExport.test.ts b/src/application/desktop/DesktopBuildExport.test.ts index ce7098dcb1..5b654c3227 100644 --- a/src/application/desktop/DesktopBuildExport.test.ts +++ b/src/application/desktop/DesktopBuildExport.test.ts @@ -1,5 +1,10 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; + import { expect, it } from "vitest"; +import { AnalysisInputError } from "../../domain/analysisErrorCore.js"; +import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; import { exportBuild } from "./DesktopBuildExport.js"; it.each([4, 8])( @@ -42,7 +47,7 @@ it.each([4, 8])( consents: [], }, { - directory: "/unused", + directory: join(await createTestTempDirectory("build-export-"), "out"), tasks: [ { task: { @@ -106,7 +111,7 @@ it.each([ consents: [], }, { - directory: "/unused", + directory: join(await createTestTempDirectory("build-export-"), "out"), tasks: [ { task: { @@ -137,3 +142,63 @@ it.each([ expect(observedTimeout).toBe(routeTimeout); }, ); + +it("refuses an unusable output folder before running anything in the computer", async () => { + const root = await createTestTempDirectory("build-export-"); + const file = join(root, "file"); + await writeFile(file, "file"); + let executions = 0; + const computer = { + exec: async () => { + executions += 1; + return { + exit_code: 0, + stdout: "{}\n", + stderr: "", + timed_out: false, + truncated: false, + }; + }, + homeFiles: async () => new Map(), + redacted: (text: string) => text, + }; + const result = await exportBuild( + computer, + { + folder: ".rea-build/c", + attempt: 0, + extraPackages: [], + secrets: [], + keep: async (handle: string) => handle, + signIn: false, + consents: [], + }, + { + directory: file, + tasks: [ + { + task: { + name: "t", + prompt: "Task", + checks: [ + { + kind: "lines_present", + file: "f0.bin", + lines: ["x"], + }, + ], + }, + }, + ], + }, + new AbortController().signal, + ); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error).toBeInstanceOf(AnalysisInputError); + if (!(result.error instanceof AnalysisInputError)) return; + expect(result.error.issues).toContainEqual( + expect.objectContaining({ path: ["directory"], reason: "invalid_value" }), + ); + expect(executions).toBe(0); +}); diff --git a/src/application/desktop/DesktopBuildExport.ts b/src/application/desktop/DesktopBuildExport.ts index 99f28cfe3b..439febec15 100644 --- a/src/application/desktop/DesktopBuildExport.ts +++ b/src/application/desktop/DesktopBuildExport.ts @@ -372,6 +372,13 @@ export const exportBuild = async ( } | undefined; try { + // Admit the host folder by the rule the bundle is written under before + // running anything in the computer, so an unusable folder is refused + // before the in-computer export runs rather than when its bundle returns. + await planOutputTree(request.directory, { + operation: EXPORT, + field: "directory", + }); const argv = [ "export-desktop-application", `${folder}/capture`, diff --git a/src/application/desktop/DesktopBuildWitness.test.ts b/src/application/desktop/DesktopBuildWitness.test.ts index e19acc0608..23cb914cf1 100644 --- a/src/application/desktop/DesktopBuildWitness.test.ts +++ b/src/application/desktop/DesktopBuildWitness.test.ts @@ -1,4 +1,11 @@ -import { access, mkdir, readFile, stat, writeFile } from "node:fs/promises"; +import { + access, + mkdir, + readFile, + stat, + symlink, + writeFile, +} from "node:fs/promises"; import { join } from "node:path"; import { describe, expect, it, vi } from "vitest"; @@ -355,3 +362,70 @@ describe("published witness cancellation recovery", () => { }, ); }); + +// Mode bits do not bind root, so a read-only folder is admitted there. +const unwritable = process.getuid?.() === 0 ? [] : ["read-only folder"]; + +describe.skipIf(process.platform === "win32")( + "seed output folder admission", + () => { + it.each(["symlinked folder", ...unwritable])( + "refuses a %s before starting the recording, and leaves the witness open for a fresh seed", + async (kind) => { + const root = await createTestTempDirectory("witness-seed-"); + const refusedFolder = join(root, "refused"); + if (kind === "symlinked folder") { + const target = join(root, "target"); + await mkdir(target); + await symlink(target, refusedFolder); + } else await mkdir(refusedFolder, { mode: 0o500 }); + let recordings = 0; + const witness = new DesktopBuildWitness( + { + ...computer, + startRecording: () => { + recordings += 1; + return Promise.reject(new Error("unstarted")); + }, + } as WitnessedComputer, + new BuildComputerActionLog(), + SETTLE_TIMING, + { + bundle: { path: await createTestTempDirectory("witness-bundle-") }, + }, + ); + const signal = new AbortController().signal; + + const refusedSeed = await witness.check( + { task, stage: "seed", directory: refusedFolder }, + signal, + ); + expect(refusedSeed.ok).toBe(false); + if (refusedSeed.ok) return; + expect(refusedSeed.error).toBeInstanceOf(AnalysisInputError); + if (!(refusedSeed.error instanceof AnalysisInputError)) return; + expect(refusedSeed.error.issues).toContainEqual( + expect.objectContaining({ + path: ["directory"], + reason: "invalid_value", + }), + ); + expect(recordings).toBe(0); + + // The refused seed opened no witness, so a fresh seed with a usable + // folder passes the folder check and reaches the bundle-task + // comparison instead of a directory or already-open refusal. + const retry = await witness.check( + { task, stage: "seed", directory: join(root, "record") }, + signal, + ); + expect(retry.ok).toBe(false); + if (retry.ok) return; + expect(retry.error).toBeInstanceOf(AnalysisInputError); + if (!(retry.error instanceof AnalysisInputError)) return; + expect(retry.error.userMessage).toContain("bundle"); + expect(recordings).toBe(0); + }, + ); + }, +); diff --git a/src/application/desktop/DesktopOutputTree.test.ts b/src/application/desktop/DesktopOutputTree.test.ts index efb7bacbee..2b8a8dce20 100644 --- a/src/application/desktop/DesktopOutputTree.test.ts +++ b/src/application/desktop/DesktopOutputTree.test.ts @@ -1,4 +1,4 @@ -import { readdir, writeFile } from "node:fs/promises"; +import { chmod, mkdir, readdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect, it } from "vitest"; import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; @@ -52,3 +52,55 @@ it("refuses a regular file in the output parent path instead of failing a host w }); expect(await readdir(root)).toEqual(["file"]); }); + +it.skipIf(process.platform === "win32" || process.getuid?.() === 0)( + "refuses an unwritable folder or parent at planning, before anything is created", + async () => { + const root = await createTestTempDirectory("rea-output-unwritable-"); + const locked = join(root, "locked"); + await mkdir(locked, { mode: 0o500 }); + const refusal = { + operation: "export_build_environment", + field: "directory", + }; + for (const directory of [locked, join(locked, "nested", "output")]) { + const failure = await planOutputTree(directory, refusal).catch( + (cause: unknown) => cause, + ); + expect(failure).toMatchObject({ + _tag: "AnalysisInputError", + operation: refusal.operation, + issues: [expect.objectContaining({ path: [refusal.field] })], + }); + } + expect(await readdir(locked)).toEqual([]); + }, +); + +it.skipIf(process.platform === "win32" || process.getuid?.() === 0)( + "refuses a folder whose parent publication cannot open to sync", + async () => { + const root = await createTestTempDirectory("rea-output-unreadable-"); + const parent = join(root, "parent"); + await mkdir(join(parent, "empty"), { recursive: true }); + await chmod(parent, 0o300); + const refusal = { + operation: "export_build_environment", + field: "directory", + }; + try { + for (const directory of [join(parent, "empty"), join(parent, "absent")]) + await expect(planOutputTree(directory, refusal)).rejects.toMatchObject({ + _tag: "AnalysisInputError", + issues: [expect.objectContaining({ path: [refusal.field] })], + }); + // A parent publication creates itself is owner-only, so only the + // existing ancestor's write access matters there. + await expect( + planOutputTree(join(parent, "absent", "output"), refusal), + ).resolves.toMatchObject({ requested: join(parent, "absent", "output") }); + } finally { + await chmod(parent, 0o700); + } + }, +); diff --git a/src/application/desktop/DesktopOutputTree.ts b/src/application/desktop/DesktopOutputTree.ts index ead9ed8ab6..abf080b201 100644 --- a/src/application/desktop/DesktopOutputTree.ts +++ b/src/application/desktop/DesktopOutputTree.ts @@ -1,5 +1,6 @@ import { HOST_PLATFORM } from "../../platform/HostPlatform.js"; -import { lstat, mkdir, readdir } from "node:fs/promises"; +import { constants } from "node:fs"; +import { access, lstat, readdir } from "node:fs/promises"; import { basename, dirname, isAbsolute } from "node:path"; import { @@ -42,6 +43,22 @@ export interface DesktopOutputPlan { readonly physical: string; } +/** The closest existing directory above a canonical path whose leaf is absent. */ +const nearestExisting = async (physical: string): Promise => { + let current = dirname(physical); + for (;;) { + const found = await lstat(current).then( + () => true, + (cause: unknown) => { + if ((cause as NodeJS.ErrnoException).code === "ENOENT") return false; + throw cause; + }, + ); + if (found || dirname(current) === current) return current; + current = dirname(current); + } +}; + /** Establish destination identity before either output tree is created. */ export const planOutputTree = async ( requested: string, @@ -78,6 +95,30 @@ export const planOutputTree = async ( throw new SafeOutputTreeDestinationRefusal( "Output directory is not empty", ); + // Publication writes into the folder, or creates it (and any missing + // parents) under its nearest existing ancestor, then opens the folder's + // parent to sync it. Check those accesses now rather than only when the + // tree is written; parents publication creates itself are owner-only. + const parent = dirname(physical); + const writable = + existing === undefined ? await nearestExisting(physical) : physical; + await access(writable, constants.W_OK | constants.X_OK).catch( + (cause: unknown) => { + throw new SafeOutputTreeDestinationRefusal( + existing === undefined + ? "Output parent is not writable" + : "Output directory is not writable", + { cause }, + ); + }, + ); + if (existing !== undefined || writable === parent) + await access(parent, constants.R_OK).catch((cause: unknown) => { + throw new SafeOutputTreeDestinationRefusal( + "Output parent is not readable", + { cause }, + ); + }); return Object.freeze({ requested, physical }); } catch (cause: unknown) { const error = @@ -115,7 +156,6 @@ export const writeOutputTree = async ( ): Promise => { const cancelled = outputCancellation(refusal.operation, signal); if (cancelled !== undefined) throw cancelled; - await mkdir(dirname(plan.physical), { recursive: true, mode: 0o700 }); const resources = new ArtifactResourceScope(); let tree: SafeOutputTree | undefined; let outcome: @@ -126,9 +166,7 @@ export const writeOutputTree = async ( tree = await SafeOutputTree.create( plan.physical, HOST_PLATFORM.platform, - { - acceptExistingEmpty: true, - }, + { acceptExistingEmpty: true, createParents: true }, ); } catch (cause: unknown) { if (cause instanceof SafeOutputTreeCreationFailure) tree = cause.tree;