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.
356 lines
12 KiB
TypeScript
356 lines
12 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
import { logError } from '@/lib/logger';
|
|
|
|
// Prisma's client errors are real classes, so `err.constructor.name` is what the
|
|
// sanitiser branches on. Reproducing them as classes rather than as plain objects
|
|
// with a `name` property is the only way to exercise the branch the way production
|
|
// reaches it.
|
|
class PrismaClientKnownRequestError extends Error {
|
|
code: string;
|
|
meta?: Record<string, unknown>;
|
|
constructor(message: string, code: string, meta?: Record<string, unknown>) {
|
|
super(message);
|
|
this.name = 'PrismaClientKnownRequestError';
|
|
this.code = code;
|
|
this.meta = meta;
|
|
}
|
|
}
|
|
|
|
class PrismaClientValidationError extends Error {
|
|
constructor(message: string) {
|
|
super(message);
|
|
this.name = 'PrismaClientValidationError';
|
|
}
|
|
}
|
|
|
|
class PrismaClientInitializationError extends Error {
|
|
errorCode: string;
|
|
constructor(message: string) {
|
|
super(message);
|
|
this.name = 'PrismaClientInitializationError';
|
|
this.errorCode = 'P1001';
|
|
}
|
|
}
|
|
|
|
// A Stripe SDK error, shaped the way the sanitiser detects it: a string `type`
|
|
// alongside a numeric `statusCode`.
|
|
class StripeCardError extends Error {
|
|
type = 'StripeCardError';
|
|
statusCode = 402;
|
|
constructor(message: string) {
|
|
super(message);
|
|
this.name = 'StripeCardError';
|
|
}
|
|
}
|
|
|
|
// The kind of message a Prisma failure actually carries: the failing statement,
|
|
// the table and column names, and the literal values from the WHERE clause. None
|
|
// of this may reach a log sink.
|
|
const LEAKY_PRISMA_MESSAGE = [
|
|
'Invalid `prisma.user.findUnique()` invocation:',
|
|
'Raw query failed. Code: `42P01`.',
|
|
'SELECT "public"."User"."id", "public"."User"."passwordHash" FROM "public"."User"',
|
|
'WHERE "public"."User"."email" = \'[email protected]\' LIMIT 1 OFFSET 0',
|
|
].join('\n');
|
|
|
|
// Swallows the output as well as capturing it, so the suite stays quiet.
|
|
function spyOnConsoleError() {
|
|
return vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
}
|
|
|
|
let errorSpy: ReturnType<typeof spyOnConsoleError>;
|
|
|
|
function loggedPayload(): unknown {
|
|
expect(errorSpy).toHaveBeenCalledTimes(1);
|
|
return errorSpy.mock.calls[0]![1];
|
|
}
|
|
|
|
function loggedText(): string {
|
|
return JSON.stringify(loggedPayload() ?? null);
|
|
}
|
|
|
|
beforeEach(() => {
|
|
errorSpy = spyOnConsoleError();
|
|
});
|
|
|
|
afterEach(() => {
|
|
errorSpy.mockRestore();
|
|
});
|
|
|
|
describe('logError', () => {
|
|
describe('Prisma errors', () => {
|
|
it('redacts a Prisma message carrying raw SQL down to the error code', () => {
|
|
logError(
|
|
'user lookup failed',
|
|
new PrismaClientKnownRequestError(LEAKY_PRISMA_MESSAGE, 'P2002')
|
|
);
|
|
|
|
expect(loggedPayload()).toEqual({
|
|
type: 'PrismaError',
|
|
code: 'P2002',
|
|
message: 'Database error [P2002]',
|
|
});
|
|
});
|
|
|
|
it('leaks no fragment of the original SQL, table names or WHERE values', () => {
|
|
logError(
|
|
'user lookup failed',
|
|
new PrismaClientKnownRequestError(LEAKY_PRISMA_MESSAGE, 'P2002')
|
|
);
|
|
|
|
const text = loggedText();
|
|
expect(text).not.toContain('SELECT');
|
|
expect(text).not.toContain('passwordHash');
|
|
expect(text).not.toContain('[email protected]');
|
|
expect(text).not.toContain('prisma.user.findUnique');
|
|
expect(text).not.toContain('"public"."User"');
|
|
});
|
|
|
|
it('never logs the `meta` object, which repeats the offending field values', () => {
|
|
const err = new PrismaClientKnownRequestError('Unique constraint failed', 'P2002', {
|
|
target: ['email'],
|
|
value: '[email protected]',
|
|
});
|
|
|
|
logError('create failed', err);
|
|
|
|
expect(loggedText()).not.toContain('[email protected]');
|
|
expect(loggedPayload()).toEqual({
|
|
type: 'PrismaError',
|
|
code: 'P2002',
|
|
message: 'Database error [P2002]',
|
|
});
|
|
});
|
|
|
|
it('substitutes UNKNOWN when the Prisma error carries no code', () => {
|
|
logError('validation failed', new PrismaClientValidationError(LEAKY_PRISMA_MESSAGE));
|
|
|
|
expect(loggedPayload()).toEqual({
|
|
type: 'PrismaError',
|
|
code: 'UNKNOWN',
|
|
message: 'Database error [UNKNOWN]',
|
|
});
|
|
});
|
|
|
|
it('redacts a Prisma initialization error, whose message embeds the database url', () => {
|
|
const err = new PrismaClientInitializationError(
|
|
"Can't reach database server at `postgresql://admin:[email protected]:5432`"
|
|
);
|
|
|
|
logError('startup failed', err);
|
|
|
|
const text = loggedText();
|
|
expect(text).not.toContain('hunter2');
|
|
expect(text).not.toContain('db.internal');
|
|
// `errorCode`, not `code`, so the string branch does not match it.
|
|
expect(loggedPayload()).toEqual({
|
|
type: 'PrismaError',
|
|
code: 'UNKNOWN',
|
|
message: 'Database error [UNKNOWN]',
|
|
});
|
|
});
|
|
|
|
it('ignores a non-string Prisma code rather than logging it', () => {
|
|
const err = new PrismaClientKnownRequestError('boom', 'P2002');
|
|
(err as unknown as Record<string, unknown>).code = 2002;
|
|
|
|
logError('create failed', err);
|
|
|
|
expect(loggedPayload()).toEqual({
|
|
type: 'PrismaError',
|
|
code: 'UNKNOWN',
|
|
message: 'Database error [UNKNOWN]',
|
|
});
|
|
});
|
|
|
|
it('prefers the Prisma branch over the Stripe branch when an error matches both', () => {
|
|
const err = new PrismaClientKnownRequestError(LEAKY_PRISMA_MESSAGE, 'P2002');
|
|
const anyErr = err as unknown as Record<string, unknown>;
|
|
anyErr.type = 'invalid_request_error';
|
|
anyErr.statusCode = 400;
|
|
|
|
logError('ambiguous failure', err);
|
|
|
|
// If the ordering flipped, `message: err.message` would ship the SQL.
|
|
expect(loggedPayload()).toEqual({
|
|
type: 'PrismaError',
|
|
code: 'P2002',
|
|
message: 'Database error [P2002]',
|
|
});
|
|
});
|
|
|
|
// An Error instance always has a constructor, so keying on `constructor.name` alone
|
|
// would stop redacting the moment an error identifies itself as Prisma only through
|
|
// `name`: one that was re-thrown or deserialised and lost its prototype, or a
|
|
// production build whose minifier renamed the class.
|
|
it('redacts an error that is Prisma only by its `name` property', () => {
|
|
const err = new Error(LEAKY_PRISMA_MESSAGE);
|
|
err.name = 'PrismaClientKnownRequestError';
|
|
(err as unknown as Record<string, unknown>).code = 'P2002';
|
|
|
|
logError('user lookup failed', err);
|
|
|
|
expect(loggedPayload()).toEqual({
|
|
type: 'PrismaError',
|
|
code: 'P2002',
|
|
message: 'Database error [P2002]',
|
|
});
|
|
});
|
|
|
|
it('redacts a name-only Prisma error that carries no code', () => {
|
|
const err = new Error(LEAKY_PRISMA_MESSAGE);
|
|
err.name = 'PrismaClientValidationError';
|
|
|
|
logError('user lookup failed', err);
|
|
|
|
expect(loggedPayload()).toEqual({
|
|
type: 'PrismaError',
|
|
code: 'UNKNOWN',
|
|
message: 'Database error [UNKNOWN]',
|
|
});
|
|
});
|
|
|
|
it('leaves a non-Prisma error alone', () => {
|
|
const err = new Error('plain failure');
|
|
err.name = 'ValidationError';
|
|
|
|
logError('lookup failed', err);
|
|
|
|
expect(loggedPayload()).toEqual({ type: 'Error', message: 'plain failure' });
|
|
});
|
|
});
|
|
|
|
describe('Stripe errors', () => {
|
|
it('keeps the message and records the http status as the code', () => {
|
|
logError('charge failed', new StripeCardError('Your card was declined.'));
|
|
|
|
expect(loggedPayload()).toEqual({
|
|
type: 'StripeCardError',
|
|
code: '402',
|
|
message: 'Your card was declined.',
|
|
});
|
|
});
|
|
|
|
it('reports the SDK `type` field rather than the class name', () => {
|
|
const err = new StripeCardError('No such customer: cus_123');
|
|
(err as unknown as Record<string, unknown>).type = 'invalid_request_error';
|
|
|
|
logError('portal failed', err);
|
|
|
|
expect(loggedPayload()).toMatchObject({ type: 'invalid_request_error', code: '402' });
|
|
});
|
|
|
|
it('falls through to the generic branch when statusCode is not numeric', () => {
|
|
const err = new StripeCardError('Your card was declined.');
|
|
(err as unknown as Record<string, unknown>).statusCode = '402';
|
|
|
|
logError('charge failed', err);
|
|
|
|
expect(loggedPayload()).toEqual({
|
|
type: 'StripeCardError',
|
|
message: 'Your card was declined.',
|
|
});
|
|
});
|
|
|
|
it('falls through to the generic branch when `type` is not a string', () => {
|
|
const err = new StripeCardError('Your card was declined.');
|
|
(err as unknown as Record<string, unknown>).type = 7;
|
|
|
|
logError('charge failed', err);
|
|
|
|
expect(loggedPayload()).toEqual({
|
|
type: 'StripeCardError',
|
|
message: 'Your card was declined.',
|
|
});
|
|
});
|
|
});
|
|
|
|
describe('plain errors', () => {
|
|
it('logs the type and message of an ordinary Error', () => {
|
|
logError('something broke', new Error('boom'));
|
|
|
|
expect(loggedPayload()).toEqual({ type: 'Error', message: 'boom' });
|
|
});
|
|
|
|
it('reports the subclass name as the type', () => {
|
|
class UploadRejectedError extends Error {}
|
|
|
|
logError('upload failed', new UploadRejectedError('too large'));
|
|
|
|
expect(loggedPayload()).toEqual({ type: 'UploadRejectedError', message: 'too large' });
|
|
});
|
|
|
|
it('never includes the stack trace, which exposes absolute server paths', () => {
|
|
const err = new Error('boom');
|
|
err.stack = 'Error: boom\n at /srv/openframe/app/api/projects/route.ts:42:11';
|
|
|
|
logError('something broke', err);
|
|
|
|
expect(loggedPayload()).not.toHaveProperty('stack');
|
|
expect(loggedText()).not.toContain('/srv/openframe');
|
|
});
|
|
|
|
it('does not include a `cause`, which can wrap the original driver error', () => {
|
|
const err = new Error('wrapped', { cause: new Error(LEAKY_PRISMA_MESSAGE) });
|
|
|
|
logError('something broke', err);
|
|
|
|
expect(loggedPayload()).toEqual({ type: 'Error', message: 'wrapped' });
|
|
expect(loggedText()).not.toContain('SELECT');
|
|
});
|
|
|
|
it('handles a TypeError thrown by the runtime itself', () => {
|
|
logError('bad access', new TypeError("Cannot read properties of undefined (reading 'id')"));
|
|
|
|
expect(loggedPayload()).toEqual({
|
|
type: 'TypeError',
|
|
message: "Cannot read properties of undefined (reading 'id')",
|
|
});
|
|
});
|
|
});
|
|
|
|
describe('non-Error values', () => {
|
|
// These were constructed by the caller, so they are already whatever the
|
|
// caller decided to expose and are passed through untouched.
|
|
it.each([
|
|
['a string', 'plain failure text'],
|
|
['a number', 42],
|
|
['a boolean', false],
|
|
['null', null],
|
|
['undefined', undefined],
|
|
])('passes %s through unchanged', (_label, value) => {
|
|
logError('context', value);
|
|
|
|
expect(loggedPayload()).toBe(value);
|
|
});
|
|
|
|
it('passes a structured object through by reference', () => {
|
|
const payload = { status: 502, provider: 'bunny' };
|
|
|
|
logError('upstream refused', payload);
|
|
|
|
expect(loggedPayload()).toBe(payload);
|
|
});
|
|
|
|
it('passes an Error-shaped plain object through, since it is not an Error instance', () => {
|
|
const payload = { name: 'PrismaClientKnownRequestError', message: LEAKY_PRISMA_MESSAGE };
|
|
|
|
logError('context', payload);
|
|
|
|
expect(loggedPayload()).toBe(payload);
|
|
});
|
|
});
|
|
|
|
it('writes to console.error with the context string first and the payload second', () => {
|
|
logError('projects.POST failed', new Error('boom'));
|
|
|
|
expect(errorSpy).toHaveBeenCalledTimes(1);
|
|
expect(errorSpy.mock.calls[0]).toHaveLength(2);
|
|
expect(errorSpy.mock.calls[0]![0]).toBe('projects.POST failed');
|
|
});
|
|
|
|
it('returns undefined rather than the sanitized payload', () => {
|
|
expect(logError('context', new Error('boom'))).toBeUndefined();
|
|
});
|
|
});
|