Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

fix(api): overview shares, references, cohorts and widgets check project access

Carl-Gerhard Lindesvärd0eff8d2715d8
diff --git a/packages/core/src/modules/cohort/cohort.rpc.test.ts b/packages/core/src/modules/cohort/cohort.rpc.test.ts
index 80c93ccc8..2123f7201 100644
--- a/packages/core/src/modules/cohort/cohort.rpc.test.ts
+++ b/packages/core/src/modules/cohort/cohort.rpc.test.ts
@@ -4,9 +4,10 @@
// end-to-end against a real Postgres is P6's (protectedProcedure) job, not
// this one's — see cohort.rpc.ts's header.
-import { expect, test } from 'bun:test';
+import { expect, mock, test } from 'bun:test';
import { stubHttpCtx } from '../../../test/rpc-fixtures';
import { makeTrpcContext } from '../../rpc/base';
+import { TRPCForbiddenError } from '../../rpc/errors';
import type { CookieOptions } from '../../shared/cookie';
import { cohortRouter } from './cohort.rpc';
@@ -134,3 +135,63 @@ test('refresh rejects an unauthenticated caller before enqueueing a recompute',
code: 'UNAUTHORIZED',
});
});
+
+// The project-access middleware and the handler both ask this ladder; a
+// refusal from either must stop the write.
+function nonMemberCaller(write: ReturnType<typeof mock>) {
+ const requireProjectAccess = mock(() =>
+ Promise.reject(
+ new TRPCForbiddenError('You do not have access to this project')
+ )
+ );
+ const { ctx } = stubHttpCtx(
+ {
+ services: {
+ auth: { requireProjectAccess },
+ cohort: { enqueueCompute: write },
+ },
+ } as unknown as Parameters<typeof stubHttpCtx>[0],
+ { session: {}, user: {}, userId: 'user_outsider' }
+ );
+ return {
+ requireProjectAccess,
+ caller: async () =>
+ cohortRouter.createCaller(
+ await makeTrpcContext(ctx, new Headers(), {
+ cookieOptions: COOKIE_OPTIONS,
+ })
+ ),
+ };
+}
+
+test('create refuses a signed-in user without write access to the project', async () => {
+ const enqueueCompute = mock(() => Promise.resolve());
+ const t = nonMemberCaller(enqueueCompute);
+ const caller = await t.caller();
+
+ await expect(
+ caller.create({
+ name: 'Power users',
+ projectId: 'proj_1',
+ definition: {
+ type: 'event',
+ criteria: {
+ operator: 'and',
+ events: [
+ {
+ name: 'purchase',
+ filters: [],
+ timeframe: { type: 'relative', value: '30d' },
+ },
+ ],
+ },
+ },
+ })
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(t.requireProjectAccess).toHaveBeenCalledWith({
+ userId: 'user_outsider',
+ projectId: 'proj_1',
+ level: 'write',
+ });
+ expect(enqueueCompute).not.toHaveBeenCalled();
+});
diff --git a/packages/core/src/modules/cohort/cohort.rpc.ts b/packages/core/src/modules/cohort/cohort.rpc.ts
index 6dd2f09b3..3a40b272c 100644
--- a/packages/core/src/modules/cohort/cohort.rpc.ts
+++ b/packages/core/src/modules/cohort/cohort.rpc.ts
@@ -105,12 +105,16 @@ export const cohortRouter = createTRPCRouter({
return cohort;
}),
- // No project-access check here — protectedProcedure's session check is the
- // only gate today. Preserved as found rather than silently added or
- // removed; this router does not yet serve live traffic.
create: protectedProcedure
.input(zCohortInput)
.mutation(async ({ input, ctx }) => {
+ const userId = ctx.session.userId;
+ await ctx.services.auth.requireProjectAccess({
+ userId,
+ projectId: input.projectId,
+ level: 'write',
+ });
+
const db = ctx.db;
const cohort = await db.cohort.create({
data: {
diff --git a/packages/core/src/modules/reference/reference.rpc.test.ts b/packages/core/src/modules/reference/reference.rpc.test.ts
index f75285d42..8ab945cb3 100644
--- a/packages/core/src/modules/reference/reference.rpc.test.ts
+++ b/packages/core/src/modules/reference/reference.rpc.test.ts
@@ -7,6 +7,7 @@
import { expect, mock, test } from 'bun:test';
import { stubHttpCtx } from '../../../test/rpc-fixtures';
import { makeTrpcContext } from '../../rpc/base';
+import { TRPCForbiddenError } from '../../rpc/errors';
import type { CookieOptions } from '../../shared/cookie';
import { referenceRouter } from './reference.rpc';
@@ -151,3 +152,52 @@ test('delete rejects an unauthenticated caller before looking up the reference',
code: 'UNAUTHORIZED',
});
});
+
+// The project-access middleware and the handler both ask this ladder; a
+// refusal from either must stop the write.
+function nonMemberCaller(write: ReturnType<typeof mock>) {
+ const requireProjectAccess = mock(() =>
+ Promise.reject(
+ new TRPCForbiddenError('You do not have access to this project')
+ )
+ );
+ const { ctx } = stubHttpCtx(
+ {
+ services: {
+ auth: { requireProjectAccess },
+ reference: { createReference: write },
+ },
+ } as unknown as Parameters<typeof stubHttpCtx>[0],
+ { session: {}, user: {}, userId: 'user_outsider' }
+ );
+ return {
+ requireProjectAccess,
+ caller: async () =>
+ referenceRouter.createCaller(
+ await makeTrpcContext(ctx, new Headers(), {
+ cookieOptions: COOKIE_OPTIONS,
+ })
+ ),
+ };
+}
+
+test('create refuses a signed-in user without write access to the project', async () => {
+ const createReference = mock(() => Promise.resolve({}));
+ const t = nonMemberCaller(createReference);
+ const caller = await t.caller();
+
+ await expect(
+ caller.create({
+ title: 'Launch',
+ description: null,
+ datetime: '2026-09-03T00:00:00.000Z',
+ projectId: 'proj_1',
+ })
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(t.requireProjectAccess).toHaveBeenCalledWith({
+ userId: 'user_outsider',
+ projectId: 'proj_1',
+ level: 'write',
+ });
+ expect(createReference).not.toHaveBeenCalled();
+});
diff --git a/packages/core/src/modules/reference/reference.rpc.ts b/packages/core/src/modules/reference/reference.rpc.ts
index 9c3fec533..2634a5d22 100644
--- a/packages/core/src/modules/reference/reference.rpc.ts
+++ b/packages/core/src/modules/reference/reference.rpc.ts
@@ -7,8 +7,7 @@
// requestId minted at the edge reaches the Postgres call.
//
// The permission ladder itself is bound once, in auth.service.ts; every
-// procedure here reaches it through `ctx.services.auth`. `create` has no
-// access check here either — a known gap, not yet fixed.
+// procedure here reaches it through `ctx.services.auth`.
import { z } from 'zod';
import {
@@ -37,7 +36,13 @@ export const referenceRouter = createTRPCRouter({
create: protectedProcedure
.input(zCreateReference)
- .mutation(({ input, ctx }) => {
+ .mutation(async ({ input, ctx }) => {
+ const userId = ctx.session.userId;
+ await ctx.services.auth.requireProjectAccess({
+ userId,
+ projectId: input.projectId,
+ level: 'write',
+ });
return ctx.services.reference.createReference(input);
}),
diff --git a/packages/core/src/modules/share/share.rpc.test.ts b/packages/core/src/modules/share/share.rpc.test.ts
index f08623c57..cd0e71fee 100644
--- a/packages/core/src/modules/share/share.rpc.test.ts
+++ b/packages/core/src/modules/share/share.rpc.test.ts
@@ -4,9 +4,10 @@
// Postgres is P6's (protectedProcedure) job, not this one's — see
// share.rpc.ts's header.
-import { expect, test } from 'bun:test';
+import { expect, mock, test } from 'bun:test';
import { stubHttpCtx } from '../../../test/rpc-fixtures';
import { makeTrpcContext } from '../../rpc/base';
+import { TRPCForbiddenError } from '../../rpc/errors';
import type { CookieOptions } from '../../shared/cookie';
import { shareRouter } from './share.rpc';
@@ -88,3 +89,52 @@ test('createReport rejects an unauthenticated caller before touching a project',
})
).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
});
+
+// The project-access middleware and the handler both ask this ladder; a
+// refusal from either must stop the write.
+function nonMemberCaller(write: ReturnType<typeof mock>) {
+ const requireProjectAccess = mock(() =>
+ Promise.reject(
+ new TRPCForbiddenError('You do not have access to this project')
+ )
+ );
+ const { ctx } = stubHttpCtx(
+ {
+ services: {
+ auth: { requireProjectAccess },
+ share: { createShareOverview: write },
+ },
+ } as unknown as Parameters<typeof stubHttpCtx>[0],
+ { session: {}, user: {}, userId: 'user_outsider' }
+ );
+ return {
+ requireProjectAccess,
+ caller: async () =>
+ shareRouter.createCaller(
+ await makeTrpcContext(ctx, new Headers(), {
+ cookieOptions: COOKIE_OPTIONS,
+ })
+ ),
+ };
+}
+
+test('createOverview refuses a signed-in user without write access to the project', async () => {
+ const createShareOverview = mock(() => Promise.resolve({}));
+ const t = nonMemberCaller(createShareOverview);
+ const caller = await t.caller();
+
+ await expect(
+ caller.createOverview({
+ organizationId: 'org_1',
+ projectId: 'proj_1',
+ public: true,
+ password: null,
+ })
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(t.requireProjectAccess).toHaveBeenCalledWith({
+ userId: 'user_outsider',
+ projectId: 'proj_1',
+ level: 'write',
+ });
+ expect(createShareOverview).not.toHaveBeenCalled();
+});
diff --git a/packages/core/src/modules/share/share.rpc.ts b/packages/core/src/modules/share/share.rpc.ts
index 374313b1b..1953d980c 100644
--- a/packages/core/src/modules/share/share.rpc.ts
+++ b/packages/core/src/modules/share/share.rpc.ts
@@ -7,8 +7,7 @@
// requestId minted at the edge reaches the Postgres call.
//
// The permission ladder itself is bound once, in auth.service.ts; every
-// procedure here reaches it through `ctx.services.auth`. `createOverview` has
-// no in-handler check — a known gap, not fixed.
+// procedure here reaches it through `ctx.services.auth`.
import { z } from 'zod';
import {
@@ -37,7 +36,13 @@ export const shareRouter = createTRPCRouter({
createOverview: protectedProcedure
.input(zShareOverview)
- .mutation(({ input, ctx }) => {
+ .mutation(async ({ input, ctx }) => {
+ const userId = ctx.session.userId;
+ await ctx.services.auth.requireProjectAccess({
+ userId,
+ projectId: input.projectId,
+ level: 'write',
+ });
return ctx.services.share.createShareOverview(input);
}),
diff --git a/packages/core/src/modules/widget/widget.rpc.ts b/packages/core/src/modules/widget/widget.rpc.ts
index 996fc22d5..438e7e757 100644
--- a/packages/core/src/modules/widget/widget.rpc.ts
+++ b/packages/core/src/modules/widget/widget.rpc.ts
@@ -127,6 +127,12 @@ export const widgetRouter = createTRPCRouter({
})
)
.mutation(async ({ input, ctx }) => {
+ await ctx.services.auth.requireProjectAccess({
+ userId: ctx.session.userId,
+ projectId: input.projectId,
+ level: 'write',
+ });
+
const defaultOptions =
input.type === 'realtime'
? zRealtimeWidgetOptions.parse({ type: 'realtime' })
@@ -149,15 +155,21 @@ export const widgetRouter = createTRPCRouter({
options: zWidgetOptions,
})
)
- .mutation(async ({ input, ctx }) =>
- upsertWidgetByType(ctx.db, {
+ .mutation(async ({ input, ctx }) => {
+ await ctx.services.auth.requireProjectAccess({
+ userId: ctx.session.userId,
+ projectId: input.projectId,
+ level: 'write',
+ });
+
+ return upsertWidgetByType(ctx.db, {
projectId: input.projectId,
organizationId: input.organizationId,
type: input.options.type,
update: { options: input.options },
create: { public: false, options: input.options },
- })
- ),
+ });
+ }),
counter: publicProcedure
.input(z.object({ shareId: z.string() }))