Skip to content

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

organization, auth, ingest: answer the caller instead of guessing

Carl-Gerhard Lindesvärdd4ab3c3376f9
diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.ts
index 5e9f5c242..b2a4d9e7c 100644
--- a/packages/core/src/modules/auth/auth.service.ts
+++ b/packages/core/src/modules/auth/auth.service.ts
@@ -282,6 +282,7 @@ import { sendEmail } from '../../clients/email';
import type { Logger } from '../../logger';
import {
TRPCAccessError,
+ TRPCBadRequestError,
TRPCForbiddenError,
TRPCNotFoundError,
} from '../../rpc/errors';
@@ -387,6 +388,19 @@ export function startOAuthSignIn(
input: StartOAuthSignInInput,
setCookie: ISetCookie
): StartOAuthSignInResult {
+ // Without this an unconfigured provider still returned a URL, with an empty
+ // `client_id` in it — the caller only found out when the provider rejected
+ // the redirect. `providers` reports the same test, so the two agree.
+ const configured = getConfiguredProviders(deps.config);
+ if (
+ (input.provider === 'github' && !configured.github) ||
+ (input.provider === 'google' && !configured.google)
+ ) {
+ throw new TRPCBadRequestError(
+ `${input.provider} sign-in is not configured on this deployment`
+ );
+ }
+
if (input.inviteId) {
setCookie('inviteId', input.inviteId, { maxAge: 60 * 10 });
}
diff --git a/packages/core/src/modules/ingest/src/incoming-event-handler.ts b/packages/core/src/modules/ingest/src/incoming-event-handler.ts
index 4f025365e..7ad4066ba 100644
--- a/packages/core/src/modules/ingest/src/incoming-event-handler.ts
+++ b/packages/core/src/modules/ingest/src/incoming-event-handler.ts
@@ -412,8 +412,11 @@ async function ingestIncomingEvent(
const payload = {
...baseEvent,
- deviceId: session?.device_id ?? '',
- sessionId: session?.id ?? '',
+ // Falls back to the ids the producer already resolved, not ''. /track
+ // returns these two in its response, so storing '' made the response
+ // describe a row that does not exist.
+ deviceId: session?.device_id || deviceId,
+ sessionId: session?.id || sessionId,
referrer: session?.referrer ?? undefined,
referrerName: session?.referrer_name ?? undefined,
referrerType: session?.referrer_type ?? undefined,
diff --git a/packages/core/src/modules/organization/organization.service.test.ts b/packages/core/src/modules/organization/organization.service.test.ts
index 87ea30387..189c630c5 100644
--- a/packages/core/src/modules/organization/organization.service.test.ts
+++ b/packages/core/src/modules/organization/organization.service.test.ts
@@ -176,12 +176,19 @@ const project = {
async ({
where,
}: {
- where?: { id?: { in: string[] }; deleteAt?: { lte: Date } };
+ where?: {
+ id?: { in: string[] };
+ deleteAt?: { lte: Date };
+ organizationId?: string;
+ };
} = {}) => {
let rows = [...projectStore.values()];
if (where?.id) {
rows = rows.filter((p) => where.id?.in.includes(p.id));
}
+ if (where?.organizationId) {
+ rows = rows.filter((p) => p.organizationId === where.organizationId);
+ }
if (where?.deleteAt) {
rows = rows.filter((p) => p.deleteAt && p.deleteAt <= new Date());
}
@@ -609,6 +616,18 @@ test('removeOrganizationMember deletes the member and their project access', asy
});
test('updateOrganizationMemberAccess replaces project access with the given grants', async () => {
+ memberStore.set('member_1', {
+ id: 'member_1',
+ organizationId: 'org_1',
+ userId: 'user_1',
+ role: 'org:member',
+ email: '[email protected]',
+ });
+ projectStore.set('proj_new', {
+ id: 'proj_new',
+ organizationId: 'org_1',
+ deleteAt: null,
+ });
projectAccessStore.set('access_old', {
id: 'access_old',
userId: 'user_1',
@@ -628,6 +647,52 @@ test('updateOrganizationMemberAccess replaces project access with the given gran
expect(remaining[0]).toMatchObject({ projectId: 'proj_new', level: 'write' });
});
+// These two guards did not exist: access rows were written for a user who was
+// never confirmed to be a member, naming a project that need not belong to the
+// organization the grant is scoped to.
+test('updateOrganizationMemberAccess refuses a user who is not a member', async () => {
+ projectStore.set('proj_new', {
+ id: 'proj_new',
+ organizationId: 'org_1',
+ deleteAt: null,
+ });
+
+ await expect(
+ subject.updateOrganizationMemberAccess(deps, {
+ organizationId: 'org_1',
+ targetUserId: 'not_a_member',
+ access: [{ projectId: 'proj_new', level: 'write' }],
+ })
+ ).rejects.toThrow(/not a member/i);
+
+ expect([...projectAccessStore.values()]).toHaveLength(0);
+});
+
+test('updateOrganizationMemberAccess refuses a project from another organization', async () => {
+ memberStore.set('member_1', {
+ id: 'member_1',
+ organizationId: 'org_1',
+ userId: 'user_1',
+ role: 'org:member',
+ email: '[email protected]',
+ });
+ projectStore.set('proj_elsewhere', {
+ id: 'proj_elsewhere',
+ organizationId: 'org_2',
+ deleteAt: null,
+ });
+
+ await expect(
+ subject.updateOrganizationMemberAccess(deps, {
+ organizationId: 'org_1',
+ targetUserId: 'user_1',
+ access: [{ projectId: 'proj_elsewhere', level: 'write' }],
+ })
+ ).rejects.toThrow(/not in this organization/i);
+
+ expect([...projectAccessStore.values()]).toHaveLength(0);
+});
+
test('inviteUserToOrganization refuses when the email is already a member', async () => {
userStore.set('user_1', { id: 'user_1', email: '[email protected]' });
memberStore.set('member_1', {
diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.ts
index 1cf5c6954..2ecfbcff8 100644
--- a/packages/core/src/modules/organization/organization.service.ts
+++ b/packages/core/src/modules/organization/organization.service.ts
@@ -17,7 +17,7 @@ import { DateTime, generateSecureId } from '@openpanel/shared';
import { cacheablePerDeps } from '../../cacheable-per-deps';
import { chQuery } from '../../ch-query';
import { sendEmail } from '../../clients/email';
-import { TRPCBadRequestError } from '../../rpc/errors';
+import { TRPCBadRequestError, TRPCNotFoundError } from '../../rpc/errors';
import type { ServiceDeps, Services } from '../../services';
import {
getOrganizationAccess,
@@ -142,9 +142,16 @@ export async function getInviteById(deps: ServiceDeps, inviteId: string) {
},
});
+ // Spreading a null result produced `{isExpired: undefined}` — a TRUTHY
+ // object — so the onboarding page rendered its invitation banner for a
+ // bogus id, with the organization name blank.
+ if (!res) {
+ throw new TRPCNotFoundError('Invite not found');
+ }
+
return {
...res,
- isExpired: res?.expiresAt && res.expiresAt < new Date(),
+ isExpired: res.expiresAt < new Date(),
};
}
@@ -750,6 +757,12 @@ export async function inviteUserToOrganization(
);
}
+ await assertProjectsInOrganization(
+ deps,
+ input.organizationId,
+ input.access ?? []
+ );
+
const invite = await db.invite.create({
data: {
id: generateSecureId('invite'),
@@ -857,6 +870,33 @@ export async function removeOrganizationMember(
]);
}
+/**
+ * A grant may only name a project inside the organization it is granted in.
+ * Without this an admin of one organization could write projectAccess rows
+ * pointing at another organization's projects.
+ */
+async function assertProjectsInOrganization(
+ deps: ServiceDeps,
+ organizationId: string,
+ access: { projectId: string }[]
+) {
+ const projectIds = [...new Set(access.map((grant) => grant.projectId))];
+ if (projectIds.length === 0) {
+ return;
+ }
+ const found = await deps.db.project.findMany({
+ where: { id: { in: projectIds }, organizationId },
+ select: { id: true },
+ });
+ if (found.length !== projectIds.length) {
+ const known = new Set(found.map((project) => project.id));
+ const unknown = projectIds.filter((id) => !known.has(id));
+ throw new TRPCBadRequestError(
+ `Project not in this organization: ${unknown.join(', ')}`
+ );
+ }
+}
+
export async function updateOrganizationMemberAccess(
deps: ServiceDeps,
input: {
@@ -866,6 +906,21 @@ export async function updateOrganizationMemberAccess(
}
) {
const db = deps.db;
+
+ // The rows below are keyed on a user this never confirmed was a member, so
+ // an unknown id silently produced access rows for a non-member.
+ const member = await db.member.findFirst({
+ where: {
+ userId: input.targetUserId,
+ organizationId: input.organizationId,
+ },
+ select: { id: true },
+ });
+ if (!member) {
+ throw new TRPCNotFoundError('User is not a member of this organization');
+ }
+ await assertProjectsInOrganization(deps, input.organizationId, input.access);
+
return db.$transaction([
db.projectAccess.deleteMany({
where: {