/ opencodehub / tests / integration / gists-route.test.ts
swadhinbiswas feat: finalize platform polish - discussions, gists, webhook queue, realtime, push-mirror, auth/metrics hardening · 8/28/2026
f02976d
459 lines · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/**
 * Integration tests for Gists routes:
 *   GET/POST /api/gists
 *   GET/PATCH/DELETE /api/gists/[id]
 *   GET /api/gists/[id]/raw/[file]
 */
import { beforeEach, describe, expect, it, vi } from "vitest";

/* ─── hoisted mocks ─── */
const mocks = vi.hoisted(() => ({
  getUserFromRequestMock: vi.fn().mockResolvedValue({
    userId: "usr_1",
    username: "alice",
    email: "[email protected]",
  }),
  generateIdMock: vi.fn(),
}));

vi.mock("@/db", () => ({
  getDatabase: () => mockDb,
}));

vi.mock("@/lib/auth", () => ({
  getUserFromRequest: mocks.getUserFromRequestMock,
}));

vi.mock("@/lib/errors", () => ({
  withErrorHandler: (fn: any) => fn,
}));

vi.mock("@/lib/logger", () => ({
  logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
}));

vi.mock("@/lib/utils", () => ({
  generateId: mocks.generateIdMock,
}));

/* ─── fixtures ─── */
import { gists } from "@/db/schema/gists";

const ownerGist = {
  id: "gist_1",
  userId: "usr_1",
  description: "my secret snippet",
  public: false,
  files: [{ filename: "a.txt", content: "hello world" }],
  createdAt: new Date("2026-01-01"),
  updatedAt: new Date("2026-01-02"),
};

/* ─── fake db ─── */
function thenable(result: unknown) {
  const p = Promise.resolve(result);
  const step = () => api;
  const api: any = {
    where: step,
    orderBy: step,
    limit: step,
    offset: step,
    innerJoin: step,
    leftJoin: step,
    then: p.then.bind(p),
    catch: p.catch.bind(p),
    finally: p.finally.bind(p),
  };
  return api;
}

function makeDb(opts: { gists?: any[] } = {}) {
  const rowsByTable = new Map<any, any[]>([[gists, opts.gists ?? [ownerGist]]]);

  const state = {
    inserted: null as any,
    updates: [] as any[],
    deletedWhere: null as any,
    /** Result returned by query.gists.findFirst */
    found: ownerGist as any,
  };

  const select = vi.fn((fields?: any) => {
    const isCount =
      fields &&
      typeof fields === "object" &&
      Object.keys(fields).length === 1 &&
      "total" in fields;
    return {
      from: (table: any) =>
        thenable(
          isCount
            ? [{ total: (rowsByTable.get(table) ?? []).length }]
            : (rowsByTable.get(table) ?? []),
        ),
    };
  });

  const insertValues = vi.fn((values: any) => {
    state.inserted = values;
    return Promise.resolve([]);
  });
  const insert = vi.fn(() => ({ values: insertValues }));

  const updateSet = vi.fn((values: any) => {
    state.updates.push(values);
    return {
      where: vi.fn().mockResolvedValue([]),
    };
  });
  const update = vi.fn(() => ({ set: updateSet }));

  const deleteWhere = vi.fn((where: any) => {
    state.deletedWhere = where;
    return Promise.resolve([]);
  });
  const del = vi.fn(() => ({ where: deleteWhere }));

  const query = {
    gists: {
      findFirst: vi.fn(async () => state.found),
    },
  };

  return {
    select,
    insert,
    insertValues,
    update,
    updateSet,
    delete: del,
    deleteWhere,
    query,
    state,
  };
}

let mockDb: ReturnType<typeof makeDb>;

/* ─── import routes ─── */
import { GET as listGists, POST as createGist } from "@/pages/api/gists/index";
import {
  DELETE as deleteGist,
  GET as getGist,
  PATCH as patchGist,
} from "@/pages/api/gists/[id]/index";
import { GET as getRawFile } from "@/pages/api/gists/[id]/raw/[file]";

const readJson = (r: Response) => r.json();

function listCtx(query = "") {
  const reqUrl = `http://localhost/api/gists${query}`;
  return { request: new Request(reqUrl), url: new URL(reqUrl) } as any;
}

function idCtx(
  request: Request,
  params: Record<string, string> = {},
) {
  return {
    request,
    url: new URL(request.url),
    params: { id: "gist_1", ...params },
  } as any;
}

const gistRequest = (
  body: unknown,
  method = "POST",
  path = "/api/gists",
) =>
  new Request(`http://localhost${path}`, {
    method,
    headers: { "Content-Type": "application/json" },
    ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
  });

beforeEach(() => {
  vi.clearAllMocks();
  mockDb = makeDb();
  mocks.generateIdMock.mockImplementation(
    (prefix?: string) => `${prefix ?? "id"}_new`,
  );
  mocks.getUserFromRequestMock.mockResolvedValue({
    userId: "usr_1",
    username: "alice",
    email: "[email protected]",
  });
});

