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