Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
173 changes: 173 additions & 0 deletions apps/server/src/assets/AssetAccess.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,179 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(layerTest)),
);

it.effect("previews draft audio and video from relative workspace paths", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-media-" });
for (const [name, mimeType] of [
["video.mp4", "video/mp4"],
["audio.wav", "audio/wav"],
] as const) {
const filePath = path.join(root, name);
yield* fs.writeFileString(filePath, "media bytes");
const result = yield* issueAssetUrl({
resource: { _tag: "draft-workspace-file", cwd: root, path: name },
workspaceRoot: root,
});
expect(result.fileRevision).toEqual(expect.any(String));
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const separator = suffix.indexOf("/");
const token = suffix.slice(0, separator);
const asset = yield* resolveAsset(token, suffix.slice(separator + 1));
expect(asset).toMatchObject({ kind: "file", path: yield* fs.realPath(filePath), mimeType });
if (asset?.kind !== "file") throw new Error("Expected draft media file");
for (const [range, status, body] of [
[undefined, 200, "media bytes"],
["bytes=2-5", 206, "dia "],
] as const) {
const resolved = yield* resolveAsset(token, suffix.slice(separator + 1));
if (resolved?.kind !== "file") throw new Error("Expected draft media file");
const response = HttpServerResponse.toWeb(yield* assetFileResponse(resolved, range));
expect(response.status).toBe(status);
expect(response.headers.get("content-type")).toBe(mimeType);
expect(response.headers.get("content-length")).toBe(String(body.length));
if (range) expect(response.headers.get("content-range")).toBe("bytes 2-5/11");
expect(yield* Effect.promise(() => response.text())).toBe(body);
}
for (const requestedPath of [
name === "video.mp4" ? "audio.wav" : "video.mp4",
`../${name}`,
]) {
expect(yield* resolveAsset(token, requestedPath)).toBeNull();
}
expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
}
}).pipe(Effect.provide(layerTest)),
);

it.effect(
"rejects draft media escapes and disallowed types without enabling non-draft media",
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-boundary-" });
const root = path.join(directory, "workspace");
yield* fs.makeDirectory(root);
for (const name of ["video.mp4", "audio.wav", "secret.txt"]) {
yield* fs.writeFileString(path.join(root, name), "workspace bytes");
yield* fs.writeFileString(path.join(directory, name), "outside bytes");
}
for (const [requestedPath, tag] of [
["../video.mp4", "AssetWorkspacePathValidationError"],
["../audio.wav", "AssetWorkspacePathValidationError"],
["secret.txt", "AssetPreviewTypeValidationError"],
] as const) {
const error = yield* issueAssetUrl({
resource: { _tag: "draft-workspace-file", cwd: root, path: requestedPath },
workspaceRoot: root,
}).pipe(Effect.flip);
expect(error._tag).toBe(tag);
}
for (const name of ["video.mp4", "audio.wav"]) {
const error = yield* issueAssetUrl({
resource: { _tag: "workspace-file", threadId: ThreadId.make("thread-1"), path: name },
workspaceRoot: root,
}).pipe(Effect.flip);
expect(error._tag).toBe("AssetPreviewTypeValidationError");
}
}).pipe(Effect.provide(layerTest)),
);

it.effect.skipIf(!symlinksSupported)(
"rejects draft media symlinks escaping the workspace or targeting disallowed types",
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-symlink-" });
const root = path.join(directory, "workspace");
yield* fs.makeDirectory(root);
const outside = path.join(directory, "outside.mp4");
const secret = path.join(root, "secret.txt");
yield* fs.writeFileString(outside, "outside bytes");
yield* fs.writeFileString(secret, "private bytes");
for (const [name, target] of [
["escape.mp4", outside],
["disguised.wav", secret],
] as const) {
yield* fs.symlink(target, path.join(root, name));
const error = yield* issueAssetUrl({
resource: { _tag: "draft-workspace-file", cwd: root, path: name },
workspaceRoot: root,
}).pipe(Effect.flip);
expect(["AssetWorkspaceAssetNotFoundError", "AssetPreviewTypeValidationError"]).toContain(
error._tag,
);
}
}).pipe(Effect.provide(layerTest)),
);

