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.
436 lines
14 KiB
TypeScript
436 lines
14 KiB
TypeScript
// Exercises checkProjectAccess() directly, against real rows, next to
|
|
// computeProjectAccess() on the same rows.
|
|
//
|
|
// Nothing did that before. Every existing test reaches checkProjectAccess()
|
|
// through a route and only ever sees the status code it produced, and
|
|
// tests/unit/lib/route-access.test.ts mocks it out entirely. That leaves its
|
|
// input resolution, the four queries it runs to decide who the caller is,
|
|
// uncovered: deleting the `wsOwner?.ownerId === userId` branch in lib/auth.ts,
|
|
// which is the line that makes a workspace owner an owner, failed exactly one
|
|
// test out of 984.
|
|
//
|
|
// The two functions resolve the same six inputs by different routes.
|
|
// computeProjectAccess() reads them off a project fetched with
|
|
// projectAccessInclude(); checkProjectAccess() queries for each relation
|
|
// separately. Since they were refactored onto one shared formula helper
|
|
// (resolveProjectPermissions) the formulas cannot drift, which makes it easy to
|
|
// read the refactor as a guarantee that the two functions agree. It is not one.
|
|
// The formulas are shared; the inputs are not, and they already disagree in one
|
|
// place, asserted below rather than smoothed over.
|
|
//
|
|
// Expected values are written out by hand for every actor. Comparing the two
|
|
// functions to each other would be a weaker test: a wrong answer that both
|
|
// produce would pass. Comparing both to the same hand-written table proves
|
|
// agreement and correctness at once.
|
|
|
|
import { beforeEach, describe, expect, it } from 'vitest';
|
|
import { ProjectMemberRole, WorkspaceMemberRole } from '@prisma/client';
|
|
import {
|
|
checkProjectAccess,
|
|
computeProjectAccess,
|
|
projectAccessInclude,
|
|
type EnrichedProjectForAccess,
|
|
} from '@/lib/auth';
|
|
import { db } from '@/lib/db';
|
|
import {
|
|
addProjectMember,
|
|
addWorkspaceMember,
|
|
createExpiredUser,
|
|
createProject,
|
|
createUser,
|
|
createWorkspace,
|
|
} from '../factories';
|
|
|
|
type Actor =
|
|
| 'an anonymous caller'
|
|
| 'an outsider'
|
|
| 'a project commentator'
|
|
| 'a project admin'
|
|
| 'a workspace commentator'
|
|
| 'a workspace admin'
|
|
| 'the workspace owner'
|
|
| 'the project owner'
|
|
| 'a project owner who also owns the workspace';
|
|
|
|
const ACTORS: readonly Actor[] = [
|
|
'an anonymous caller',
|
|
'an outsider',
|
|
'a project commentator',
|
|
'a project admin',
|
|
'a workspace commentator',
|
|
'a workspace admin',
|
|
'the workspace owner',
|
|
'the project owner',
|
|
'a project owner who also owns the workspace',
|
|
];
|
|
|
|
/** Exactly the shape both functions return, so `toEqual` covers every field. */
|
|
interface ExpectedAccess {
|
|
isOwner: boolean;
|
|
isProjectMember: boolean;
|
|
isProjectAdmin: boolean;
|
|
isWorkspaceMember: boolean;
|
|
isWorkspaceAdmin: boolean;
|
|
hasAccess: boolean;
|
|
canEdit: boolean;
|
|
canDelete: boolean;
|
|
ownerBillingActive: boolean;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// The tables
|
|
// ---------------------------------------------------------------------------
|
|
// Three scenarios, because the two functions can only disagree over inputs and
|
|
// these are the inputs they read differently: who the caller is (nine actors),
|
|
// whether the project is public (the second table), and whether the workspace
|
|
// owner still has billing access (the third). checkProjectAccess() resolves
|
|
// billing in two different queries depending on which branch it takes, so the
|
|
// expired table is the one that catches a branch that forgets to.
|
|
|
|
const PRIVATE_ACTIVE_BILLING: Record<Actor, ExpectedAccess> = {
|
|
'an anonymous caller': {
|
|
isOwner: false,
|
|
isProjectMember: false,
|
|
isProjectAdmin: false,
|
|
isWorkspaceMember: false,
|
|
isWorkspaceAdmin: false,
|
|
hasAccess: false,
|
|
canEdit: false,
|
|
canDelete: false,
|
|
ownerBillingActive: true,
|
|
},
|
|
// Their ADMIN roles live in an unrelated workspace, so they buy nothing here.
|
|
'an outsider': {
|
|
isOwner: false,
|
|
isProjectMember: false,
|
|
isProjectAdmin: false,
|
|
isWorkspaceMember: false,
|
|
isWorkspaceAdmin: false,
|
|
hasAccess: false,
|
|
canEdit: false,
|
|
canDelete: false,
|
|
ownerBillingActive: true,
|
|
},
|
|
'a project commentator': {
|
|
isOwner: false,
|
|
isProjectMember: true,
|
|
isProjectAdmin: false,
|
|
isWorkspaceMember: false,
|
|
isWorkspaceAdmin: false,
|
|
hasAccess: true,
|
|
canEdit: false,
|
|
canDelete: false,
|
|
ownerBillingActive: true,
|
|
},
|
|
'a project admin': {
|
|
isOwner: false,
|
|
isProjectMember: true,
|
|
isProjectAdmin: true,
|
|
isWorkspaceMember: false,
|
|
isWorkspaceAdmin: false,
|
|
hasAccess: true,
|
|
canEdit: true,
|
|
canDelete: false,
|
|
ownerBillingActive: true,
|
|
},
|
|
'a workspace commentator': {
|
|
isOwner: false,
|
|
isProjectMember: false,
|
|
isProjectAdmin: false,
|
|
isWorkspaceMember: true,
|
|
isWorkspaceAdmin: false,
|
|
hasAccess: true,
|
|
canEdit: false,
|
|
canDelete: false,
|
|
ownerBillingActive: true,
|
|
},
|
|
'a workspace admin': {
|
|
isOwner: false,
|
|
isProjectMember: false,
|
|
isProjectAdmin: false,
|
|
isWorkspaceMember: true,
|
|
isWorkspaceAdmin: true,
|
|
hasAccess: true,
|
|
canEdit: true,
|
|
canDelete: false,
|
|
ownerBillingActive: true,
|
|
},
|
|
// The workspace owner has no WorkspaceMember row; the OWNER role is derived
|
|
// from workspace.ownerId, and deleting the project is theirs alone.
|
|
'the workspace owner': {
|
|
isOwner: false,
|
|
isProjectMember: false,
|
|
isProjectAdmin: false,
|
|
isWorkspaceMember: true,
|
|
isWorkspaceAdmin: true,
|
|
hasAccess: true,
|
|
canEdit: true,
|
|
canDelete: true,
|
|
ownerBillingActive: true,
|
|
},
|
|
'the project owner': {
|
|
isOwner: true,
|
|
isProjectMember: false,
|
|
isProjectAdmin: false,
|
|
isWorkspaceMember: false,
|
|
isWorkspaceAdmin: false,
|
|
hasAccess: true,
|
|
canEdit: true,
|
|
canDelete: true,
|
|
ownerBillingActive: true,
|
|
},
|
|
'a project owner who also owns the workspace': {
|
|
isOwner: true,
|
|
isProjectMember: false,
|
|
isProjectAdmin: false,
|
|
isWorkspaceMember: true,
|
|
isWorkspaceAdmin: true,
|
|
hasAccess: true,
|
|
canEdit: true,
|
|
canDelete: true,
|
|
ownerBillingActive: true,
|
|
},
|
|
};
|
|
|
|
// Public only moves the two actors who had no relationship to the project.
|
|
const PUBLIC_ACTIVE_BILLING: Record<Actor, ExpectedAccess> = {
|
|
...PRIVATE_ACTIVE_BILLING,
|
|
'an anonymous caller': { ...PRIVATE_ACTIVE_BILLING['an anonymous caller'], hasAccess: true },
|
|
'an outsider': { ...PRIVATE_ACTIVE_BILLING['an outsider'], hasAccess: true },
|
|
};
|
|
|
|
/**
|
|
* With the workspace owner's billing lapsed, the identity flags still resolve
|
|
* and every permission closes, including the project owner's own. The project
|
|
* owner is a separate person with a live trial of their own: it is the
|
|
* *workspace* owner's billing that pays for the workspace.
|
|
*/
|
|
const PRIVATE_EXPIRED_BILLING: Record<Actor, ExpectedAccess> = Object.fromEntries(
|
|
ACTORS.map((actor) => [
|
|
actor,
|
|
{
|
|
...PRIVATE_ACTIVE_BILLING[actor],
|
|
hasAccess: false,
|
|
canEdit: false,
|
|
canDelete: false,
|
|
ownerBillingActive: false,
|
|
},
|
|
])
|
|
) as Record<Actor, ExpectedAccess>;
|
|
|
|
interface Scenario {
|
|
name: string;
|
|
visibility: 'PRIVATE' | 'PUBLIC';
|
|
billing: 'active' | 'expired';
|
|
expected: Record<Actor, ExpectedAccess>;
|
|
}
|
|
|
|
const SCENARIOS: readonly Scenario[] = [
|
|
{
|
|
name: 'a PRIVATE project whose workspace owner has billing access',
|
|
visibility: 'PRIVATE',
|
|
billing: 'active',
|
|
expected: PRIVATE_ACTIVE_BILLING,
|
|
},
|
|
{
|
|
name: 'a PUBLIC project whose workspace owner has billing access',
|
|
visibility: 'PUBLIC',
|
|
billing: 'active',
|
|
expected: PUBLIC_ACTIVE_BILLING,
|
|
},
|
|
{
|
|
name: 'a PRIVATE project whose workspace owner has lost billing access',
|
|
visibility: 'PRIVATE',
|
|
billing: 'expired',
|
|
expected: PRIVATE_EXPIRED_BILLING,
|
|
},
|
|
];
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// ---------------------------------------------------------------------------
|
|
// Fixtures
|
|
// ---------------------------------------------------------------------------
|
|
|
|
interface Seeded {
|
|
/** The project every actor except the last one is measured against. */
|
|
projectId: string;
|
|
/** A second project in the same workspace, owned by the workspace owner. */
|
|
ownedProjectId: string;
|
|
userIdFor: (actor: Actor) => string | undefined;
|
|
}
|
|
|
|
/**
|
|
* One workspace, two projects in it, and a user for every actor.
|
|
*
|
|
* The second project matters. Almost every real workspace has projects owned by
|
|
* the person who owns the workspace (that is what signing up produces), and that
|
|
* is the only actor for whom the two functions disagree. A fixture that only had
|
|
* a project owned by somebody other than the workspace owner would agree
|
|
* everywhere and prove less than it looks.
|
|
*
|
|
* The outsider is deliberately not a blank user: they are an ADMIN of another
|
|
* workspace and of a project inside it. Both of checkProjectAccess()'s
|
|
* membership lookups are keyed on a compound unique, and if either lost its
|
|
* project or workspace half the query would still find a row for this user. A
|
|
* blank outsider cannot tell the difference.
|
|
*/
|
|
async function seedScenario(scenario: Scenario): Promise<Seeded> {
|
|
const workspaceOwner =
|
|
scenario.billing === 'active' ? await createUser() : await createExpiredUser();
|
|
const projectOwner = await createUser();
|
|
const projectAdmin = await createUser();
|
|
const projectCommentator = await createUser();
|
|
const workspaceAdmin = await createUser();
|
|
const workspaceCommentator = await createUser();
|
|
const outsider = await createUser();
|
|
|
|
const workspace = await createWorkspace({ ownerId: workspaceOwner.id });
|
|
const project = await createProject({
|
|
ownerId: projectOwner.id,
|
|
workspaceId: workspace.id,
|
|
visibility: scenario.visibility,
|
|
});
|
|
const ownedProject = await createProject({
|
|
ownerId: workspaceOwner.id,
|
|
workspaceId: workspace.id,
|
|
visibility: scenario.visibility,
|
|
});
|
|
|
|
await addProjectMember({
|
|
projectId: project.id,
|
|
userId: projectAdmin.id,
|
|
role: ProjectMemberRole.ADMIN,
|
|
});
|
|
await addProjectMember({
|
|
projectId: project.id,
|
|
userId: projectCommentator.id,
|
|
role: ProjectMemberRole.COMMENTATOR,
|
|
});
|
|
await addWorkspaceMember({
|
|
workspaceId: workspace.id,
|
|
userId: workspaceAdmin.id,
|
|
role: WorkspaceMemberRole.ADMIN,
|
|
});
|
|
await addWorkspaceMember({
|
|
workspaceId: workspace.id,
|
|
userId: workspaceCommentator.id,
|
|
role: WorkspaceMemberRole.COMMENTATOR,
|
|
});
|
|
|
|
const elsewhere = await createWorkspace({ ownerId: outsider.id });
|
|
const elsewhereProject = await createProject({
|
|
ownerId: outsider.id,
|
|
workspaceId: elsewhere.id,
|
|
visibility: 'PRIVATE',
|
|
});
|
|
await addWorkspaceMember({
|
|
workspaceId: elsewhere.id,
|
|
userId: outsider.id,
|
|
role: WorkspaceMemberRole.ADMIN,
|
|
});
|
|
await addProjectMember({
|
|
projectId: elsewhereProject.id,
|
|
userId: outsider.id,
|
|
role: ProjectMemberRole.ADMIN,
|
|
});
|
|
|
|
const userIds: Record<Actor, string | undefined> = {
|
|
'an anonymous caller': undefined,
|
|
'an outsider': outsider.id,
|
|
'a project commentator': projectCommentator.id,
|
|
'a project admin': projectAdmin.id,
|
|
'a workspace commentator': workspaceCommentator.id,
|
|
'a workspace admin': workspaceAdmin.id,
|
|
'the workspace owner': workspaceOwner.id,
|
|
'the project owner': projectOwner.id,
|
|
'a project owner who also owns the workspace': workspaceOwner.id,
|
|
};
|
|
|
|
return {
|
|
projectId: project.id,
|
|
ownedProjectId: ownedProject.id,
|
|
userIdFor: (actor) => userIds[actor],
|
|
};
|
|
}
|
|
|
|
/** The project an actor is measured against. */
|
|
function projectIdFor(actor: Actor, seeded: Seeded): string {
|
|
return actor === 'a project owner who also owns the workspace'
|
|
? seeded.ownedProjectId
|
|
: seeded.projectId;
|
|
}
|
|
|
|
/** The project as a route fetches it, with everything computeProjectAccess reads. */
|
|
async function fetchEnriched(
|
|
projectId: string,
|
|
userId: string | undefined
|
|
): Promise<EnrichedProjectForAccess> {
|
|
return db.project.findUniqueOrThrow({
|
|
where: { id: projectId },
|
|
include: projectAccessInclude(userId),
|
|
});
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// The matrix
|
|
// ---------------------------------------------------------------------------
|
|
// hasBillingAccess() short-circuits to true when Stripe is disabled, which would
|
|
// flatten the expired scenario into the active one. OPENFRAME_ENABLE_STRIPE is
|
|
// "true" in .env.test, so the gate is armed for every test here.
|
|
|
|
for (const scenario of SCENARIOS) {
|
|
describe(`checkProjectAccess on ${scenario.name}`, () => {
|
|
let seeded: Seeded;
|
|
|
|
beforeEach(async () => {
|
|
seeded = await seedScenario(scenario);
|
|
});
|
|
|
|
for (const actor of ACTORS) {
|
|
it(`resolves ${actor} exactly as computeProjectAccess does`, async () => {
|
|
const userId = seeded.userIdFor(actor);
|
|
const projectId = projectIdFor(actor, seeded);
|
|
const expected = scenario.expected[actor];
|
|
const enriched = await fetchEnriched(projectId, userId);
|
|
|
|
// The pure half first: given the rows, this is the answer.
|
|
expect(computeProjectAccess(enriched, userId), 'computeProjectAccess').toEqual(expected);
|
|
|
|
// And the querying half, which has to arrive at the same place from the same rows.
|
|
// It used to take an `intent` that skipped the workspace queries for an owner at
|
|
// `view`, which is what made these two disagree; there is one code path now.
|
|
expect(await checkProjectAccess(enriched, userId), 'checkProjectAccess').toEqual(expected);
|
|
});
|
|
}
|
|
});
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// The divergence, on its own
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('checkProjectAccess and computeProjectAccess agree about the workspace role', () => {
|
|
// This was the one cell of the matrix that diverged, and it is the shape every real
|
|
// signup produces: app/api/projects/route.ts gives a new project the workspace owner's
|
|
// id. checkProjectAccess() used to skip both workspace queries for an owner at `view`
|
|
// intent, so the two identity flags read as if this user were a stranger to the
|
|
// workspace they own.
|
|
it('reports a project owner who also owns the workspace as a workspace admin', async () => {
|
|
const owner = await createUser();
|
|
const workspace = await createWorkspace({ ownerId: owner.id });
|
|
const project = await createProject({
|
|
ownerId: owner.id,
|
|
workspaceId: workspace.id,
|
|
visibility: 'PRIVATE',
|
|
});
|
|
|
|
const enriched = await fetchEnriched(project.id, owner.id);
|
|
const computed = computeProjectAccess(enriched, owner.id);
|
|
|
|
expect(computed.isWorkspaceMember).toBe(true);
|
|
expect(computed.isWorkspaceAdmin).toBe(true);
|
|
|
|
expect(await checkProjectAccess(enriched, owner.id)).toEqual(computed);
|
|
});
|
|
});
|