fix(producer): download links serve only the render's own file, removed once fetched (#8673)

* fix(producer): download links serve only the render's own file, removed once fetched

A download opens the registered file without following links and checks its identity. Server-named outputs get a unique name, live in a private default folder, and are deleted after a full download or on token expiry. Confined requests refuse output folders another account can change.

* fix(producer): a caller's own output file is not held open after its render

Only a server-named output is pinned. A caller-named one keeps its dev:ino check from a stat at register, so a caller that reads its file from disk and deletes it frees the space at once. The folder refusal names the folder.
This commit is contained in:
Miguel Ángel
2026-11-24 09:18:17 +00:00
committed by GitHub
parent 903051c40b
commit 91027eafb5
4 changed files with 305 additions and 31 deletions
+1 -1
View File
@@ -229,7 +229,7 @@ except `/health` then requires `Authorization: Bearer <token>`, and the server r
start without one. A request's `projectDir` must resolve, symlinks included, inside
`projectsDir` (`PRODUCER_PROJECTS_DIR`, default: the working directory). Its `entryFile`
must stay inside that project, and `outputPath` must be inside `rendersDir`
(`PRODUCER_RENDERS_DIR`, default `/tmp`). `debug: true` is refused unless you set
(`PRODUCER_RENDERS_DIR`, default: a new private folder in the OS temp dir). `debug: true` is refused unless you set
`allowDebug` or `PRODUCER_ALLOW_DEBUG=1`. `createProducerApp` applies these path and
debug checks by default. `createRenderHandlers`, for mounting the handlers inside your own
trusted service, applies them only with `confineRequests: true`.
+1 -1
View File
@@ -51,7 +51,7 @@ except `/health` then requires `Authorization: Bearer <token>`, and the server r
start without one. A request's `projectDir` must resolve, symlinks included, inside
`projectsDir` (`PRODUCER_PROJECTS_DIR`, default: the working directory). Its `entryFile`
must stay inside that project, and `outputPath` must be inside `rendersDir`
(`PRODUCER_RENDERS_DIR`, default `/tmp`). `debug: true` is refused unless you set
(`PRODUCER_RENDERS_DIR`, default: a new private folder in the OS temp dir). `debug: true` is refused unless you set
`allowDebug` or `PRODUCER_ALLOW_DEBUG=1`. `createProducerApp` applies these path and
debug checks by default. `createRenderHandlers`, for mounting the handlers inside your own
trusted service, applies them only with `confineRequests: true`.
@@ -0,0 +1,179 @@
import {
chmodSync,
existsSync,
lstatSync,
mkdirSync,
mkdtempSync,
readdirSync,
readlinkSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { basename, dirname, join } from "node:path";
import type { Hono } from "hono";
import { afterEach, describe, expect, it, vi } from "vitest";
vi.mock("./services/renderOrchestrator.js", () => ({
RenderCancelledError: class extends Error {},
resolveRenderDebugDir: () => join(tmpdir(), "hf-server-outputs-debug"),
createRenderJob: (config: Record<string, unknown>) => ({
id: "job-id",
config,
progress: 0,
currentStage: "queued",
warnings: [],
}),
executeRenderJob: async (job: Record<string, unknown>, _projectDir: string, output: string) => {
writeFileSync(output, "rendered video");
job.outcome = "completed";
},
}));
import { createProducerApp, type HandlerOptions } from "./server.js";
const noUid = process.getuid === undefined;
function setup(options: HandlerOptions = {}) {
const root = mkdtempSync(join(tmpdir(), "hf-server-outputs-"));
const projectsDir = join(root, "projects");
const rendersDir = join(root, "renders");
mkdirSync(join(projectsDir, "demo"), { recursive: true });
writeFileSync(join(projectsDir, "demo", "index.html"), "<html></html>");
const secret = join(root, "secret.txt");
writeFileSync(secret, "not a render");
const app = createProducerApp({ projectsDir, rendersDir, ...options });
return { root, rendersDir, secret, app };
}
async function render(app: Hono, body: Record<string, unknown>) {
const res = await app.request("http://localhost:9847/render", {
method: "POST",
headers: { host: "localhost:9847" },
body: JSON.stringify({ projectDir: "demo", ...body }),
});
const json = (await res.json()) as { outputPath: string; outputUrl: string; error?: string };
return { status: res.status, ...json };
}
function download(app: Hono, url: string) {
return app.request(`http://localhost:9847${url}`, { headers: { host: "localhost:9847" } });
}
const settle = () => new Promise((done) => setImmediate(done));
describe("producer outputs: download tokens", () => {
it("serves a render the server named, then removes it once downloaded", async () => {
const { app, rendersDir } = setup();
const { status, outputPath, outputUrl } = await render(app, {});
expect(status).toBe(200);
expect(dirname(outputPath)).toBe(rendersDir);
const res = await download(app, outputUrl);
expect(res.status).toBe(200);
expect(await res.text()).toBe("rendered video");
await vi.waitFor(() => expect(existsSync(outputPath)).toBe(false));
expect((await download(app, outputUrl)).status).toBe(404);
});
it("gives two renders of one project a file each", async () => {
const { app } = setup();
const first = await render(app, {});
const second = await render(app, {});
expect(basename(first.outputPath)).toMatch(/^demo-/);
expect(second.outputPath).not.toBe(first.outputPath);
});
it("keeps an output the caller named after it is downloaded", async () => {
const { app, rendersDir } = setup();
const { outputPath, outputUrl } = await render(app, {
outputPath: join(rendersDir, "mine.mp4"),
});
expect(await (await download(app, outputUrl)).text()).toBe("rendered video");
await settle();
expect(existsSync(outputPath)).toBe(true);
expect(await (await download(app, outputUrl)).text()).toBe("rendered video");
});
it("removes a render the server named when its token expires", async () => {
const { app } = setup({ artifactTtlMs: 0 });
const { outputPath, outputUrl } = await render(app, {});
expect((await download(app, outputUrl)).status).toBe(404);
expect(existsSync(outputPath)).toBe(false);
});
it("never serves a link put at the output's name", async () => {
const { app, rendersDir, secret } = setup();
const { outputPath, outputUrl } = await render(app, { outputPath: join(rendersDir, "a.mp4") });
rmSync(outputPath);
symlinkSync(secret, outputPath);
const res = await download(app, outputUrl);
expect(res.status).toBe(404);
expect(await res.text()).not.toContain("not a render");
});
it("never serves another file put at the name of a render the server named", async () => {
const { app } = setup();
const { outputPath, outputUrl } = await render(app, {});
rmSync(outputPath);
writeFileSync(outputPath, "someone else's file");
const res = await download(app, outputUrl);
expect(res.status).toBe(404);
expect(await res.text()).not.toContain("someone else's file");
});
});
describe.skipIf(!existsSync("/proc/self/fd"))("producer outputs: open files", () => {
it("holds nothing open on an output the caller named, so deleting it frees the space", async () => {
const { app, rendersDir } = setup();
const { outputPath } = await render(app, { outputPath: join(rendersDir, "theirs.mp4") });
rmSync(outputPath);
const open = readdirSync("/proc/self/fd").map((fd) => {
try {
return readlinkSync(join("/proc/self/fd", fd));
} catch {
return "";
}
});
expect(open.filter((target) => target.startsWith(outputPath))).toEqual([]);
});
});
describe.skipIf(noUid)("producer outputs: renders folder", () => {
const envBefore = process.env.PRODUCER_RENDERS_DIR;
afterEach(() => {
if (envBefore === undefined) delete process.env.PRODUCER_RENDERS_DIR;
else process.env.PRODUCER_RENDERS_DIR = envBefore;
});
it("refuses an output folder another account can change, and creates nothing", async () => {
const { app, rendersDir } = setup();
const shared = join(rendersDir, "shared");
mkdirSync(shared, { recursive: true });
chmodSync(shared, 0o777);
const { status, error } = await render(app, { outputPath: join(shared, "sub", "x.mp4") });
expect(status).toBe(400);
expect(error).toContain(`another account can change ${shared}`);
expect(existsSync(join(shared, "sub"))).toBe(false);
});
it("still renders straight into a shared sticky root such as /tmp", async () => {
const root = mkdtempSync(join(tmpdir(), "hf-server-outputs-sticky-"));
chmodSync(root, 0o1777);
const { app } = setup({ rendersDir: root });
const { status } = await render(app, { outputPath: join(root, "x.mp4") });
expect(status).toBe(200);
});
it("defaults to a private renders folder of its own, not the shared temp dir", async () => {
delete process.env.PRODUCER_RENDERS_DIR;
const { app } = setup({ rendersDir: undefined });
const { status, outputPath } = await render(app, {});
expect(status).toBe(200);
const folder = dirname(outputPath);
expect(folder).not.toBe(tmpdir());
expect(folder).not.toBe("/tmp");
expect(lstatSync(folder).mode & 0o077).toBe(0);
});
});
+124 -29
View File
@@ -19,15 +19,21 @@ import {
type ExpectedOutputDimensions,
} from "./services/render/outputDimensions.js";
import {
type BigIntStats,
closeSync,
constants as fsConstants,
existsSync,
fstatSync,
lstatSync,
mkdirSync,
openSync,
statSync,
mkdtempSync,
writeFileSync,
rmSync,
createReadStream,
} from "node:fs";
import { resolve, dirname, join } from "node:path";
import { basename, resolve, dirname, join } from "node:path";
import { tmpdir } from "node:os";
import { parseArgs } from "node:util";
import { isIP } from "node:net";
@@ -41,6 +47,7 @@ import {
referenceBackgroundResult,
} from "@hyperframes/engine";
import { isSafePath } from "@hyperframes/core/safe-path";
import { foreignWritablePath } from "@hyperframes/core/cache-dir";
import {
RenderCancelledError,
createRenderJob,
@@ -76,7 +83,7 @@ export interface HandlerOptions {
logger?: ProducerLogger;
/** Extract or generate a request ID. Defaults to x-request-id header or random UUID. */
getRequestId?: (c: Context) => string;
/** Directory for rendered output files. Defaults to PRODUCER_RENDERS_DIR or /tmp. */
/** Directory for rendered output files. Defaults to PRODUCER_RENDERS_DIR or a new private temp folder. */
rendersDir?: string;
/** Prefix for output URLs in responses. Default: "/outputs". */
outputUrlPrefix?: string;
@@ -392,18 +399,45 @@ function resolvePreparedRenderOutput(
rendersDir: string,
log: ProducerLogger,
confineOutput: boolean,
): { input: RenderInput; cleanupProjectDir?: string; absoluteOutputPath: string } {
): {
input: RenderInput;
cleanupProjectDir?: string;
absoluteOutputPath: string;
serverNamed: boolean;
} {
const { input, cleanupProjectDir } = prepared;
const absoluteOutputPath = resolveOutputPath(input.projectDir, input.outputPath, rendersDir, log);
const serverNamed = input.outputPath == null;
const outputCandidate =
input.outputPath ??
join(rendersDir, `${basename(resolve(input.projectDir))}-${crypto.randomUUID()}.mp4`);
const absoluteOutputPath = resolveOutputPath(input.projectDir, outputCandidate, rendersDir, log);
const outputDir = dirname(absoluteOutputPath);
if (confineOutput) {
mkdirSync(rendersDir, { recursive: true });
mkdirSync(rendersDir, { recursive: true, mode: SERVER_FOLDER_MODE });
if (!isSafePath(rendersDir, absoluteOutputPath)) {
throw new Error("outputPath must be inside the renders directory");
}
const foreign = folderAnotherAccountCanChange(outputDir, rendersDir);
if (foreign) {
throw new Error(
`outputPath must be in a folder only this server's account can change; another account can change ${foreign}`,
);
}
}
const outputDir = dirname(absoluteOutputPath);
if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
return { input, cleanupProjectDir, absoluteOutputPath };
if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true, mode: SERVER_FOLDER_MODE });
return { input, cleanupProjectDir, absoluteOutputPath, serverNamed };
}
const STICKY_BIT = 0o1000;
/** Never group- or world-writable, whatever the umask, or the folder check below refuses the server's own folders. */
const SERVER_FOLDER_MODE = 0o755;
/** A shared sticky root such as /tmp is allowed; any folder below it must be this account's alone. */
function folderAnotherAccountCanChange(dir: string, rendersDir: string): string | undefined {
const foreign = foreignWritablePath(dir, rendersDir);
const stickyRoot =
foreign === resolve(rendersDir) && (lstatSync(foreign).mode & STICKY_BIT) !== 0;
return stickyRoot ? undefined : foreign;
}
type PreparedRenderJob =
@@ -412,6 +446,7 @@ type PreparedRenderJob =
input: RenderInput;
cleanupProjectDir?: string;
absoluteOutputPath: string;
serverNamed: boolean;
}
| { error: string };
@@ -646,37 +681,90 @@ function resolveOutputPath(
// ---------------------------------------------------------------------------
interface OutputArtifact {
path: string;
identity: string | undefined;
/** A server-named file is held open until its token is forgotten, so its inode number cannot pass on. */
pin: number | undefined;
/** The server chose the name: the file goes once downloaded or expired. A caller's outputPath stays. */
serverNamed: boolean;
expiresAtMs: number;
}
function createArtifactStore(ttlMs: number) {
function createArtifactStore(ttlMs: number, log: ProducerLogger) {
const artifacts = new Map<string, OutputArtifact>();
const forget = (token: string): void => {
const artifact = artifacts.get(token);
if (!artifact) return;
artifacts.delete(token);
if (artifact.pin !== undefined) closeSync(artifact.pin);
if (!artifact.serverNamed) return;
try {
rmSync(artifact.path, { force: true });
} catch (error) {
log.warn("Failed to remove output artifact", {
path: artifact.path,
error: error instanceof Error ? error.message : String(error),
});
}
};
const cleanup = setInterval(() => {
const now = Date.now();
for (const [token, artifact] of artifacts.entries()) {
if (artifact.expiresAtMs <= now) {
artifacts.delete(token);
}
if (artifact.expiresAtMs <= now) forget(token);
}
}, 60_000);
cleanup.unref();
return {
register(path: string): string {
register(path: string, serverNamed: boolean): string {
// A caller's file is its to delete after reading it from disk, so only a server-named file is held open.
const pin = serverNamed ? openNoFollow(path) : undefined;
const stat =
pin === undefined
? lstatSync(path, { bigint: true, throwIfNoEntry: false })
: fstatSync(pin, { bigint: true });
const identity = stat && fileIdentity(stat);
const token = crypto.randomUUID();
artifacts.set(token, { path, expiresAtMs: Date.now() + ttlMs });
artifacts.set(token, { path, identity, pin, serverNamed, expiresAtMs: Date.now() + ttlMs });
return token;
},
get(token: string): OutputArtifact | undefined {
return artifacts.get(token);
},
delete(token: string) {
artifacts.delete(token);
const artifact = artifacts.get(token);
if (artifact && artifact.expiresAtMs <= Date.now()) {
forget(token);
return undefined;
}
return artifact;
},
forget,
};
}
function openArtifact(artifact: OutputArtifact): number | undefined {
const fd = openNoFollow(artifact.path);
if (fd === undefined) return undefined;
const stat = fstatSync(fd, { bigint: true });
if (stat.isFile() && fileIdentity(stat) === artifact.identity) return fd;
closeSync(fd);
return undefined;
}
/** Undefined when nothing, or a link, is at the name; any other failure to open is a real error. */
function openNoFollow(path: string): number | undefined {
try {
return openSync(path, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "ENOENT" || code === "ELOOP" || code === "ENOTDIR") return undefined;
throw error;
}
}
function fileIdentity(stat: BigIntStats): string {
return `${stat.dev}:${stat.ino}`;
}
function cleanupTempDir(dir: string | undefined, log: ProducerLogger): void {
if (!dir) return;
try {
@@ -831,11 +919,14 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandle
const getRequestId =
options.getRequestId ?? ((c: Context) => c.req.header("x-request-id") || crypto.randomUUID());
const outputUrlPrefix = options.outputUrlPrefix ?? "/outputs";
const rendersDir = options.rendersDir ?? process.env.PRODUCER_RENDERS_DIR ?? "/tmp";
const rendersDir =
options.rendersDir ??
process.env.PRODUCER_RENDERS_DIR ??
mkdtempSync(join(tmpdir(), "hyperframes-renders-"));
const policy = options.confineRequests ? resolveRenderRequestPolicy(options) : undefined;
const artifactTtlMs =
options.artifactTtlMs ?? Number(process.env.PRODUCER_OUTPUT_ARTIFACT_TTL_MS || 15 * 60 * 1000);
const store = createArtifactStore(artifactTtlMs);
const store = createArtifactStore(artifactTtlMs, log);
const maxConcurrentRenders =
options.maxConcurrentRenders ?? Number(process.env.PRODUCER_MAX_CONCURRENT_RENDERS || 2);
const renderSemaphore = new Semaphore(maxConcurrentRenders);
@@ -913,7 +1004,7 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandle
if ("error" in preparedJob) {
return c.json({ success: false, requestId, error: preparedJob.error }, 400);
}
const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
const { job, input, cleanupProjectDir, absoluteOutputPath, serverNamed } = preparedJob;
const release = await renderSemaphore.acquire();
@@ -934,7 +1025,7 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandle
const fileSize = outputFileSize(absoluteOutputPath);
const durationMs = Date.now() - t0;
const outputToken = store.register(absoluteOutputPath);
const outputToken = store.register(absoluteOutputPath, serverNamed);
const outputUrl = `${outputUrlPrefix}/${outputToken}`;
log.info("render completed", {
requestId,
@@ -1012,7 +1103,7 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandle
});
return;
}
const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
const { job, input, cleanupProjectDir, absoluteOutputPath, serverNamed } = preparedJob;
log.info("render-stream started", { requestId, projectDir: input.projectDir });
const abortController = new AbortController();
@@ -1046,7 +1137,7 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandle
clearInterval(keepalive);
const fileSize = outputFileSize(absoluteOutputPath);
const outputToken = store.register(absoluteOutputPath);
const outputToken = store.register(absoluteOutputPath, serverNamed);
const outputUrl = `${outputUrlPrefix}/${outputToken}`;
log.info("render-stream completed", { requestId, fileSize, perf: job.perfSummary ?? null });
await stream.writeSSE({
@@ -1092,15 +1183,19 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandle
if (!artifact) {
return c.json({ success: false, error: "Output artifact not found or expired" }, 404);
}
if (!existsSync(artifact.path)) {
store.delete(token);
const fd = openArtifact(artifact);
if (fd === undefined) {
store.forget(token);
return c.json({ success: false, error: "Output artifact file missing" }, 404);
}
const stats = statSync(artifact.path);
return new Response(createReadStream(artifact.path) as unknown as ReadableStream, {
const { size } = fstatSync(fd);
const body = createReadStream("", { fd });
// Removed once read to the end; a read that stops early leaves it until the token expires.
if (artifact.serverNamed) body.once("end", () => store.forget(token));
return new Response(body as unknown as ReadableStream, {
headers: {
"content-type": "video/mp4",
"content-length": String(stats.size),
"content-length": String(size),
"cache-control": "no-store",
},
});