mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 09:36:08 +00:00
The suite that landed in #43/#44 was written against existing behaviour, so a number of tests pinned bugs rather than asserting correct behaviour. This fixes the production code and moves each of those tests onto the fixed behaviour in the same change. Security: - project-download: derive the archive entry extension from the last path segment and restrict it to a short alphanumeric run, so an extensionless allowlisted url can no longer contribute a path separator; validate the r2 branch against the strict proxy-path pattern instead of a `startsWith`, which let `/api/upload/video/clip.mp4/../../etc/passwd` through verbatim. - rate-limit: hash a key or action wider than its column instead of skipping the query. Both the guard and the failing INSERT used to answer "allowed", so the limit stopped applying entirely. Warn at startup when TRUSTED_PROXY_MODE is unset in production. - video uploads: the file name decides the content type; a client-declared video mime no longer makes `payload.exe` acceptable. - email templates: escape in the helpers rather than relying on every caller, with an explicit `rawEmailHtml()` opt-out for the one call site that builds markup. `escapeHtml` now covers the single quote. - CSP: allow loopback object storage outside production only. - route-access: reach the billing redirect only for the workspace owner. Keying it off the owner's billing status alone made the redirect target an oracle for whose subscription had lapsed, and sent members to a page they cannot act on. - search: carry the same billing condition every other read path carries. - logger: check `err.name` as well as `err.constructor.name`, so a re-thrown, deserialised or minified Prisma error is still redacted. - upload tokens: resolve the signing secret outside the try, so a server booted without one fails loudly instead of reporting every grant as a forgery. - invitations: never downgrade an existing membership, and report a scoped invitation that points at nothing as not_found rather than accepted. - auth: resolve the workspace role for every signed-in caller, so checkProjectAccess and computeProjectAccess stop disagreeing about the owner who also owns the workspace. The `intent` option is gone with it. - r2-media-proxy: validate the object key inside the proxy so the guard travels with the function; delete the unused, unanchored `mediaUrlToR2Key`. - r2: sign the content type into presigned PUT grants. Correctness: - frame rate snapping picks the nearest standard, not the first within tolerance, so 24, 30 and 60 fps are reachable at all. - a version upload registers its Bunny cleanup as soon as bunny-init answers, so a failed tus upload no longer leaves a billed video behind. - deleting videos clears storage before the rows, so a refused DELETE leaves a retryable row rather than an orphaned object. - an expired upload session can be cancelled, which is what releases its quota. - `voice/` joins the delete allowlist, so a voice note can be removed by the module that wrote it. - a failed CORS write propagates instead of being mistaken for an empty config and replacing the bucket's rules. - filtering projects by workspace no longer hides projects the unfiltered call returns. - upload retries skip aborts and permanent 4xx; progress no longer divides by zero. - reply edits no longer clear the comment's tag; optimistic resolve rolls back to the state it replaced; the delete snapshot is captured once. - assorted UI fixes: duplicate React keys, double-click guards reading stale closures, the tag list fetched twice per load, a failed member list rendering as an empty one, a stale "Initializing upload..." beside a failure, and a registration banner pointing at an email that never arrives. Consistency and access: - the two download routes answer 404 for an id belonging to another tenant, as the comment export route already did. A caller who does belong still gets 403. - accessible names for the share-link password field, the guest name gates, the version dialog inputs and the comment-tag controls. Repository health: - the runner image installs production dependencies only. - a setup file for the unit project restores stubbed env centrally. - native tsconfig path resolution replaces vite-tsconfig-paths. - `uploadBytesWithProgress` exists once. - admin stats bill Bunny storage to the workspace owner like every other quota, gate on the configured flag, wire up the single-flight guard and count the statuses that belonged to no bucket. - `r2Client.destroy()` releases the presign client too. - `prepare` tolerates a production install, where husky is absent.
222 lines
8.1 KiB
TypeScript
222 lines
8.1 KiB
TypeScript
// Exercises lib/r2-upload-session.ts, the bookkeeping either side of a direct
|
|
// upload.
|
|
//
|
|
// Small module, but the `where` clause on the cancel is load-bearing in two
|
|
// directions: it must not let a caller cancel a session that is not theirs to
|
|
// cancel, and it must actually match the session they do own, because the
|
|
// r2-init DELETE route releases the quota reservation only when the update
|
|
// reports a row. A cancel that quietly matches nothing leaves the reservation
|
|
// pinned for its whole TTL.
|
|
|
|
import { describe, expect, it } from 'vitest';
|
|
import { randomUUID } from 'crypto';
|
|
import { db } from '@/lib/db';
|
|
import { cancelR2UploadSession, createR2UploadSession } from '@/lib/r2-upload-session';
|
|
import { seedProject } from '../factories';
|
|
|
|
const HOUR_MS = 60 * 60 * 1000;
|
|
|
|
async function newSession(
|
|
overrides: { expiresAt?: Date; multipartUploadId?: string | null; reservationId?: string } = {}
|
|
) {
|
|
const scenario = await seedProject();
|
|
const fileId = randomUUID();
|
|
const session = await createR2UploadSession({
|
|
userId: scenario.owner.id,
|
|
projectId: scenario.project.id,
|
|
billedUserId: scenario.owner.id,
|
|
objectKey: `videos/${fileId}.mp4`,
|
|
thumbnailObjectKey: `images/${fileId}.jpg`,
|
|
declaredSizeBytes: BigInt(4096),
|
|
contentType: 'video/mp4',
|
|
reservationId: overrides.reservationId ?? null,
|
|
uploadJti: randomUUID(),
|
|
expiresAt: overrides.expiresAt ?? new Date(Date.now() + HOUR_MS),
|
|
...(overrides.multipartUploadId === undefined
|
|
? {}
|
|
: { multipartUploadId: overrides.multipartUploadId }),
|
|
});
|
|
return { scenario, session, fileId };
|
|
}
|
|
|
|
describe('createR2UploadSession', () => {
|
|
it('writes an INITIATED row carrying every field the finalizer reads back', async () => {
|
|
const scenario = await seedProject();
|
|
const fileId = randomUUID();
|
|
const uploadJti = randomUUID();
|
|
const expiresAt = new Date(Date.now() + HOUR_MS);
|
|
|
|
const created = await createR2UploadSession({
|
|
userId: scenario.owner.id,
|
|
projectId: scenario.project.id,
|
|
billedUserId: scenario.owner.id,
|
|
objectKey: `videos/${fileId}.mp4`,
|
|
thumbnailObjectKey: `images/${fileId}.jpg`,
|
|
declaredSizeBytes: BigInt(123_456),
|
|
contentType: 'video/webm',
|
|
reservationId: null,
|
|
uploadJti,
|
|
expiresAt,
|
|
});
|
|
|
|
const row = await db.videoUploadSession.findUniqueOrThrow({ where: { id: created.id } });
|
|
expect(row.status).toBe('INITIATED');
|
|
expect(row.userId).toBe(scenario.owner.id);
|
|
expect(row.projectId).toBe(scenario.project.id);
|
|
expect(row.billedUserId).toBe(scenario.owner.id);
|
|
expect(row.objectKey).toBe(`videos/${fileId}.mp4`);
|
|
expect(row.thumbnailObjectKey).toBe(`images/${fileId}.jpg`);
|
|
expect(row.declaredSizeBytes).toBe(BigInt(123_456));
|
|
expect(row.contentType).toBe('video/webm');
|
|
expect(row.uploadJti).toBe(uploadJti);
|
|
expect(row.expiresAt.getTime()).toBe(expiresAt.getTime());
|
|
expect(row.reservationId).toBeNull();
|
|
expect(row.consumedAt).toBeNull();
|
|
});
|
|
|
|
// The field is optional on the input but the column is not nullable-by-
|
|
// accident: a single-shot PUT must store null rather than undefined, because
|
|
// the complete route branches on it to decide whether to assemble parts.
|
|
it('stores a null multipart id when none is supplied', async () => {
|
|
const { session } = await newSession();
|
|
|
|
expect(session.multipartUploadId).toBeNull();
|
|
});
|
|
|
|
it('stores an explicit null multipart id as null', async () => {
|
|
const { session } = await newSession({ multipartUploadId: null });
|
|
|
|
expect(session.multipartUploadId).toBeNull();
|
|
});
|
|
|
|
it('records the multipart upload id when the upload is chunked', async () => {
|
|
const { session } = await newSession({ multipartUploadId: 'multipart-upload-id-1' });
|
|
|
|
expect(session.multipartUploadId).toBe('multipart-upload-id-1');
|
|
});
|
|
|
|
it('links the quota reservation the caller already took', async () => {
|
|
const scenario = await seedProject();
|
|
const reservation = await db.uploadReservation.create({
|
|
data: {
|
|
billedUserId: scenario.owner.id,
|
|
sizeBytes: BigInt(4096),
|
|
expiresAt: new Date(Date.now() + HOUR_MS),
|
|
},
|
|
});
|
|
const fileId = randomUUID();
|
|
|
|
const created = await createR2UploadSession({
|
|
userId: scenario.owner.id,
|
|
projectId: scenario.project.id,
|
|
billedUserId: scenario.owner.id,
|
|
objectKey: `videos/${fileId}.mp4`,
|
|
thumbnailObjectKey: `images/${fileId}.jpg`,
|
|
declaredSizeBytes: BigInt(4096),
|
|
contentType: 'video/mp4',
|
|
reservationId: reservation.id,
|
|
uploadJti: randomUUID(),
|
|
expiresAt: new Date(Date.now() + HOUR_MS),
|
|
});
|
|
|
|
expect(created.reservationId).toBe(reservation.id);
|
|
});
|
|
|
|
// objectKey is unique in the schema, which is what stops two sessions from
|
|
// ever pointing at the same object and racing each other's cleanup.
|
|
it('refuses a second session for the same object key', async () => {
|
|
const { scenario, fileId } = await newSession();
|
|
|
|
await expect(
|
|
createR2UploadSession({
|
|
userId: scenario.owner.id,
|
|
projectId: scenario.project.id,
|
|
billedUserId: scenario.owner.id,
|
|
objectKey: `videos/${fileId}.mp4`,
|
|
thumbnailObjectKey: `images/${fileId}.jpg`,
|
|
declaredSizeBytes: BigInt(4096),
|
|
contentType: 'video/mp4',
|
|
reservationId: null,
|
|
uploadJti: randomUUID(),
|
|
expiresAt: new Date(Date.now() + HOUR_MS),
|
|
})
|
|
).rejects.toThrow();
|
|
});
|
|
});
|
|
|
|
describe('cancelR2UploadSession', () => {
|
|
it('flips an INITIATED session to CANCELLED and stamps consumedAt', async () => {
|
|
const { session } = await newSession();
|
|
|
|
const result = await cancelR2UploadSession(session.id);
|
|
|
|
expect(result.count).toBe(1);
|
|
const row = await db.videoUploadSession.findUniqueOrThrow({ where: { id: session.id } });
|
|
expect(row.status).toBe('CANCELLED');
|
|
expect(row.consumedAt).toBeInstanceOf(Date);
|
|
});
|
|
|
|
it('matches nothing on a second cancel, so the route cannot double-release', async () => {
|
|
const { session } = await newSession();
|
|
await cancelR2UploadSession(session.id);
|
|
|
|
const result = await cancelR2UploadSession(session.id);
|
|
|
|
expect(result.count).toBe(0);
|
|
});
|
|
|
|
it('refuses to cancel a session that was already finalized', async () => {
|
|
const { session } = await newSession();
|
|
await db.videoUploadSession.update({
|
|
where: { id: session.id },
|
|
data: { status: 'FINALIZED' },
|
|
});
|
|
|
|
const result = await cancelR2UploadSession(session.id);
|
|
|
|
expect(result.count).toBe(0);
|
|
expect(
|
|
(await db.videoUploadSession.findUniqueOrThrow({ where: { id: session.id } })).status
|
|
).toBe('FINALIZED');
|
|
});
|
|
|
|
// An `expiresAt: { gt: now }` clause used to make this match zero rows once a session
|
|
// lapsed, so it stayed INITIATED with a null consumedAt for good. The r2-init DELETE
|
|
// route releases the quota reservation only when the update reports a row, so every
|
|
// abandoned upload held its reserved bytes against the user's quota permanently.
|
|
// Cancelling something already expired is the case that most needs to work.
|
|
it('cancels a session that has already expired', async () => {
|
|
const { session } = await newSession({ expiresAt: new Date(Date.now() - 60_000) });
|
|
|
|
const result = await cancelR2UploadSession(session.id);
|
|
|
|
expect(result.count).toBe(1);
|
|
const row = await db.videoUploadSession.findUniqueOrThrow({ where: { id: session.id } });
|
|
expect(row.status).toBe('CANCELLED');
|
|
expect(row.consumedAt).not.toBeNull();
|
|
});
|
|
|
|
it('does nothing for an id that matches no row', async () => {
|
|
const { session } = await newSession();
|
|
|
|
const result = await cancelR2UploadSession('no-such-session');
|
|
|
|
expect(result.count).toBe(0);
|
|
expect(
|
|
(await db.videoUploadSession.findUniqueOrThrow({ where: { id: session.id } })).status
|
|
).toBe('INITIATED');
|
|
});
|
|
|
|
it('leaves every other session alone', async () => {
|
|
const target = await newSession();
|
|
const bystander = await newSession();
|
|
|
|
await cancelR2UploadSession(target.session.id);
|
|
|
|
expect(
|
|
(await db.videoUploadSession.findUniqueOrThrow({ where: { id: bystander.session.id } }))
|
|
.status
|
|
).toBe('INITIATED');
|
|
});
|
|
});
|