Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: bind Drive recording verification to content identity

Richie McIlroy9cd11a729521
diff --git a/apps/web/__tests__/unit/desktop-recording-source.test.ts b/apps/web/__tests__/unit/desktop-recording-source.test.ts
index e124b08e7..dd5488868 100644
--- a/apps/web/__tests__/unit/desktop-recording-source.test.ts
+++ b/apps/web/__tests__/unit/desktop-recording-source.test.ts
@@ -118,6 +118,7 @@ function storageFixture(provider = "s3") {
const key = source.slice("recordings/".length);
const value = object(key);
if (
+ provider === "s3" &&
options.CopySourceIfMatch !== undefined &&
options.CopySourceIfMatch !== value.identity
) {
@@ -145,6 +146,9 @@ function storageFixture(provider = "s3") {
ContentLength: value.size,
ETag: value.identity,
Metadata: value.metadata,
+ ...(provider === "googleDrive"
+ ? { RecordingContentSHA256: hash(value.body ?? String(value.size)) }
+ : {}),
};
}),
),
@@ -420,6 +424,157 @@ beforeEach(() => {
});
describe("durable desktop recording source commit", () => {
+ it("reuses a checksum-verified Drive copy when checksum readiness delayed its receipt", async () => {
+ const storage = storageFixture("googleDrive");
+ seedSegments(storage, [1], false);
+ const video = recording();
+ const checkpoint = await advanceToPhase(
+ video,
+ snapshotCheckpoint(),
+ "copy",
+ );
+ const head = storage.bucket.headObject.getMockImplementation();
+ if (!head) throw new Error("Missing head implementation");
+ let ready = false;
+ storage.bucket.headObject.mockImplementation((key) =>
+ head(key).pipe(
+ Effect.map((value) => ({
+ ...value,
+ RecordingContentETag:
+ !ready && key.includes("/copies/")
+ ? null
+ : `"cap-drive-content-v1:${hash(key + storage.object(key).body)}"`,
+ })),
+ ),
+ );
+ await expect(
+ advanceDesktopRecordingSourceCommit(video, checkpoint),
+ ).rejects.toThrow("Recording content identity is unavailable");
+ expect(storage.bucket.copyObject).toHaveBeenCalledTimes(2);
+ ready = true;
+ const source = await finishSnapshot(video, checkpoint);
+ expect(
+ (await buildDesktopRecordingSourceUrls(video, source)).sourceObjects,
+ ).toHaveLength(2);
+ expect(storage.bucket.copyObject).toHaveBeenCalledTimes(2);
+ });
+
+ it.each([false, true])(
+ "keeps legacy Drive checkpoint identities strict after content tags are introduced (changed=%s)",
+ async (changed) => {
+ const storage = storageFixture("googleDrive");
+ seedSegments(storage);
+ const video = recording();
+ const checkpoint = await advanceToPhase(
+ video,
+ snapshotCheckpoint(),
+ "verify",
+ );
+ const savedPages = [...storage.objects.entries()]
+ .filter(([key]) => key.endsWith(".json"))
+ .map(([key, object]) => [key, object.body]);
+ const head = storage.bucket.headObject.getMockImplementation();
+ if (!head) throw new Error("Missing head implementation");
+ storage.bucket.headObject.mockImplementation((key) =>
+ head(key).pipe(
+ Effect.map((value) => ({
+ ...value,
+ RecordingContentETag: `"cap-drive-content-v1:${hash(key + storage.object(key).body)}"`,
+ })),
+ ),
+ );
+ if (changed) {
+ for (const object of storage.objects.values())
+ object.identity = '"changed-version"';
+ await expect(finishSnapshot(video, checkpoint)).rejects.toThrow(
+ "Recording source changed",
+ );
+ for (const [key, body] of savedPages)
+ expect(storage.object(key as string).body).toBe(body);
+ } else {
+ const source = await finishSnapshot(video, checkpoint);
+ const urls = await buildDesktopRecordingSourceUrls(video, source);
+ expect(
+ urls.sourceObjects.every((object) =>
+ object.objectIdentity.startsWith('"snapshot-'),
+ ),
+ ).toBe(true);
+ }
+ },
+ );
+
+ it("preserves new Drive copy receipts across metadata-only version changes", async () => {
+ const storage = storageFixture("googleDrive");
+ seedSegments(storage);
+ const head = storage.bucket.headObject.getMockImplementation();
+ if (!head) throw new Error("Missing head implementation");
+ storage.bucket.headObject.mockImplementation((key) =>
+ head(key).pipe(
+ Effect.map((value) => ({
+ ...value,
+ RecordingContentETag: `"cap-drive-content-v1:${hash(key + storage.object(key).body)}"`,
+ })),
+ ),
+ );
+ const video = recording();
+ const checkpoint = await advanceToPhase(
+ video,
+ snapshotCheckpoint(),
+ "verify",
+ );
+ for (const object of storage.objects.values())
+ object.identity = '"metadata-version-6"';
+ const source = await finishSnapshot(video, checkpoint);
+ const urls = await buildDesktopRecordingSourceUrls(video, source);
+ expect(urls.sourceObjects).toHaveLength(5);
+ expect(
+ urls.sourceObjects.every((object) =>
+ object.objectIdentity.startsWith('"cap-drive-content-v1:'),
+ ),
+ ).toBe(true);
+ });
+
+ it("rejects a same-size wrong Drive copy through the actual source commit path", async () => {
+ const storage = storageFixture("googleDrive");
+ seedSegments(storage);
+ const copy = storage.bucket.copyObject.getMockImplementation();
+ if (!copy) throw new Error("Missing copy implementation");
+ storage.bucket.copyObject.mockImplementation((source, key, options) =>
+ copy(source, key, options).pipe(
+ Effect.tap(() =>
+ Effect.sync(() => {
+ const object = storage.object(key);
+ object.body = "x".repeat(object.size);
+ }),
+ ),
+ ),
+ );
+ await expect(
+ commitDesktopRecordingSource(recording(), generation),
+ ).rejects.toThrow(
+ "Recording snapshot content does not match its original source",
+ );
+ expect(
+ [...storage.objects.keys()].some((key) => key.endsWith("receipt.json")),
+ ).toBe(false);
+ });
+
+ it("keeps missing Drive checksum retryable without minting a copy receipt", async () => {
+ const storage = storageFixture("googleDrive");
+ seedSegments(storage);
+ const head = storage.bucket.headObject.getMockImplementation();
+ if (!head) throw new Error("Missing head implementation");
+ storage.bucket.headObject.mockImplementation((key) =>
+ head(key).pipe(
+ Effect.map((value) => ({ ...value, RecordingContentETag: null })),
+ ),
+ );
+ await expect(
+ commitDesktopRecordingSource(recording(), generation),
+ ).rejects.toThrow("Recording content identity is unavailable");
+ expect(storage.bucket.copyObject).not.toHaveBeenCalled();
+ });
+
it.each([
{ status: 404, code: "source-missing" },
{ status: 412, code: "source-changed" },
diff --git a/apps/web/__tests__/unit/desktop-recording-upload-status.test.ts b/apps/web/__tests__/unit/desktop-recording-upload-status.test.ts
index 8dc085301..4d1473e3e 100644
--- a/apps/web/__tests__/unit/desktop-recording-upload-status.test.ts
+++ b/apps/web/__tests__/unit/desktop-recording-upload-status.test.ts
@@ -230,6 +230,77 @@ describe("desktop recording audio verification strength", () => {
});
describe("segmented recording preservation receipts", () => {
+ it("publishes and rechecks a content-bound Drive receipt across metadata changes", async () => {
+ const fixture = segmentedFixture();
+ const identity = `"cap-drive-content-v1:${"d".repeat(64)}"`;
+ mocks.head.mockReturnValue(
+ Effect.succeed({
+ ContentLength: output.fileSize,
+ ETag: '"drive-file:3"',
+ RecordingContentETag: identity,
+ }),
+ );
+ const receipt = await createVerifiedRecordingReceipt(
+ video(),
+ fixture.request,
+ fixture.output,
+ true,
+ identity,
+ fixture.options,
+ );
+ expect(receipt.objectIdentity).toBe(identity);
+ mocks.head.mockReturnValue(
+ Effect.succeed({
+ ContentLength: output.fileSize,
+ ETag: '"drive-file:6"',
+ RecordingContentETag: identity,
+ }),
+ );
+ expect(
+ await verifyDesktopRecordingUpload(video(receipt), fixture.request),
+ ).toMatchObject({ fullDecode: true, requiredAudioVerified: true });
+ mocks.head.mockReturnValue(
+ Effect.succeed({
+ ContentLength: output.fileSize,
+ ETag: '"drive-file:6"',
+ RecordingContentETag: `"cap-drive-content-v1:${"e".repeat(64)}"`,
+ }),
+ );
+ expect(
+ await verifyDesktopRecordingUpload(video(receipt), fixture.request),
+ ).toBeNull();
+ });
+
+ it("does not reinterpret an old Drive receipt when its version changes", async () => {
+ const fixture = segmentedFixture();
+ const identity = `"cap-drive-content-v1:${"d".repeat(64)}"`;
+ mocks.head.mockReturnValue(
+ Effect.succeed({
+ ContentLength: output.fileSize,
+ ETag: '"drive-file:1"',
+ RecordingContentETag: identity,
+ }),
+ );
+ const receipt = await createVerifiedRecordingReceipt(
+ video(),
+ fixture.request,
+ fixture.output,
+ true,
+ '"drive-file:1"',
+ fixture.options,
+ );
+ mocks.head.mockReturnValue(
+ Effect.succeed({
+ ContentLength: output.fileSize,
+ ETag: '"drive-file:6"',
+ RecordingContentETag: identity,
+ }),
+ );
+ expect(
+ await verifyDesktopRecordingUpload(video(receipt), fixture.request),
+ ).toBeNull();
+ });
+
it.each([
{
name: "legacy object estimates",
diff --git a/apps/web/__tests__/unit/google-drive-storage.test.ts b/apps/web/__tests__/unit/google-drive-storage.test.ts
index 385420434..ee9388b67 100644
--- a/apps/web/__tests__/unit/google-drive-storage.test.ts
+++ b/apps/web/__tests__/unit/google-drive-storage.test.ts
@@ -19,9 +19,14 @@ import {
findGoogleDriveFileByObjectKey,
GOOGLE_DRIVE_FOLDER_MIME_TYPE,
type GoogleDriveTokenStore,
+ getGoogleDriveRecordingResponse,
syncGoogleDriveVideoNames,
} from "../../../../packages/web-backend/src/Storage/GoogleDrive";
import { getGoogleDriveVideoNames } from "../../../../packages/web-backend/src/Storage/google-drive-names";
+import {
+ getGoogleDriveRecordingIdentity,
+ getRecordingObjectIdentity,
+} from "../../../../packages/web-backend/src/Storage/recording-object-identity";
import {
type GoogleDriveIntegrationConfig,
type StorageObjectInput,
@@ -331,6 +336,255 @@ afterEach(() => {
vi.restoreAllMocks();
});
+describe("Google Drive recording content identity", () => {
+ const file = {
+ id: "recording-file",
+ size: "8",
+ version: "1",
+ sha256Checksum: "a".repeat(64),
+ headRevisionId: "revision-1",
+ };
+ const identity = getGoogleDriveRecordingIdentity(file) as string;
+
+ it("matches the media-server upload identity wire vector", () => {
+ expect(
+ getGoogleDriveRecordingIdentity({
+ ...file,
+ id: "drive-file-1",
+ size: "11",
+ }),
+ ).toBe(
+ '"cap-drive-content-v1:9c353d47a7cf9c0f30c3008eb3576c4629a878019572a4d68404cbe0f222b88c"',
+ );
+ });
+
+ it.each(["metadata", "revision"])(
+ "cancels a stalled %s request",
+ async (stage) => {
+ const controller = new AbortController();
+ let started: () => void = () => undefined;
+ const pendingRequest = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ if (stage === "revision" && !String(input).includes("/revisions/"))
+ return jsonResponse(file);
+ return new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener(
+ "abort",
+ () => reject(init.signal?.reason),
+ { once: true },
+ );
+ started();
+ });
+ }),
+ );
+ const pending = Effect.runPromise(
+ getGoogleDriveRecordingResponse(
+ makeConfig(),
+ file.id,
+ null,
+ { objectIdentity: identity, signal: controller.signal },
+ makeTokenStore(),
+ ),
+ );
+ await pendingRequest;
+ controller.abort(new Error("Test cancelled"));
+ await expect(pending).rejects.toThrow(
+ stage === "metadata"
+ ? "Test cancelled"
+ : "Recording revision is unavailable",
+ );
+ },
+ );
+
+ it("separates stable content identity from strict legacy version identity", () => {
+ const changedMetadata = { ...file, version: "6", name: "Renamed" };
+ expect(getGoogleDriveRecordingIdentity(changedMetadata)).toBe(identity);
+ const head = { ETag: '"recording-file:6"', RecordingContentETag: identity };
+ expect(getRecordingObjectIdentity(head)).toBe(identity);
+ expect(getRecordingObjectIdentity(head, identity)).toBe(identity);
+ expect(getRecordingObjectIdentity(head, '"recording-file:1"')).not.toBe(
+ '"recording-file:1"',
+ );
+ expect(
+ getGoogleDriveRecordingIdentity({
+ ...file,
+ sha256Checksum: "b".repeat(64),
+ }),
+ ).not.toBe(identity);
+ expect(
+ getGoogleDriveRecordingIdentity({ ...file, id: "replacement" }),
+ ).not.toBe(identity);
+ });
+
+ it.each([
+ { sha256Checksum: undefined },
+ { sha256Checksum: "invalid" },
+ { headRevisionId: undefined },
+ { size: "0" },
+ { size: "9007199254740992" },
+ ])("does not mint content proof with incomplete metadata %j", (change) => {
+ expect(getGoogleDriveRecordingIdentity({ ...file, ...change })).toBeNull();
+ expect(
+ getRecordingObjectIdentity({
+ ETag: '"legacy"',
+ RecordingContentETag: null,
+ }),
+ ).toBeUndefined();
+ });
+
+ it.each([null, "bytes=0-0", "bytes=3-", "bytes=-2"])(
+ "pins verification reads to the checked revision for range %s",
+ async (range) => {
+ const request = vi.fn(
+ async (input: string | URL | Request, init?: RequestInit) => {
+ const url = new URL(String(input));
+ if (!url.pathname.includes("/revisions/"))
+ return jsonResponse({ ...file, version: "6" });
+ expect(url.pathname).toBe(
+ "/drive/v3/files/recording-file/revisions/revision-1",
+ );
+ expect(new Headers(init?.headers).get("range")).toBe(range);
+ const [start, end] =
+ range === "bytes=0-0"
+ ? [0, 0]
+ : range === "bytes=3-"
+ ? [3, 7]
+ : range === "bytes=-2"
+ ? [6, 7]
+ : [0, 7];
+ return new Response("12345678".slice(start, end + 1), {
+ status: range ? 206 : 200,
+ headers: {
+ "Content-Length": String(end - start + 1),
+ ...(range ? { "Content-Range": `bytes ${start}-${end}/8` } : {}),
+ },
+ });
+ },
+ );
+ vi.stubGlobal("fetch", request);
+ const result = await Effect.runPromise(
+ getGoogleDriveRecordingResponse(
+ makeConfig(),
+ file.id,
+ range,
+ { objectIdentity: identity },
+ makeTokenStore(),
+ ),
+ );
+ expect((await result.text()).length).toBe(
+ range === "bytes=0-0"
+ ? 1
+ : range === "bytes=3-"
+ ? 5
+ : range === "bytes=-2"
+ ? 2
+ : 8,
+ );
+ expect(request).toHaveBeenCalledTimes(2);
+ },
+ );
+
+ it.each([403, 404])(
+ "never falls back to current content after revision %i",
+ async (status) => {
+ const request = vi.fn(async (input: string | URL | Request) =>
+ String(input).includes("/revisions/")
+ ? response(status)
+ : jsonResponse(file),
+ );
+ vi.stubGlobal("fetch", request);
+ await expect(
+ Effect.runPromise(
+ getGoogleDriveRecordingResponse(
+ makeConfig(),
+ file.id,
+ null,
+ { objectIdentity: identity },
+ makeTokenStore(),
+ ),
+ ),
+ ).rejects.toThrow("Recording revision is unavailable");
+ expect(request).toHaveBeenCalledTimes(2);
+ },
+ );
+
+ it.each([
+ { version: "1", sha256Checksum: "b".repeat(64) },
+ { id: "replacement-file" },
+ ])(
+ "rejects changed bytes or file identity before downloading %j",
+ async (change) => {
+ const request = vi.fn(async () => jsonResponse({ ...file, ...change }));
+ vi.stubGlobal("fetch", request);
+ await expect(
+ Effect.runPromise(
+ getGoogleDriveRecordingResponse(
+ makeConfig(),
+ file.id,
+ null,
+ { objectIdentity: identity },
+ makeTokenStore(),
+ ),
+ ),
+ ).rejects.toThrow("Recording object changed");
+ expect(request).toHaveBeenCalledOnce();
+ },
+ );
+
+ it("rejects a legacy version mismatch even when SHA256 matches", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => jsonResponse({ ...file, version: "6" })),
+ );
+ await expect(
+ Effect.runPromise(
+ getGoogleDriveRecordingResponse(
+ makeConfig(),
+ file.id,
+ null,
+ { objectIdentity: '"recording-file:1"' },
+ makeTokenStore(),
+ ),
+ ),
+ ).rejects.toThrow("Recording object changed");
+ expect(fetch).toHaveBeenCalledOnce();
+ });
+
+ it("cancels an incorrect revision range response", async () => {
+ const cancel = vi.fn();
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: string | URL | Request) =>
+ String(input).includes("/revisions/")
+ ? new Response(new ReadableStream({ cancel }), {
+ status: 206,
+ headers: {
+ "Content-Length": "1",
+ "Content-Range": "bytes 1-1/8",
+ },
+ })
+ : jsonResponse(file),
+ ),
+ );
+ await expect(
+ Effect.runPromise(
+ getGoogleDriveRecordingResponse(
+ makeConfig(),
+ file.id,
+ "bytes=0-0",
+ { objectIdentity: identity },
+ makeTokenStore(),
+ ),
+ ),
+ ).rejects.toThrow("Recording revision response is incomplete");
+ expect(cancel).toHaveBeenCalledOnce();
+ });
+});
+
describe("Google Drive video names", () => {
it("preserves exact valid titles and rejects blank or control-character names", () => {
expect(getGoogleDriveVideoNames("Launch 🚀: Q3/Q4? (final)")).toEqual({
diff --git a/apps/web/__tests__/unit/recording-storage-lifecycle.test.ts b/apps/web/__tests__/unit/recording-storage-lifecycle.test.ts
index 84bab590a..7cba42a54 100644
--- a/apps/web/__tests__/unit/recording-storage-lifecycle.test.ts
+++ b/apps/web/__tests__/unit/recording-storage-lifecycle.test.ts
@@ -637,7 +637,14 @@ async function driveFixture() {
const files = new Map<string, GoogleDriveFile>([
[
"original-file",
- { id: "original-file", version: "1", size: "10", mimeType: "video/mp4" },
+ {
+ id: "original-file",
+ version: "1",
+ size: "10",
+ mimeType: "video/mp4",
+ sha256Checksum: "a".repeat(64),
+ headRevisionId: "revision-1",
+ },
],
]);
const repo = await Effect.runPromise(
@@ -1704,7 +1711,36 @@ describe("recording storage lifecycle", () => {
);
});
- it.each(["source-version", "destination-size"] as const)(
+ it("allows native Drive copies to change metadata versions without changing bytes", async () => {
+ const drive = await driveFixture();
+ const nativeCopy = mocks.driveCopy.getMockImplementation();
+ if (!nativeCopy) throw new Error("Missing native Drive copy fixture");
+ mocks.driveCopy.mockImplementation(
+ (input: Parameters<typeof copyGoogleDriveFile>[0]) =>
+ nativeCopy(input).pipe(
+ Effect.tap(() =>
+ Effect.sync(() => {
+ for (const file of drive.files.values()) file.version = "6";
+ }),
+ ),
+ ),
+ );
+ await Effect.runPromise(
+ drive.access.copyObjectForRecording(
+ `google-drive/${outputKey}`,
+ `${newPrefix}result.mp4`,
+ ),
+ );
+ expect(drive.records.get(`${newPrefix}result.mp4`)?.providerObjectId).toBe(
+ "copied-file",
+ );
+ });
+
+ it.each([
+ "source-checksum",
+ "destination-checksum",
+ "destination-size",
+ ] as const)(
"rejects a Drive copy when %s changes during readback",
async (change) => {
const drive = await driveFixture();
@@ -1715,16 +1751,17 @@ describe("recording storage lifecycle", () => {
nativeCopy(input).pipe(
Effect.tap(() =>
Effect.sync(() => {
- if (change === "source-version") {
+ if (change === "source-checksum") {
const original = drive.files.get("original-file");
if (!original)
throw new Error("Missing original Drive fixture");
- original.version = "2";
+ original.sha256Checksum = "b".repeat(64);
} else {
const destination = drive.files.get("copied-file");
if (!destination)
throw new Error("Missing copied Drive fixture");
- destination.size = "9";
+ if (change === "destination-size") destination.size = "9";
+ else destination.sha256Checksum = "b".repeat(64);
}
}),
),
diff --git a/apps/web/__tests__/unit/storage-object-verification.test.ts b/apps/web/__tests__/unit/storage-object-verification.test.ts
index 1563bc49c..255fb7bed 100644
--- a/apps/web/__tests__/unit/storage-object-verification.test.ts
+++ b/apps/web/__tests__/unit/storage-object-verification.test.ts
@@ -1,3 +1,5 @@
+import { RecordingObjectReadError } from "@cap/web-backend/src/Storage/recording-object-identity";
+import { Storage as StorageDomain } from "@cap/web-domain";
import { Effect } from "effect";
import { NextRequest } from "next/server";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -43,7 +45,7 @@ vi.mock("@/lib/server", async () => {
});
vi.mock("@/utils/helpers", () => ({ CACHE_CONTROL_HEADERS: {} }));
-import { GET } from "@/app/api/storage/object/route";
+import { GET, HEAD } from "@/app/api/storage/object/route";
function request(
headers: Record<string, string> = {},
@@ -80,6 +82,105 @@ describe("recording verification object reads", () => {
expect(mocks.head).not.toHaveBeenCalled();
});
+ it("serves content-bound HEAD without downloading media", async () => {
+ const identity = `"cap-drive-content-v1:${"a".repeat(64)}"`;
+ mocks.head.mockReturnValue(
+ Effect.succeed({
+ ETag: '"drive-file:6"',
+ RecordingContentETag: identity,
+ ContentLength: 100,
+ }),
+ );
+ const response = await HEAD(
+ new NextRequest(
+ "https://cap.test/api/storage/object?videoId=video&key=owner/video/result.mp4&token=test",
+ {
+ method: "HEAD",
+ headers: {
+ "X-Cap-Recording-Verification": "1",
+ "If-Match": identity,
+ },
+ },
+ ),
+ );
+ expect(response.status).toBe(200);
+ expect(response.headers.get("ETag")).toBe(identity);
+ expect(response.headers.get("Content-Length")).toBe("100");
+ expect(mocks.read).not.toHaveBeenCalled();
+ });
+
+ it("passes content identity and cancellation through a verification range read", async () => {
+ const identity = `"cap-drive-content-v1:${"a".repeat(64)}"`;
+ mocks.head.mockReturnValue(
+ Effect.succeed({
+ ETag: '"drive-file:6"',
+ RecordingContentETag: identity,
+ ContentLength: 100,
+ }),
+ );
+ const response = await request({
+ "X-Cap-Recording-Verification": "1",
+ "If-Match": identity,
+ Range: "bytes=0-3",
+ });
+ expect(response.headers.get("ETag")).toBe(identity);
+ expect(mocks.read).toHaveBeenCalledWith(
+ "owner/video/result.mp4",
+ "bytes=0-3",
+ { objectIdentity: identity, signal: expect.any(AbortSignal) },
+ );
+ });
+
+ it("keeps an old expected version strict when content identity is also available", async () => {
+ mocks.head.mockReturnValue(
+ Effect.succeed({
+ ETag: '"drive-file:6"',
+ RecordingContentETag: `"cap-drive-content-v1:${"a".repeat(64)}"`,
+ ContentLength: 100,
+ }),
+ );
+ const response = await request({
+ "X-Cap-Recording-Verification": "1",
+ "If-Match": '"drive-file:1"',
+ });
+ expect(response.status).toBe(412);
+ expect(mocks.read).not.toHaveBeenCalled();
+ });
+
+ it("does not fall back to a version tag when new content proof is unavailable", async () => {
+ mocks.head.mockReturnValue(
+ Effect.succeed({
+ ETag: '"drive-file:6"',
+ RecordingContentETag: null,
+ ContentLength: 100,
+ }),
+ );
+ expect(
+ (await request({ "X-Cap-Recording-Verification": "1" })).status,
+ ).toBe(503);
+ expect(mocks.read).not.toHaveBeenCalled();
+ });
+
+ it.each([412, 503] as const)(
+ "returns a pinned read failure %s without serving bytes",
+ async (status) => {
+ mocks.read.mockReturnValue(
+ Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new RecordingObjectReadError(
+ status,
+ "Pinned revision unavailable",
+ { cause: new Error("Google Drive request failed: 404") },
+ ),
+ }),
+ ),
+ );
+ expect(
+ (await request({ "X-Cap-Recording-Verification": "1" })).status,
+ ).toBe(status);
+ },
+ );
+
it("returns the provider version with a verification read", async () => {
const response = await request({
"X-Cap-Recording-Verification": "1",
@@ -90,6 +191,7 @@ describe("recording verification object reads", () => {
expect(mocks.read).toHaveBeenCalledWith(
"owner/video/result.mp4",
"bytes=0-3",
+ { objectIdentity: '"drive-file:42"', signal: expect.any(AbortSignal) },
);
});
@@ -132,7 +234,10 @@ describe("recording verification object reads", () => {
key,
);
expect(response.status).toBe(206);
- expect(mocks.read).toHaveBeenCalledWith(key, null);
+ expect(mocks.read).toHaveBeenCalledWith(key, null, {
+ objectIdentity: '"drive-file:42"',
+ signal: expect.any(AbortSignal),
+ });
});
it("does not authorize another retained object using a valid token", async () => {
diff --git a/apps/web/app/api/storage/object/route.ts b/apps/web/app/api/storage/object/route.ts
index 87f342721..3bf3ce433 100644
--- a/apps/web/app/api/storage/object/route.ts
+++ b/apps/web/app/api/storage/object/route.ts
@@ -5,6 +5,7 @@ import {
VideosRepo,
verifyStorageObjectToken,
} from "@cap/web-backend";
+import { getRecordingObjectIdentity } from "@cap/web-backend/src/Storage/recording-object-identity";
import { isInternalRecordingKey } from "@cap/web-backend/src/Storage/recording-output";
import { Storage as StorageDomain, Video } from "@cap/web-domain";
import { Effect, Option } from "effect";
@@ -71,6 +72,13 @@ const isObjectNotFoundError = (error: unknown) => {
};
const toProxyErrorResponse = (error: unknown) => {
+ const recordingReadStatus = getRecordingReadStatus(error);
+ if (recordingReadStatus) {
+ return new Response(
+ recordingReadStatus === 412 ? "Object changed" : "Object is unavailable",
+ { status: recordingReadStatus },
+ );
+ }
if (isObjectNotFoundError(error) || isPolicyDeniedError(error)) {
return new Response("Not found", { status: 404 });
}
@@ -80,6 +88,19 @@ const toProxyErrorResponse = (error: unknown) => {
return new Response("Internal server error", { status: 500 });
};
+const getRecordingReadStatus = (error: unknown): 412 | 503 | undefined => {
+ const record = asRecord(error);
+ if (
+ record?._tag === "RecordingObjectReadError" &&
+ (record.status === 412 || record.status === 503)
+ ) {
+ return record.status;
+ }
+ return record?.cause && record.cause !== error
+ ? getRecordingReadStatus(record.cause)
+ : undefined;
+};
+
const getTokenVideo = (videoId: Video.VideoId) =>
Effect.gen(function* () {
const repo = yield* VideosRepo;
@@ -146,13 +167,16 @@ export async function GET(request: NextRequest) {
const verificationRequested =
request.headers.get("x-cap-recording-verification") === "1";
- const identity = verificationRequested
- ? (yield* storage.headObject(key)).ETag
+ const expectedIdentity = request.headers.get("if-match");
+ const head = verificationRequested
+ ? yield* storage.headObject(key)
+ : undefined;
+ const identity = head
+ ? getRecordingObjectIdentity(head, expectedIdentity ?? undefined)
: undefined;
if (verificationRequested && !identity) {
return new Response("Object identity is unavailable", { status: 503 });
}
- const expectedIdentity = request.headers.get("if-match");
if (
verificationRequested &&
expectedIdentity &&
@@ -160,10 +184,26 @@ export async function GET(request: NextRequest) {
) {
return new Response("Object changed", { status: 412 });
}
- const upstream = yield* storage.getObjectResponse(
- key,
- request.headers.get("range"),
- );
+ if (
+ verificationRequested &&
+ request.method === "HEAD" &&
+ head &&
+ identity
+ ) {
+ const headers = new Headers(CACHE_CONTROL_HEADERS);
+ headers.set("ETag", identity);
+ headers.set("Accept-Ranges", "bytes");
+ if (head.ContentLength !== undefined)
+ headers.set("Content-Length", String(head.ContentLength));
+ if (head.ContentType) headers.set("Content-Type", head.ContentType);
+ return new Response(null, { status: 200, headers });
+ }
+ const upstream = identity
+ ? yield* storage.getObjectResponse(key, request.headers.get("range"), {
+ objectIdentity: identity,
+ signal: request.signal,
+ })
+ : yield* storage.getObjectResponse(key, request.headers.get("range"));
const headers = new Headers(CACHE_CONTROL_HEADERS);
if (identity) headers.set("ETag", identity);
copyHeader(upstream.headers, headers, "content-type", "Content-Type");
diff --git a/apps/web/lib/desktop-recording-source.ts b/apps/web/lib/desktop-recording-source.ts
index 1da52b0f6..1073e539b 100644
--- a/apps/web/lib/desktop-recording-source.ts
+++ b/apps/web/lib/desktop-recording-source.ts
@@ -1,6 +1,7 @@
import { createHash, randomUUID } from "node:crypto";
import type { videos } from "@cap/database/schema";
import { Storage } from "@cap/web-backend/src/Storage/index";
+import { getRecordingObjectIdentity } from "@cap/web-backend/src/Storage/recording-object-identity";
import { getPublishedRecordingOutputKey } from "@cap/web-backend/src/Storage/recording-output";
import { Video } from "@cap/web-domain";
import { Effect, Option, Runtime } from "effect";
@@ -615,9 +616,17 @@ async function captureOriginal(
const head = await context.run(
context.bucket.headObject(original.originalKey),
);
+ const expectedIdentity =
+ original.track === "mp4" && verification?.artifact.kind === "mp4"
+ ? verification.artifact.objectIdentity
+ : undefined;
+ const identity = getRecordingObjectIdentity(head, expectedIdentity);
+ if (!identity && "RecordingContentETag" in head) {
+ throw new Error("Recording content identity is unavailable");
+ }
if (
- !head.ETag ||
- !recordingObjectIdentitySchema.safeParse(head.ETag).success ||
+ !identity ||
+ !recordingObjectIdentitySchema.safeParse(identity).success ||
!head.ContentLength ||
!Number.isSafeInteger(head.ContentLength) ||
head.ContentLength < 0
@@ -631,14 +640,14 @@ async function captureOriginal(
original.track === "mp4" &&
verification?.artifact.kind === "mp4" &&
(verification.artifact.fileSize !== head.ContentLength ||
- verification.artifact.objectIdentity !== head.ETag)
+ verification.artifact.objectIdentity !== identity)
) {
throw new DesktopRecordingSourceError(
"source-changed",
"Uploaded recording does not match its original object identity",
);
}
- return { ...original, originalIdentity: head.ETag, size: head.ContentLength };
+ return { ...original, originalIdentity: identity, size: head.ContentLength };
}
function copyMetadata(original: OriginalObject) {
@@ -653,14 +662,19 @@ async function checkOriginal(context: SourceContext, original: OriginalObject) {
const head = await context.run(
context.bucket.headObject(original.originalKey),
);
+ const identity = getRecordingObjectIdentity(head, original.originalIdentity);
+ if (!identity && "RecordingContentETag" in head) {
+ throw new Error("Recording content identity is unavailable");
+ }
if (
- head.ETag !== original.originalIdentity ||
+ identity !== original.originalIdentity ||
head.ContentLength !== original.size
)
throw new DesktopRecordingSourceError(
"source-changed",
"Recording source changed while its durable snapshot was being saved",
);
+ return head;
}
async function checkCopy(
@@ -670,15 +684,35 @@ async function checkCopy(
expectedIdentity?: string,
): Promise<SourceObject> {
assertContextKey(context, key);
- const [head] = await Promise.all([
+ const [head, originalHead] = await Promise.all([
context.run(context.bucket.headObject(key)),
checkOriginal(context, original),
]);
+ const identity = getRecordingObjectIdentity(head, expectedIdentity);
+ if (!identity && "RecordingContentETag" in head) {
+ throw new Error("Recording content identity is unavailable");
+ }
+ if (context.bucket.provider === "googleDrive") {
+ if (
+ !("RecordingContentSHA256" in head) ||
+ !("RecordingContentSHA256" in originalHead) ||
+ !head.RecordingContentSHA256 ||
+ !originalHead.RecordingContentSHA256
+ ) {
+ throw new Error("Recording content checksum is unavailable");
+ }
+ if (head.RecordingContentSHA256 !== originalHead.RecordingContentSHA256) {
+ throw new DesktopRecordingSourceError(
+ "source-changed",
+ "Recording snapshot content does not match its original source",
+ );
+ }
+ }
if (
- !head.ETag ||
- !recordingObjectIdentitySchema.safeParse(head.ETag).success ||
+ !identity ||
+ !recordingObjectIdentitySchema.safeParse(identity).success ||
head.ContentLength !== original.size ||
- (expectedIdentity !== undefined && head.ETag !== expectedIdentity)
+ (expectedIdentity !== undefined && identity !== expectedIdentity)
) {
throw new DesktopRecordingSourceError(
"source-changed",
@@ -696,7 +730,7 @@ async function checkCopy(
"Recording snapshot is missing its original source identity",
);
}
- return { ...original, key, objectIdentity: head.ETag };
+ return { ...original, key, objectIdentity: identity };
}
function objectDirectory(key: string) {
@@ -746,6 +780,11 @@ async function reusableCopy(
) {
return checkCopy(context, original, key, receipt.data.objectIdentity);
}
+ } else if (context.bucket.provider === "googleDrive") {
+ return saveObjectReceipt(
+ context,
+ await checkCopy(context, original, key),
+ );
} else if (context.bucket.provider === "s3") {
const head = await context.run(context.bucket.headObject(key));
if (
diff --git a/apps/web/lib/desktop-recording-upload-status.ts b/apps/web/lib/desktop-recording-upload-status.ts
index f975ba309..9ef3d20a7 100644
--- a/apps/web/lib/desktop-recording-upload-status.ts
+++ b/apps/web/lib/desktop-recording-upload-status.ts
@@ -1,5 +1,6 @@
import type { videos } from "@cap/database/schema";
import { Storage } from "@cap/web-backend";
+import { getRecordingObjectIdentity } from "@cap/web-backend/src/Storage/recording-object-identity";
import { Video } from "@cap/web-domain";
import { Effect, Option } from "effect";
import {
@@ -165,10 +166,11 @@ export async function createVerifiedRecordingReceipt(
}
const bucket = await getRecordingStorage(video);
const head = await EffectRuntime.runPromise(bucket.headObject(outputKey));
- if (!head.ETag || head.ContentLength !== output.fileSize) {
+ const identity = getRecordingObjectIdentity(head, objectIdentity);
+ if (!identity || head.ContentLength !== output.fileSize) {
throw new Error("Final recording object is not fully uploaded");
}
- if (head.ETag !== objectIdentity) {
+ if (identity !== objectIdentity) {
throw new Error("Recording changed while its content was verified");
}
return recordingUploadReceiptSchema.parse({
@@ -179,7 +181,7 @@ export async function createVerifiedRecordingReceipt(
hasAudio: Boolean(output.audioCodec),
fullDecode: true,
requiredAudioVerified,
- objectIdentity: head.ETag,
+ objectIdentity: identity,
outputKey,
...(outputSha256 === undefined ? {} : { outputSha256 }),
...(sourceProof === undefined ? {} : { sourceProof }),
diff --git a/apps/web/lib/desktop-recording-verification.ts b/apps/web/lib/desktop-recording-verification.ts
index bd89c1443..198cb294f 100644
--- a/apps/web/lib/desktop-recording-verification.ts
+++ b/apps/web/lib/desktop-recording-verification.ts
@@ -1,4 +1,8 @@
import { createHash } from "node:crypto";
+import {
+ getRecordingObjectIdentity,
+ type RecordingObjectHead,
+} from "@cap/web-backend/src/Storage/recording-object-identity";
import { z } from "zod";
const positiveNumber = z.number().finite().positive();
@@ -199,13 +203,13 @@ export type RecordingUploadReceipt = z.infer<
>;
export function assertRecordingObjectIdentity(
- head: { ContentLength?: number; ETag?: string },
+ head: RecordingObjectHead & { ContentLength?: number },
expected: { fileSize: number; objectIdentity: string },
) {
if (
head.ContentLength !== expected.fileSize ||
- !head.ETag ||
- head.ETag !== expected.objectIdentity
+ getRecordingObjectIdentity(head, expected.objectIdentity) !==
+ expected.objectIdentity
) {
throw new Error("Uploaded recording object changed or is incomplete");
}
diff --git a/packages/web-backend/src/Storage/GoogleDrive.ts b/packages/web-backend/src/Storage/GoogleDrive.ts
index daddeccd9..c8978309d 100644
--- a/packages/web-backend/src/Storage/GoogleDrive.ts
+++ b/packages/web-backend/src/Storage/GoogleDrive.ts
@@ -3,6 +3,11 @@ import { serverEnv } from "@cap/env";
import { Storage, type User, type Video } from "@cap/web-domain";
import { Effect, Either, Option, Schedule } from "effect";
import { getGoogleDriveVideoNames } from "./google-drive-names.ts";
+import {
+ getGoogleDriveRecordingIdentity,
+ getRecordingObjectIdentity,
+ RecordingObjectReadError,
+} from "./recording-object-identity.ts";
import type {
GoogleDriveAccessTokenCache,
GoogleDriveIntegrationConfig,
@@ -28,6 +33,8 @@ export type GoogleDriveFile = {
size?: string;
version?: string;
md5Checksum?: string;
+ sha256Checksum?: string;
+ headRevisionId?: string;
modifiedTime?: string;
parents?: string[];
trashed?: boolean;
@@ -1108,7 +1115,7 @@ export const createGoogleDriveResumableUpload = (
driveFetch(
config,
appendSharedDriveCreateParams(
- `${DRIVE_UPLOAD_BASE}/files/${encodeURIComponent(fileId)}?uploadType=resumable&fields=id,name,mimeType,size,version`,
+ `${DRIVE_UPLOAD_BASE}/files/${encodeURIComponent(fileId)}?uploadType=resumable&fields=id,name,mimeType,size,version,sha256Checksum,headRevisionId`,
),
{
method: "PATCH",
@@ -1124,7 +1131,7 @@ export const createGoogleDriveResumableUpload = (
const uploadUrl = yield* driveFetch(
config,
appendSharedDriveCreateParams(
- `${DRIVE_UPLOAD_BASE}/files?uploadType=resumable&fields=id,name,mimeType,size,version`,
+ `${DRIVE_UPLOAD_BASE}/files?uploadType=resumable&fields=id,name,mimeType,size,version,sha256Checksum,headRevisionId`,
),
{
method: "POST",
@@ -1275,13 +1282,14 @@ export const getGoogleDriveFileMetadata = (
config: GoogleDriveIntegrationConfig,
fileId: string,
tokenStore?: GoogleDriveTokenStore,
+ signal?: AbortSignal,
) =>
driveFetch(
config,
appendSharedDriveCreateParams(
- `${DRIVE_API_BASE}/files/${encodeURIComponent(fileId)}?fields=id,name,mimeType,size,version,md5Checksum,parents,trashed,appProperties,capabilities(canRename)`,
+ `${DRIVE_API_BASE}/files/${encodeURIComponent(fileId)}?fields=id,name,mimeType,size,version,md5Checksum,sha256Checksum,headRevisionId,parents,trashed,appProperties,capabilities(canRename)`,
),
- undefined,
+ { signal },
tokenStore,
).pipe(
Effect.flatMap((response) =>
@@ -1381,6 +1389,121 @@ export const getGoogleDriveObjectResponse = (
return response;
});
+export type GoogleDriveRecordingRead = {
+ objectIdentity: string;
+ signal?: AbortSignal;
+};
+
+export const getGoogleDriveRecordingResponse = (
+ config: GoogleDriveIntegrationConfig,
+ fileId: string,
+ range: string | null | undefined,
+ verification: GoogleDriveRecordingRead,
+ tokenStore?: GoogleDriveTokenStore,
+) =>
+ Effect.gen(function* () {
+ const metadata = yield* getGoogleDriveFileMetadata(
+ config,
+ fileId,
+ tokenStore,
+ verification.signal,
+ );
+ const identity = getRecordingObjectIdentity(
+ {
+ ETag: metadata.version
+ ? `"${metadata.id}:${metadata.version}"`
+ : undefined,
+ RecordingContentETag: getGoogleDriveRecordingIdentity(metadata),
+ },
+ verification.objectIdentity,
+ );
+ if (!identity) {
+ return yield* Effect.fail(
+ new Storage.StorageError({
+ cause: new RecordingObjectReadError(
+ 503,
+ "Recording content identity is unavailable",
+ ),
+ }),
+ );
+ }
+ if (metadata.id !== fileId || identity !== verification.objectIdentity) {
+ return yield* Effect.fail(
+ new Storage.StorageError({
+ cause: new RecordingObjectReadError(412, "Recording object changed"),
+ }),
+ );
+ }
+ if (!metadata.headRevisionId || !getUsableGoogleDriveFileSize(metadata)) {
+ return yield* Effect.fail(
+ new Storage.StorageError({
+ cause: new RecordingObjectReadError(
+ 503,
+ "Recording revision identity is unavailable",
+ ),
+ }),
+ );
+ }
+ const headers = new Headers();
+ headers.set("Accept-Encoding", "identity");
+ if (range) headers.set("Range", range);
+ const response = yield* driveFetch(
+ config,
+ `${DRIVE_API_BASE}/files/${encodeURIComponent(fileId)}/revisions/${encodeURIComponent(metadata.headRevisionId)}?alt=media`,
+ { headers, signal: verification.signal },
+ tokenStore,
+ ).pipe(
+ Effect.mapError(
+ (cause) =>
+ new Storage.StorageError({
+ cause: new RecordingObjectReadError(
+ 503,
+ "Recording revision is unavailable",
+ { cause },
+ ),
+ }),
+ ),
+ );
+ const contentRange = response.headers
+ .get("content-range")
+ ?.match(/^bytes (\d+)-(\d+)\/(\d+)$/);
+ const requestedRange = range?.match(/^bytes=(\d*)-(\d*)$/);
+ const expectedStart = requestedRange?.[1]
+ ? Number(requestedRange[1])
+ : Math.max(0, Number(metadata.size) - Number(requestedRange?.[2]));
+ const expectedEnd =
+ requestedRange?.[1] && requestedRange[2]
+ ? Math.min(Number(metadata.size) - 1, Number(requestedRange[2]))
+ : Number(metadata.size) - 1;
+ const validResponse = range
+ ? response.status === 206 &&
+ Boolean(requestedRange?.[1] || requestedRange?.[2]) &&
+ contentRange !== undefined &&
+ contentRange !== null &&
+ Number(contentRange[3]) === Number(metadata.size) &&
+ Number(contentRange[1]) === expectedStart &&
+ Number(contentRange[2]) === expectedEnd &&
+ Number(contentRange[1]) <= Number(contentRange[2]) &&
+ Number(contentRange[2]) < Number(metadata.size) &&
+ Number(response.headers.get("content-length")) ===
+ Number(contentRange[2]) - Number(contentRange[1]) + 1
+ : response.status === 200 &&
+ Number(response.headers.get("content-length")) ===
+ Number(metadata.size);
+ if (!validResponse) {
+ yield* discardGoogleDriveResponseBody(response);
+ return yield* Effect.fail(
+ new Storage.StorageError({
+ cause: new RecordingObjectReadError(
+ 503,
+ "Recording revision response is incomplete",
+ ),
+ }),
+ );
+ }
+ return response;
+ });
+
const discardGoogleDriveResponseBody = (response: Response) =>
Effect.tryPromise({
try: async () => {
diff --git a/packages/web-backend/src/Storage/index.ts b/packages/web-backend/src/Storage/index.ts
index ca6d24328..ec05449d8 100644
--- a/packages/web-backend/src/Storage/index.ts
+++ b/packages/web-backend/src/Storage/index.ts
@@ -19,14 +19,20 @@ import {
findGoogleDriveFileByObjectKey,
GOOGLE_DRIVE_FOLDER_MIME_TYPE,
type GoogleDriveFile,
+ type GoogleDriveRecordingRead,
GoogleDriveRequestError,
type GoogleDriveTokenStore,
getGoogleDriveFileMetadata,
getGoogleDriveObjectResponse,
getGoogleDriveObjectText,
+ getGoogleDriveRecordingResponse,
parseVideoIdFromObjectKey,
syncGoogleDriveVideoNames,
} from "./GoogleDrive.ts";
+import {
+ getGoogleDriveRecordingIdentity,
+ type RecordingObjectHead,
+} from "./recording-object-identity.ts";
import { resolveRecordingObjectKey } from "./recording-output.ts";
import { createStorageObjectToken } from "./SignedObject.ts";
import type { GoogleDriveIntegrationConfig } from "./StorageRepo.ts";
@@ -40,6 +46,13 @@ type UploadTargetInput = {
videoTitle?: string;
};
+type StorageObjectHead = RecordingObjectHead & {
+ ContentLength?: number;
+ ContentType?: string;
+ Metadata?: Record<string, string | undefined>;
+ RecordingContentSHA256?: string;
+};
+
type MultipartAccess = {
copyPart?: (
key: string,
@@ -434,12 +447,14 @@ const makeS3Access = (s3: S3BucketAccess) => ({
),
headObject: (key: string) =>
mapStorageError(s3.headObject(key)).pipe(
- Effect.map((result) => ({
- ContentLength: result.ContentLength,
- ContentType: result.ContentType,
- Metadata: result.Metadata,
- ETag: result.ETag,
- })),
+ Effect.map(
+ (result): StorageObjectHead => ({
+ ContentLength: result.ContentLength,
+ ContentType: result.ContentType,
+ Metadata: result.Metadata,
+ ETag: result.ETag,
+ }),
+ ),
),
putObject: (
key: string,
@@ -679,10 +694,7 @@ const makeGoogleDriveAccess = ({
);
const { fileSize } = yield* recordingCopyMetadata({
ContentLength: parseGoogleDriveContentLength(before) ?? undefined,
- ETag:
- before.id && before.version
- ? `"${before.id}:${before.version}"`
- : undefined,
+ ETag: getGoogleDriveRecordingIdentity(before) ?? undefined,
});
yield* copyGoogleDriveFile({
repo,
@@ -712,15 +724,15 @@ const makeGoogleDriveAccess = ({
]);
yield* recordingCopyMetadata({
ContentLength: parseGoogleDriveContentLength(copied) ?? undefined,
- ETag:
- copied.id && copied.version
- ? `"${copied.id}:${copied.version}"`
- : undefined,
+ ETag: getGoogleDriveRecordingIdentity(copied) ?? undefined,
});
if (
currentSource.providerObjectId !== before.id ||
after.id !== before.id ||
- after.version !== before.version ||
+ getGoogleDriveRecordingIdentity(after) !==
+ getGoogleDriveRecordingIdentity(before) ||
+ copied.sha256Checksum?.toLowerCase() !==
+ before.sha256Checksum?.toLowerCase() ||
parseGoogleDriveContentLength(after) !== fileSize ||
parseGoogleDriveContentLength(copied) !== fileSize
) {
@@ -865,16 +877,25 @@ const makeGoogleDriveAccess = ({
withRecoveredDriveFile(key, object, (fileId) =>
getGoogleDriveFileMetadata(config, fileId, tokenStore),
).pipe(
- Effect.map((metadata) => ({
- ContentLength: metadata.size
- ? Number(metadata.size)
- : (object.contentLength ?? undefined),
- ContentType: metadata.mimeType ?? object.contentType ?? undefined,
- Metadata: object.metadata ?? undefined,
- ETag: metadata.version
- ? `"${metadata.id}:${metadata.version}"`
- : undefined,
- })),
+ Effect.map(
+ (metadata): StorageObjectHead => ({
+ ContentLength: metadata.size
+ ? Number(metadata.size)
+ : (object.contentLength ?? undefined),
+ ContentType:
+ metadata.mimeType ?? object.contentType ?? undefined,
+ Metadata: object.metadata ?? undefined,
+ ETag: metadata.version
+ ? `"${metadata.id}:${metadata.version}"`
+ : undefined,
+ RecordingContentETag: getGoogleDriveRecordingIdentity(metadata),
+ RecordingContentSHA256: getGoogleDriveRecordingIdentity(
+ metadata,
+ )
+ ? metadata.sha256Checksum?.toLowerCase()
+ : undefined,
+ }),
+ ),
),
),
),
@@ -1009,12 +1030,24 @@ const makeGoogleDriveAccess = ({
mapStorageError,
Effect.map((url) => toDriveUploadTarget(url, input.contentType)),
),
- getObjectResponse: (key: string, range?: string | null) =>
+ getObjectResponse: (
+ key: string,
+ range?: string | null,
+ verification?: GoogleDriveRecordingRead,
+ ) =>
getObjectRecord(key).pipe(
Effect.flatMap((object) =>
- withRecoveredDriveFile(key, object, (fileId) =>
- getGoogleDriveObjectResponse(config, fileId, range, tokenStore),
- ),
+ verification
+ ? getGoogleDriveRecordingResponse(
+ config,
+ object.providerObjectId,
+ range,
+ verification,
+ tokenStore,
+ )
+ : withRecoveredDriveFile(key, object, (fileId) =>
+ getGoogleDriveObjectResponse(config, fileId, range, tokenStore),
+ ),
),
),
};
@@ -1054,8 +1087,11 @@ function withPublishedRecordingOutput<
};
if (access.provider === "googleDrive") {
return Object.assign({}, access, shared, {
- getObjectResponse: (key: string, range?: string | null) =>
- access.getObjectResponse(resolve(key), range),
+ getObjectResponse: (
+ key: string,
+ range?: string | null,
+ verification?: GoogleDriveRecordingRead,
+ ) => access.getObjectResponse(resolve(key), range, verification),
});
}
return Object.assign({}, access, shared);
diff --git a/packages/web-backend/src/Storage/recording-object-identity.ts b/packages/web-backend/src/Storage/recording-object-identity.ts
new file mode 100644
index 000000000..380340e56
--- /dev/null
+++ b/packages/web-backend/src/Storage/recording-object-identity.ts
@@ -0,0 +1,64 @@
+import { createHash } from "node:crypto";
+
+const DRIVE_CONTENT_IDENTITY_PREFIX = '"cap-drive-content-v1:';
+
+export type RecordingObjectHead = {
+ ETag?: string;
+ RecordingContentETag?: string | null;
+};
+
+export class RecordingObjectReadError extends Error {
+ readonly _tag = "RecordingObjectReadError";
+
+ constructor(
+ readonly status: 412 | 503,
+ message: string,
+ options?: ErrorOptions,
+ ) {
+ super(message, options);
+ }
+}
+
+export function getRecordingObjectIdentity(
+ head: RecordingObjectHead,
+ expectedIdentity?: string,
+) {
+ if (expectedIdentity !== undefined) {
+ return expectedIdentity.startsWith(DRIVE_CONTENT_IDENTITY_PREFIX)
+ ? (head.RecordingContentETag ?? undefined)
+ : head.ETag;
+ }
+ return "RecordingContentETag" in head
+ ? (head.RecordingContentETag ?? undefined)
+ : head.ETag;
+}
+
+export function getGoogleDriveRecordingIdentity(file: {
+ id: string;
+ size?: string;
+ sha256Checksum?: string;
+ headRevisionId?: string;
+}) {
+ if (
+ !file.id ||
+ !file.headRevisionId ||
+ !file.size ||
+ !/^\d+$/.test(file.size) ||
+ !Number.isSafeInteger(Number(file.size)) ||
+ Number(file.size) <= 0 ||
+ !file.sha256Checksum ||
+ !/^[a-fA-F0-9]{64}$/.test(file.sha256Checksum)
+ ) {
+ return null;
+ }
+ const digest = createHash("sha256")
+ .update(
+ JSON.stringify([
+ file.id,
+ Number(file.size),
+ file.sha256Checksum.toLowerCase(),
+ ]),
+ )
+ .digest("hex");
+ return `${DRIVE_CONTENT_IDENTITY_PREFIX}${digest}"`;
+}