⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
perf(api): read each project once in the access guards (#728)
Croffd54d0e2c1ee4
diff --git a/apps/api/src/modules/attachments/index.ts b/apps/api/src/modules/attachments/index.tsindex bbdd5942..17066e71 100644--- a/apps/api/src/modules/attachments/index.ts+++ b/apps/api/src/modules/attachments/index.ts@@ -1,8 +1,8 @@import { Elysia, t } from 'elysia';import { noContent } from '#shared/http';import { authContext } from '#shared/auth-context';-import { assertMcpAllowed, entityGuard } from '#shared/guards';-import { assertPermission, assertProjectFeature } from '#shared/access';+import { assertMcpAllowed, assertProjectReachable, entityGuard } from '#shared/guards';+import { assertPermission } from '#shared/access';import { HttpError } from '#shared/lib';import { pinnedFetch } from '#shared/net';import { mcpImageTool, mcpTool } from '#mcp/generate';@@ -96,8 +96,7 @@ export const attachmentRoutes = new Elysia({const projectId = await getInitiativeAttachmentProjectId(id);if (!row || projectId == null) throw new HttpError(404, 'Attachment not found');await assertPermission(projectId, user, 'initiatives', 'read');- await assertProjectFeature(projectId, 'initiatives');- await assertMcpAllowed(projectId, request.headers);+ await assertProjectReachable(projectId, request, 'initiatives');const dto = { ...attachmentDto(row), url: `/initiative-attachments/${id}/raw` };return { viewed: { row, dto } };},diff --git a/apps/api/src/modules/issues/index.ts b/apps/api/src/modules/issues/index.tsindex 6a991c20..18861672 100644--- a/apps/api/src/modules/issues/index.ts+++ b/apps/api/src/modules/issues/index.ts@@ -2,12 +2,17 @@ import { Elysia, t, type DocumentDecoration } from 'elysia';import { listIssueAgentRuns, getIssueAgentRunTrace } from './agent-runs';import { mcpTool } from '#mcp/generate';import { noContent } from '#shared/http';-import { guards, entityGuard, assertMcpAllowed, requiresPermission } from '#shared/guards';+import {+ guards,+ entityGuard,+ assertMcpAllowed,+ assertProjectReachable,+ requiresPermission,+} from '#shared/guards';import { authContext } from '#shared/auth-context';import {assertPermission,assertProjectOwner,- assertProjectWritable,assertWritable,readableProjectIds,requireUser,@@ -277,8 +282,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issuesawait assertPermission(entry.projectId, user, 'work_items', 'edit');if (entry.userId !== requireUser(user).id)await assertProjectOwner(entry.projectId, user);- await assertMcpAllowed(entry.projectId, request.headers);- await assertProjectWritable(entry.projectId, request.method);+ await assertProjectReachable(entry.projectId, request);return { projectId: entry.projectId };},};@@ -308,8 +312,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issuesawait assertPermission(entry.projectId, user, 'work_items', 'edit');if (entry.actorUserId !== requireUser(user).id)await assertProjectOwner(entry.projectId, user);- await assertMcpAllowed(entry.projectId, request.headers);- await assertProjectWritable(entry.projectId, request.method);+ await assertProjectReachable(entry.projectId, request);return { projectId: entry.projectId };},};diff --git a/apps/api/src/modules/projects/copy.ts b/apps/api/src/modules/projects/copy.tsindex 2b616b7e..b078d63b 100644--- a/apps/api/src/modules/projects/copy.ts+++ b/apps/api/src/modules/projects/copy.ts@@ -296,6 +296,7 @@ export async function copyProject(teamName: ownerTeam.name,teamSlug: ownerTeam.slug,teamMcpEnabled: ownerTeam.mcpEnabled,+ workspaceId: ownerTeam.workspaceId,});await joinTeamAsCreator(tx, ownerTeam.id, ownerId);await tx.insert(projectMember).values({ projectId: proj.id, userId: ownerId, role: 'owner' });diff --git a/apps/api/src/modules/projects/service.ts b/apps/api/src/modules/projects/service.tsindex ca00da65..db5b39d4 100644--- a/apps/api/src/modules/projects/service.ts+++ b/apps/api/src/modules/projects/service.ts@@ -37,7 +37,7 @@ import { PROJECT_KEY_PATTERN } from './key';import type { Permissions } from '#shared/permissions';import { getProjectSetting, setProjectSetting } from '#shared/project-settings';import { PROJECT_FEATURES, featureLabel, type ProjectFeature } from '#shared/features';-import { getTeamLimits } from '#shared/limits';+import { getLimits, getTeamLimits } from '#shared/limits';import { projectAccess, type AccessVia } from '#shared/workspace-roles';import { toMemberContext, type MemberRole } from '#modules/members/service';import { workspaceGrants } from '#modules/workspaces/service';@@ -120,6 +120,7 @@ type ProjectWithTeam = typeof project.$inferSelect & {teamName: string;teamSlug: string | null;teamMcpEnabled: boolean;+ workspaceId: number;};const projectWithTeam = {@@ -127,13 +128,14 @@ const projectWithTeam = {teamName: team.name,teamSlug: team.slug,teamMcpEnabled: team.mcpEnabled,+ workspaceId: team.workspaceId,};// A blocked section reads as off whatever the project has stored, so masking here is// what turns a feature off everywhere: the web app reads the flags off this DTO, and// the route guards read them off the project the guard resolved.export async function mapProject(row: ProjectWithTeam): Promise<ProjectRow> {- const { blockedFeatures } = await getTeamLimits(row.teamId);+ const { blockedFeatures } = await getLimits(row.workspaceId);const on = (feature: ProjectFeature, stored: boolean) =>stored && !blockedFeatures.includes(feature);return {@@ -407,6 +409,7 @@ export async function targetTeam(userId: string, teamId: number): Promise<Targetslug: team.slug,mcpEnabled: team.mcpEnabled,defaultAgentIds: team.defaultAgentIds,+ workspaceId: team.workspaceId,}).from(team).where(eq(team.id, teamId));@@ -433,6 +436,7 @@ export interface TargetTeam {slug: string | null;mcpEnabled: boolean;defaultAgentIds: number[];+ workspaceId: number;}// Every new project starts with one column per state type, so it's usable (has@@ -587,6 +591,7 @@ export async function createProject(teamName: ownerTeam.name,teamSlug: ownerTeam.slug,teamMcpEnabled: ownerTeam.mcpEnabled,+ workspaceId: ownerTeam.workspaceId,});});}diff --git a/apps/api/src/shared/guards.ts b/apps/api/src/shared/guards.tsindex b39445dd..1d9812f0 100644--- a/apps/api/src/shared/guards.ts+++ b/apps/api/src/shared/guards.ts@@ -14,13 +14,11 @@ import {assertPermission,assertMcpEnabled,assertWritable,- assertProjectWritable,assertFeatureEnabled,- assertProjectFeature,type AuthUser,} from './access';import type { ProjectFeature } from './features';-import { getProjectById } from '#modules/projects/service';+import { getProjectById, type ProjectRow } from '#modules/projects/service';import { runsTeam, teamMcpEnabled } from '#modules/teams/service';import { requireWorkspaceManager } from '#modules/workspaces/service';import { boundProjectId, isMcpRequest } from './mcp-request';@@ -84,26 +82,47 @@ export function entityGuard(const projectId = await resolveProjectId(params as Record<string, string>);if (projectId == null) throw new HttpError(404, notFound);await assertPermission(projectId, user, resource, action);- if (feature) await assertProjectFeature(projectId, feature);- await assertMcpAllowed(projectId, request.headers);- await assertProjectWritable(projectId, request.method);+ await assertProjectReachable(projectId, request, feature);return { projectId };},});}+// What a route that resolved its project by an object's id checks on it: the section+// it belongs to, the run binding and the MCP toggle (see assertMcpAllowed), and that an+// archived project is not written to. The project is read once, and only when a check+// needs it.+export async function assertProjectReachable(+ projectId: number,+ request: Request,+ feature?: ProjectFeature,+): Promise<void> {+ const mcp = isMcpRequest(request.headers);+ const reads = request.method === 'GET' || request.method === 'HEAD';+ const project = feature || mcp || !reads ? await getProjectById(projectId) : null;+ if (project && feature) assertFeatureEnabled(project, feature);+ assertBoundProject(projectId, request.headers);+ if (!project) return;+ assertMcpEnabled(project, mcp);+ assertWritable(project, request.method);+}+// What the request carries about the project, for a route or a guard that resolved the// project by an object's id rather than through one of the :projectKey macros: an// internal agent's run is bound to its own project, and an MCP call obeys the// per-project MCP toggle. A plain request passes untouched.export async function assertMcpAllowed(projectId: number, headers: Headers): Promise<void> {+ assertBoundProject(projectId, headers);+ if (!isMcpRequest(headers)) return;+ const project = await getProjectById(projectId);+ if (project) assertMcpEnabled(project, true);+}++function assertBoundProject(projectId: number, headers: Headers): void {const bound = boundProjectId(headers);if (bound != null && bound !== projectId) {throw new HttpError(403, 'Outside the project this run works in');}- if (!isMcpRequest(headers)) return;- const project = await getProjectById(projectId);- if (project) assertMcpEnabled(project, true);}// The path param carried by every project-scoped route. The macros read it off@@ -161,13 +180,16 @@ export const guards = new Elysia({ name: 'guards' }).use(authContext).macro({// The optional section a route belongs to, set beside the permission the route// asserts. A section its project has turned off closes its routes, so what the- // settings page hides cannot be reached through the API either. It resolves the- // project through the membership check as well, so it belongs on a route that- // already requires membership — not on one a team owner reaches without it.+ // settings page hides cannot be reached through the API either. It reads the project+ // the route's guard resolved when that guard is set before it in the route options;+ // otherwise it resolves the project through the membership check itself, so it+ // belongs on a route that already requires membership.feature(name: ProjectFeature) {return {- async resolve({ params, user }) {- const project = await requireProjectAccess((params as ProjectKeyParams).projectKey, user);+ async resolve(ctx) {+ const project =+ (ctx as { project?: ProjectRow }).project ??+ (await requireProjectAccess((ctx.params as ProjectKeyParams).projectKey, ctx.user));assertFeatureEnabled(project, name);},};