Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/packages/aws-lambda.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ The handler uses `@sparticuz/chromium` by default, with a build-time fallback fo

The handler sets `PRODUCER_RESTRICT_PAGE_NETWORK=true` unless the function already sets it, so a rendered page reaches only its own project files and public internet addresses. Loopback, private, link-local and IPv6 addresses are refused for anything the page loads. An asset on a VPC-only host or behind private DNS is missing from the video.

Keep it on when you render compositions you did not write. To turn it off, set `PRODUCER_RESTRICT_PAGE_NETWORK=false` in the function's environment.
Keep it on when you render compositions you did not write. To turn it off, set `PRODUCER_RESTRICT_PAGE_NETWORK=false` in the function's environment. Only `false`, `0`, `no` or `off` turn it off. Any other value keeps it on, and a value the handler does not recognise logs a warning.

## Using the SDK

Expand Down
9 changes: 9 additions & 0 deletions docs/packages/producer.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,15 @@ address a name resolves to and connects to the address it checked. A refused req
fails like any other unreachable asset. Leave it unset for local renders that load
assets from your own machine or network.

The setting accepts `true`, `1`, `yes` or `on` to turn the restriction on and `false`, `0`,
`no` or `off` to leave it off, in any letter case. Any other value turns it on and logs a
warning, so a misspelled value never leaves a render service open.

With the restriction on, a video or audio URL is downloaded through the same address
checks before FFmpeg reads it. A file FFmpeg does read by URL, such as a signed storage
URL for a project's video, must be a self-contained container like MP4, WebM or WAV. A
playlist, manifest or concat list under a media file name is refused.

If your network routes a range that is not a private one, such as a cluster's pod range,
add it with `PRODUCER_NON_PUBLIC_CIDRS`, a comma-separated list like `192.160.0.0/16`. Asset
downloads and the render browser then refuse those addresses too. A malformed entry
Expand Down
34 changes: 33 additions & 1 deletion packages/engine/src/config.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { join } from "node:path";
import { tmpdir } from "node:os";
import {
Expand All @@ -14,6 +14,7 @@ import {
defaultExtractCacheDir,
EXTRACT_CACHE_DIR_DISABLED_ALIASES,
validateEngineConfigSnapshot,
resolveRestrictPageNetwork,
} from "./config.js";
import type { EngineConfig } from "./config.js";
import { isLowMemorySystem } from "./services/systemMemory.js";
Expand Down Expand Up @@ -1009,3 +1010,34 @@ describe("validateEngineConfigSnapshot fps", () => {
expect(() => validateEngineConfigSnapshot({ ...resolveConfig(), fps: 50 })).toThrow(/fps/);
});
});

describe("resolveRestrictPageNetwork", () => {
afterEach(() => {
vi.unstubAllEnvs();
vi.restoreAllMocks();
});

it.each(["true", "1", "TRUE", "yes", "On", " true\n"])("restricts for %j", (value) => {
vi.stubEnv("PRODUCER_RESTRICT_PAGE_NETWORK", value);
expect(resolveRestrictPageNetwork()).toBe(true);
});

it.each(["", " ", "false", "0", "NO", "off\n"])("stays open for %j", (value) => {
vi.stubEnv("PRODUCER_RESTRICT_PAGE_NETWORK", value);
expect(resolveRestrictPageNetwork()).toBe(false);
});

it("stays open when unset", () => {
vi.stubEnv("PRODUCER_RESTRICT_PAGE_NETWORK", undefined);
expect(resolveRestrictPageNetwork()).toBe(false);
});

it("restricts for an unrecognised value and warns once", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
vi.stubEnv("PRODUCER_RESTRICT_PAGE_NETWORK", "maybe");
expect(resolveRestrictPageNetwork()).toBe(true);
expect(resolveRestrictPageNetwork()).toBe(true);
expect(warn).toHaveBeenCalledTimes(1);
expect(warn).toHaveBeenCalledWith(expect.stringContaining("PRODUCER_RESTRICT_PAGE_NETWORK"));
});
});
18 changes: 17 additions & 1 deletion packages/engine/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -819,12 +819,28 @@ export function resolvePageNavigationTimeout(): number {
return Number.isFinite(parsed) ? parsed : DEFAULT_CONFIG.pageNavigationTimeout;
}