/* ─── POST /api/gists (create) ─── */
describe("POST /api/gists", () => {
  it("returns 401 when not authenticated", async () => {
    mocks.getUserFromRequestMock.mockResolvedValue(null);
    const res = await createGist({
      request: gistRequest({ files: [{ filename: "a.txt", content: "x" }] }),
      url: new URL("http://localhost/api/gists"),
    } as any);
    expect(res.status).toBe(401);
  });

  it("returns 201 and creates a gist", async () => {
    const res = await createGist({
      request: gistRequest({
        description: "demo",
        public: true,
        files: [{ filename: "a.txt", content: "hello" }],
      }),
      url: new URL("http://localhost/api/gists"),
    } as any);
    expect(res.status).toBe(201);
    const json = await readJson(res);
    expect(json.data.id).toBe("gist_new");
    expect(json.data.description).toBe("demo");
    expect(json.data.public).toBe(true);
    expect(json.data.fileCount).toBe(1);
    expect(mockDb.state.inserted.userId).toBe("usr_1");
    expect(mocks.generateIdMock).toHaveBeenCalledWith("gist");
  });

  it("defaults description to '' and visibility to secret", async () => {
    const res = await createGist({
      request: gistRequest({ files: [{ filename: "a.txt", content: "x" }] }),
      url: new URL("http://localhost/api/gists"),
    } as any);
    const json = await readJson(res);
    expect(json.data.description).toBe("");
    expect(json.data.public).toBe(false);
  });

  it("returns 400 for path-traversal filenames", async () => {
    for (const filename of ["../escape.txt", "/etc/passwd", "a/b.txt"]) {
      const res = await createGist({
        request: gistRequest({ files: [{ filename, content: "x" }] }),
        url: new URL("http://localhost/api/gists"),
      } as any);
      expect(res.status).toBe(400);
      const json = await readJson(res);
      expect(json.error.code).toBe("BAD_REQUEST");
    }
  });

  it("returns 400 when files array is empty or exceeds 10 files", async () => {
    const empty = await createGist({
      request: gistRequest({ files: [] }),
      url: new URL("http://localhost/api/gists"),
    } as any);
    expect(empty.status).toBe(400);

    const tooMany = Array.from({ length: 11 }, (_, i) => ({
      filename: `f${i}.txt`,
      content: "x",
    }));
    const res = await createGist({
      request: gistRequest({ files: tooMany }),
      url: new URL("http://localhost/api/gists"),
    } as any);
    expect(res.status).toBe(400);
  });

  it("returns 400 when total content exceeds 1MB", async () => {
    const half = "a".repeat(512 * 1024);
    const res = await createGist({
      request: gistRequest({
        files: [
          { filename: "one.txt", content: half },
          { filename: "two.txt", content: half + "overflow" },
        ],
      }),
      url: new URL("http://localhost/api/gists"),
    } as any);
    expect(res.status).toBe(400);
  });
});

/* ─── GET /api/gists (list) ─── */
describe("GET /api/gists", () => {
  it("returns 401 when not authenticated", async () => {
    mocks.getUserFromRequestMock.mockResolvedValue(null);
    const res = await listGists(listCtx());
    expect(res.status).toBe(401);
  });

  it("returns 200 with pagination meta for authenticated user", async () => {
    const res = await listGists(listCtx());
    expect(res.status).toBe(200);
    const json = await readJson(res);
    expect(json.success).toBe(true);
    expect(Array.isArray(json.data)).toBe(true);
    expect(json.data[0].fileCount).toBe(1);
    expect(json.meta.page).toBe(1);
    expect(json.meta.total).toBe(1);
  });
});

/* ─── GET /api/gists/[id] ─── */
describe("GET /api/gists/[id]", () => {
  it("lets the owner read a secret gist", async () => {
    const res = await getGist(idCtx(gistRequest(undefined, "GET")));
    expect(res.status).toBe(200);
    const json = await readJson(res);
    expect(json.data.isOwner).toBe(true);
  });

  it("hides secret gists from non-owners (404)", async () => {
    mocks.getUserFromRequestMock.mockResolvedValue({
      userId: "usr_other",
      username: "bob",
    });
    const res = await getGist(idCtx(gistRequest(undefined, "GET")));
    expect(res.status).toBe(404);
  });

  it("serves public gists to anonymous users without isOwner", async () => {
    mockDb.state.found = { ...ownerGist, public: true };
    mocks.getUserFromRequestMock.mockResolvedValue(null);
    const res = await getGist(idCtx(gistRequest(undefined, "GET")));
    expect(res.status).toBe(200);
    const json = await readJson(res);
    expect(json.data.isOwner).toBe(false);
  });

  it("returns 404 for unknown ids", async () => {
    mockDb.state.found = undefined;
    const res = await getGist(idCtx(gistRequest(undefined, "GET")));
    expect(res.status).toBe(404);
  });
});

