Open History to see the last commit
1import * as DocumentText from "../provider/DocumentText.ts";
2// @effect-diagnostics nodeBuiltinImport:off
3import * as NodeFS from "node:fs";
4import * as NodePath from "node:path";
5
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { describe, expect, it } from "@effect/vitest";
8import { ChatAttachmentId } from "@t3tools/contracts";
9import * as Deferred from "effect/Deferred";
10import * as Effect from "effect/Effect";
11import * as Fiber from "effect/Fiber";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as PlatformError from "effect/PlatformError";
15import * as Schema from "effect/Schema";
16import * as Stream from "effect/Stream";
17
18import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
19import { base64UrlEncode, signPayload } from "../auth/utils.ts";
20import * as ServerConfig from "../config.ts";
21import {
22 claimPendingAttachments,
23 releaseClaimedAttachments,
24} from "../orchestration-v2/AttachmentClaims.ts";
25import {
26 ATTACHMENT_UPLOAD_ROUTE_PREFIX,
27 deletePendingAttachment,
28 issueAttachmentUploadUrl,
29 storeAttachmentUpload,
30 validateAttachmentUploadToken,
31} from "./AttachmentUpload.ts";
32
33const layerTest = ServerSecretStore.layer.pipe(
34 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-attachment-upload-" })),
35 Layer.provideMerge(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
36);
37
38const uploadInput = {
39 name: "screenshot.png",
40 mimeType: "image/png",
41 sizeBytes: 6,
42} as const;
43
44const LegacyAttachmentUploadClaims = Schema.Struct({
45 version: Schema.Literal(1),
46 kind: Schema.Literal("attachment-upload"),
47 attachmentId: Schema.String,
48 name: Schema.String,
49 mimeType: Schema.String,
50 sizeBytes: Schema.Number,
51 expiresAt: Schema.Number,
52});
53const encodeLegacyAttachmentUploadClaims = Schema.encodeEffect(
54 Schema.fromJsonString(LegacyAttachmentUploadClaims),
55);
56
57describe("AttachmentUpload", () => {
58 it.effect.each([false, true])(
59 "persists and replays immutable uploads (hard links unsupported: %s)",
60 (unsupported) =>
61 Effect.gen(function* () {
62 const config = yield* ServerConfig.ServerConfig;
63 const fileSystem = yield* FileSystem.FileSystem;
64 const store = (claims: Parameters<typeof storeAttachmentUpload>[0], bytes: Uint8Array) =>
65 storeAttachmentUpload(claims, bytes).pipe(
66 Effect.provideService(
67 FileSystem.FileSystem,
68 unsupported
69 ? {
70 ...fileSystem,
71 link: () =>
72 Effect.fail(
73 PlatformError.systemError({
74 _tag: "Unknown",
75 module: "FileSystem",
76 method: "link",
77 }),
78 ),
79 }
80 : fileSystem,
81 ),
82 );
83 const bytes = new TextEncoder().encode(
84 JSON.stringify({
85 cells: [{ cell_type: "markdown", source: ["# Cargo\n", "Violet crates: 19"] }],
86 }),
87 );
88 const issued = yield* issueAttachmentUploadUrl({
89 type: "file",
90 name: "cargo.ipynb",
91 mimeType: "application/x-ipynb+json",
92 sizeBytes: bytes.length,
93 });
94 const claims = yield* validateAttachmentUploadToken(
95 issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length),
96 );
97 if (!claims) throw new Error("Expected upload claims");
98 expect(yield* store(claims, bytes)).toEqual({ ok: true });
99 expect(yield* store(claims, bytes)).toEqual({ ok: true });
100 const path = NodePath.join(config.attachmentsDir, `${issued.attachmentId}.ipynb`);
101 expect(NodeFS.readFileSync(`${path}.txt`, "utf8")).toContain("Violet crates: 19");
102 const replacement = new TextEncoder().encode(
103 new TextDecoder().decode(bytes).replace("Violet crates: 19", "Violet crates: 28"),
104 );
105 expect(yield* store(claims, replacement)).toMatchObject({
106 ok: false,
107 status: 409,
108 });
109 expect(NodeFS.readFileSync(path)).toEqual(Buffer.from(bytes));
110 expect(NodeFS.readFileSync(`${path}.txt`, "utf8")).toContain("Violet crates: 19");
111 const claimed = yield* claimPendingAttachments({
112 threadId: "document-thread",
113 attachments: [
114 {
115 type: "file",
116 id: ChatAttachmentId.make(issued.attachmentId),
117 name: claims.name,
118 mimeType: claims.mimeType,
119 sizeBytes: bytes.length,
120 },
121 ],
122 });
123 expect(claimed.claimedPaths).toHaveLength(2);
124 expect(NodeFS.readFileSync(claimed.claimedPaths[1]!, "utf8")).toContain(
125 "Violet crates: 19",
126 );
127 yield* deletePendingAttachment(issued.attachmentId);
128 expect(NodeFS.existsSync(path)).toBe(false);
129 expect(NodeFS.existsSync(`${path}.txt`)).toBe(false);
130 expect(NodeFS.existsSync(claimed.claimedPaths[1]!)).toBe(true);
131 yield* releaseClaimedAttachments(claimed.claimedPaths);
132 expect(NodeFS.existsSync(claimed.claimedPaths[1]!)).toBe(false);
133 }).pipe(Effect.provide(layerTest)),
134 );
135 it.effect("rejects tampered and malformed upload tokens", () =>
136 Effect.gen(function* () {
137 const issued = yield* issueAttachmentUploadUrl(uploadInput);
138 const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
139 const [payload, signature] = token.split(".");
140
141 expect(yield* validateAttachmentUploadToken(`${payload}x.${signature}`)).toBeNull();
142 expect(yield* validateAttachmentUploadToken(`${token}.extra`)).toBeNull();
143 expect(yield* validateAttachmentUploadToken("garbage")).toBeNull();
144 }).pipe(Effect.provide(layerTest)),
145 );
146
147 it.effect("accepts unexpired image upload tokens issued before file support", () =>
148 Effect.gen(function* () {
149 const issued = yield* issueAttachmentUploadUrl(uploadInput);
150 const secretStore = yield* ServerSecretStore.ServerSecretStore;
151 const secret = yield* secretStore.getOrCreateRandom("asset-access-signing-key", 32);
152 const encodedPayload = base64UrlEncode(
153 yield* encodeLegacyAttachmentUploadClaims({
154 version: 1,
155 kind: "attachment-upload",
156 attachmentId: issued.attachmentId,
157 name: uploadInput.name,
158 mimeType: uploadInput.mimeType,
159 sizeBytes: uploadInput.sizeBytes,
160 expiresAt: issued.expiresAt,
161 }),
162 );
163 const legacyToken = `${encodedPayload}.${signPayload(encodedPayload, secret)}`;
164
165 expect(yield* validateAttachmentUploadToken(legacyToken)).toMatchObject({
166 type: "image",
167 attachmentId: issued.attachmentId,
168 });
169 }).pipe(Effect.provide(layerTest)),
170 );
171
172 it.effect("stores the expected bytes without leaving temporary files", () =>
173 Effect.gen(function* () {
174 const config = yield* ServerConfig.ServerConfig;
175 const issued = yield* issueAttachmentUploadUrl(uploadInput);
176 const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
177 const claims = yield* validateAttachmentUploadToken(token);
178 if (!claims) {
179 throw new Error("Expected valid upload claims.");
180 }
181
182 expect(yield* storeAttachmentUpload(claims, new Uint8Array([1, 2, 3]))).toMatchObject({
183 ok: false,
184 status: 400,
185 });
186 expect(yield* storeAttachmentUpload(claims, new Uint8Array(6))).toEqual({ ok: true });
187 expect(
188 NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${issued.attachmentId}.png`)),
189 ).toBe(true);
190 expect(
191 NodeFS.readdirSync(config.attachmentsDir).filter((entry) => entry.endsWith(".part")),
192 ).toEqual([]);
193 }).pipe(Effect.provide(layerTest)),
194 );
195
196 it.effect("streams generic files to a path with their original extension", () =>
197 Effect.gen(function* () {
198 const config = yield* ServerConfig.ServerConfig;
199 const issued = yield* issueAttachmentUploadUrl({
200 type: "file",
201 name: "report.PDF",
202 mimeType: "application/pdf",
203 sizeBytes: 6,
204 });
205 const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
206 const claims = yield* validateAttachmentUploadToken(token);
207 if (!claims) {
208 throw new Error("Expected valid upload claims.");
209 }
210
211 expect(
212 yield* storeAttachmentUpload(
213 claims,
214 Stream.make(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])),
215 ),
216 ).toEqual({ ok: true });
217 expect(issued.attachmentId).toMatch(/-pdf$/);
218 expect(
219 NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${issued.attachmentId}.pdf`)),
220 ).toEqual(Buffer.from([1, 2, 3, 4, 5, 6]));
221
222 yield* deletePendingAttachment(issued.attachmentId);
223 expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([]);
224 }).pipe(Effect.provide(layerTest)),
225 );
226
227 it.effect("stores MIME-identified SVG files with a previewable signed extension", () =>
228 Effect.gen(function* () {
229 const config = yield* ServerConfig.ServerConfig;
230 const bytes = new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"/>');
231 for (const name of ["diagram", "diagram.bin"]) {
232 const issued = yield* issueAttachmentUploadUrl({
233 type: "file",
234 name,
235 mimeType: "image/svg+xml",
236 sizeBytes: bytes.length,
237 });
238 const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
239 const claims = yield* validateAttachmentUploadToken(token);
240 if (!claims) throw new Error("Expected valid SVG upload claims.");
241 expect(claims.name).toBe(`${name}.svg`);
242 expect(issued.attachmentId).toMatch(/-svg$/);
243 expect(yield* storeAttachmentUpload(claims, bytes)).toEqual({ ok: true });
244 expect(
245 NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${issued.attachmentId}.svg`)),
246 ).toEqual(Buffer.from(bytes));
247 const claimed = yield* claimPendingAttachments({
248 threadId: "svg-upload-thread",
249 attachments: [
250 {
251 type: "file",
252 id: ChatAttachmentId.make(issued.attachmentId),
253 name,
254 mimeType: "image/svg+xml",
255 sizeBytes: bytes.length,
256 },
257 ],
258 });
259 expect(claimed.attachments[0]?.name).toBe(`${name}.svg`);
260 expect(NodeFS.readFileSync(claimed.claimedPaths[0]!)).toEqual(Buffer.from(bytes));
261 yield* releaseClaimedAttachments(claimed.claimedPaths);
262 yield* deletePendingAttachment(issued.attachmentId);
263 }
264 expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([]);
265 }).pipe(Effect.provide(layerTest)),
266 );
267
268 it.effect("removes partial streamed uploads that exceed their signed size", () =>
269 Effect.gen(function* () {
270 const config = yield* ServerConfig.ServerConfig;
271 const issued = yield* issueAttachmentUploadUrl(uploadInput);
272 const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
273 const claims = yield* validateAttachmentUploadToken(token);
274 if (!claims) {
275 throw new Error("Expected valid upload claims.");
276 }
277
278 expect(yield* storeAttachmentUpload(claims, Stream.make(new Uint8Array(7)))).toMatchObject({
279 ok: false,
280 status: 400,
281 });
282 expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([]);
283 }).pipe(Effect.provide(layerTest)),
284 );
285
286 it.effect("removes partial streamed uploads when the upload is interrupted", () =>
287 Effect.gen(function* () {
288 const config = yield* ServerConfig.ServerConfig;
289 const issued = yield* issueAttachmentUploadUrl(uploadInput);
290 const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
291 const claims = yield* validateAttachmentUploadToken(token);
292 if (!claims) {
293 throw new Error("Expected valid upload claims.");
294 }
295
296 const nextChunkRequested = yield* Deferred.make<void>();
297 const body = Stream.make(new Uint8Array([1, 2, 3])).pipe(
298 Stream.concat(
299 Stream.fromEffect(
300 Deferred.succeed(nextChunkRequested, undefined).pipe(Effect.andThen(Effect.never)),
301 ),
302 ),
303 );
304 const upload = yield* storeAttachmentUpload(claims, body).pipe(Effect.forkScoped);
305
306 yield* Deferred.await(nextChunkRequested);
307 expect(
308 NodeFS.readdirSync(config.attachmentsDir).filter((entry) => entry.endsWith(".part")),
309 ).toHaveLength(1);
310
311 yield* Fiber.interrupt(upload);
312 expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([]);
313 }).pipe(Effect.provide(layerTest)),
314 );
315
316 it.effect("deletes pending uploads without deleting thread-owned copies", () =>
317 Effect.gen(function* () {
318 const config = yield* ServerConfig.ServerConfig;
319 const uuid = "00000000-0000-4000-8000-0000000000dd";
320 const pendingPath = NodePath.join(config.attachmentsDir, `pending-${uuid}.png`);
321 const claimedPath = NodePath.join(config.attachmentsDir, `thread-1-${uuid}.png`);
322 NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
323 NodeFS.writeFileSync(claimedPath, Buffer.from("pixels"));
324
325 yield* deletePendingAttachment(`pending-${uuid}`);
326 yield* deletePendingAttachment(`pending-${uuid}`);
327 yield* deletePendingAttachment(`thread-1-${uuid}`);
328
329 expect(NodeFS.existsSync(pendingPath)).toBe(false);
330 expect(NodeFS.existsSync(claimedPath)).toBe(true);
331 }).pipe(Effect.provide(layerTest)),
332 );
333});