Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(render-farm): accept only a dispatch's own HLS segments and re-sign the playlist

Richie McIlroy5c25675b2205
diff --git a/apps/render-farm/src/coordinator.test.ts b/apps/render-farm/src/coordinator.test.ts
index ea9112ab3..d31af9fd5 100644
--- a/apps/render-farm/src/coordinator.test.ts
+++ b/apps/render-farm/src/coordinator.test.ts
@@ -423,6 +423,41 @@ describe("coordinator recovery", () => {
});
});
+test("segment reports only list objects the reporting dispatch wrote", async () => {
+ const h = harness();
+ const j = job();
+ j.hls = await h.newHlsState("hls/job");
+ const original = videoState(j);
+ h.jobs.set(j.id, j);
+ await h.dispatchedTask(j, original);
+ const report = (key: string) =>
+ h.fetch(
+ new Request(
+ `http://test/tasks/${encodeURIComponent(original.task.taskId)}/segment`,
+ {
+ method: "POST",
+ headers: {
+ authorization: "Bearer test",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ chunk: 0,
+ index: 0,
+ frames: [0, 30],
+ key,
+ last: true,
+ extradata: "",
+ }),
+ },
+ ),
+ );
+ expect((await report("media/private.mp4")).status).toBe(400);
+ expect((await report("hls/job/c0-p12-0.m4s")).status).toBe(400);
+ expect(j.hls.segments.size).toBe(0);
+ expect((await report("hls/job/c0-p2-0.m4s")).status).toBe(200);
+ expect(j.hls.segments.get(0)?.get(0)?.key).toBe("hls/job/c0-p2-0.m4s");
+});
+
test("job acknowledgement waits for a planning receipt and receipt-only jobs resume", async () => {
const h = harness();
const planned: string[] = [];
diff --git a/apps/render-farm/src/coordinator.ts b/apps/render-farm/src/coordinator.ts
index e7c5f1fba..0f213caf2 100644
--- a/apps/render-farm/src/coordinator.ts
+++ b/apps/render-farm/src/coordinator.ts
@@ -3,7 +3,7 @@ import { mkdirSync, rmSync } from "node:fs";
import { join } from "node:path";
import { Engine } from "./engine";
import { initSegment, playlist } from "./fmp4";
-import { segmentCuts } from "./hls";
+import { checkSegmentReport, segmentCuts, segmentKey } from "./hls";
import { type FileSpec, ProjectCache } from "./materialize";
import {
avcC,
@@ -459,7 +459,6 @@ const SOURCE_KEY_PREFIXES = (process.env.RF_SOURCE_KEY_PREFIXES ?? "")
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) {
@@ -1010,6 +1009,8 @@ function segmentsFromResult(
result: VideoResult,
): SegmentReport[] {
if (!job.hls) return [];
+ // Parts are numbered from the dispatch's first part, which names its segments.
+ const firstPart = Math.min(...result.parts.map((part) => part.partNumber));
const cuts = segmentCuts(
result.keyframes,
result.sizes.length,
@@ -1019,7 +1020,7 @@ function segmentsFromResult(
chunk: chunk.index,
index,
frames: [chunk.frames[0] + a, chunk.frames[0] + b],
- key: `${job.hls?.prefix}/c${chunk.index}-${index}.m4s`,
+ key: segmentKey(job.hls?.prefix ?? "", chunk.index, firstPart, index),
last: index === cuts.length - 1,
extradata: result.extradata,
}));
@@ -2172,14 +2173,20 @@ Bun.serve({
const taskId = decodeURIComponent(segmentMatch[1] ?? "");
const job = jobs.get(taskId.split(":")[0] ?? "");
if (!job?.hls) return new Response("unknown job", { status: 404 });
- const report = (await request.json()) as SegmentReport;
+ const state = job.tasks.get(taskId);
+ const plan =
+ state?.task.kind === "video" ? job.chunks[state.task.chunk] : undefined;
+ const report = plan
+ ? checkSegmentReport(await request.json(), job.hls.prefix, plan)
+ : null;
+ if (!report) return new Response("invalid segment", { status: 400 });
job.hls.extradata ??= report.extradata || undefined;
let chunk = job.hls.segments.get(report.chunk);
if (!chunk) {
chunk = new Map();
job.hls.segments.set(report.chunk, chunk);
}
- // First copy wins (a hedge writes the same key with equivalent bytes).
+ // First copy wins; other copies wrote their own objects.
if (!chunk.has(report.index)) chunk.set(report.index, report);
publishPlaylist(job);
return Response.json({ ok: true });
@@ -2368,9 +2375,19 @@ Bun.serve({
setTimeout(resolve, 100_000);
});
}
- return Response.json(
- job.final ? { ...job.final, verified: job.verified } : summary(job),
- );
+ const body = job.final
+ ? { ...job.final, verified: job.verified }
+ : summary(job);
+ // Re-signed per read: a URL issued at submission lapses with its
+ // signature or the instance credentials behind it.
+ if (job.hls) {
+ body.hlsUrl = await s3.presignFresh(
+ "GET",
+ `${job.hls.prefix}/index.m3u8`,
+ 6 * 3600,
+ );
+ }
+ return Response.json(body);
}
if (url.pathname === "/usage") {
diff --git a/apps/render-farm/src/hls.test.ts b/apps/render-farm/src/hls.test.ts
index 4b8577d77..240f07200 100644
--- a/apps/render-farm/src/hls.test.ts
+++ b/apps/render-farm/src/hls.test.ts
@@ -1,5 +1,10 @@
import { describe, expect, test } from "bun:test";
-import { closesSegment, segmentCuts } from "./hls";
+import {
+ checkSegmentReport,
+ closesSegment,
+ segmentCuts,
+ segmentKey,
+} from "./hls";
// The worker applies `closesSegment` as each GOP finishes; this replays that
// incremental rule so it can be compared with the coordinator's re-derivation.
@@ -60,3 +65,47 @@ describe("segmentCuts", () => {
}
});
});
+
+describe("checkSegmentReport", () => {
+ const chunk = {
+ index: 3,
+ frames: [90, 150] as [number, number],
+ firstPart: 40,
+ partLimit: 10,
+ dispatches: 2,
+ };
+ const report = (overrides: Record<string, unknown> = {}) => ({
+ chunk: 3,
+ index: 1,
+ frames: [120, 150],
+ key: segmentKey("hls/job", 3, 50, 1),
+ last: true,
+ extradata: "",
+ ...overrides,
+ });
+
+ test("accepts a segment from any dispatched range of the chunk", () => {
+ expect(checkSegmentReport(report(), "hls/job", chunk)).not.toBeNull();
+ expect(
+ checkSegmentReport(
+ report({ key: segmentKey("hls/job", 3, 40, 1) }),
+ "hls/job",
+ chunk,
+ ),
+ ).not.toBeNull();
+ });
+
+ test.each([
+ ["a key outside the job", { key: "out/other-job.mp4" }],
+ ["a range not yet dispatched", { key: segmentKey("hls/job", 3, 60, 1) }],
+ ["another chunk's key", { key: segmentKey("hls/job", 2, 40, 1) }],
+ ["a key for another index", { key: segmentKey("hls/job", 3, 40, 0) }],
+ ["another chunk", { chunk: 2 }],
+ ["frames outside the chunk", { frames: [60, 120] }],
+ ["empty frames", { frames: [120, 120] }],
+ ["a fractional index", { index: 1.5 }],
+ ["a missing last flag", { last: undefined }],
+ ])("rejects %s", (_, overrides) => {
+ expect(checkSegmentReport(report(overrides), "hls/job", chunk)).toBeNull();
+ });
+});
diff --git a/apps/render-farm/src/hls.ts b/apps/render-farm/src/hls.ts
index 08fa67ed6..a553df465 100644
--- a/apps/render-farm/src/hls.ts
+++ b/apps/render-farm/src/hls.ts
@@ -1,3 +1,5 @@
+import type { SegmentReport } from "./protocol";
+
/**
* Whether a segment that started at frame `start` closes at the GOP boundary
* `boundary`. Workers apply this as each GOP finishes encoding; a restarted
@@ -29,3 +31,64 @@ export function segmentCuts(
cuts.push([start, total]);
return cuts;
}
+
+/**
+ * Every dispatch of a chunk writes its own segment objects (named by the
+ * dispatch's first upload part), so a hedge or retry finishing late never
+ * replaces bytes a playlist already lists.
+ */
+export function segmentKey(
+ prefix: string,
+ chunk: number,
+ firstPart: number,
+ index: number,
+) {
+ return `${prefix}/c${chunk}-p${firstPart}-${index}.m4s`;
+}
+
+/**
+ * A worker's segment report, accepted only for objects its own dispatch of
+ * this chunk wrote: the coordinator presigns report keys into the playlist.
+ */
+export function checkSegmentReport(
+ report: unknown,
+ prefix: string,
+ chunk: {
+ index: number;
+ frames: [number, number];
+ firstPart: number;
+ partLimit: number;
+ dispatches: number;
+ },
+): SegmentReport | null {
+ if (!report || typeof report !== "object") return null;
+ const { index, frames, key, last, extradata } = report as Record<
+ string,
+ unknown
+ >;
+ if (
+ (report as { chunk?: unknown }).chunk !== chunk.index ||
+ typeof index !== "number" ||
+ !Number.isInteger(index) ||
+ index < 0 ||
+ typeof last !== "boolean" ||
+ typeof extradata !== "string" ||
+ extradata.length > 4096 ||
+ !Array.isArray(frames) ||
+ frames.length !== 2 ||
+ !frames.every(Number.isInteger) ||
+ frames[0] < chunk.frames[0] ||
+ frames[0] >= frames[1] ||
+ frames[1] > chunk.frames[1] ||
+ typeof key !== "string"
+ ) {
+ return null;
+ }
+ for (let range = 0; range < Math.max(chunk.dispatches, 1); range++) {
+ const firstPart = chunk.firstPart + range * chunk.partLimit;
+ if (key === segmentKey(prefix, chunk.index, firstPart, index)) {
+ return report as SegmentReport;
+ }
+ }
+ return null;
+}
diff --git a/apps/render-farm/src/validate.ts b/apps/render-farm/src/validate.ts
index cc2ff26ca..bac9ab105 100644
--- a/apps/render-farm/src/validate.ts
+++ b/apps/render-farm/src/validate.ts
@@ -1,6 +1,5 @@
import { COMPRESSION_BPP, type JobRequest } from "./protocol";
-/** Rejects malformed or out-of-range export requests before any work starts. */
export function validateJobRequest(body: unknown): JobRequest | string {
if (!body || typeof body !== "object") return "body must be a JSON object";
const request = body as Record<string, unknown>;
diff --git a/apps/render-farm/src/worker.ts b/apps/render-farm/src/worker.ts
index d591afb10..85b759b31 100644
--- a/apps/render-farm/src/worker.ts
+++ b/apps/render-farm/src/worker.ts
@@ -4,7 +4,7 @@ import { availableParallelism, hostname } from "node:os";
import { join } from "node:path";
import { Engine, processCpuSeconds, sampleThreads } from "./engine";
import { segmentHeader } from "./fmp4";
-import { closesSegment } from "./hls";
+import { closesSegment, segmentKey } from "./hls";
import { ProjectCache } from "./materialize";
import type { Run } from "./mp4";
import {
@@ -271,7 +271,12 @@ class SegmentStream {
body.set(header, 0);
body.set(video, header.byteLength);
body.set(audio.data, header.byteLength + video.byteLength);
- const key = `${task.hls.prefix}/c${task.chunk}-${index}.m4s`;
+ const key = segmentKey(
+ task.hls.prefix,
+ task.chunk,
+ task.upload.firstPart,
+ index,
+ );
await s3.put(key, body, "video/iso.segment");
this.firstUploadedMs ??= performance.now() - this.started;
const report: SegmentReport = {