it.effect.skipIf(!symlinksSupported)(
"preserves absolute draft previews through stable symlinks",
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-absolute-" });
for (const extension of ["png", "mp4", "wav"]) {
const target = path.join(root, `target.${extension}`);
const alias = path.join(root, `alias.${extension}`);
yield* fs.writeFileString(target, "preview bytes");
yield* fs.symlink(target, alias);
const result = yield* issueAssetUrl({
resource: { _tag: "draft-workspace-file", cwd: root, path: alias },
workspaceRoot: root,
});
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const separator = suffix.indexOf("/");
expect(
yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
).toMatchObject({ kind: "file", path: yield* fs.realPath(target) });
}
}).pipe(Effect.provide(layerTest)),
);

it.effect.skipIf(!symlinksSupported)(
"rejects a draft media path swapped after workspace containment validation",
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-swap-" });
const root = path.join(directory, "workspace");
yield* fs.makeDirectory(root);
const filePath = path.join(root, "video.mp4");
const outside = path.join(directory, "outside.mp4");
yield* fs.writeFileString(filePath, "workspace video");
yield* fs.writeFileString(outside, "outside video");
const canonicalFile = yield* fs.realPath(filePath);
let swapped = false;
const swappingFileSystem = FileSystem.FileSystem.of({
...fs,
stat: Effect.fn(function* (requestedPath) {
const info = yield* fs.stat(requestedPath);
if (requestedPath === canonicalFile && !swapped) {
swapped = true;
yield* fs.remove(filePath);
yield* fs.symlink(outside, filePath);
}
return info;
}),
});
const result = yield* issueAssetUrl({
resource: { _tag: "draft-workspace-file", cwd: root, path: "video.mp4" },
workspaceRoot: root,
}).pipe(Effect.result, Effect.provideService(FileSystem.FileSystem, swappingFileSystem));
expect(swapped).toBe(true);
expect(result).toMatchObject({
_tag: "Failure",
failure: { _tag: "AssetWorkspaceAssetNotFoundError" },
});
}).pipe(Effect.provide(layerTest)),
);

it.effect("resolves home-relative media paths independently of the workspace", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
Expand Down
25 changes: 23 additions & 2 deletions apps/server/src/assets/AssetAccess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ import {
import {
audioMimeTypeFromExtension,
hostPreviewMimeTypeFromExtension,
isWorkspaceAudioPreviewPath,
isWorkspaceImagePreviewPath,
isWorkspacePreviewEntryPath,
isWorkspaceVideoPreviewPath,
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
} from "@t3tools/shared/filePreview";
Expand Down Expand Up @@ -351,6 +353,7 @@ const readImageDimensionsFromHeader = (filePath: string) =>
const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMediaFileAsset")(
function* (input: {
readonly requestedPath: string;
readonly expectedCanonicalPath?: string;
readonly workspaceRoot: string | undefined;
readonly resource: AssetResource;
readonly expiresAt: number;
Expand All @@ -376,7 +379,12 @@ const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMe
(cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
),
);
if (!canonicalFile) {
// The workspace caller pins its containment-checked path; never follow a
// replacement symlink to a different file during this second resolution.
if (
!canonicalFile ||
(input.expectedCanonicalPath !== undefined && canonicalFile !== input.expectedCanonicalPath)
) {
return yield* new AssetWorkspaceAssetNotFoundError({
resource: input.resource,
checkedPath: input.requestedPath,
Expand Down Expand Up @@ -451,7 +459,11 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA
}),
),
);
if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
const isDraftMedia =
input.resource._tag === "draft-workspace-file" &&
(isWorkspaceAudioPreviewPath(resolved.relativePath) ||
isWorkspaceVideoPreviewPath(resolved.relativePath));
if (!isDraftMedia && !isWorkspacePreviewEntryPath(resolved.relativePath)) {
return yield* new AssetPreviewTypeValidationError({
resource: input.resource,
});
Expand All @@ -473,6 +485,13 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA
resource: input.resource,
});
}
if (isDraftMedia) {
return yield* finalizeAbsoluteMediaFileAsset({
...input,
requestedPath: canonicalFile,
expectedCanonicalPath: canonicalFile,
});
}
const canonicalWorkspaceRoot = yield* fileSystem.realPath(input.workspaceRoot).pipe(
Effect.mapError(
(cause) =>
Expand Down Expand Up @@ -505,6 +524,7 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA
},
fileName: path.basename(resolved.relativePath),
imageDimensions,
fileRevision: undefined,
};
},
);
Expand Down Expand Up @@ -617,6 +637,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
claims = finalized.claims;
fileName = finalized.fileName;
imageDimensions = finalized.imageDimensions;
fileRevision = finalized.fileRevision;
break;
}
case "attachment": {
Expand Down
Loading