fix(desktop): admit build export folders before running the in-computer export (#11307)

* fix(desktop): output-directory admission agrees with SafeOutputTree for #9291

* fix(desktop): admit build export and witness folders through planOutputTree

Main now owns new-or-empty folder admission in planOutputTree, so the
separate admitNewOrEmptyOutputDirectory check is superseded. Keep the
remaining parts of #9291 on that owner:

- export_build_environment plans the caller's directory before running
  export-desktop-application in the build computer.
- planOutputTree refuses a folder, or the nearest existing ancestor of an
  absent one, that the host cannot write, so check_build_task refuses it at
  the seed instead of after the recording ends.
- writeOutputTree creates missing parents through SafeOutputTree's
  createParents, which maps a file or denied parent to a destination
  refusal, instead of a raw mkdir before admission.

Restore main's withheld-copy test, which this design leaves unchanged.

* fix(desktop): require a readable parent where publication syncs it

SafeOutputTree.commit opens the output folder's parent read-only to sync
it, so a write-only parent passed admission and failed only at
publication. planOutputTree now also requires read access on that parent
when it already exists.

---------

Co-authored-by: Phon <twilyt1@proton.me>
This commit is contained in:
morlutoandPhon authored and GitHub committed 2026-11-16 00:18:11 +08:00
1 parent 6a5121363c
commit 3fb17d72a9
5 files changed
+245 -9

No files matched your search

@@ -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);
});
@@ -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`,
@@ -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);
},
);
},
);
@@ -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);
}
},
);
+43 -5
View File
@@ -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<string> => {
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<DesktopOutputCompletion> => {
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;