diff --git a/server/models/GroupMembership.test.ts b/server/models/GroupMembership.test.ts index 79d0ec0e4a..0229c48a3f 100644 --- a/server/models/GroupMembership.test.ts +++ b/server/models/GroupMembership.test.ts @@ -1,4 +1,12 @@ -import { buildCollection, buildGroup, buildUser } from "@server/test/factories"; +import { CollectionPermission } from "@shared/types"; +import { sleep } from "@shared/utils/timers"; +import { sequelize } from "@server/storage/database"; +import { + buildCollection, + buildDocument, + buildGroup, + buildUser, +} from "@server/test/factories"; import GroupMembership from "./GroupMembership"; describe("GroupMembership", () => { @@ -26,4 +34,49 @@ describe("GroupMembership", () => { expect(permission?.collection?.id).toEqual(collection.id); }); }); + + describe("findOneForUpdate", () => { + it("should create one membership for concurrent grants", async () => { + const document = await buildDocument(); + const group = await buildGroup({ teamId: document.teamId }); + + const grant = (permission: CollectionPermission, ids: string[]) => + sequelize.transaction(async (transaction) => { + const [documentId, groupId] = ids; + const membership = await GroupMembership.findOneForUpdate( + { documentId, groupId }, + { transaction } + ); + await sleep(50); + + if (membership) { + membership.permission = permission; + return membership.save({ transaction }); + } + + return GroupMembership.create( + { + documentId, + groupId, + permission, + createdById: document.createdById, + }, + { transaction } + ); + }); + + await Promise.all([ + grant(CollectionPermission.Read, [document.id, group.id]), + grant(CollectionPermission.ReadWrite, [ + document.id.toUpperCase(), + group.id.toUpperCase(), + ]), + ]); + + const memberships = await GroupMembership.findAll({ + where: { documentId: document.id, groupId: group.id }, + }); + expect(memberships).toHaveLength(1); + }); + }); }); diff --git a/server/models/GroupMembership.ts b/server/models/GroupMembership.ts index 18de933aa0..613c2e571f 100644 --- a/server/models/GroupMembership.ts +++ b/server/models/GroupMembership.ts @@ -5,6 +5,7 @@ import { type FindOptions, type DestroyOptions, type WhereOptions, + type Transaction, } from "sequelize"; import { BelongsTo, @@ -135,6 +136,38 @@ class GroupMembership extends ParanoidModel< // static methods + /** + * Find the membership of a group on a collection or document and lock it for + * the remainder of the transaction. The lock is held even when no membership + * exists, so that concurrent grants cannot each create a membership. + * + * @param where the group and the collection or document of the membership. + * @param options additional options to pass to the query, with a transaction. + * @returns a promise that resolves to the membership, or null. + */ + public static async findOneForUpdate( + where: { + groupId: string; + collectionId?: string | null; + documentId?: string | null; + }, + options: FindOptions & { transaction: Transaction } + ) { + const { groupId, collectionId, documentId } = where; + const targetId = collectionId ?? documentId; + await LockHelper.acquire( + this.sequelize!, + `groupMembership:${targetId}:${groupId}`.toLowerCase(), + options.transaction + ); + + return this.findOne({ + ...options, + where: collectionId ? { groupId, collectionId } : { groupId, documentId }, + lock: options.transaction.LOCK.UPDATE, + }); + } + /** * Copy group memberships from one document to another. * diff --git a/server/models/UserMembership.test.ts b/server/models/UserMembership.test.ts index fcf7ba0c6f..b3c5c3e50e 100644 --- a/server/models/UserMembership.test.ts +++ b/server/models/UserMembership.test.ts @@ -6,6 +6,7 @@ import { buildGroup, buildUser, } from "@server/test/factories"; +import { sequelize } from "@server/storage/database"; import { withAPIContext } from "@server/test/support"; import Event from "./Event"; import GroupMembership from "./GroupMembership"; @@ -105,4 +106,49 @@ describe("UserMembership", () => { ); }); }); + + describe("findOneForUpdate", () => { + it("should create one membership for concurrent grants", async () => { + const collection = await buildCollection(); + const user = await buildUser({ teamId: collection.teamId }); + + const grant = (permission: CollectionPermission, ids: string[]) => + sequelize.transaction(async (transaction) => { + const [collectionId, userId] = ids; + const membership = await UserMembership.findOneForUpdate( + { collectionId, userId }, + { transaction } + ); + await sleep(50); + + if (membership) { + membership.permission = permission; + return membership.save({ transaction }); + } + + return UserMembership.create( + { + collectionId, + userId, + permission, + createdById: user.id, + }, + { transaction } + ); + }); + + await Promise.all([ + grant(CollectionPermission.Read, [collection.id, user.id]), + grant(CollectionPermission.ReadWrite, [ + collection.id.toUpperCase(), + user.id.toUpperCase(), + ]), + ]); + + const memberships = await UserMembership.findAll({ + where: { collectionId: collection.id, userId: user.id }, + }); + expect(memberships).toHaveLength(1); + }); + }); }); diff --git a/server/models/UserMembership.ts b/server/models/UserMembership.ts index 1dda32588d..253d08091f 100644 --- a/server/models/UserMembership.ts +++ b/server/models/UserMembership.ts @@ -1,5 +1,10 @@ import type { InferAttributes, InferCreationAttributes } from "sequelize"; -import { Op, type SaveOptions, type FindOptions } from "sequelize"; +import { + Op, + type SaveOptions, + type FindOptions, + type Transaction, +} from "sequelize"; import type { WhereOptions } from "sequelize"; import { Column, @@ -135,6 +140,38 @@ class UserMembership extends IdModel< // static methods + /** + * Find the membership of a user on a collection or document and lock it for + * the remainder of the transaction. The lock is held even when no membership + * exists, so that concurrent grants cannot each create a membership. + * + * @param where the user and the collection or document of the membership. + * @param options additional options to pass to the query, with a transaction. + * @returns a promise that resolves to the membership, or null. + */ + public static async findOneForUpdate( + where: { + userId: string; + collectionId?: string | null; + documentId?: string | null; + }, + options: FindOptions & { transaction: Transaction } + ) { + const { userId, collectionId, documentId } = where; + const targetId = collectionId ?? documentId; + await LockHelper.acquire( + this.sequelize!, + `userMembership:${targetId}:${userId}`.toLowerCase(), + options.transaction + ); + + return this.findOne({ + ...options, + where: collectionId ? { userId, collectionId } : { userId, documentId }, + lock: options.transaction.LOCK.UPDATE, + }); + } + /** * Copy user memberships from one document to another. * diff --git a/server/routes/api/accessRequests/accessRequests.ts b/server/routes/api/accessRequests/accessRequests.ts index 2eb0f35622..4cac8af61a 100644 --- a/server/routes/api/accessRequests/accessRequests.ts +++ b/server/routes/api/accessRequests/accessRequests.ts @@ -114,14 +114,10 @@ router.post( throw InvalidRequestError("Access request has already been responded to"); } - const membership = await UserMembership.findOne({ - where: { - userId: accessRequest.userId, - documentId: accessRequest.documentId, - }, - lock: transaction.LOCK.UPDATE, - transaction, - }); + const membership = await UserMembership.findOneForUpdate( + { userId: accessRequest.userId, documentId: accessRequest.documentId }, + { transaction } + ); if (!membership) { await UserMembership.createWithCtx(ctx, { diff --git a/server/routes/api/collections/collections.ts b/server/routes/api/collections/collections.ts index 7e77ccedbc..89f2a4a10d 100644 --- a/server/routes/api/collections/collections.ts +++ b/server/routes/api/collections/collections.ts @@ -249,14 +249,10 @@ router.post( authorize(user, "manageUsers", collection); authorize(user, "read", group); - let membership = await GroupMembership.findOne({ - where: { - collectionId: id, - groupId, - }, - lock: transaction.LOCK.UPDATE, - ...ctx.context, - }); + let membership = await GroupMembership.findOneForUpdate( + { collectionId: id, groupId }, + { transaction } + ); if (membership) { membership.permission = permission; @@ -407,14 +403,10 @@ router.post( authorize(actor, "manageUsers", collection); authorize(actor, "read", user); - let membership = await UserMembership.findOne({ - where: { - collectionId: id, - userId, - }, - lock: transaction.LOCK.UPDATE, - ...ctx.context, - }); + let membership = await UserMembership.findOneForUpdate( + { collectionId: id, userId }, + { transaction } + ); if (membership) { membership.permission = permission || user.defaultCollectionPermission; @@ -653,13 +645,10 @@ router.post( permission !== CollectionPermission.ReadWrite && collection.permission === CollectionPermission.ReadWrite ) { - let membership = await UserMembership.findOne({ - where: { - collectionId: collection.id, - userId: user.id, - }, - transaction, - }); + const membership = await UserMembership.findOneForUpdate( + { collectionId: collection.id, userId: user.id }, + { transaction } + ); if (!membership) { await UserMembership.create( diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index 9f30f7a97b..028a26c952 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -1973,14 +1973,10 @@ router.post( UserMemberships.length ? UserMemberships[0].index : null ); - let membership = await UserMembership.findOne({ - where: { - documentId: id, - userId, - }, - lock: transaction.LOCK.UPDATE, - ...ctx.context, - }); + let membership = await UserMembership.findOneForUpdate( + { documentId: id, userId }, + { transaction } + ); if (membership) { if (permission) { @@ -2088,14 +2084,10 @@ router.post( authorize(user, "manageUsers", document); authorize(user, "read", group); - let membership = await GroupMembership.findOne({ - where: { - documentId: id, - groupId, - }, - lock: transaction.LOCK.UPDATE, - ...ctx.context, - }); + let membership = await GroupMembership.findOneForUpdate( + { documentId: id, groupId }, + { transaction } + ); if (membership) { if (permission) {