const RESTRICT_PAGE_NETWORK_ON = new Set(["true", "1", "yes", "on"]);
const RESTRICT_PAGE_NETWORK_OFF = new Set(["false", "0", "no", "off"]);
let warnedRestrictPageNetworkValue: string | undefined;

/**
* `PRODUCER_RESTRICT_PAGE_NETWORK=true`: the render page may reach only its own server and public addresses.
* Unset or blank is off. `true`, `1`, `yes` and `on` turn it on and `false`, `0`, `no` and `off` turn it off,
* in any letter case and with surrounding whitespace. Any other value restricts and logs a warning once.
* A property of the host (a shared render service), not of one render, so it stays out of EngineConfig snapshots.
*/
export function resolveRestrictPageNetwork(): boolean {
return process.env.PRODUCER_RESTRICT_PAGE_NETWORK === "true";
const raw = process.env.PRODUCER_RESTRICT_PAGE_NETWORK ?? "";
const value = raw.trim().toLowerCase();
if (value === "" || RESTRICT_PAGE_NETWORK_OFF.has(value)) return false;
if (RESTRICT_PAGE_NETWORK_ON.has(value)) return true;
if (warnedRestrictPageNetworkValue !== raw) {
warnedRestrictPageNetworkValue = raw;
console.warn(
`[hyperframes] PRODUCER_RESTRICT_PAGE_NETWORK=${JSON.stringify(raw)} is neither true nor false; the render network stays restricted.`,
);
}
return true;
}

