Skip to content

Commit be1b9d4

Browse files
committed
fix: safely replace downloads and preserve destination modes
1 parent 132256d commit be1b9d4

3 files changed

Lines changed: 237 additions & 14 deletions

File tree

‎packages/runtime/src/utils/download.ts‎

Lines changed: 77 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,79 @@
11
import { httpTransport } from "bailian-cli-core";
2-
import { createWriteStream, mkdirSync, renameSync, unlinkSync } from "fs";
2+
import {
3+
chmodSync,
4+
copyFileSync,
5+
createWriteStream,
6+
existsSync,
7+
mkdirSync,
8+
renameSync,
9+
statSync,
10+
unlinkSync,
11+
} from "fs";
312
import { basename, dirname, join } from "path";
413
import { BailianError, ExitCode } from "bailian-cli-core";
514
import { createProgressBar } from "../output/progress.ts";
615
import type { ReadableStreamReadResult } from "stream/web";
716

8-
/** Replace dest with temp; Windows cannot rename over an existing path. */
9-
function publishDownloadedFile(tempPath: string, destPath: string): void {
10-
try {
17+
function errnoCode(error: unknown): string | undefined {
18+
if (error !== null && typeof error === "object" && "code" in error) {
19+
return (error as NodeJS.ErrnoException).code;
20+
}
21+
return undefined;
22+
}
23+
24+
/**
25+
* Publish temp over dest without unlinking dest first.
26+
* Existing dest is moved aside and restored if publish fails.
27+
*/
28+
function publishDownloadedFile(
29+
tempPath: string,
30+
destPath: string,
31+
preserveMode: number | undefined,
32+
): void {
33+
if (!existsSync(destPath)) {
1134
renameSync(tempPath, destPath);
12-
} catch (error) {
13-
const code =
14-
error !== null && typeof error === "object" && "code" in error
15-
? (error as NodeJS.ErrnoException).code
16-
: undefined;
17-
if (code === "EEXIST" || code === "EPERM") {
18-
unlinkSync(destPath);
35+
return;
36+
}
37+
38+
const backupPath = join(
39+
dirname(destPath),
40+
`.${basename(destPath)}.${process.pid}.${Date.now()}.bak`,
41+
);
42+
renameSync(destPath, backupPath);
43+
44+
try {
45+
try {
1946
renameSync(tempPath, destPath);
20-
return;
47+
} catch (renameError) {
48+
const code = errnoCode(renameError);
49+
// Windows cannot rename onto an existing name; EXDEV needs a copy.
50+
// Never unlink dest first — backup already holds the previous bytes.
51+
if (code === "EEXIST" || code === "EPERM" || code === "EXDEV") {
52+
copyFileSync(tempPath, destPath);
53+
try {
54+
unlinkSync(tempPath);
55+
} catch {
56+
/* best effort */
57+
}
58+
} else {
59+
throw renameError;
60+
}
61+
}
62+
63+
if (preserveMode !== undefined) {
64+
chmodSync(destPath, preserveMode);
65+
}
66+
unlinkSync(backupPath);
67+
} catch (error) {
68+
try {
69+
if (existsSync(destPath)) unlinkSync(destPath);
70+
} catch {
71+
/* best effort */
72+
}
73+
try {
74+
renameSync(backupPath, destPath);
75+
} catch {
76+
/* best effort */
2177
}
2278
throw error;
2379
}
@@ -39,6 +95,14 @@ export async function downloadFile(
3995
if (!reader) throw new BailianError("No response body", ExitCode.GENERAL);
4096

4197
mkdirSync(dirname(destPath), { recursive: true });
98+
99+
let preserveMode: number | undefined;
100+
try {
101+
preserveMode = statSync(destPath).mode & 0o7777;
102+
} catch {
103+
// Destination does not exist yet.
104+
}
105+
42106
// Same-directory temp so rename stays on one filesystem; never truncate dest until publish.
43107
const tempPath = join(
44108
dirname(destPath),
@@ -90,7 +154,7 @@ export async function downloadFile(
90154
}
91155

92156
try {
93-
publishDownloadedFile(tempPath, destPath);
157+
publishDownloadedFile(tempPath, destPath, preserveMode);
94158
} catch (error) {
95159
try {
96160
unlinkSync(tempPath);
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
import { afterEach, beforeEach, expect, test, vi } from "vite-plus/test";
2+
import {
3+
chmodSync,
4+
mkdtempSync,
5+
readFileSync,
6+
readdirSync,
7+
rmSync,
8+
statSync,
9+
writeFileSync,
10+
} from "node:fs";
11+
import { tmpdir } from "node:os";
12+
import { join } from "node:path";
13+
import { httpTransport } from "bailian-cli-core";
14+
import { downloadFile } from "../src/utils/download.ts";
15+
16+
// Publish-path failures (thrown after the body is fully downloaded) must never
17+
// lose the previous destination bytes. renameSync/copyFileSync errnos are
18+
// injected without touching real permissions: `renameCodes` is consumed in call
19+
// order, null lets the real rename run.
20+
const injection = vi.hoisted(() => ({
21+
renameCodes: [] as Array<string | null>,
22+
copyErrorCode: undefined as string | undefined,
23+
}));
24+
25+
vi.mock("fs", async (importOriginal) => {
26+
const actual = await importOriginal<typeof import("node:fs")>();
27+
const fail = (code: string, action: string): never => {
28+
const error = new Error(`injected ${code}: ${action}`) as NodeJS.ErrnoException;
29+
error.code = code;
30+
throw error;
31+
};
32+
return {
33+
...actual,
34+
renameSync: ((from: string, to: string) => {
35+
const code = injection.renameCodes.shift();
36+
if (code !== undefined && code !== null) fail(code, `rename ${from} -> ${to}`);
37+
return actual.renameSync(from, to);
38+
}) as typeof actual.renameSync,
39+
copyFileSync: ((from: string, to: string) => {
40+
if (injection.copyErrorCode !== undefined) {
41+
fail(injection.copyErrorCode, `copy ${from} -> ${to}`);
42+
}
43+
return actual.copyFileSync(from, to);
44+
}) as typeof actual.copyFileSync,
45+
};
46+
});
47+
48+
function serveBody(text: string): void {
49+
vi.spyOn(httpTransport, "fetch").mockResolvedValue(
50+
new Response(
51+
new ReadableStream({
52+
start(controller) {
53+
controller.enqueue(new TextEncoder().encode(text));
54+
controller.close();
55+
},
56+
}),
57+
{ headers: { "content-length": String(text.length) } },
58+
),
59+
);
60+
}
61+
62+
let directory = "";
63+
let destination = "";
64+
65+
beforeEach(() => {
66+
injection.renameCodes = [];
67+
injection.copyErrorCode = undefined;
68+
directory = mkdtempSync(join(tmpdir(), "bl-download-publish-"));
69+
destination = join(directory, "take.wav");
70+
writeFileSync(destination, "original-audio", { mode: 0o600 });
71+
chmodSync(destination, 0o600);
72+
});
73+
74+
afterEach(() => {
75+
vi.restoreAllMocks();
76+
rmSync(directory, { recursive: true, force: true });
77+
});
78+
79+
test("backup rename EPERM aborts publish with the destination untouched", async () => {
80+
serveBody("new-audio");
81+
injection.renameCodes = ["EPERM", "EIO"];
82+
await expect(
83+
downloadFile("https://example.invalid/file", destination, { quiet: true }),
84+
).rejects.toThrow("injected EPERM");
85+
expect(readFileSync(destination, "utf-8")).toBe("original-audio");
86+
expect(statSync(destination).mode & 0o777).toBe(0o600);
87+
expect(readdirSync(directory)).toEqual(["take.wav"]);
88+
});
89+
90+
test("publish rename EPERM then copy EIO restores the previous file", async () => {
91+
serveBody("new-audio");
92+
injection.renameCodes = [null, "EPERM"];
93+
injection.copyErrorCode = "EIO";
94+
await expect(
95+
downloadFile("https://example.invalid/file", destination, { quiet: true }),
96+
).rejects.toThrow("injected EIO");
97+
expect(readFileSync(destination, "utf-8")).toBe("original-audio");
98+
expect(statSync(destination).mode & 0o777).toBe(0o600);
99+
expect(readdirSync(directory)).toEqual(["take.wav"]);
100+
});
101+
102+
test("publish rename EIO without fallback restores the previous file", async () => {
103+
serveBody("new-audio");
104+
injection.renameCodes = [null, "EIO"];
105+
await expect(
106+
downloadFile("https://example.invalid/file", destination, { quiet: true }),
107+
).rejects.toThrow("injected EIO");
108+
expect(readFileSync(destination, "utf-8")).toBe("original-audio");
109+
expect(readdirSync(directory)).toEqual(["take.wav"]);
110+
});
111+
112+
test("publish rename EPERM falls back to copy and keeps the previous mode", async () => {
113+
serveBody("new-audio");
114+
injection.renameCodes = [null, "EPERM"];
115+
expect(await downloadFile("https://example.invalid/file", destination, { quiet: true })).toEqual({
116+
size: 9,
117+
});
118+
expect(readFileSync(destination, "utf-8")).toBe("new-audio");
119+
expect(statSync(destination).mode & 0o777).toBe(0o600);
120+
expect(readdirSync(directory)).toEqual(["take.wav"]);
121+
});

‎packages/runtime/tests/progress-output.test.ts‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
11
import { afterEach, expect, test, vi } from "vite-plus/test";
2-
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
2+
import {
3+
chmodSync,
4+
existsSync,
5+
mkdtempSync,
6+
readFileSync,
7+
readdirSync,
8+
rmSync,
9+
statSync,
10+
writeFileSync,
11+
} from "node:fs";
312
import { tmpdir } from "node:os";
413
import { join } from "node:path";
514
import { httpTransport, type Client, type Settings } from "bailian-cli-core";
@@ -147,6 +156,35 @@ test("successful download replaces destination via temp publish", async () => {
147156
}
148157
});
149158

159+
test("successful overwrite preserves the previous destination mode", async () => {
160+
const directory = mkdtempSync(join(tmpdir(), "bl-download-mode-"));
161+
const destination = join(directory, "take.wav");
162+
writeFileSync(destination, "original-audio", { mode: 0o600 });
163+
chmodSync(destination, 0o600);
164+
expect(statSync(destination).mode & 0o777).toBe(0o600);
165+
vi.spyOn(httpTransport, "fetch").mockResolvedValue(
166+
new Response(
167+
new ReadableStream({
168+
start(controller) {
169+
controller.enqueue(new TextEncoder().encode("new-audio"));
170+
controller.close();
171+
},
172+
}),
173+
{ headers: { "content-length": "9" } },
174+
),
175+
);
176+
try {
177+
expect(
178+
await downloadFile("https://example.invalid/file", destination, { quiet: true }),
179+
).toEqual({ size: 9 });
180+
expect(readFileSync(destination, "utf-8")).toBe("new-audio");
181+
expect(statSync(destination).mode & 0o777).toBe(0o600);
182+
expect(readdirSync(directory).filter((name) => name.endsWith(".bak"))).toEqual([]);
183+
} finally {
184+
rmSync(directory, { recursive: true, force: true });
185+
}
186+
});
187+
150188
test("poll uses the complete snapshot loader for completion and failure predicates", async () => {
151189
const firstPage = { status: "SUCCEEDED" };
152190
const completeSnapshot = { jobs: [firstPage, { status: "RUNNING" }] };

0 commit comments

Comments
 (0)