Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(render-farm): bound what a recording manifest can make the fleet fetch

Richie McIlroy1042c6e2a67a
diff --git a/apps/render-farm/README.md b/apps/render-farm/README.md
index f2366083c..5b86cd977 100644
--- a/apps/render-farm/README.md
+++ b/apps/render-farm/README.md
@@ -83,6 +83,9 @@ expires `hls/` and `jobs/` objects.
| `RF_LEAD_IN_SECONDS` | `4` | Length of the lead-in chunk |
| `RF_JOURNAL` | on | Resume unfinished jobs after a coordinator restart |
| `RF_MAX_ACTIVE_JOBS` | `32` | Further `POST /jobs` get `429` |
+| `RF_MAX_SOURCE_FILES` / `RF_MAX_SOURCE_BYTES` | `4096` / 256 GiB | Largest recording manifest a job accepts |
+| `RF_MAX_EXPORT_SECONDS` | 4 h | Longest export a job accepts |
+| `RF_SOURCE_KEY_PREFIXES` | none | Shared bucket prefixes a manifest may reference besides its own recording |
| `RF_JOB_STALL_MS` / `RF_JOB_RETENTION_MS` | 10 min / 1 h | Job watchdog and summary retention |
| `RF_STALL_MS` | `30000` | Worker engine watchdog |
| `RF_DRAIN_MS` | 15 min | Longest a `SIGTERM` drain may take |
diff --git a/apps/render-farm/package.json b/apps/render-farm/package.json
index 6a9f8bfe7..5da9d8eae 100644
--- a/apps/render-farm/package.json
+++ b/apps/render-farm/package.json
@@ -9,6 +9,6 @@
"typecheck": "tsc --noEmit"
},
"devDependencies": {
- "@types/bun": "latest"
+ "@types/bun": "1.4.0"
}
}
diff --git a/apps/render-farm/src/coordinator.test.ts b/apps/render-farm/src/coordinator.test.ts
index fb45e22d7..ea9112ab3 100644
--- a/apps/render-farm/src/coordinator.test.ts
+++ b/apps/render-farm/src/coordinator.test.ts
@@ -9,7 +9,7 @@ import * as planning from "./planning";
import * as protocol from "./protocol";
import * as recovery from "./recovery";
import { pickQueued } from "./scheduler";
-import { validateJobRequest } from "./validate";
+import * as validate from "./validate";
function harness() {
const objects = new Map<string, Uint8Array>();
@@ -53,7 +53,7 @@ function harness() {
const deps = {
timingSafeEqual,
randomUUID,
- validateJobRequest,
+ ...validate,
...fmp4,
...hls,
...mp4,
diff --git a/apps/render-farm/src/coordinator.ts b/apps/render-farm/src/coordinator.ts
index 1385704c1..e7c5f1fba 100644
--- a/apps/render-farm/src/coordinator.ts
+++ b/apps/render-farm/src/coordinator.ts
@@ -35,7 +35,12 @@ import {
} from "./recovery";
import { S3, s3ConfigFromEnv } from "./s3";
import { pickQueued as pickQueuedTask } from "./scheduler";
-import { validateJobRequest } from "./validate";
+import {
+ AUDIO_FILE,
+ checkManifestBounds,
+ sourceLimitsFromEnv,
+ validateJobRequest,
+} from "./validate";
const s3 = new S3(s3ConfigFromEnv());
const ENGINE_BIN = process.env.RF_ENGINE_BIN ?? "cap-render-farm";
@@ -380,6 +385,9 @@ async function mp4MetaRanges(key: string, size: number) {
let moovStart: number;
let moovBytes: Uint8Array;
if (location && "start" in location && location.start !== undefined) {
+ if (location.size > SOURCE_LIMITS.moovBytes) {
+ throw new Error(`${key} has a ${location.size} byte moov`);
+ }
moovStart = location.start;
moovBytes =
location.start + location.size <= head.byteLength
@@ -391,6 +399,9 @@ async function mp4MetaRanges(key: string, size: number) {
);
} else if (location && "next" in location && location.next !== undefined) {
// Moov after mdat (Cap's recorder): fetch the tail in one request.
+ if (size - location.next > SOURCE_LIMITS.moovBytes) {
+ throw new Error(`${key} has ${size - location.next} bytes after mdat`);
+ }
const tail = await s3.getRange(key, location.next, size - 1);
const found = locateMoov(tail, tail.byteLength);
if (!found || !("start" in found) || found.start === undefined) {
@@ -446,8 +457,21 @@ const SOURCE_KEY_PREFIXES = (process.env.RF_SOURCE_KEY_PREFIXES ?? "")
.split(",")
.filter(Boolean);
+const SOURCE_LIMITS = sourceLimitsFromEnv(process.env);
+
+/** Reads a small object whole, refusing one over `limit` bytes. */
+async function getBounded(key: string, limit: number) {
+ const bytes = await s3.getRange(key, 0, limit);
+ if (bytes.byteLength > limit) {
+ throw new Error(`${key} is larger than ${limit} bytes`);
+ }
+ return bytes;
+}
+
/** Manifests name local paths and bucket keys; neither may escape its scope. */
function checkManifest(manifest: Manifest, prefix: string) {
+ const bounds = checkManifestBounds(manifest, SOURCE_LIMITS);
+ if (bounds) throw new Error(bounds);
for (const file of manifest.files) {
const parts = file.path.split("/");
if (
@@ -472,7 +496,9 @@ async function sourceIndex(prefix: string): Promise<SourceIndex> {
process.env.RF_INDEX_CACHE !== "0" ? sourceIndexes.get(prefix) : undefined;
if (cached) return cached;
const manifest = JSON.parse(
- new TextDecoder().decode(await s3.get(`${prefix}/manifest.json`)),
+ new TextDecoder().decode(
+ await getBounded(`${prefix}/manifest.json`, SOURCE_LIMITS.metadataBytes),
+ ),
) as Manifest;
checkManifest(manifest, prefix);
const keyOf = (file: { path: string; key?: string }) =>
@@ -482,7 +508,9 @@ async function sourceIndex(prefix: string): Promise<SourceIndex> {
);
if (!metaFile) throw new Error("recording has no recording-meta.json");
const recordingMeta = JSON.parse(
- new TextDecoder().decode(await s3.get(keyOf(metaFile))),
+ new TextDecoder().decode(
+ await getBounded(keyOf(metaFile), SOURCE_LIMITS.metadataBytes),
+ ),
) as RecordingMeta;
const mediaMeta: SourceIndex["mediaMeta"] = new Map();
await Promise.all(
@@ -516,7 +544,7 @@ async function planJob(job: Job) {
file.path.endsWith(".mp4"),
);
const audioFiles = manifest.files.filter((file) =>
- /\.(ogg|m4a|wav|mp3|aac|opus|flac)$/i.test(file.path),
+ AUDIO_FILE.test(file.path),
);
const smallFiles = manifest.files.filter(
(file) => !mediaFiles.includes(file) && !audioFiles.includes(file),
@@ -590,6 +618,11 @@ async function planJob(job: Job) {
(request.frameLimit * SAMPLE_RATE) / job.fps,
);
}
+ if (probe.total_frames > job.fps * SOURCE_LIMITS.exportSeconds) {
+ throw new Error(
+ `export is ${Math.round(probe.total_frames / job.fps)} s (limit ${SOURCE_LIMITS.exportSeconds} s)`,
+ );
+ }
job.totalFrames = probe.total_frames;
job.totalSamples = probe.total_samples;
job.width = probe.width;
diff --git a/apps/render-farm/src/validate.test.ts b/apps/render-farm/src/validate.test.ts
index 4b2328b33..1b435617c 100644
--- a/apps/render-farm/src/validate.test.ts
+++ b/apps/render-farm/src/validate.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, test } from "bun:test";
-import { validateJobRequest } from "./validate";
+import {
+ checkManifestBounds,
+ sourceLimitsFromEnv,
+ validateJobRequest,
+} from "./validate";
describe("validateJobRequest", () => {
test("accepts a typical export", () => {
@@ -39,3 +43,68 @@ describe("validateJobRequest", () => {
expect(result as string).toContain(message);
});
});
+
+describe("checkManifestBounds", () => {
+ const limits = {
+ ...sourceLimitsFromEnv({}),
+ files: 4,
+ sourceBytes: 1000,
+ sidecarBytes: 100,
+ };
+ const file = (path: string, size: number) => ({ path, size });
+
+ test("accepts a manifest within its limits", () => {
+ expect(
+ checkManifestBounds(
+ {
+ files: [
+ file("recording-meta.json", 50),
+ file("content/segments/segment-0/display.mp4", 800),
+ file("content/segments/segment-0/audio-input.ogg", 120),
+ ],
+ },
+ limits,
+ ),
+ ).toBeNull();
+ });
+
+ test.each([
+ [{}, "no files list"],
+ [
+ { files: Array.from({ length: 5 }, (_, i) => file(`${i}.json`, 1)) },
+ "5 files",
+ ],
+ [
+ { files: [file("display.mp4", 999), file("camera.mp4", 2)] },
+ "recording is 1001 bytes",
+ ],
+ [{ files: [file("cursors/0.png", 101)] }, "cursors/0.png is 101 bytes"],
+ [{ files: [file("display.mp4", -1)] }, "non-negative integer"],
+ [{ files: [file("display.mp4", Number.NaN)] }, "non-negative integer"],
+ [{ files: [{ path: "", size: 1 }] }, "manifest paths"],
+ [{ files: [{ path: "a.json", size: 1, key: 5 }] }, "manifest key"],
+ [{ files: [null] }, "not an object"],
+ ])("rejects %j", (manifest, message) => {
+ expect(checkManifestBounds(manifest, limits)).toContain(message);
+ });
+
+ test("large video and audio files are bounded only by the total", () => {
+ expect(
+ checkManifestBounds(
+ { files: [file("display.mp4", 600), file("audio-input.ogg", 300)] },
+ limits,
+ ),
+ ).toBeNull();
+ });
+
+ test("environment overrides apply only to valid positive numbers", () => {
+ const parsed = sourceLimitsFromEnv({
+ RF_MAX_SOURCE_FILES: "10",
+ RF_MAX_SOURCE_BYTES: "-5",
+ RF_MAX_EXPORT_SECONDS: "abc",
+ });
+ expect(parsed.files).toBe(10);
+ expect(parsed.sourceBytes).toBe(256 * 2 ** 30);
+ expect(parsed.exportSeconds).toBe(4 * 3600);
+ });
+});
diff --git a/apps/render-farm/src/validate.ts b/apps/render-farm/src/validate.ts
index 6ff68a294..cc2ff26ca 100644
--- a/apps/render-farm/src/validate.ts
+++ b/apps/render-farm/src/validate.ts
@@ -77,3 +77,81 @@ export function validateJobRequest(body: unknown): JobRequest | string {
}
return request as JobRequest;
}
+
+/** Audio sources: fetched whole for Studio Sound, never byte-range indexed. */
+export const AUDIO_FILE = /\.(ogg|m4a|wav|mp3|aac|opus|flac)$/i;
+
+export type SourceLimits = {
+ /** Largest manifest.json or recording-meta.json read into memory. */
+ metadataBytes: number;
+ files: number;
+ /** Sum of every source file's declared size. */
+ sourceBytes: number;
+ /** Files other than video and audio, which every chunk fetches whole. */
+ sidecarBytes: number;
+ /** An MP4's moov box, or the file tail searched for it. */
+ moovBytes: number;
+ exportSeconds: number;
+};
+
+export function sourceLimitsFromEnv(
+ env: Record<string, string | undefined>,
+): SourceLimits {
+ const read = (name: string, fallback: number) => {
+ const value = Number(env[name]);
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+ };
+ return {
+ metadataBytes: 4 << 20,
+ files: read("RF_MAX_SOURCE_FILES", 4096),
+ sourceBytes: read("RF_MAX_SOURCE_BYTES", 256 * 2 ** 30),
+ sidecarBytes: 64 << 20,
+ moovBytes: 256 << 20,
+ exportSeconds: read("RF_MAX_EXPORT_SECONDS", 4 * 3600),
+ };
+}
+
+/**
+ * Bounds what one recording can make the coordinator and the fleet fetch and
+ * hold. Recordings are uploaded by users, so their manifest is untrusted.
+ */
+export function checkManifestBounds(
+ manifest: unknown,
+ limits: SourceLimits,
+): string | null {
+ const files =
+ manifest && typeof manifest === "object"
+ ? (manifest as { files?: unknown }).files
+ : undefined;
+ if (!Array.isArray(files)) return "manifest has no files list";
+ if (files.length > limits.files) {
+ return `manifest lists ${files.length} files (limit ${limits.files})`;
+ }
+ let total = 0;
+ for (const file of files) {
+ if (!file || typeof file !== "object")
+ return "manifest entry is not an object";
+ const { path, key, size } = file as Record<string, unknown>;
+ if (typeof path !== "string" || path.length === 0 || path.length > 1024) {
+ return "manifest paths must be strings of 1 to 1024 characters";
+ }
+ if (key !== undefined && (typeof key !== "string" || key.length > 1024)) {
+ return `manifest key for ${path} must be a string of at most 1024 characters`;
+ }
+ if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) {
+ return `manifest size for ${path} must be a non-negative integer`;
+ }
+ if (
+ !path.endsWith(".mp4") &&
+ !AUDIO_FILE.test(path) &&
+ size > limits.sidecarBytes
+ ) {
+ return `${path} is ${size} bytes (limit ${limits.sidecarBytes})`;
+ }
+ total += size;
+ }
+ if (total > limits.sourceBytes) {
+ return `recording is ${total} bytes (limit ${limits.sourceBytes})`;
+ }
+ return null;
+}
diff --git a/bun.lock b/bun.lock
index f3595ec6f..bf5178d75 100644
--- a/bun.lock
+++ b/bun.lock
@@ -225,7 +225,7 @@
"apps/render-farm": {
"name": "@cap/render-farm",
"devDependencies": {
- "@types/bun": "latest",
+ "@types/bun": "1.4.0",
},
},
"apps/web": {
@@ -5944,8 +5944,6 @@
"@cap/env/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "6.21.0" } }, "sha512-QWlFW2wf3nTjC13/DqRnBpR4ZO36VJH/JVBkA/vcnmbTBNQIlnObqyqZE1tUR7+Ni23Lda8R1BxMfbXRpCUx5g=="],
- "@cap/render-farm/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.2" } }, "sha512-GimotNn7+ZV0uVArItBbriZsR1oNf0+WTzPkdcFrzShI7k2norL0uzEaJT8T33dWr7O/c9ZDuAFQrctKCi72oQ=="],
-
"@cap/ui/@tauri-apps/cli": ["@tauri-apps/[email protected]", "", { "dependencies": { "semver": "7.8.5" }, "optionalDependencies": { "@tauri-apps/cli-darwin-arm64": "1.6.3", "@tauri-apps/cli-darwin-x64": "1.6.3", "@tauri-apps/cli-linux-arm-gnueabihf": "1.6.3", "@tauri-apps/cli-linux-arm64-gnu": "1.6.3", "@tauri-apps/cli-linux-arm64-musl": "1.6.3", "@tauri-apps/cli-linux-x64-gnu": "1.6.3", "@tauri-apps/cli-linux-x64-musl": "1.6.3", "@tauri-apps/cli-win32-arm64-msvc": "1.6.3", "@tauri-apps/cli-win32-ia32-msvc": "1.6.3", "@tauri-apps/cli-win32-x64-msvc": "1.6.3" }, "bin": { "tauri": "tauri.js" } }, "sha512-q46umd6QLRKDd4Gg6WyZBGa2fWvk0pbeUA5vFomm4uOs1/17LIciHv2iQ4UD+2Yv5H7AO8YiE1t50V0POiEGEw=="],
"@cap/ui/lucide-react": ["[email protected]", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0" } }, "sha512-V7o0/VECSGbLHn3/1O67FUgBwWB+hmzshrgDVRJQhMh8uj5D3HBuIvhuAmQTtlupILSplwIZg5FTc4tTKMA2SA=="],
@@ -7264,8 +7262,6 @@
"@cap/discord-bot/vitest/vite-node": ["[email protected]", "", { "dependencies": { "cac": "6.7.14", "debug": "4.4.3", "es-module-lexer": "1.7.0", "pathe": "1.1.2", "vite": "5.4.21" }, "bin": { "vite-node": "vite-node.mjs" } }, "sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA=="],
- "@cap/render-farm/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-bxV1FgK7yBIzjRe5zBozIM4Bem11ZJcCXSrjWRG3YWLt8yFDePu4cLjpebO8OvPeIE9trbyPF4fuj3Cia4Fj3w=="],
-
"@cap/ui/@tauri-apps/cli/@tauri-apps/cli-darwin-arm64": ["@tauri-apps/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-fQN6IYSL8bG4NvkdKE4sAGF4dF/QqqQq4hOAU+t8ksOzHJr0hUlJYfncFeJYutr/MMkdF7hYKadSb0j5EE9r0A=="],
"@cap/ui/@tauri-apps/cli/@tauri-apps/cli-darwin-x64": ["@tauri-apps/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-1yTXZzLajKAYINJOJhZfmMhCzweHSgKQ3bEgJSn6t+1vFkOgY8Yx4oFgWcybrrWI5J1ZLZAl47+LPOY81dLcyA=="],
@@ -8610,8 +8606,6 @@
"@cap/discord-bot/vitest/vite/postcss": ["[email protected]", "", { "dependencies": { "nanoid": "3.3.15", "picocolors": "1.1.1", "source-map-js": "1.2.1" } }, "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg=="],
- "@cap/render-farm/@types/bun/bun-types/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "6.21.0" } }, "sha512-QWlFW2wf3nTjC13/DqRnBpR4ZO36VJH/JVBkA/vcnmbTBNQIlnObqyqZE1tUR7+Ni23Lda8R1BxMfbXRpCUx5g=="],
-
"@cap/ui/vite/postcss/nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA=="],
"@cap/web/eslint/@eslint/eslintrc/globals": ["[email protected]", "", {}, "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ=="],