Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodePath from "node:path";
4
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import { describe, expect, it } from "@effect/vitest";
7import * as Deferred from "effect/Deferred";
8import * as Effect from "effect/Effect";
9import * as Fiber from "effect/Fiber";
10import * as Layer from "effect/Layer";
11import * as Schema from "effect/Schema";
12import * as Stream from "effect/Stream";
13
14import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
15import { base64UrlEncode, signPayload } from "../auth/utils.ts";
16import * as ServerConfig from "../config.ts";
17import {
18 ATTACHMENT_UPLOAD_ROUTE_PREFIX,
19 deletePendingAttachment,
20 issueAttachmentUploadUrl,
21 storeAttachmentUpload,
22 validateAttachmentUploadToken,
23} from "./AttachmentUpload.ts";
24
25const layerTest = ServerSecretStore.layer.pipe(
26 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-attachment-upload-" })),
27 Layer.provideMerge(NodeServices.layer),
28);
29
30const uploadInput = {
31 name: "screenshot.png",
32 mimeType: "image/png",
33 sizeBytes: 6,
34} as const;
35
36const LegacyAttachmentUploadClaims = Schema.Struct({
37 version: Schema.Literal(1),
38 kind: Schema.Literal("attachment-upload"),
39 attachmentId: Schema.String,
40 name: Schema.String,
41 mimeType: Schema.String,
42 sizeBytes: Schema.Number,
43 expiresAt: Schema.Number,
44});
45const encodeLegacyAttachmentUploadClaims = Schema.encodeEffect(
46 Schema.fromJsonString(LegacyAttachmentUploadClaims),
47);
48
49describe("AttachmentUpload", () => {
50 it.effect("rejects tampered and malformed upload tokens", () =>
51 Effect.gen(function* () {
52 const issued = yield* issueAttachmentUploadUrl(uploadInput);
53 const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
54 const [payload, signature] = token.split(".");
55
56 expect(yield* validateAttachmentUploadToken(`${payload}x.${signature}`)).toBeNull();
57 expect(yield* validateAttachmentUploadToken(`${token}.extra`)).toBeNull();
58 expect(yield* validateAttachmentUploadToken("garbage")).toBeNull();
59 }).pipe(Effect.provide(layerTest)),
60 );
61
62 it.effect("accepts unexpired image upload tokens issued before file support", () =>
63 Effect.gen(function* () {
64 const issued = yield* issueAttachmentUploadUrl(uploadInput);
65 const secretStore = yield* ServerSecretStore.ServerSecretStore;
66 const secret = yield* secretStore.getOrCreateRandom("asset-access-signing-key", 32);
67 const encodedPayload = base64UrlEncode(
68 yield* encodeLegacyAttachmentUploadClaims({
69 version: 1,
70 kind: "attachment-upload",
71 attachmentId: issued.attachmentId,
72 name: uploadInput.name,
73 mimeType: uploadInput.mimeType,
74 sizeBytes: uploadInput.sizeBytes,
75 expiresAt: issued.expiresAt,
76 }),
77 );
78 const legacyToken = `${encodedPayload}.${signPayload(encodedPayload, secret)}`;
79
80 expect(yield* validateAttachmentUploadToken(legacyToken)).toMatchObject({
81 type: "image",
82 attachmentId: issued.attachmentId,
83 });
84 }).pipe(Effect.provide(layerTest)),
85 );
86
87 it.effect("stores the expected bytes without leaving temporary files", () =>
88 Effect.gen(function* () {
89 const config = yield* ServerConfig.ServerConfig;
90 const issued = yield* issueAttachmentUploadUrl(uploadInput);
91 const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
92 const claims = yield* validateAttachmentUploadToken(token);
93 if (!claims) {
94 throw new Error("Expected valid upload claims.");
95 }
96
97 expect(yield* storeAttachmentUpload(claims, new Uint8Array([1, 2, 3]))).toMatchObject({
98 ok: false,
99 status: 400,
100 });
101 expect(yield* storeAttachmentUpload(claims, new Uint8Array(6))).toEqual({ ok: true });
102 expect(
103 NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${issued.attachmentId}.png`)),
104 ).toBe(true);
105 expect(
106 NodeFS.readdirSync(config.attachmentsDir).filter((entry) => entry.endsWith(".part")),
107 ).toEqual([]);
108 }).pipe(Effect.provide(layerTest)),
109 );
110
111 it.effect("streams generic files to a path with their original extension", () =>
112 Effect.gen(function* () {
113 const config = yield* ServerConfig.ServerConfig;
114 const issued = yield* issueAttachmentUploadUrl({
115 type: "file",
116 name: "report.PDF",
117 mimeType: "application/pdf",
118 sizeBytes: 6,
119 });
120 const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
121 const claims = yield* validateAttachmentUploadToken(token);
122 if (!claims) {
123 throw new Error("Expected valid upload claims.");
124 }
125
126 expect(
127 yield* storeAttachmentUpload(
128 claims,
129 Stream.make(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])),
130 ),
131 ).toEqual({ ok: true });
132 expect(issued.attachmentId).toMatch(/-pdf$/);
133 expect(
134 NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${issued.attachmentId}.pdf`)),
135 ).toEqual(Buffer.from([1, 2, 3, 4, 5, 6]));
136
137 yield* deletePendingAttachment(issued.attachmentId);
138 expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([]);
139 }).pipe(Effect.provide(layerTest)),
140 );
141
142 it.effect("removes partial streamed uploads that exceed their signed size", () =>
143 Effect.gen(function* () {
144 const config = yield* ServerConfig.ServerConfig;
145 const issued = yield* issueAttachmentUploadUrl(uploadInput);
146 const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
147 const claims = yield* validateAttachmentUploadToken(token);
148 if (!claims) {
149 throw new Error("Expected valid upload claims.");
150 }
151
152 expect(yield* storeAttachmentUpload(claims, Stream.make(new Uint8Array(7)))).toMatchObject({
153 ok: false,
154 status: 400,
155 });
156 expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([]);
157 }).pipe(Effect.provide(layerTest)),
158 );
159
160 it.effect("removes partial streamed uploads when the upload is interrupted", () =>
161 Effect.gen(function* () {
162 const config = yield* ServerConfig.ServerConfig;
163 const issued = yield* issueAttachmentUploadUrl(uploadInput);
164 const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
165 const claims = yield* validateAttachmentUploadToken(token);
166 if (!claims) {
167 throw new Error("Expected valid upload claims.");
168 }
169
170 const nextChunkRequested = yield* Deferred.make<void>();
171 const body = Stream.make(new Uint8Array([1, 2, 3])).pipe(
172 Stream.concat(
173 Stream.fromEffect(
174 Deferred.succeed(nextChunkRequested, undefined).pipe(Effect.andThen(Effect.never)),
175 ),
176 ),
177 );
178 const upload = yield* storeAttachmentUpload(claims, body).pipe(Effect.forkScoped);
179
180 yield* Deferred.await(nextChunkRequested);
181 expect(
182 NodeFS.readdirSync(config.attachmentsDir).filter((entry) => entry.endsWith(".part")),
183 ).toHaveLength(1);
184
185 yield* Fiber.interrupt(upload);
186 expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([]);
187 }).pipe(Effect.provide(layerTest)),
188 );
189
190 it.effect("deletes pending uploads without deleting thread-owned copies", () =>
191 Effect.gen(function* () {
192 const config = yield* ServerConfig.ServerConfig;
193 const uuid = "00000000-0000-4000-8000-0000000000dd";
194 const pendingPath = NodePath.join(config.attachmentsDir, `pending-${uuid}.png`);
195 const claimedPath = NodePath.join(config.attachmentsDir, `thread-1-${uuid}.png`);
196 NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
197 NodeFS.writeFileSync(claimedPath, Buffer.from("pixels"));
198
199 yield* deletePendingAttachment(`pending-${uuid}`);
200 yield* deletePendingAttachment(`pending-${uuid}`);
201 yield* deletePendingAttachment(`thread-1-${uuid}`);
202
203 expect(NodeFS.existsSync(pendingPath)).toBe(false);
204 expect(NodeFS.existsSync(claimedPath)).toBe(true);
205 }).pipe(Effect.provide(layerTest)),
206 );
207});