Skip to content

Commit 133b9b0

Browse files
fix(server): serve audio and video from draft workspaces (pingdotgg#24275)
1 parent 3ed4890 commit 133b9b0

2 files changed

Lines changed: 196 additions & 2 deletions

File tree

‎apps/server/src/assets/AssetAccess.test.ts‎

Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,179 @@ describe("AssetAccess", () => {
271271
}).pipe(Effect.provide(layerTest)),
272272
);
273273

274+
it.effect("previews draft audio and video from relative workspace paths", () =>
275+
Effect.gen(function* () {
276+
const fs = yield* FileSystem.FileSystem;
277+
const path = yield* Path.Path;
278+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-media-" });
279+
for (const [name, mimeType] of [
280+
["video.mp4", "video/mp4"],
281+
["audio.wav", "audio/wav"],
282+
] as const) {
283+
const filePath = path.join(root, name);
284+
yield* fs.writeFileString(filePath, "media bytes");
285+
const result = yield* issueAssetUrl({
286+
resource: { _tag: "draft-workspace-file", cwd: root, path: name },
287+
workspaceRoot: root,
288+
});
289+
expect(result.fileRevision).toEqual(expect.any(String));
290+
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
291+
const separator = suffix.indexOf("/");
292+
const token = suffix.slice(0, separator);
293+
const asset = yield* resolveAsset(token, suffix.slice(separator + 1));
294+
expect(asset).toMatchObject({ kind: "file", path: yield* fs.realPath(filePath), mimeType });
295+
if (asset?.kind !== "file") throw new Error("Expected draft media file");
296+
for (const [range, status, body] of [
297+
[undefined, 200, "media bytes"],
298+
["bytes=2-5", 206, "dia "],
299+
] as const) {
300+
const resolved = yield* resolveAsset(token, suffix.slice(separator + 1));
301+
if (resolved?.kind !== "file") throw new Error("Expected draft media file");
302+
const response = HttpServerResponse.toWeb(yield* assetFileResponse(resolved, range));
303+
expect(response.status).toBe(status);
304+
expect(response.headers.get("content-type")).toBe(mimeType);
305+
expect(response.headers.get("content-length")).toBe(String(body.length));
306+
if (range) expect(response.headers.get("content-range")).toBe("bytes 2-5/11");
307+
expect(yield* Effect.promise(() => response.text())).toBe(body);
308+
}
309+
for (const requestedPath of [
310+
name === "video.mp4" ? "audio.wav" : "video.mp4",
311+
`../${name}`,
312+
]) {
313+
expect(yield* resolveAsset(token, requestedPath)).toBeNull();
314+
}
315+
expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
316+
}
317+
}).pipe(Effect.provide(layerTest)),
318+
);
319+
320+
it.effect(
321+
"rejects draft media escapes and disallowed types without enabling non-draft media",
322+
() =>
323+
Effect.gen(function* () {
324+
const fs = yield* FileSystem.FileSystem;
325+
const path = yield* Path.Path;
326+
const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-boundary-" });
327+
const root = path.join(directory, "workspace");
328+
yield* fs.makeDirectory(root);
329+
for (const name of ["video.mp4", "audio.wav", "secret.txt"]) {
330+
yield* fs.writeFileString(path.join(root, name), "workspace bytes");
331+
yield* fs.writeFileString(path.join(directory, name), "outside bytes");
332+
}
333+
for (const [requestedPath, tag] of [
334+
["../video.mp4", "AssetWorkspacePathValidationError"],
335+
["../audio.wav", "AssetWorkspacePathValidationError"],
336+
["secret.txt", "AssetPreviewTypeValidationError"],
337+
] as const) {
338+
const error = yield* issueAssetUrl({
339+
resource: { _tag: "draft-workspace-file", cwd: root, path: requestedPath },
340+
workspaceRoot: root,
341+
}).pipe(Effect.flip);
342+
expect(error._tag).toBe(tag);
343+
}
344+
for (const name of ["video.mp4", "audio.wav"]) {
345+
const error = yield* issueAssetUrl({
346+
resource: { _tag: "workspace-file", threadId: ThreadId.make("thread-1"), path: name },
347+
workspaceRoot: root,
348+
}).pipe(Effect.flip);
349+
expect(error._tag).toBe("AssetPreviewTypeValidationError");
350+
}
351+
}).pipe(Effect.provide(layerTest)),
352+
);
353+
354+
it.effect.skipIf(!symlinksSupported)(
355+
"rejects draft media symlinks escaping the workspace or targeting disallowed types",
356+
() =>
357+
Effect.gen(function* () {
358+
const fs = yield* FileSystem.FileSystem;
359+
const path = yield* Path.Path;
360+
const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-symlink-" });
361+
const root = path.join(directory, "workspace");
362+
yield* fs.makeDirectory(root);
363+
const outside = path.join(directory, "outside.mp4");
364+
const secret = path.join(root, "secret.txt");
365+
yield* fs.writeFileString(outside, "outside bytes");
366+
yield* fs.writeFileString(secret, "private bytes");
367+
for (const [name, target] of [
368+
["escape.mp4", outside],
369+
["disguised.wav", secret],
370+
] as const) {
371+
yield* fs.symlink(target, path.join(root, name));
372+
const error = yield* issueAssetUrl({
373+
resource: { _tag: "draft-workspace-file", cwd: root, path: name },
374+
workspaceRoot: root,
375+
}).pipe(Effect.flip);
376+
expect(["AssetWorkspaceAssetNotFoundError", "AssetPreviewTypeValidationError"]).toContain(
377+
error._tag,
378+
);
379+
}
380+
}).pipe(Effect.provide(layerTest)),
381+
);
382+
383+
it.effect.skipIf(!symlinksSupported)(
384+
"preserves absolute draft previews through stable symlinks",
385+
() =>
386+
Effect.gen(function* () {
387+
const fs = yield* FileSystem.FileSystem;
388+
const path = yield* Path.Path;
389+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-absolute-" });
390+
for (const extension of ["png", "mp4", "wav"]) {
391+
const target = path.join(root, `target.${extension}`);
392+
const alias = path.join(root, `alias.${extension}`);
393+
yield* fs.writeFileString(target, "preview bytes");
394+
yield* fs.symlink(target, alias);
395+
const result = yield* issueAssetUrl({
396+
resource: { _tag: "draft-workspace-file", cwd: root, path: alias },
397+
workspaceRoot: root,
398+
});
399+
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
400+
const separator = suffix.indexOf("/");
401+
expect(
402+
yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
403+
).toMatchObject({ kind: "file", path: yield* fs.realPath(target) });
404+
}
405+
}).pipe(Effect.provide(layerTest)),
406+
);
407+
408+
it.effect.skipIf(!symlinksSupported)(
409+
"rejects a draft media path swapped after workspace containment validation",
410+
() =>
411+
Effect.gen(function* () {
412+
const fs = yield* FileSystem.FileSystem;
413+
const path = yield* Path.Path;
414+
const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-swap-" });
415+
const root = path.join(directory, "workspace");
416+
yield* fs.makeDirectory(root);
417+
const filePath = path.join(root, "video.mp4");
418+
const outside = path.join(directory, "outside.mp4");
419+
yield* fs.writeFileString(filePath, "workspace video");
420+
yield* fs.writeFileString(outside, "outside video");
421+
const canonicalFile = yield* fs.realPath(filePath);
422+
let swapped = false;
423+
const swappingFileSystem = FileSystem.FileSystem.of({
424+
...fs,
425+
stat: Effect.fn(function* (requestedPath) {
426+
const info = yield* fs.stat(requestedPath);
427+
if (requestedPath === canonicalFile && !swapped) {
428+
swapped = true;
429+
yield* fs.remove(filePath);
430+
yield* fs.symlink(outside, filePath);
431+
}
432+
return info;
433+
}),
434+
});
435+
const result = yield* issueAssetUrl({
436+
resource: { _tag: "draft-workspace-file", cwd: root, path: "video.mp4" },
437+
workspaceRoot: root,
438+
}).pipe(Effect.result, Effect.provideService(FileSystem.FileSystem, swappingFileSystem));
439+
expect(swapped).toBe(true);
440+
expect(result).toMatchObject({
441+
_tag: "Failure",
442+
failure: { _tag: "AssetWorkspaceAssetNotFoundError" },
443+
});
444+
}).pipe(Effect.provide(layerTest)),
445+
);
446+
274447
it.effect("resolves home-relative media paths independently of the workspace", () =>
275448
Effect.gen(function* () {
276449
const fs = yield* FileSystem.FileSystem;

‎apps/server/src/assets/AssetAccess.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,10 @@ import {
2121
import {
2222
audioMimeTypeFromExtension,
2323
hostPreviewMimeTypeFromExtension,
24+
isWorkspaceAudioPreviewPath,
2425
isWorkspaceImagePreviewPath,
2526
isWorkspacePreviewEntryPath,
27+
isWorkspaceVideoPreviewPath,
2628
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
2729
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
2830
} from "@t3tools/shared/filePreview";
@@ -346,6 +348,7 @@ const readImageDimensionsFromHeader = (filePath: string) =>
346348
const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMediaFileAsset")(
347349
function* (input: {
348350
readonly requestedPath: string;
351+
readonly expectedCanonicalPath?: string;
349352
readonly workspaceRoot: string | undefined;
350353
readonly resource: AssetResource;
351354
readonly expiresAt: number;
@@ -371,7 +374,12 @@ const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMe
371374
(cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
372375
),
373376
);
374-
if (!canonicalFile) {
377+
// The workspace caller pins its containment-checked path; never follow a
378+
// replacement symlink to a different file during this second resolution.
379+
if (
380+
!canonicalFile ||
381+
(input.expectedCanonicalPath !== undefined && canonicalFile !== input.expectedCanonicalPath)
382+
) {
375383
return yield* new AssetWorkspaceAssetNotFoundError({
376384
resource: input.resource,
377385
checkedPath: input.requestedPath,
@@ -446,7 +454,11 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA
446454
}),
447455
),
448456
);
449-
if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
457+
const isDraftMedia =
458+
input.resource._tag === "draft-workspace-file" &&
459+
(isWorkspaceAudioPreviewPath(resolved.relativePath) ||
460+
isWorkspaceVideoPreviewPath(resolved.relativePath));
461+
if (!isDraftMedia && !isWorkspacePreviewEntryPath(resolved.relativePath)) {
450462
return yield* new AssetPreviewTypeValidationError({
451463
resource: input.resource,
452464
});
@@ -468,6 +480,13 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA
468480
resource: input.resource,
469481
});
470482
}
483+
if (isDraftMedia) {
484+
return yield* finalizeAbsoluteMediaFileAsset({
485+
...input,
486+
requestedPath: canonicalFile,
487+
expectedCanonicalPath: canonicalFile,
488+
});
489+
}
471490
const canonicalWorkspaceRoot = yield* fileSystem.realPath(input.workspaceRoot).pipe(
472491
Effect.mapError(
473492
(cause) =>
@@ -500,6 +519,7 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA
500519
},
501520
fileName: path.basename(resolved.relativePath),
502521
imageDimensions,
522+
fileRevision: undefined,
503523
};
504524
},
505525
);
@@ -612,6 +632,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
612632
claims = finalized.claims;
613633
fileName = finalized.fileName;
614634
imageDimensions = finalized.imageDimensions;
635+
fileRevision = finalized.fileRevision;
615636
break;
616637
}
617638
case "attachment": {

0 commit comments

Comments
 (0)