/* ─── PATCH /api/gists/[id] ─── */
describe("PATCH /api/gists/[id]", () => {
  it("is owner-only: returns 403 for authenticated non-owner", async () => {
    mocks.getUserFromRequestMock.mockResolvedValue({
      userId: "usr_other",
      username: "bob",
    });
    const res = await patchGist(
      idCtx(gistRequest({ description: "hack" }, "PATCH")),
    );
    expect(res.status).toBe(403);
    expect(mockDb.state.updates).toHaveLength(0);
  });

  it("returns 401 when unauthenticated", async () => {
    mocks.getUserFromRequestMock.mockResolvedValue(null);
    const res = await patchGist(
      idCtx(gistRequest({ description: "x" }, "PATCH")),
    );
    expect(res.status).toBe(401);
  });

  it("replaces description, visibility and files wholesale for the owner", async () => {
    const payload = {
      description: "updated",
      public: true,
      files: [{ filename: "new.txt", content: "new content" }],
    };
    const res = await patchGist(idCtx(gistRequest(payload, "PATCH")));
    expect(res.status).toBe(200);
    const applied = mockDb.state.updates[0];
    expect(applied.description).toBe("updated");
    expect(applied.public).toBe(true);
    expect(applied.files).toEqual(payload.files);
    expect(applied.updatedAt).toBeInstanceOf(Date);
  });

  it("returns 400 for invalid replacement files", async () => {
    const res = await patchGist(
      idCtx(gistRequest({ files: [{ filename: "../x", content: "" }] }, "PATCH")),
    );
    expect(res.status).toBe(400);
  });

  it("returns 404 when gist does not exist", async () => {
    mockDb.state.found = undefined;
    const res = await patchGist(
      idCtx(gistRequest({ description: "x" }, "PATCH")),
    );
    expect(res.status).toBe(404);
  });
});

/* ─── DELETE /api/gists/[id] ─── */
describe("DELETE /api/gists/[id]", () => {
  it("deletes for the owner and returns 204", async () => {
    const res = await deleteGist(idCtx(new Request("http://localhost/api/gists/gist_1", { method: "DELETE" })));
    expect(res.status).toBe(204);
    expect(mockDb.state.deletedWhere).toBeDefined();
  });

  it("is owner-only: returns 403 for authenticated non-owner", async () => {
    mocks.getUserFromRequestMock.mockResolvedValue({
      userId: "usr_other",
      username: "bob",
    });
    const res = await deleteGist(idCtx(new Request("http://localhost/api/gists/gist_1", { method: "DELETE" })));
    expect(res.status).toBe(403);
    expect(mockDb.state.deletedWhere).toBeNull();
  });

  it("returns 404 for unknown ids", async () => {
    mockDb.state.found = undefined;
    const res = await deleteGist(idCtx(new Request("http://localhost/api/gists/gist_1", { method: "DELETE" })));
    expect(res.status).toBe(404);
  });
});

/* ─── GET /api/gists/[id]/raw/[file] ─── */
describe("GET /api/gists/[id]/raw/[file]", () => {
  const rawCtx = (file: string, params = {}) =>
    idCtx(new Request(`http://localhost/api/gists/gist_1/raw/${file}`), {
      file,
      ...params,
    });

  it("serves file content as text/plain charset=utf-8", async () => {
    const res = await getRawFile(rawCtx("a.txt"));
    expect(res.status).toBe(200);
    expect(res.headers.get("Content-Type")).toBe("text/plain; charset=utf-8");
    expect(await res.text()).toBe("hello world");
  });

  it("allows anonymous access to public gists", async () => {
    mockDb.state.found = { ...ownerGist, public: true };
    mocks.getUserFromRequestMock.mockResolvedValue(null);
    const res = await getRawFile(rawCtx("a.txt"));
    expect(res.status).toBe(200);
    expect(res.headers.get("Content-Type")).toContain("text/plain");
  });

  it("requires auth for secret gists (401 anonymous)", async () => {
    mocks.getUserFromRequestMock.mockResolvedValue(null);
    const res = await getRawFile(rawCtx("a.txt"));
    expect(res.status).toBe(401);
  });

  it("hides secret gists from non-owners (404)", async () => {
    mocks.getUserFromRequestMock.mockResolvedValue({
      userId: "usr_other",
      username: "bob",
    });
    const res = await getRawFile(rawCtx("a.txt"));
    expect(res.status).toBe(404);
  });

  it("returns 404 for filenames not present in the gist", async () => {
    const res = await getRawFile(rawCtx("missing.txt"));
    expect(res.status).toBe(404);
  });

  it("decodes URL-encoded filenames", async () => {
    mockDb.state.found = {
      ...ownerGist,
      files: [{ filename: "my file.txt", content: "spaces are ok" }],
    };
    const res = await getRawFile(rawCtx("my%20file.txt"));
    expect(res.status).toBe(200);
    expect(await res.text()).toBe("spaces are ok");
  });
});