⭐️⭐️⭐️ 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
fix(api): serialize team ownership changes (#387)
I'm Groot 🌳5181d7b15b25
diff --git a/apps/api/src/modules/teams/__tests__/integration/teams.test.ts b/apps/api/src/modules/teams/__tests__/integration/teams.test.tsindex 20a5b357..9c0250b5 100644--- a/apps/api/src/modules/teams/__tests__/integration/teams.test.ts+++ b/apps/api/src/modules/teams/__tests__/integration/teams.test.ts@@ -943,6 +943,58 @@ describe('teams', () => {});});+ describe('concurrent ownership changes', () => {+ async function twoOwners() {+ const owner = await signUpClient();+ const teamId = (await owner.api.teams.get()).data![0].id;+ const second = await addTeamMember(owner, teamId);+ await owner.api+ .teams({ teamId })+ .members({ userId: second.user.userId })+ .patch({ role: 'owner' });+ return { owner, second, teamId };+ }++ it('keeps an owner when both owners leave concurrently', async () => {+ const { owner, second, teamId } = await twoOwners();+ const results = await Promise.all([+ owner.api.teams({ teamId }).leave.post(),+ second.api.teams({ teamId }).leave.post(),+ ]);+ expect(results.map((result) => result.status).sort()).toEqual([204, 409]);+ const teams = await Promise.all([owner.api.teams.get(), second.api.teams.get()]);+ expect(+ teams.flatMap((result) => result.data ?? []).filter((row) => row.id === teamId),+ ).toHaveLength(1);+ });++ it('keeps an owner when owners demote each other concurrently', async () => {+ const { owner, second, teamId } = await twoOwners();+ const results = await Promise.all([+ owner.api+ .teams({ teamId })+ .members({ userId: second.user.userId })+ .patch({ role: 'member' }),+ second.api+ .teams({ teamId })+ .members({ userId: owner.user.userId })+ .patch({ role: 'member' }),+ ]);+ expect(results.map((result) => result.status).sort()).toEqual([204, 403]);+ expect((await owner.api.teams({ teamId }).get()).data?.ownerCount).toBe(1);+ });++ it('keeps an owner when owners remove each other concurrently', async () => {+ const { owner, second, teamId } = await twoOwners();+ const results = await Promise.all([+ owner.api.teams({ teamId }).members({ userId: second.user.userId }).delete(),+ second.api.teams({ teamId }).members({ userId: owner.user.userId }).delete(),+ ]);+ expect(results.filter((result) => result.status === 204)).toHaveLength(1);+ expect(results.some((result) => result.status === 403 || result.status === 404)).toBe(true);+ });+ });+describe('leave', () => {it('rejects the last owner leaving', async () => {const { api } = await signUpClient();diff --git a/apps/api/src/modules/teams/index.ts b/apps/api/src/modules/teams/index.tsindex f320dbeb..e28fe99d 100644--- a/apps/api/src/modules/teams/index.ts+++ b/apps/api/src/modules/teams/index.ts@@ -406,7 +406,7 @@ export const teamRoutes = new Elysia({ name: 'teams', detail: { tags: ['Teams'].post('/teams/:teamId/leave',async ({ membership }) => {- await leaveTeam(membership.teamId, membership.userId, membership.role);+ await leaveTeam(membership.teamId, membership.userId);return noContent();},{diff --git a/apps/api/src/modules/teams/service.ts b/apps/api/src/modules/teams/service.tsindex 98560b5b..7f2ea3b1 100644--- a/apps/api/src/modules/teams/service.ts+++ b/apps/api/src/modules/teams/service.ts@@ -749,6 +749,18 @@ export async function renameTeam(teamId: number, name: string, userId: string):return row;}+async function membershipInTransaction(+ tx: Transaction,+ teamId: number,+ userId: string,+): Promise<TeamStanding | null> {+ const [row] = await tx+ .select({ role: teamMember.role })+ .from(teamMember)+ .where(and(eq(teamMember.teamId, teamId), eq(teamMember.userId, userId)));+ return row ? (row.role as TeamStanding) : null;+}+// Changes what a member ranks as in the team. An agent's standing comes from its// agent settings, and nobody sets their own rank. Only an owner grants the owner rank// or changes what another owner holds, which is also what keeps the last owner in@@ -759,19 +771,24 @@ export async function setTeamMemberRole(userId: string,role: TeamRole,): Promise<void> {- if (userId === actor.userId) throw new HttpError(409, 'You cannot change your own rank');-- const current = await getTeamMembership(teamId, userId);- if (!current) throw new HttpError(404, 'Member not found');- if (current === 'agent')- throw new HttpError(409, "An agent's rank comes from its agent settings");- if (actor.role !== 'owner' && (role === 'owner' || current === 'owner'))- throw new HttpError(403, 'Only a team owner can grant or take the owner rank');-- await db- .update(teamMember)- .set({ role })- .where(and(eq(teamMember.teamId, teamId), eq(teamMember.userId, userId)));+ await db.transaction(async (tx) => {+ await tx.select({ id: team.id }).from(team).where(eq(team.id, teamId)).for('update');+ const actorRole = await membershipInTransaction(tx, teamId, actor.userId);+ if (!runsTeam(actorRole))+ throw new HttpError(403, 'Only a team owner or manager can change ranks');+ if (userId === actor.userId) throw new HttpError(409, 'You cannot change your own rank');+ const current = await membershipInTransaction(tx, teamId, userId);+ if (!current) throw new HttpError(404, 'Member not found');+ if (current === 'agent')+ throw new HttpError(409, "An agent's rank comes from its agent settings");+ if (actorRole !== 'owner' && (role === 'owner' || current === 'owner')) {+ throw new HttpError(403, 'Only a team owner can grant or take the owner rank');+ }+ await tx+ .update(teamMember)+ .set({ role })+ .where(and(eq(teamMember.teamId, teamId), eq(teamMember.userId, userId)));+ });}// Refuses to end a membership that would leave a project of the team without an owner:@@ -779,11 +796,12 @@ export async function setTeamMemberRole(// routes refuse such a removal for the same reason. The other owner has to be named// first, from the project's member list.async function assertLeavesNoProjectOwnerless(+ tx: Transaction,teamId: number,userId: string,subject: 'You' | 'They',): Promise<void> {- const soleOwned = await db+ const soleOwned = await tx.select({ key: project.key }).from(projectMember).innerJoin(project, eq(project.id, projectMember.projectId))@@ -808,38 +826,40 @@ async function assertLeavesNoProjectOwnerless(// Ends a team membership: the member leaves the team and every project it owns. What// they already did in those projects stays — issues keep their assignee and their// author.-async function dropTeamMembership(teamId: number, userId: string): Promise<void> {- await db.transaction(async (tx) => {- const teamProjects = tx- .select({ id: project.id })- .from(project)- .where(eq(project.teamId, teamId));- await tx- .delete(projectMember)- .where(and(eq(projectMember.userId, userId), inArray(projectMember.projectId, teamProjects)));- // A column cannot keep assigning issues to someone who no longer belongs to the- // project, the same rule remove_member follows.- await tx- .update(projectColumn)- .set({ autoAssignUserId: null })- .where(- and(- eq(projectColumn.autoAssignUserId, userId),- inArray(projectColumn.projectId, teamProjects),- ),- );- await tx- .delete(teamMember)- .where(and(eq(teamMember.teamId, teamId), eq(teamMember.userId, userId)));- });+async function dropTeamMembership(tx: Transaction, teamId: number, userId: string): Promise<void> {+ const teamProjects = tx+ .select({ id: project.id })+ .from(project)+ .where(eq(project.teamId, teamId));+ await tx+ .delete(projectMember)+ .where(and(eq(projectMember.userId, userId), inArray(projectMember.projectId, teamProjects)));+ // A column cannot keep assigning issues to someone who no longer belongs to the+ // project, the same rule remove_member follows.+ await tx+ .update(projectColumn)+ .set({ autoAssignUserId: null })+ .where(+ and(+ eq(projectColumn.autoAssignUserId, userId),+ inArray(projectColumn.projectId, teamProjects),+ ),+ );+ await tx+ .delete(teamMember)+ .where(and(eq(teamMember.teamId, teamId), eq(teamMember.userId, userId)));}// A membership the SCIM group reconciliation owns ends at the identity provider: the// next sync would put it back, and dropping it here would take the project memberships// that same sync granted with it. Only the plain member rows it writes — a rank raised// by hand is the team's, and the reconciliation leaves those alone too.-async function assertNotProvisioned(teamId: number, userId: string): Promise<void> {- const [row] = await db+async function assertNotProvisioned(+ tx: Transaction,+ teamId: number,+ userId: string,+): Promise<void> {+ const [row] = await tx.select({ role: teamMember.role, source: teamMember.source }).from(teamMember).where(and(eq(teamMember.teamId, teamId), eq(teamMember.userId, userId)));@@ -856,15 +876,20 @@ export async function removeTeamMember(actorId: string,userId: string,): Promise<void> {- if (userId === actorId) throw new HttpError(409, 'Leave the team instead of removing yourself');-- const current = await getTeamMembership(teamId, userId);- if (!current) throw new HttpError(404, 'Member not found');- if (current === 'agent') throw new HttpError(409, 'An agent is removed with its agent settings');- await assertNotProvisioned(teamId, userId);- await assertLeavesNoProjectOwnerless(teamId, userId, 'They');-- await dropTeamMembership(teamId, userId);+ await db.transaction(async (tx) => {+ await tx.select({ id: team.id }).from(team).where(eq(team.id, teamId)).for('update');+ if ((await membershipInTransaction(tx, teamId, actorId)) !== 'owner') {+ throw new HttpError(403, 'Only a team owner can remove members');+ }+ if (userId === actorId) throw new HttpError(409, 'Leave the team instead of removing yourself');+ const current = await membershipInTransaction(tx, teamId, userId);+ if (!current) throw new HttpError(404, 'Member not found');+ if (current === 'agent')+ throw new HttpError(409, 'An agent is removed with its agent settings');+ await assertNotProvisioned(tx, teamId, userId);+ await assertLeavesNoProjectOwnerless(tx, teamId, userId, 'They');+ await dropTeamMembership(tx, teamId, userId);+ });}// Drops the caller's own membership, with their access to the team's projects. The@@ -872,16 +897,21 @@ export async function removeTeamMember(// owner has nobody who can rename it. Neither can the only owner of one of its// projects, for the same reason one project down. An agent cannot either: its standing// is written with the agent and nothing puts it back, so leaving would strand it.-export async function leaveTeam(teamId: number, userId: string, role: TeamStanding): Promise<void> {- if (role === 'agent') throw new HttpError(409, 'An agent is removed with its agent settings');- if (role === 'owner') {- const [{ count }] = await db- .select({ count: sql<number>`count(*)::int` })- .from(teamMember)- .where(and(eq(teamMember.teamId, teamId), eq(teamMember.role, 'owner')));- if (count === 1) throw new HttpError(409, 'The last owner cannot leave the team');- }- await assertNotProvisioned(teamId, userId);- await assertLeavesNoProjectOwnerless(teamId, userId, 'You');- await dropTeamMembership(teamId, userId);+export async function leaveTeam(teamId: number, userId: string): Promise<void> {+ await db.transaction(async (tx) => {+ await tx.select({ id: team.id }).from(team).where(eq(team.id, teamId)).for('update');+ const role = await membershipInTransaction(tx, teamId, userId);+ if (!role) throw new HttpError(404, 'Member not found');+ if (role === 'agent') throw new HttpError(409, 'An agent is removed with its agent settings');+ if (role === 'owner') {+ const [{ count }] = await tx+ .select({ count: sql<number>`count(*)::int` })+ .from(teamMember)+ .where(and(eq(teamMember.teamId, teamId), eq(teamMember.role, 'owner')));+ if (count === 1) throw new HttpError(409, 'The last owner cannot leave the team');+ }+ await assertNotProvisioned(tx, teamId, userId);+ await assertLeavesNoProjectOwnerless(tx, teamId, userId, 'You');+ await dropTeamMembership(tx, teamId, userId);+ });}