export function resolveConfig(overrides?: Partial<EngineConfig>): EngineConfig {
Expand Down
2 changes: 2 additions & 0 deletions packages/engine/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export type {
export {
resolveConfig,
resolvePageNavigationTimeout,
resolveRestrictPageNetwork,
validateEngineConfigSnapshot,
DEFAULT_CONFIG,
scaleProtocolTimeoutForComposition,
Expand Down Expand Up @@ -422,6 +423,7 @@ export {
fetchPublicHttpsText,
isHttpUrl,
safeDownloadUrlIdentity,
isUrlNotPermittedError,
writeUrlDownloadTelemetry,
type SafeDownloadUrlIdentity,
type UrlDownloadOptions,
Expand Down
32 changes: 20 additions & 12 deletions packages/engine/src/utils/urlDownloader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,24 @@ export class UrlDownloadError extends Error {
}
}

const URL_NOT_PERMITTED = "Download URL is not permitted";
const REDIRECT_NOT_PERMITTED = "Download redirect target is not permitted";

function notPermittedError(redirect: boolean): UrlDownloadError {
return new UrlDownloadError(
"http_rejected",
false,
redirect ? REDIRECT_NOT_PERMITTED : URL_NOT_PERMITTED,
);
}

export function isUrlNotPermittedError(error: unknown): boolean {
return (
error instanceof UrlDownloadError &&
(error.message === URL_NOT_PERMITTED || error.message === REDIRECT_NOT_PERMITTED)
);
}

function classifyHttpFailure(status: number): UrlDownloadError {
// Response.statusText is remote-controlled and some CDNs/proxies echo the
// signed request URL into it. The numeric status is sufficient and bounded.
Expand Down Expand Up @@ -473,11 +491,7 @@ function assertAllowedDownloadUrl(url: string, redirect: boolean): void {
try {
assertPublicHttpsUrl(url);
} catch {
throw new UrlDownloadError(
"http_rejected",
false,
redirect ? "Download redirect target is not permitted" : "Download URL is not permitted",
);
throw notPermittedError(redirect);
}
}

Expand Down Expand Up @@ -525,13 +539,7 @@ async function fetchWithValidatedRedirects(
headers: { "accept-encoding": "identity" },
}).catch((error: unknown) => {
if (!refusedNonPublicAddress(error)) throw error;
throw new UrlDownloadError(
"http_rejected",
false,
redirects > 0
? "Download redirect target is not permitted"
: "Download URL is not permitted",
);
throw notPermittedError(redirects > 0);
});
if (!REDIRECT_STATUSES.has(response.status)) return { response, finalUrl: currentUrl };

Expand Down
69 changes: 57 additions & 12 deletions packages/engine/src/utils/urlInput.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { spawnSync } from "node:child_process";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
import { VideoSourceExtractionError } from "../services/videoFrameExtractor.js";
import { getFfmpegBinary, getFfprobeBinary } from "./ffmpegBinaries.js";
import { redactUrlQueriesInError, urlInputArgs } from "./urlInput.js";

const signed =
Expand Down Expand Up @@ -32,19 +37,59 @@ describe("urlInputArgs", () => {
expect(urlInputArgs(signed, { tool: "ffprobe", caBundles })).toEqual(verifyAndReconnect);
});

it("limits what an https input may open to HTTPS on a render service", () => {
vi.stubEnv("PRODUCER_RESTRICT_PAGE_NETWORK", "true");
try {
expect(urlInputArgs(signed, { tool: "ffprobe", caBundles })).toEqual([
...verifyAndReconnect,
"-protocol_whitelist",
"https,tls,tcp",
]);
expect(urlInputArgs("/plan/compiled/bg.mp4", { caBundles: [] })).toEqual([]);
} finally {
it.each(["true", "1", " TRUE\n"])(
"limits what an https input may open to HTTPS on a render service (%j)",
(flag) => {
vi.stubEnv("PRODUCER_RESTRICT_PAGE_NETWORK", flag);
try {
expect(urlInputArgs(signed, { tool: "ffprobe", caBundles })).toEqual([
...verifyAndReconnect,
"-protocol_whitelist",
"https,tls,tcp",
"-format_whitelist",
expect.any(String),
]);
expect(urlInputArgs("/plan/compiled/bg.mp4", { caBundles: [] })).toEqual([]);
} finally {
vi.unstubAllEnvs();
}
},
);

it.skipIf(spawnSync(getFfprobeBinary(), ["-version"]).status !== 0)(
"on a render service lets ffprobe open a video but not a playlist or concat list named .mp4",
() => {
vi.stubEnv("PRODUCER_RESTRICT_PAGE_NETWORK", "true");
const args = urlInputArgs(signed, { caBundles });
vi.unstubAllEnvs();
}
});
const formats = args[args.indexOf("-format_whitelist") + 1]!;
const dir = mkdtempSync(join(tmpdir(), "hf-url-input-"));
try {
const video = join(dir, "clip.mp4");
const lavfi = ["-f", "lavfi", "-i", "testsrc2=size=32x32:rate=5:duration=1"];
spawnSync(getFfmpegBinary(), ["-v", "error", "-y", ...lavfi, "-c:v", "mpeg4", video]);
const playlist = join(dir, "playlist.mp4");
writeFileSync(playlist, "#EXTM3U\n#EXTINF:1,\nhttps://127.0.0.1:9/a.ts\n#EXT-X-ENDLIST\n");
const concat = join(dir, "concat.mp4");
writeFileSync(concat, "ffconcat version 1.0\nfile https://127.0.0.1:9/a.mp4\n");
const probe = (path: string) =>
spawnSync(getFfprobeBinary(), [
"-v",
"error",
"-format_whitelist",
formats,
"-show_format",
"--",
path,
]).status;
expect(probe(video)).toBe(0);
expect(probe(playlist)).not.toBe(0);
expect(probe(concat)).not.toBe(0);
} finally {
rmSync(dir, { recursive: true, force: true });
}
},
);

it("adds nothing for local paths and plain http", () => {
expect(urlInputArgs("/plan/compiled/bg.mp4", { caBundles: [] })).toEqual([]);
Expand Down
11 changes: 7 additions & 4 deletions packages/engine/src/utils/urlInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ const CA_BUNDLES = [
// Lambda's ffprobe 4.0 accepts these but not -reconnect_on_network_error; a stalled read fails after 30 s.
const RECONNECT_ARGS = ["-rw_timeout", "30000000", "-reconnect", "1", "-reconnect_delay_max", "2"];

/** ffmpeg and ffprobe skip TLS certificate checks unless told to; an https input must be verified, and on a render service whatever it names must be HTTPS too. */
const SELF_CONTAINED_FORMATS =
"mov,matroska,mxf,avi,mpeg,mpegts,mpegvideo,flv,asf,ogg,wav,mp3,aac,flac,aiff,gif,image2,png_pipe,jpeg_pipe,webp_pipe,bmp_pipe,tiff_pipe";

/** ffmpeg and ffprobe skip TLS certificate checks unless told to; an https input must be verified, and on a render service be a self-contained container that names only HTTPS. */
export function urlInputArgs(
input: string,
{
Expand All @@ -28,8 +31,8 @@ export function urlInputArgs(
);
}
const networkRetry = tool === "ffmpeg" ? ["-reconnect_on_network_error", "1"] : [];
const nestedOpensStayOnHttps = resolveRestrictPageNetwork()
? ["-protocol_whitelist", "https,tls,tcp"]
const renderServiceLimits = resolveRestrictPageNetwork()
? ["-protocol_whitelist", "https,tls,tcp", "-format_whitelist", SELF_CONTAINED_FORMATS]
: [];
return [
"-tls_verify",
Expand All @@ -38,7 +41,7 @@ export function urlInputArgs(
caFile,
...RECONNECT_ARGS,
...networkRetry,
...nestedOpensStayOnHttps,
...renderServiceLimits,
];
}

Expand Down
7 changes: 6 additions & 1 deletion packages/producer/src/services/distributed/plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ import {
withChunkCaptureCost,
} from "./chunkWeights.js";
import { runAudioStage } from "../render/stages/audioStage.js";
import { audioWorkDir } from "../render/shared.js";
import { runCompileStage } from "../render/stages/compileStage.js";
import {
appendVideoAudioFromProbe,
Expand Down Expand Up @@ -1874,7 +1875,11 @@ export async function buildPlanAudio(
});
try {
let stageStarted = Date.now();
await appendVideoAudioFromProbe(c);
await appendVideoAudioFromProbe({
...c,
downloadDir: audioWorkDir(c.workDir),
signal: c.abortSignal,
});
logPlanStage(c.log, "extract", stageStarted);
stageStarted = Date.now();
const mixed = await mixPlanAudio(c, c.compiledDir);
Expand Down
4 changes: 4 additions & 0 deletions packages/producer/src/services/render/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ export interface CompositionMetadata {
* slightly different `end` / `mediaStart` / `volume` than the compiled
* HTML and we want to ignore sub-millisecond float noise.
*/
export function audioWorkDir(workDir: string): string {
return join(workDir, "audio-work");
}

export const BROWSER_MEDIA_EPSILON = 0.0001;

/**
Expand Down
4 changes: 2 additions & 2 deletions packages/producer/src/services/render/stages/audioStage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import {
type AudioProcessingFailure,
type MixResult,
} from "@hyperframes/engine";
import type { CompositionMetadata } from "../shared.js";
import { audioWorkDir, type CompositionMetadata } from "../shared.js";
import type { ProducerLogger } from "../../../logger.js";
import { encoderFailureError } from "../encoderInterruption.js";
import { limitDeliveryPeaks } from "../audioDeliveryLimit.js";
Expand Down Expand Up @@ -202,7 +202,7 @@ async function mixAudioForDelivery(
audioResult = await processCompositionAudio(
audios,
projectDir,
join(workDir, "audio-work"),
audioWorkDir(workDir),
audioOutputPath,
duration,
abortSignal,
Expand Down
Loading
Loading