fix: Make membership grants for the same subject atomic (#14274)

* fix: Serialize membership grants for the same subject

* fix: Normalize ID case in membership lock names
This commit is contained in:
Tom Moor authored and GitHub committed 2026-10-24 07:24:16 -04:00
1 parent e76f0dcf8e
commit c84b9f10a0
7 files changed
+195 -49

No files matched your search

+54 -1
View File
@@ -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);
});
});
});
+33
View File
@@ -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<GroupMembership> & { 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.
*
+46
View File
@@ -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);
});
});
});
+38 -1
View File
@@ -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<UserMembership> & { 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.
*
@@ -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, {
+12 -23
View File
@@ -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(
+8 -16
View File
@@ -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) {