Skip to content

Commit 48d388a

Browse files
committed
fix(web): sign published MP4 storage keys
1 parent ea509a5 commit 48d388a

6 files changed

Lines changed: 163 additions & 17 deletions

File tree

‎apps/web/__tests__/unit/segment-playlist-route.test.ts‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@ const mocks = vi.hoisted(() => ({
77
audioInitExists: false,
88
storageUnavailable: false,
99
denied: false,
10+
defaultBucket: false,
11+
source: { type: "desktopSegments" } as {
12+
type: "desktopSegments" | "desktopMP4";
13+
outputKey?: string;
14+
},
1015
sign: vi.fn(),
1116
read: vi.fn(),
1217
dispose: async () => {},
@@ -23,6 +28,7 @@ vi.mock("@cap/web-backend", async (importOriginal) => {
2328
const { Context, Effect, Option } = await import("effect");
2429
const { Policy, Storage: StorageDomain } = await import("@cap/web-domain");
2530
const bucket = {
31+
provider: "s3",
2632
getObject: () =>
2733
Effect.sync(() => {
2834
mocks.read();
@@ -48,7 +54,11 @@ vi.mock("@cap/web-backend", async (importOriginal) => {
4854
effect: import("effect").Effect.Effect<A, E, R>,
4955
) => effect,
5056
Storage: Object.assign(Context.GenericTag("PlaylistTestStorage"), {
51-
getAccessForVideo: () => Effect.succeed([bucket, false] as const),
57+
getAccessForVideo: () =>
58+
Effect.succeed([
59+
bucket,
60+
mocks.defaultBucket ? Option.none() : Option.some({}),
61+
] as const),
5262
}),
5363
Videos: Object.assign(Context.GenericTag("PlaylistTestVideos"), {
5464
testService: {
@@ -60,7 +70,7 @@ vi.mock("@cap/web-backend", async (importOriginal) => {
6070
{
6171
id: "recording",
6272
ownerId: "owner",
63-
source: { type: "desktopSegments" },
73+
source: mocks.source,
6474
},
6575
]),
6676
),
@@ -121,6 +131,8 @@ describe("Instant playlist readiness API", () => {
121131
mocks.audioInitExists = false;
122132
mocks.storageUnavailable = false;
123133
mocks.denied = false;
134+
mocks.defaultBucket = false;
135+
mocks.source = { type: "desktopSegments" };
124136
});
125137
afterAll(() => mocks.dispose());
126138

@@ -170,4 +182,20 @@ describe("Instant playlist readiness API", () => {
170182
expect((await request()).status).toBe(401);
171183
expect(mocks.read).not.toHaveBeenCalled();
172184
});
185+
186+
it.each(["custom", "default"] as const)(
187+
"redirects a published MP4 in a %s bucket to its retained storage key",
188+
async (bucket) => {
189+
mocks.defaultBucket = bucket === "default";
190+
mocks.source = {
191+
type: "desktopMP4",
192+
outputKey: "owner/recording/.recording/outputs/generation/result.mp4",
193+
};
194+
const response = await request("mp4", "");
195+
expect(response.status).toBe(302);
196+
expect(mocks.sign).toHaveBeenCalledExactlyOnceWith(
197+
mocks.source.outputKey,
198+
);
199+
},
200+
);
173201
});

‎apps/web/__tests__/unit/share-playback.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,31 @@ describe("share page playback URL", () => {
7979
source: publishedVideo.source,
8080
storageIntegrationId: Option.some("drive-integration"),
8181
});
82+
expect(mocks.sign).toHaveBeenCalledExactlyOnceWith(
83+
publishedVideo.source.outputKey,
84+
);
85+
});
86+
87+
it("signs the audio leveled output when it is the published source", async () => {
88+
mocks.sign.mockReturnValue(
89+
Effect.succeed("https://media.example.com/audio.mp4"),
90+
);
91+
mocks.access.mockReturnValue(
92+
Effect.succeed([{ getSignedObjectUrl: mocks.sign }, Option.none()]),
93+
);
94+
const outputKey = "owner/video/.recording/outputs/generation/result.mp4";
95+
const audioLevelOutputKey =
96+
"owner/video/.recording/outputs/audio-quality-v3/result.mp4";
97+
await getSharePlaybackUrl({
98+
...video,
99+
source: {
100+
type: "desktopMP4",
101+
outputKey,
102+
audioLevelSourceKey: outputKey,
103+
audioLevelOutputKey,
104+
},
105+
});
106+
expect(mocks.sign).toHaveBeenCalledExactlyOnceWith(audioLevelOutputKey);
82107
});
83108

84109
it("allows the player to use its existing route when storage resolution fails", async () => {
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import { Video } from "@cap/web-domain";
2+
import { Effect } from "effect";
3+
import { beforeEach, describe, expect, it, vi } from "vitest";
4+
5+
const mocks = vi.hoisted(() => ({
6+
rows: [] as unknown[][],
7+
sign: vi.fn(),
8+
access: vi.fn(),
9+
}));
10+
11+
vi.mock("@cap/database", () => ({
12+
db: () => ({
13+
select: () => ({
14+
from: () => ({ where: () => Promise.resolve(mocks.rows.shift() ?? []) }),
15+
}),
16+
}),
17+
}));
18+
vi.mock("@cap/database/auth/session", () => ({
19+
getCurrentUser: () => Promise.resolve({ id: "owner" }),
20+
}));
21+
vi.mock("@cap/web-backend", () => ({
22+
Storage: { getAccessForVideo: mocks.access },
23+
}));
24+
vi.mock("@/lib/video-download-permissions", () => ({
25+
canUserDownloadVideo: () => Promise.resolve(true),
26+
}));
27+
vi.mock("@/lib/server", () => ({ runPromise: Effect.runPromise }));
28+
29+
import { getVideoDownloadInfo } from "@/actions/videos/download";
30+
31+
describe("current video download", () => {
32+
beforeEach(() => {
33+
mocks.rows = [];
34+
mocks.sign.mockReset();
35+
mocks.access.mockReset();
36+
});
37+
38+
it.each(["current", "original"] as const)(
39+
"signs the %s MP4 key",
40+
async (variant) => {
41+
const outputKey = "owner/video/.recording/outputs/generation/result.mp4";
42+
const originalKey = "owner/video/.recording/sources/original.mp4";
43+
mocks.rows = [
44+
[
45+
{
46+
id: "video",
47+
ownerId: "owner",
48+
orgId: "organization",
49+
name: "Recording",
50+
public: true,
51+
source: { type: "desktopMP4", outputKey },
52+
metadata: null,
53+
bucket: "custom-bucket",
54+
storageIntegrationId: null,
55+
folderId: null,
56+
transcriptionStatus: null,
57+
width: null,
58+
height: null,
59+
duration: null,
60+
createdAt: new Date(),
61+
updatedAt: new Date(),
62+
},
63+
],
64+
variant === "current" ? [] : [{ sourceKey: originalKey }],
65+
];
66+
mocks.sign.mockReturnValue(
67+
Effect.succeed("https://media.example.com/video.mp4"),
68+
);
69+
mocks.access.mockReturnValue(
70+
Effect.succeed([
71+
{
72+
headObject: () => Effect.succeed({}),
73+
getSignedObjectUrl: mocks.sign,
74+
},
75+
]),
76+
);
77+
78+
expect(
79+
await getVideoDownloadInfo(Video.VideoId.make("video"), variant),
80+
).toMatchObject({
81+
success: true,
82+
});
83+
expect(mocks.sign).toHaveBeenCalledExactlyOnceWith(
84+
variant === "current" ? outputKey : originalKey,
85+
);
86+
},
87+
);
88+
});

‎apps/web/actions/videos/download.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { db } from "@cap/database";
44
import { getCurrentUser } from "@cap/database/auth/session";
55
import { videoEdits, videos, videoUploads } from "@cap/database/schema";
66
import { Storage } from "@cap/web-backend";
7-
import type { Video } from "@cap/web-domain";
7+
import { Video } from "@cap/web-domain";
88
import { eq } from "drizzle-orm";
99
import { Effect } from "effect";
1010
import { runPromise } from "@/lib/server";
@@ -141,10 +141,15 @@ export async function getVideoDownloadInfo(
141141
}
142142

143143
try {
144+
const decodedVideo = decodeStorageVideo(video);
145+
if (variant === "current") {
146+
const source = Video.Video.getSource(decodedVideo);
147+
if (source instanceof Video.Mp4Source) {
148+
downloadKey = source.getFileKey();
149+
}
150+
}
144151
const downloadUrl = await Effect.gen(function* () {
145-
const [bucket] = yield* Storage.getAccessForVideo(
146-
decodeStorageVideo(video),
147-
);
152+
const [bucket] = yield* Storage.getAccessForVideo(decodedVideo);
148153
const exists = yield* bucket.headObject(downloadKey).pipe(
149154
Effect.as(true),
150155
Effect.catchAll(() => Effect.succeed(false)),

‎apps/web/app/api/playlist/route.ts‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -170,8 +170,11 @@ const getPlaylistResponse = (
170170
) =>
171171
Effect.gen(function* () {
172172
const [bucket, customBucket] = yield* Storage.getAccessForVideo(video);
173-
const isMp4Source =
174-
video.source.type === "desktopMP4" || video.source.type === "webMP4";
173+
const source = Video.Video.getSource(video);
174+
const isMp4Source = source instanceof Video.Mp4Source;
175+
const mp4Key = isMp4Source
176+
? source.getFileKey()
177+
: `${video.ownerId}/${video.id}/result.mp4`;
175178

176179
if (urlParams.videoType === "raw-preview") {
177180
const rawFileKey = yield* resolveRawPreviewKey(video);
@@ -364,8 +367,7 @@ const getPlaylistResponse = (
364367
if (bucket.provider === "s3" && Option.isNone(customBucket)) {
365368
let redirect = `${video.ownerId}/${video.id}/combined-source/stream.m3u8`;
366369

367-
if (isMp4Source || urlParams.videoType === "mp4")
368-
redirect = `${video.ownerId}/${video.id}/result.mp4`;
370+
if (isMp4Source || urlParams.videoType === "mp4") redirect = mp4Key;
369371
else if (video.source.type === "MediaConvert")
370372
redirect = `${video.ownerId}/${video.id}/output/video_recording_000.m3u8`;
371373

@@ -443,11 +445,9 @@ const getPlaylistResponse = (
443445
},
444446
});
445447
} else if (isMp4Source) {
446-
yield* Effect.log(
447-
`Returning path ${`${video.ownerId}/${video.id}/result.mp4`}`,
448-
);
448+
yield* Effect.log(`Returning path ${mp4Key}`);
449449
return yield* bucket
450-
.getSignedObjectUrl(`${video.ownerId}/${video.id}/result.mp4`)
450+
.getSignedObjectUrl(mp4Key)
451451
.pipe(Effect.map(HttpServerResponse.redirect));
452452
}
453453

‎apps/web/lib/share-playback.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@ export const getSharePlaybackUrl = (video: SharePlaybackVideo) =>
2020
updatedAt: video.updatedAt.toISOString(),
2121
});
2222
const [bucket] = yield* Storage.getAccessForVideo(loadedVideo);
23-
return yield* bucket.getSignedObjectUrl(
24-
`${video.owner.id}/${video.id}/result.mp4`,
25-
);
23+
const source = Video.Video.getSource(loadedVideo);
24+
if (!(source instanceof Video.Mp4Source)) return null;
25+
return yield* bucket.getSignedObjectUrl(source.getFileKey());
2626
})
2727
.pipe(runPromise)
2828
.catch(() => null);

0 commit comments

Comments
 (0)