Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: unblock verified recording sources across S3 and Drive (#2229)

Richie McIlroy46ac332e276f
diff --git a/.github/workflows/docker-build-media-server.yml b/.github/workflows/docker-build-media-server.yml
index ad4ef258c..74cd28846 100644
--- a/.github/workflows/docker-build-media-server.yml
+++ b/.github/workflows/docker-build-media-server.yml
@@ -80,6 +80,9 @@ jobs:
docker run --rm --network none --entrypoint bun "$MEDIA_IMAGE" test \
src/__tests__/lib/recording-verification.integration.test.ts \
src/__tests__/lib/job-manager.test.ts
+ docker run --rm --network none --entrypoint bun "$MEDIA_IMAGE" test \
+ src/__tests__/lib/media-size.test.ts \
+ src/__tests__/lib/media-probe.integration.test.ts
docker run --rm --network none --entrypoint bun "$MEDIA_IMAGE" test \
src/__tests__/lib/media-transfer.test.ts
docker run --rm --network none --entrypoint bun "$MEDIA_IMAGE" test \
diff --git a/apps/media-server/Dockerfile b/apps/media-server/Dockerfile
index c46db3cf6..2c77c9ca6 100644
--- a/apps/media-server/Dockerfile
+++ b/apps/media-server/Dockerfile
@@ -11,7 +11,8 @@ RUN bun install --frozen-lockfile --production
COPY apps/media-server/src ./src
-RUN bun test src/__tests__/lib/recording-verification.integration.test.ts src/__tests__/lib/job-manager.test.ts \
+RUN bun test src/__tests__/lib/media-size.test.ts src/__tests__/lib/media-probe.integration.test.ts \
+ && bun test src/__tests__/lib/recording-verification.integration.test.ts src/__tests__/lib/job-manager.test.ts \
&& bun test src/__tests__/lib/media-transfer.test.ts \
&& bun test src/__tests__/routes/recording-verification.test.ts \
&& bun test src/__tests__/routes/video.test.ts \
diff --git a/apps/media-server/src/__tests__/lib/media-probe.integration.test.ts b/apps/media-server/src/__tests__/lib/media-probe.integration.test.ts
index fea3aff63..2f41b63c3 100644
--- a/apps/media-server/src/__tests__/lib/media-probe.integration.test.ts
+++ b/apps/media-server/src/__tests__/lib/media-probe.integration.test.ts
@@ -130,6 +130,7 @@ describe("mediaProbe integration tests", () => {
expect(metadata.duration).toBeGreaterThan(0);
expect(metadata.videoCodec).toBeTruthy();
+ expect(metadata.fileSize).toBe(videoData.length);
} finally {
await server.stop(true);
}
diff --git a/apps/media-server/src/__tests__/lib/media-size.test.ts b/apps/media-server/src/__tests__/lib/media-size.test.ts
new file mode 100644
index 000000000..6b7304121
--- /dev/null
+++ b/apps/media-server/src/__tests__/lib/media-size.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, test } from "bun:test";
+import { getSourceSize } from "../../lib/media-common";
+
+describe("remote media size", () => {
+ for (const sample of [
+ {
+ status: 206,
+ headers: { "Content-Range": "bytes 0-0/1024", "Content-Length": "1" },
+ size: 1024,
+ },
+ { status: 200, headers: { "Content-Length": "1024" }, size: 1024 },
+ { status: 403, headers: { "Content-Length": "1024" }, size: null },
+ { status: 206, headers: { "Content-Length": "1" }, size: null },
+ { status: 206, headers: { "Content-Range": "bytes 1-1/1024" }, size: null },
+ {
+ status: 206,
+ headers: { "Content-Range": "bytes 0-0/9007199254740992" },
+ size: null,
+ },
+ { status: 200, headers: {}, size: null },
+ ]) {
+ test(`validates size response ${JSON.stringify(sample)}`, async () => {
+ const server = Bun.serve({
+ port: 0,
+ fetch(request) {
+ expect(request.method).toBe("GET");
+ expect(request.headers.get("range")).toBe("bytes=0-0");
+ return new Response(
+ sample.size === 1024 && sample.status === 200
+ ? new Uint8Array(1024)
+ : null,
+ {
+ status: sample.status,
+ headers: sample.headers,
+ },
+ );
+ },
+ });
+ try {
+ const result = getSourceSize(
+ `${server.url}video.mp4`.replace("http:", "HTTP:"),
+ );
+ if (sample.size === null) {
+ await expect(result).rejects.toThrow(
+ "Media input size is unavailable",
+ );
+ } else {
+ expect(await result).toBe(sample.size);
+ }
+ } finally {
+ await server.stop(true);
+ }
+ });
+ }
+});
diff --git a/apps/media-server/src/__tests__/lib/media-transfer.test.ts b/apps/media-server/src/__tests__/lib/media-transfer.test.ts
index 23cfe4308..5fa0b37e0 100644
--- a/apps/media-server/src/__tests__/lib/media-transfer.test.ts
+++ b/apps/media-server/src/__tests__/lib/media-transfer.test.ts
@@ -51,6 +51,33 @@ function fetcher(
return Object.assign(run, { preconnect: fetch.preconnect }) as typeof fetch;
}
describe("bounded revision downloads", () => {
+ test("pins the descriptor with an application header and rejects changed identity", async () => {
+ process.env.MEDIA_SERVER_WEBHOOK_SECRET = "worker-secret";
+ globalThis.fetch = fetcher((_input, init) => {
+ const headers = new Headers(init?.headers);
+ expect(headers.get("if-match")).toBeNull();
+ expect(headers.get("x-cap-recording-object-identity")).toBe('"identity"');
+ return Response.json(target());
+ });
+ expect(
+ await getMediaDownloadTarget(
+ "https://cap.so/api/storage/object",
+ undefined,
+ '"identity"',
+ ),
+ ).toEqual(target());
+ globalThis.fetch = fetcher(() =>
+ Response.json({ ...target(), objectIdentity: '"changed"' }),
+ );
+ await expect(
+ getMediaDownloadTarget(
+ "https://cap.so/api/storage/object",
+ undefined,
+ '"identity"',
+ ),
+ ).rejects.toThrow("Recording object changed");
+ });
+
test("resumes an interrupted pinned revision without rereading completed bytes", async () => {
const path = await destination();
let calls = 0;
diff --git a/apps/media-server/src/__tests__/lib/recording-verification.integration.test.ts b/apps/media-server/src/__tests__/lib/recording-verification.integration.test.ts
index 30e2f5c4f..a40240607 100644
--- a/apps/media-server/src/__tests__/lib/recording-verification.integration.test.ts
+++ b/apps/media-server/src/__tests__/lib/recording-verification.integration.test.ts
@@ -1075,8 +1075,8 @@ describe("source-preserving recording mux", () => {
},
);
- test.each([-1, 1, -23_333])(
- "preserves a true partial final frame with duration offset %d ticks when muxing",
+ test.each([-1, 1, -23_333, 670_000])(
+ "preserves the final frame with duration offset %d ticks when muxing",
async (offsetTicks) => {
const input = await fragmentedSource(0, { last: offsetTicks });
const sourceEvidence = await inspectRecordingSources(input, null);
@@ -1098,12 +1098,21 @@ describe("source-preserving recording mux", () => {
throw new Error("Fixture has no final packet");
expect(sourceTail.duration).toBe(33_333 + offsetTicks);
expect(outputTail.duration).toBe(sourceTail.duration);
+ expect(sourceEvidence.video.duration).toBeCloseTo(
+ (sourceTail.pts + sourceTail.duration - (sourcePackets[0]?.pts ?? 0)) /
+ 1_000_000,
+ 9,
+ );
const verified = await verifyRecording(output, {
requireAudio: false,
sourceEvidence,
});
expect(verified.sourcePreserved).toBe(true);
expect(verified.video.frameCount).toBe(31);
+ expect(verified.video.duration).toBeCloseTo(
+ sourceEvidence.video.duration,
+ 9,
+ );
expect(verified.integrity).toEqual(sourceEvidence.integrity);
},
);
@@ -1287,7 +1296,10 @@ describe("source-preserving recording mux", () => {
const output = await fragmentedSource(0, { first: 2_000_000, last: -1 });
const sourceEvidence = await inspectRecordingSources(input, null);
const outputEvidence = await inspectRecordingSources(output, null);
- expect(outputEvidence.video).toEqual(sourceEvidence.video);
+ expect(outputEvidence.video.duration).toBeCloseTo(
+ sourceEvidence.video.duration - 0.000_001,
+ 9,
+ );
expect(outputEvidence.integrity.video.contentSha256).toBe(
sourceEvidence.integrity.video.contentSha256,
);
diff --git a/apps/media-server/src/lib/media-common.ts b/apps/media-server/src/lib/media-common.ts
index be2c4b7c4..ad3c69224 100644
--- a/apps/media-server/src/lib/media-common.ts
+++ b/apps/media-server/src/lib/media-common.ts
@@ -198,17 +198,29 @@ export function normalizeLocalPath(path: string): string {
}
export async function getSourceSize(path: string): Promise<number> {
- try {
- const url = new URL(path);
- if (url.protocol === "http:" || url.protocol === "https:") {
- const response = await mediaFetch(path, {
- method: "HEAD",
- signal: AbortSignal.timeout(10_000),
- });
- const contentLength = response.headers.get("content-length");
- return contentLength ? Number.parseInt(contentLength, 10) || 0 : 0;
+ if (/^https?:\/\//i.test(path)) {
+ const response = await mediaFetch(path, {
+ headers: { Range: "bytes=0-0" },
+ signal: AbortSignal.timeout(10_000),
+ });
+ try {
+ const length =
+ response.status === 206
+ ? response.headers
+ .get("content-range")
+ ?.match(/^bytes 0-0\/(\d+)$/)?.[1]
+ : response.status === 200
+ ? response.headers.get("content-length")
+ : undefined;
+ const size = Number(length);
+ if (!Number.isSafeInteger(size) || size <= 0) {
+ throw new Error("Media input size is unavailable");
+ }
+ return size;
+ } finally {
+ await response.body?.cancel().catch(() => {});
}
- } catch {}
+ }
try {
return (await stat(normalizeLocalPath(path))).size;
diff --git a/apps/media-server/src/lib/media-transfer.ts b/apps/media-server/src/lib/media-transfer.ts
index c1eeb0b42..c3c3e5877 100644
--- a/apps/media-server/src/lib/media-transfer.ts
+++ b/apps/media-server/src/lib/media-transfer.ts
@@ -171,7 +171,9 @@ export async function getMediaDownloadTarget(
headers: {
"x-cap-internal-download": "1",
"x-media-server-secret": secret,
- ...(expectedIdentity ? { "if-match": expectedIdentity } : {}),
+ ...(expectedIdentity
+ ? { "x-cap-recording-object-identity": expectedIdentity }
+ : {}),
},
signal,
redirect: "manual",
diff --git a/apps/media-server/src/lib/recording-verification.ts b/apps/media-server/src/lib/recording-verification.ts
index 6d0a0a1c1..040e62b7a 100644
--- a/apps/media-server/src/lib/recording-verification.ts
+++ b/apps/media-server/src/lib/recording-verification.ts
@@ -539,6 +539,19 @@ function validateEvidence(
audio: audioEvidence && audio ? integrity(audio) : null,
},
};
+ if (videoTiming?.terminalPacketCount === 1) {
+ const duration =
+ Number(
+ videoTiming.lastTimestampTicks -
+ videoTiming.firstTimestampTicks +
+ videoTiming.lastDurationTicks,
+ ) / videoTiming.timeScale;
+ result.video = {
+ ...result.video,
+ duration,
+ endTime: result.video.startTime + duration,
+ };
+ }
if (options.sourceEvidence) {
assertSourcePreserved(options.sourceEvidence, result);
result.sourcePreserved = true;
diff --git a/apps/web/__tests__/unit/storage-object-verification.test.ts b/apps/web/__tests__/unit/storage-object-verification.test.ts
index 961913352..2f1320222 100644
--- a/apps/web/__tests__/unit/storage-object-verification.test.ts
+++ b/apps/web/__tests__/unit/storage-object-verification.test.ts
@@ -99,26 +99,29 @@ describe("recording verification object reads", () => {
expect(mocks.download).not.toHaveBeenCalled();
});
- it("authorizes an internal descriptor without downloading media", async () => {
- mocks.download.mockReturnValue(
- Effect.succeed({
- version: 1,
- url: "https://www.googleapis.com/drive/v3/files/file/revisions/revision?alt=media",
- }),
- );
- const response = await request({
- "x-cap-internal-download": "1",
- "x-media-server-secret": "test-media-secret",
- "if-match": '"identity"',
- });
- expect(response.status).toBe(200);
- expect(response.headers.get("Cache-Control")).toBe("private, no-store");
- expect(mocks.download).toHaveBeenCalledWith(
- "owner/video/result.mp4",
- expect.objectContaining({ objectIdentity: '"identity"' }),
- );
- expect(mocks.read).not.toHaveBeenCalled();
- });
+ it.each(["if-match", "x-cap-recording-object-identity"])(
+ "authorizes an internal descriptor using %s without downloading media",
+ async (identityHeader) => {
+ mocks.download.mockReturnValue(
+ Effect.succeed({
+ version: 1,
+ url: "https://www.googleapis.com/drive/v3/files/file/revisions/revision?alt=media",
+ }),
+ );
+ const response = await request({
+ "x-cap-internal-download": "1",
+ "x-media-server-secret": "test-media-secret",
+ [identityHeader]: '"identity"',
+ });
+ expect(response.status).toBe(200);
+ expect(response.headers.get("Cache-Control")).toBe("private, no-store");
+ expect(mocks.download).toHaveBeenCalledWith(
+ "owner/video/result.mp4",
+ expect.objectContaining({ objectIdentity: '"identity"' }),
+ );
+ expect(mocks.read).not.toHaveBeenCalled();
+ },
+ );
it("does not add metadata requests to ordinary playback", async () => {
const response = await request();
diff --git a/apps/web/app/api/storage/object/route.ts b/apps/web/app/api/storage/object/route.ts
index bbbd1473d..184b774f9 100644
--- a/apps/web/app/api/storage/object/route.ts
+++ b/apps/web/app/api/storage/object/route.ts
@@ -186,7 +186,10 @@ export async function GET(request: NextRequest) {
if (!("getInternalDownload" in storage))
return new Response("Unsupported storage", { status: 400 });
const target = yield* storage.getInternalDownload(key, {
- objectIdentity: request.headers.get("if-match") ?? undefined,
+ objectIdentity:
+ request.headers.get("x-cap-recording-object-identity") ??
+ request.headers.get("if-match") ??
+ undefined,
signal: request.signal,
});
return Response.json(target, {