OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
fix(api): removing a member or narrowing their access takes effect at once
Carl-Gerhard Lindesvärdf88ca4f0268e
diff --git a/packages/core/src/modules/organization/organization.service.test.ts b/packages/core/src/modules/organization/organization.service.test.tsindex 189c630c5..8b9215480 100644--- a/packages/core/src/modules/organization/organization.service.test.ts+++ b/packages/core/src/modules/organization/organization.service.test.ts@@ -438,6 +438,7 @@ const deps = {// Real `cacheable` overloads on `(fn, ttl)` OR `(name, fn, ttl)` — this// module uses the first form, access.service.ts (reached via// connectUserToOrganization) the second.+const clearedCacheKeys: string[] = [];function cacheableStub(fnOrName: ((...args: unknown[]) => unknown) | string,fnOrTtl: ((...args: unknown[]) => unknown) | number@@ -446,12 +447,35 @@ function cacheableStub(typeof fnOrName === 'function'? fnOrName: (fnOrTtl as (...args: unknown[]) => unknown);+ const name = typeof fnOrName === 'string' ? fnOrName : fnOrName.name;return Object.assign(fn, {getKey: () => '',- clear: async () => 0,+ clear: async (...args: unknown[]) => {+ clearedCacheKeys.push(`${name}:${JSON.stringify(args[0])}`);+ return 0;+ },set: () => async () => 'OK' as const,});}++function seedMemberWithTwoProjects() {+ memberStore.set('member_1', {+ id: 'member_1',+ organizationId: 'org_1',+ userId: 'user_1',+ role: 'org:member',+ email: '[email protected]',+ });+ for (const id of ['proj_1', 'proj_2']) {+ projectStore.set(id, { id, organizationId: 'org_1', deleteAt: null });+ }+}++const EXPECTED_CLEARED_ACCESS_KEYS = [+ 'getOrganizationAccess:{"userId":"user_1","organizationId":"org_1"}',+ 'getProjectAccessV2:{"userId":"user_1","projectId":"proj_1"}',+ 'getProjectAccessV2:{"userId":"user_1","projectId":"proj_2"}',+];// Spread the real module: `mock.module` replaces this specifier process-wide,// and `event-buffer.ts` value-imports `publishEvent` from here, so a partial// factory turns this file's own barrel import into a SyntaxError.@@ -493,6 +517,7 @@ beforeAll(async () => {beforeEach(() => {resetStores();sentEmails.length = 0;+ clearedCacheKeys.length = 0;});test('scheduleOrganizationDeletion sets deleteAt on the org and its projects', async () => {@@ -615,6 +640,55 @@ test('removeOrganizationMember deletes the member and their project access', asyexpect(projectAccessStore.has('access_1')).toBe(false);});+// The lookups cache a granted answer for minutes; without these clears a+// removed or restricted member kept their access until the entry expired.+test('removeOrganizationMember drops the cached access for every project of the organization', async () => {+ seedMemberWithTwoProjects();++ await subject.removeOrganizationMember(deps, {+ organizationId: 'org_1',+ memberId: 'member_1',+ targetUserId: 'user_1',+ requestedByUserId: 'user_admin',+ });++ expect(clearedCacheKeys.sort()).toEqual(EXPECTED_CLEARED_ACCESS_KEYS);+});++test('updateOrganizationMemberAccess drops the cached access for every project of the organization', async () => {+ seedMemberWithTwoProjects();++ await subject.updateOrganizationMemberAccess(deps, {+ organizationId: 'org_1',+ targetUserId: 'user_1',+ access: [{ projectId: 'proj_1', level: 'read' }],+ });++ expect(clearedCacheKeys.sort()).toEqual(EXPECTED_CLEARED_ACCESS_KEYS);+});++test('connectUserToOrganization drops the cached access for every project of the organization', async () => {+ seedMemberWithTwoProjects();+ memberStore.clear();+ inviteStore.set('invite_1', {+ id: 'invite_1',+ email: '[email protected]',+ organizationId: 'org_1',+ role: 'org:member',+ createdById: 'user_admin',+ projectAccess: [{ projectId: 'proj_1', level: 'read' }],+ expiresAt: new Date(Date.now() + 60_000),+ createdAt: EPOCH,+ });++ await subject.connectUserToOrganization(deps, {+ user: { id: 'user_1', email: '[email protected]' } as never,+ inviteId: 'invite_1',+ });++ expect(clearedCacheKeys.sort()).toEqual(EXPECTED_CLEARED_ACCESS_KEYS);+});+test('updateOrganizationMemberAccess replaces project access with the given grants', async () => {memberStore.set('member_1', {id: 'member_1',diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.tsindex 2ecfbcff8..336189d02 100644--- a/packages/core/src/modules/organization/organization.service.ts+++ b/packages/core/src/modules/organization/organization.service.ts@@ -185,6 +185,29 @@ export async function getMembers(})) as IServiceMember[];}+/**+ * The access lookups cache a granted answer for minutes, so every change to a+ * membership or its project grants must drop that user's entries for every+ * project of the organization. A grant on one project also revokes the+ * implicit org-wide default on all the others. Call it after the write, or a+ * concurrent request can cache the old answer again.+ */+async function clearMemberAccessCache(+ deps: ServiceDeps,+ { userId, organizationId }: { userId: string; organizationId: string }+): Promise<void> {+ const projects = await deps.db.project.findMany({+ where: { organizationId },+ select: { id: true },+ });+ await Promise.all([+ getOrganizationAccess.clear({ userId, organizationId }),+ ...projects.map((project) =>+ getProjectAccess.clear({ userId, projectId: project.id })+ ),+ ]);+}+export async function connectUserToOrganization(deps: ServiceDeps,{@@ -239,29 +262,23 @@ export async function connectUserToOrganization(},});- await getOrganizationAccess.clear({+ for (const grant of invite.projectAccess) {+ await db.projectAccess.create({+ data: {+ projectId: grant.projectId,+ userId: user.id,+ organizationId: invite.organizationId,+ // The level the inviting admin chose, not a hardcoded default.+ level: grant.level,+ },+ });+ }++ await clearMemberAccessCache(deps, {userId: user.id,organizationId: invite.organizationId,});- if (invite.projectAccess.length > 0) {- for (const grant of invite.projectAccess) {- await getProjectAccess.clear({- userId: user.id,- projectId: grant.projectId,- });- await db.projectAccess.create({- data: {- projectId: grant.projectId,- userId: user.id,- organizationId: invite.organizationId,- // The level the inviting admin chose, not a hardcoded default.- level: grant.level,- },- });- }- }-await db.invite.delete({where: {id: inviteId,@@ -868,6 +885,10 @@ export async function removeOrganizationMember(},}),]);+ await clearMemberAccessCache(deps, {+ userId: input.targetUserId,+ organizationId: input.organizationId,+ });}/**@@ -921,7 +942,7 @@ export async function updateOrganizationMemberAccess(}await assertProjectsInOrganization(deps, input.organizationId, input.access);- return db.$transaction([+ const result = await db.$transaction([db.projectAccess.deleteMany({where: {userId: input.targetUserId,@@ -940,6 +961,11 @@ export async function updateOrganizationMemberAccess(})),}),]);+ await clearMemberAccessCache(deps, {+ userId: input.targetUserId,+ organizationId: input.organizationId,+ });+ return result;}export function createOrganizationService(