Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AssetAccess.test.ts

476 lines19.3 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { AssetPreviewTypeValidationError, ThreadId } from "@t3tools/contracts";
3import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
4import { describe, expect, it } from "@effect/vitest";
5import * as Crypto from "effect/Crypto";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Path from "effect/Path";
10import * as PlatformError from "effect/PlatformError";
11import * as TestClock from "effect/testing/TestClock";
12​
13import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
14import * as ServerConfig from "../config.ts";
15import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
16import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
17import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
18import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts";
19​
20const configLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
21 prefix: "t3-asset-access-test-",
22});
23const testLayer = Layer.mergeAll(
24 configLayer,
25 WorkspacePaths.layer,
26 ProjectFaviconResolver.layer.pipe(
27 Layer.provide(WorkspacePaths.layer),
28 Layer.provide(T3ProjectFileLoader.layer),
29 ),
30 ServerSecretStore.layer.pipe(Layer.provide(configLayer)),
31).pipe(Layer.provideMerge(NodeServices.layer));
32​
33describe("AssetAccess", () => {
34 it.effect("issues workspace URLs that resolve the entry file and sibling assets", () =>
35 Effect.gen(function* () {
36 const fileSystem = yield* FileSystem.FileSystem;
37 const path = yield* Path.Path;
38 const root = yield* fileSystem.makeTempDirectoryScoped({
39 prefix: "t3-asset-workspace-",
40 });
41 const htmlPath = path.join(root, "report.html");
42 const cssPath = path.join(root, "report.css");
43 yield* fileSystem.writeFileString(htmlPath, '<link rel="stylesheet" href="report.css">');
44 yield* fileSystem.writeFileString(cssPath, "body { color: red; }");
45 yield* fileSystem.writeFileString(path.join(root, ".env"), "SECRET=value");
46 const canonicalHtmlPath = yield* fileSystem.realPath(htmlPath);
47 const canonicalCssPath = yield* fileSystem.realPath(cssPath);
48​
49 const result = yield* issueAssetUrl({
50 resource: {
51 _tag: "workspace-file",
52 threadId: ThreadId.make("thread-1"),
53 path: htmlPath,
54 },
55 workspaceRoot: root,
56 });
57 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
58 const separatorIndex = suffix.indexOf("/");
59 const token = suffix.slice(0, separatorIndex);
60​
61 expect(yield* resolveAsset(token, "report.html")).toEqual({
62 kind: "file",
63 path: canonicalHtmlPath,
64 });
65 expect(yield* resolveAsset(token, "report.css")).toEqual({
66 kind: "file",
67 path: canonicalCssPath,
68 });
69 expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
70 expect(yield* resolveAsset(token, ".env")).toBeNull();
71 expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull();
72 }).pipe(Effect.provide(testLayer)),
73 );
74​
75 it.effect("rejects workspace files outside the authorized root", () =>
76 Effect.gen(function* () {
77 const fileSystem = yield* FileSystem.FileSystem;
78 const path = yield* Path.Path;
79 const root = yield* fileSystem.makeTempDirectoryScoped({
80 prefix: "t3-asset-root-",
81 });
82 const outside = yield* fileSystem.makeTempDirectoryScoped({
83 prefix: "t3-asset-outside-",
84 });
85 const htmlPath = path.join(outside, "report.html");
86 yield* fileSystem.writeFileString(htmlPath, "<p>outside</p>");
87​
88 const error = yield* issueAssetUrl({
89 resource: {
90 _tag: "workspace-file",
91 threadId: ThreadId.make("thread-1"),
92 path: htmlPath,
93 },
94 workspaceRoot: root,
95 }).pipe(Effect.flip);
96 expect(error.message).toBe("Workspace file path must be relative to the project root.");
97 expect(error).toMatchObject({
98 _tag: "AssetWorkspacePathValidationError",
99 resource: {
100 _tag: "workspace-file",
101 threadId: "thread-1",
102 path: htmlPath,
103 },
104 });
105 expect(error.cause).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
106 }).pipe(Effect.provide(testLayer)),
107 );
108​
109 it.effect("preserves non-missing canonical path failures when issuing asset URLs", () =>
110 Effect.gen(function* () {
111 const fileSystem = yield* FileSystem.FileSystem;
112 const path = yield* Path.Path;
113 const root = yield* fileSystem.makeTempDirectoryScoped({
114 prefix: "t3-asset-permission-root-",
115 });
116 const htmlPath = path.join(root, "report.html");
117 yield* fileSystem.writeFileString(htmlPath, "<p>report</p>");
118 const cause = PlatformError.systemError({
119 _tag: "PermissionDenied",
120 module: "FileSystem",
121 method: "realPath",
122 pathOrDescriptor: htmlPath,
123 });
124 const failingFileSystem = FileSystem.FileSystem.of({
125 ...fileSystem,
126 realPath: () => Effect.fail(cause),
127 });
128​
129 const error = yield* issueAssetUrl({
130 resource: {
131 _tag: "workspace-file",
132 threadId: ThreadId.make("thread-1"),
133 path: htmlPath,
134 },
135 workspaceRoot: root,
136 }).pipe(Effect.provideService(FileSystem.FileSystem, failingFileSystem), Effect.flip);
137​
138 expect(error.message).toBe("Failed to inspect the workspace asset.");
139 expect(error).toMatchObject({
140 _tag: "AssetWorkspaceAssetInspectionError",
141 resource: {
142 _tag: "workspace-file",
143 threadId: "thread-1",
144 path: htmlPath,
145 },
146 });
147 expect(error.cause).toBe(cause);
148 }).pipe(Effect.provide(testLayer)),
149 );
150​
151 it.effect("issues exact workspace URLs for image previews", () =>
152 Effect.gen(function* () {
153 const fileSystem = yield* FileSystem.FileSystem;
154 const path = yield* Path.Path;
155 const root = yield* fileSystem.makeTempDirectoryScoped({
156 prefix: "t3-asset-image-workspace-",
157 });
158 const assetsDirectory = path.join(root, "assets");
159 const imagePath = path.join(assetsDirectory, "icon.png");
160 const siblingPath = path.join(assetsDirectory, "other.png");
161 yield* fileSystem.makeDirectory(assetsDirectory, { recursive: true });
162 yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
163 yield* fileSystem.writeFile(siblingPath, new Uint8Array([137, 80, 78, 71]));
164 const canonicalImagePath = yield* fileSystem.realPath(imagePath);
165​
166 const result = yield* issueAssetUrl({
167 resource: {
168 _tag: "workspace-file",
169 threadId: ThreadId.make("thread-1"),
170 path: imagePath,
171 },
172 workspaceRoot: root,
173 });
174 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
175 const separatorIndex = suffix.indexOf("/");
176 const token = suffix.slice(0, separatorIndex);
177​
178 expect(yield* resolveAsset(token, "icon.png")).toEqual({
179 kind: "file",
180 path: canonicalImagePath,
181 });
182 expect(yield* resolveAsset(token, "other.png")).toBeNull();
183 expect(yield* resolveAsset(token, "../icon.png")).toBeNull();
184 }).pipe(Effect.provide(testLayer)),
185 );
186​
187 it.effect("issues exact attachment capabilities by attachment id", () =>
188 Effect.gen(function* () {
189 const config = yield* ServerConfig.ServerConfig;
190 const fileSystem = yield* FileSystem.FileSystem;
191 const path = yield* Path.Path;
192 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001";
193 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.png`);
194 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
195 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
196​
197 const result = yield* issueAssetUrl({
198 resource: { _tag: "attachment", attachmentId },
199 });
200 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
201 const separatorIndex = suffix.indexOf("/");
202 const token = suffix.slice(0, separatorIndex);
203​
204 expect(yield* resolveAsset(token, "ignored.png")).toEqual({
205 kind: "file",
206 path: attachmentPath,
207 });
208 }).pipe(Effect.provide(testLayer)),
209 );
210​
211 it.effect("serves video attachments inline", () =>
212 Effect.gen(function* () {
213 const config = yield* ServerConfig.ServerConfig;
214 const fileSystem = yield* FileSystem.FileSystem;
215 const path = yield* Path.Path;
216 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001-mp4";
217 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.mp4`);
218 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
219 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
220​
221 const result = yield* issueAssetUrl({
222 resource: {
223 _tag: "attachment",
224 attachmentId,
225 fileName: "demo.mp4",
226 mimeType: 'video/mp4; codecs="avc1.42E01E"',
227 },
228 });
229 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
230 const separatorIndex = suffix.indexOf("/");
231​
232 expect(
233 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
234 ).toEqual({
235 kind: "file",
236 path: attachmentPath,
237 fileName: "demo.mp4",
238 mimeType: "video/mp4",
239 });
240 }).pipe(Effect.provide(testLayer)),
241 );
242 it.effect("issues project favicon capabilities with a signed fallback", () =>
243 Effect.gen(function* () {
244 const fileSystem = yield* FileSystem.FileSystem;
245 const path = yield* Path.Path;
246 const root = yield* fileSystem.makeTempDirectoryScoped({
247 prefix: "t3-asset-favicon-",
248 });
249 const faviconPath = path.join(root, "favicon.svg");
250 const initialFavicon = "<svg>a</svg>";
251 const updatedFavicon = "<svg>b</svg>";
252 expect(updatedFavicon).toHaveLength(initialFavicon.length);
253 yield* fileSystem.writeFileString(faviconPath, initialFavicon);
254 const canonicalFaviconPath = yield* fileSystem.realPath(faviconPath);
255​
256 const faviconResult = yield* issueAssetUrl({
257 resource: { _tag: "project-favicon", cwd: root },
258 });
259 expect(faviconResult.sourcePath).toBe("favicon.svg");
260 expect(faviconResult.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
261 expect(
262 yield* issueAssetUrl({
263 resource: { _tag: "project-favicon", cwd: root },
264 }),
265 ).toEqual(faviconResult);
266 const faviconSuffix = faviconResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
267 const faviconSeparatorIndex = faviconSuffix.indexOf("/");
268 expect(
269 yield* resolveAsset(
270 faviconSuffix.slice(0, faviconSeparatorIndex),
271 faviconSuffix.slice(faviconSeparatorIndex + 1),
272 ),
273 ).toEqual({ kind: "file", path: canonicalFaviconPath });
274​
275 yield* fileSystem.writeFileString(faviconPath, updatedFavicon);
276 const updatedFaviconResult = yield* issueAssetUrl({
277 resource: { _tag: "project-favicon", cwd: root },
278 });
279 expect(
280 updatedFaviconResult.relativeUrl.slice(updatedFaviconResult.relativeUrl.lastIndexOf("/")),
281 ).not.toBe(faviconResult.relativeUrl.slice(faviconResult.relativeUrl.lastIndexOf("/")));
282​
283 yield* fileSystem.remove(faviconPath);
284 const fallbackResult = yield* issueAssetUrl({
285 resource: { _tag: "project-favicon", cwd: root },
286 });
287 expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
288 expect(fallbackResult.sourcePath).toBeUndefined();
289 const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
290 const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
291 expect(
292 yield* resolveAsset(
293 fallbackSuffix.slice(0, fallbackSeparatorIndex),
294 fallbackSuffix.slice(fallbackSeparatorIndex + 1),
295 ),
296 ).toBeNull();
297 }).pipe(Effect.provide(testLayer)),
298 );
299​
300 it.effect("issues project favicon capabilities for a saved override", () =>
301 Effect.gen(function* () {
302 const fileSystem = yield* FileSystem.FileSystem;
303 const path = yield* Path.Path;
304 const root = yield* fileSystem.makeTempDirectoryScoped({
305 prefix: "t3-asset-favicon-override-",
306 });
307 yield* fileSystem.makeDirectory(path.join(root, "brand"));
308 yield* fileSystem.writeFileString(path.join(root, "brand", "custom.svg"), "<svg />");
309 yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg>auto</svg>");
310​
311 const result = yield* issueAssetUrl({
312 resource: { _tag: "project-favicon", cwd: root },
313 projectFaviconPath: "brand/custom.svg",
314 });
315​
316 expect(result.sourcePath).toBe("brand/custom.svg");
317 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.svg$/);
318 }).pipe(Effect.provide(testLayer)),
319 );
320​
321 it.effect("issues an exact capability for a saved favicon outside the workspace", () =>
322 Effect.gen(function* () {
323 const fileSystem = yield* FileSystem.FileSystem;
324 const path = yield* Path.Path;
325 const root = yield* fileSystem.makeTempDirectoryScoped({
326 prefix: "t3-asset-favicon-workspace-",
327 });
328 const pictures = yield* fileSystem.makeTempDirectoryScoped({
329 prefix: "t3-asset-favicon-pictures-",
330 });
331 const externalPath = path.join(pictures, "custom.png");
332 const siblingPath = path.join(pictures, "sibling.png");
333 yield* fileSystem.writeFile(externalPath, new Uint8Array([1, 2, 3]));
334 yield* fileSystem.writeFile(siblingPath, new Uint8Array([4, 5, 6]));
335 const canonicalPath = yield* fileSystem.realPath(externalPath);
336 const canonicalSiblingPath = yield* fileSystem.realPath(siblingPath);
337​
338 const result = yield* issueAssetUrl({
339 resource: { _tag: "project-favicon", cwd: root },
340 projectFaviconPath: externalPath,
341 });
342 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
343 const separatorIndex = suffix.indexOf("/");
344​
345 expect(result.sourcePath).toBe(externalPath);
346 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.png$/);
347 expect(
348 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
349 ).toEqual({ kind: "file", path: canonicalPath });
350 const tamperedSuffixResult = yield* resolveAsset(
351 suffix.slice(0, separatorIndex),
352 "sibling.png",
353 );
354 expect(tamperedSuffixResult).toEqual({ kind: "file", path: canonicalPath });
355 expect(tamperedSuffixResult).not.toEqual({ kind: "file", path: canonicalSiblingPath });
356 }).pipe(Effect.provide(testLayer)),
357 );
358​
359 it.effect("ignores a client favicon path hint", () =>
360 Effect.gen(function* () {
361 const fileSystem = yield* FileSystem.FileSystem;
362 const path = yield* Path.Path;
363 const root = yield* fileSystem.makeTempDirectoryScoped({
364 prefix: "t3-asset-favicon-hint-",
365 });
366 yield* fileSystem.makeDirectory(path.join(root, "brand"));
367 yield* fileSystem.writeFileString(path.join(root, "brand", "hint.svg"), "<svg>hint</svg>");
368 yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
369​
370 const result = yield* issueAssetUrl({
371 resource: { _tag: "project-favicon", cwd: root, path: "brand/hint.svg" },
372 projectFaviconPath: "brand/saved.svg",
373 });
374​
375 expect(result.sourcePath).toBe("brand/saved.svg");
376 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-saved\.svg$/);
377 }).pipe(Effect.provide(testLayer)),
378 );
379​
380 it.effect("keeps automatic favicon resolution separate from a saved override", () =>
381 Effect.gen(function* () {
382 const fileSystem = yield* FileSystem.FileSystem;
383 const path = yield* Path.Path;
384 const root = yield* fileSystem.makeTempDirectoryScoped({
385 prefix: "t3-asset-favicon-automatic-",
386 });
387 yield* fileSystem.makeDirectory(path.join(root, "brand"));
388 yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
389 yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg>automatic</svg>");
390​
391 const result = yield* issueAssetUrl({
392 resource: { _tag: "project-favicon", cwd: root },
393 });
394​
395 expect(result.sourcePath).toBe("favicon.svg");
396 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
397 }).pipe(Effect.provide(testLayer)),
398 );
399​
400 it.effect("rejects a resolved project favicon with a non-image extension", () =>
401 Effect.gen(function* () {
402 const fileSystem = yield* FileSystem.FileSystem;
403 const path = yield* Path.Path;
404 const root = yield* fileSystem.makeTempDirectoryScoped({
405 prefix: "t3-asset-favicon-type-",
406 });
407 yield* fileSystem.writeFileString(path.join(root, "secret.txt"), "not an image");
408​
409 const error = yield* issueAssetUrl({
410 resource: { _tag: "project-favicon", cwd: root },
411 projectFaviconPath: "secret.txt",
412 }).pipe(Effect.flip);
413​
414 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
415 }).pipe(Effect.provide(testLayer)),
416 );
417​
418 it.effect("buckets project favicon expiry after content hashing", () =>
419 Effect.gen(function* () {
420 const crypto = yield* Crypto.Crypto;
421 const fileSystem = yield* FileSystem.FileSystem;
422 const path = yield* Path.Path;
423 const root = yield* fileSystem.makeTempDirectoryScoped({
424 prefix: "t3-asset-favicon-expiry-",
425 });
426 yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg />");
427​
428 const bucketMs = 30 * 60 * 1000;
429 yield* TestClock.setTime(bucketMs - 1);
430 const crossingCrypto = Crypto.make({
431 randomBytes: (size) => new Uint8Array(size),
432 digest: (algorithm, data) =>
433 TestClock.adjust("2 millis").pipe(Effect.andThen(crypto.digest(algorithm, data))),
434 });
435 const result = yield* issueAssetUrl({
436 resource: { _tag: "project-favicon", cwd: root },
437 }).pipe(Effect.provideService(Crypto.Crypto, crossingCrypto));
438​
439 expect(result.expiresAt).toBe(3 * bucketMs);
440 }).pipe(Effect.provide(testLayer)),
441 );
442​
443 it.effect("preserves structured project favicon resolution causes", () =>
444 Effect.gen(function* () {
445 const fileSystem = yield* FileSystem.FileSystem;
446 const root = yield* fileSystem.makeTempDirectoryScoped({
447 prefix: "t3-asset-favicon-error-",
448 });
449 const platformCause = PlatformError.systemError({
450 _tag: "PermissionDenied",
451 module: "FileSystem",
452 method: "stat",
453 });
454 const resolutionCause = new ProjectFaviconResolver.ProjectFaviconResolutionError({
455 operation: "stat-candidate",
456 workspaceRoot: root,
457 relativePath: "favicon.svg",
458 cause: platformCause,
459 });
460 const resolver = ProjectFaviconResolver.ProjectFaviconResolver.of({
461 resolvePath: () => Effect.fail(resolutionCause),
462 });
463​
464 const error = yield* issueAssetUrl({
465 resource: { _tag: "project-favicon", cwd: root },
466 }).pipe(
467 Effect.provideService(ProjectFaviconResolver.ProjectFaviconResolver, resolver),
468 Effect.flip,
469 );
470​
471 expect(error.message).toBe("Failed to resolve project favicon.");
472 expect(error._tag).toBe("AssetProjectFaviconResolutionError");
473 expect(error.cause).toBe(resolutionCause);
474 }).pipe(Effect.provide(testLayer)),
475 );
476});