diff --git a/e2e/specs/mock/scenarios/tts-cache.spec.ts b/e2e/specs/mock/scenarios/tts-cache.spec.ts index 5d56229c05..963e8dc24b 100644 --- a/e2e/specs/mock/scenarios/tts-cache.spec.ts +++ b/e2e/specs/mock/scenarios/tts-cache.spec.ts @@ -29,6 +29,15 @@ test.afterAll(async () => { await deleteConversations(createdConversationIds); }); +/** + * A third of a second of silence as MPEG-1 Layer III frames. Read-aloud streams the response into + * a MediaSource, and bytes the decoder rejects fail the playback, which cancels the request: the + * audio was then cached only when the response happened to finish before the decoder gave up. + */ +const SILENT_MP3_FRAME = Buffer.alloc(417); +SILENT_MP3_FRAME.set([0xff, 0xfb, 0x90, 0x00]); +const SILENT_MP3 = Buffer.concat(Array.from({ length: 12 }, () => SILENT_MP3_FRAME)); + /** Stands in for a configured external TTS provider: the e2e config has none. */ async function routeExternalSpeech( target: Page | BrowserContext, @@ -44,10 +53,7 @@ async function routeExternalSpeech( ); await target.route('**/api/files/speech/tts/manual', (route) => { ttsRequests += 1; - return route.fulfill({ - body: Buffer.from([0xff, 0xf3, 0x00, 0x00]), - contentType: 'audio/mpeg', - }); + return route.fulfill({ body: SILENT_MP3, contentType: 'audio/mpeg' }); }); return { requests: () => ttsRequests }; } @@ -66,7 +72,9 @@ async function replyToReadAloud(page: Page, prefix: string) { await expect(page.getByText(replyText(label)).first()).toBeVisible({ timeout: 20000 }); const conversationId = new URL(page.url()).pathname.split('/c/')[1]; if (conversationId) createdConversationIds.push(conversationId); - return page.getByRole('button', { name: 'Read aloud' }).last(); + /** By test id, not by name: the button is named "Stop" while its message is read aloud, and a + * name-based locator then resolves to the user message's read-aloud button instead. */ + return page.getByTestId('read-aloud-button'); } const cacheStorageNames = (page: Page) => page.evaluate(() => caches.keys()); diff --git a/e2e/specs/mock/schedules-execution.spec.ts b/e2e/specs/mock/schedules-execution.spec.ts index 30dfb13e5f..d1d1eaca4b 100644 --- a/e2e/specs/mock/schedules-execution.spec.ts +++ b/e2e/specs/mock/schedules-execution.spec.ts @@ -233,7 +233,13 @@ test.describe('scheduled chat execution', () => { const save = editDialog.getByRole('button', { name: 'Save' }); await save.scrollIntoViewIfNeeded(); await expect(save).toBeInViewport(); + /** The reload discards a request still in flight, so the save has to land before it. */ + const saved = page.waitForResponse( + (response) => + response.request().method() === 'PATCH' && response.url().includes('/api/schedules/'), + ); await save.click(); + expect((await saved).ok()).toBeTruthy(); await page.reload(); await openSchedulesPanel(page); diff --git a/packages/api/src/acl/accessControlService.ts b/packages/api/src/acl/accessControlService.ts index 3d8ea68588..425d997dc6 100644 --- a/packages/api/src/acl/accessControlService.ts +++ b/packages/api/src/acl/accessControlService.ts @@ -144,6 +144,8 @@ export class AccessControlService { session?: ClientSession; roleId?: string | Types.ObjectId; expiredAt?: Date; + /** For a grant that can race with itself: concurrent calls then create one entry, not several. */ + uniqueEntry?: boolean; }): Promise { const { principalType, @@ -154,6 +156,7 @@ export class AccessControlService { grantedBy, session, expiredAt, + uniqueEntry, } = args; try { if (!Object.values(PrincipalType).includes(principalType)) { @@ -207,6 +210,7 @@ export class AccessControlService { session, role._id, expiredAt, + uniqueEntry, ); } catch (error) { logger.error( diff --git a/packages/api/src/shared-links/service.test.ts b/packages/api/src/shared-links/service.test.ts index 4511fbbab9..c352a2607e 100644 --- a/packages/api/src/shared-links/service.test.ts +++ b/packages/api/src/shared-links/service.test.ts @@ -184,6 +184,44 @@ describe('autoMigrateLegacyLink', () => { }).lean(); expect(ownerEntries).toHaveLength(1); }); + + /** + * The share page requests a link's config and its messages together, and both requests run the + * migration. Each finds no grant, so each used to write its own. + */ + test('grants each principal once when a legacy link is first viewed by concurrent requests', async () => { + const links = await Promise.all(Array.from({ length: 40 }, () => createLegacyLink(true))); + + /** One link at a time keeps each link's requests overlapping instead of queueing for a socket. */ + for (const link of links) { + await Promise.all( + Array.from({ length: 8 }, () => + autoMigrateLegacyLink({ + _id: link._id, + conversationId: link.conversationId, + user: userId, + shareId: link.shareId, + isPublic: true, + }), + ), + ); + } + + const entries = await AclEntry.find({ + resourceId: { $in: links.map((link) => link._id) }, + }).lean(); + const grants = new Map(); + for (const entry of entries) { + const grant = `${entry.resourceId.toString()}:${entry.principalType}`; + grants.set(grant, (grants.get(grant) ?? 0) + 1); + } + expect(grants.size).toBe(links.length * 2); + expect([...grants.values()].every((count) => count === 1)).toBe(true); + const migrated = await mongoose.connection + .db!.collection('sharedlinks') + .countDocuments({ _id: { $in: links.map((link) => link._id) }, isPublic: { $exists: true } }); + expect(migrated).toBe(0); + }); }); describe('grantCreationPermissions', () => { diff --git a/packages/api/src/shared-links/service.ts b/packages/api/src/shared-links/service.ts index a6ab3e4d8a..cc9b7c2f6f 100644 --- a/packages/api/src/shared-links/service.ts +++ b/packages/api/src/shared-links/service.ts @@ -34,6 +34,11 @@ interface RawSharedLink { expiredAt?: Date; } +/** + * The share page reads a link's config and its messages together, so the first view of a legacy + * link runs this twice at once, in one process or two: both find no grant and both write one. + * The grants are therefore made as unique entries, which the database refuses to insert twice. + */ export async function autoMigrateLegacyLink(share: RawSharedLink): Promise { const shareId = share._id; if (!shareId) { @@ -62,6 +67,7 @@ export async function autoMigrateLegacyLink(share: RawSharedLink): Promise accessRoleId: AccessRoleIds.SHARED_LINK_OWNER, grantedBy: share.user, expiredAt: share.expiredAt, + uniqueEntry: true, }); existingOwner = true; ownerGranted = true; @@ -90,6 +96,7 @@ export async function autoMigrateLegacyLink(share: RawSharedLink): Promise accessRoleId: AccessRoleIds.SHARED_LINK_VIEWER, grantedBy: share.user, expiredAt: share.expiredAt, + uniqueEntry: true, }); publicGranted = true; } catch (err) { diff --git a/packages/data-provider/specs/request-interceptor.spec.ts b/packages/data-provider/specs/request-interceptor.spec.ts index 462f096df7..65d95b26fb 100644 --- a/packages/data-provider/specs/request-interceptor.spec.ts +++ b/packages/data-provider/specs/request-interceptor.spec.ts @@ -758,6 +758,157 @@ describe('axios 401 interceptor — Authorization header guard', () => { expect(retriedHeaders.get('Authorization')).toBe('Bearer fresh-token'); }); + /** + * A burst of requests leaves with one bearer, and some of their 401s are delivered only after + * the refresh the first 401 started has settled. Those describe a bearer that is already gone. + */ + it('replays a 401 that carried a superseded bearer without a second refresh', async () => { + expect.assertions(5); + setTokenHeader('expired-token'); + const lateRejection = createDeferred(); + const sentBearers: Record = {}; + const recoveryStates: string[] = []; + const recordRecovery = (event: Event) => { + recoveryStates.push((event as CustomEvent<{ state: string }>).detail.state); + }; + window.addEventListener('authRecovery', recordRecovery); + + mockAdapter.mockImplementation((config: InternalAxiosRequestConfig) => { + const url = config.url ?? ''; + if (url.includes('/api/auth/refresh')) { + return createAdapterResponse(config, { token: 'new-token' }); + } + const authorization = String(config.headers?.Authorization); + (sentBearers[url] ??= []).push(authorization); + if (authorization !== 'Bearer expired-token') { + return createAdapterResponse(config, { ok: true }); + } + if (url === '/api/convos') { + return lateRejection.promise.then(() => create401Error(config)); + } + return create401Error(config); + }); + + try { + const lateRequest = axios.get('/api/convos'); + const recovered = await axios.get('/api/messages'); + lateRejection.resolve(); + const replayed = await lateRequest; + + expect([recovered.data, replayed.data]).toEqual([{ ok: true }, { ok: true }]); + expect(getCallsForUrl('/api/auth/refresh')).toHaveLength(1); + expect(sentBearers['/api/messages']).toEqual(['Bearer expired-token', 'Bearer new-token']); + expect(sentBearers['/api/convos']).toEqual(['Bearer expired-token', 'Bearer new-token']); + expect(recoveryStates).toEqual(['started', 'finished']); + } finally { + window.removeEventListener('authRecovery', recordRecovery); + } + }); + + it('still refreshes when the replayed request is rejected with the current bearer', async () => { + expect.assertions(3); + setTokenHeader('expired-token'); + const lateRejection = createDeferred(); + let refreshes = 0; + + mockAdapter.mockImplementation((config: InternalAxiosRequestConfig) => { + const url = config.url ?? ''; + if (url.includes('/api/auth/refresh')) { + refreshes += 1; + return createAdapterResponse(config, { token: `token-${refreshes}` }); + } + const authorization = String(config.headers?.Authorization); + if (url === '/api/convos' && authorization === 'Bearer expired-token') { + return lateRejection.promise.then(() => create401Error(config)); + } + if (authorization === 'Bearer token-2') { + return createAdapterResponse(config, { ok: true }); + } + if (url === '/api/messages' && authorization === 'Bearer token-1') { + return createAdapterResponse(config, { ok: true }); + } + return create401Error(config); + }); + + const lateRequest = axios.get('/api/convos'); + await axios.get('/api/messages'); + lateRejection.resolve(); + const replayed = await lateRequest; + + expect(replayed.data).toEqual({ ok: true }); + expect(refreshes).toBe(2); + expect(getCallsForUrl('/api/convos')).toHaveLength(3); + }); + + it('replays an authenticated fetch whose bearer was superseded without a second refresh', async () => { + expect.assertions(4); + setTokenHeader('expired-token'); + const lateRejection = createDeferred(); + + mockAdapter.mockImplementation((config: InternalAxiosRequestConfig) => { + if (config.url?.includes('/api/auth/refresh') === true) { + return createAdapterResponse(config, { token: 'new-token' }); + } + if (String(config.headers?.Authorization) === 'Bearer expired-token') { + return create401Error(config); + } + return createAdapterResponse(config, { ok: true }); + }); + const fetchSpy = jest + .spyOn(globalThis, 'fetch') + .mockReturnValueOnce(lateRejection.promise) + .mockResolvedValueOnce(new Response(null, { status: 200 })); + + const upload = dataRequest.authenticatedFetch('/api/files', { method: 'POST' }); + await axios.get('/api/messages'); + lateRejection.resolve(new Response(null, { status: 401 })); + const response = await upload; + + expect(response.status).toBe(200); + expect(getCallsForUrl('/api/auth/refresh')).toHaveLength(1); + expect(fetchSpy).toHaveBeenCalledTimes(2); + expect(new Headers(fetchSpy.mock.calls[1][1]?.headers).get('Authorization')).toBe( + 'Bearer new-token', + ); + }); + + it('still refreshes when the replayed fetch is rejected with the current bearer', async () => { + expect.assertions(4); + setTokenHeader('expired-token'); + const lateRejection = createDeferred(); + let refreshes = 0; + + mockAdapter.mockImplementation((config: InternalAxiosRequestConfig) => { + if (config.url?.includes('/api/auth/refresh') === true) { + refreshes += 1; + return createAdapterResponse(config, { token: `token-${refreshes}` }); + } + if (String(config.headers?.Authorization) === 'Bearer expired-token') { + return create401Error(config); + } + return createAdapterResponse(config, { ok: true }); + }); + const fetchSpy = jest + .spyOn(globalThis, 'fetch') + .mockReturnValueOnce(lateRejection.promise) + .mockResolvedValueOnce(new Response(null, { status: 401 })) + .mockResolvedValueOnce(new Response(null, { status: 200 })); + + const upload = dataRequest.authenticatedFetch('/api/files', { method: 'POST' }); + await axios.get('/api/messages'); + lateRejection.resolve(new Response(null, { status: 401 })); + const response = await upload; + + expect(response.status).toBe(200); + expect(refreshes).toBe(2); + expect(new Headers(fetchSpy.mock.calls[1][1]?.headers).get('Authorization')).toBe( + 'Bearer token-1', + ); + expect(new Headers(fetchSpy.mock.calls[2][1]?.headers).get('Authorization')).toBe( + 'Bearer token-2', + ); + }); + it('does not wait on the in-flight recovery when the refresh request itself fails', async () => { expect.assertions(3); setTokenHeader(createJwt(Date.now() + 60_000)); diff --git a/packages/data-provider/src/request.ts b/packages/data-provider/src/request.ts index c8edc6a1b0..6a7d40b5a8 100644 --- a/packages/data-provider/src/request.ts +++ b/packages/data-provider/src/request.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import axios from 'axios'; +import axios, { AxiosHeaders } from 'axios'; import type { AxiosRequestConfig, AxiosResponse } from 'axios'; import type * as t from './types'; import { TWO_FACTOR_ENROLLMENT_REQUIRED_CODE } from './config'; @@ -334,14 +334,33 @@ const redirectToLoginOnce = () => { window.location.href = href; }; -const getBearerToken = () => { - const authorization = axios.defaults.headers.common['Authorization']; +const parseBearerToken = (authorization: unknown) => { if (typeof authorization !== 'string' || !authorization.startsWith('Bearer ')) { return null; } return authorization.slice('Bearer '.length); }; +const getBearerToken = () => parseBearerToken(axios.defaults.headers.common['Authorization']); + +const getRequestBearerToken = ({ headers }: AxiosRequestConfig) => + parseBearerToken( + headers instanceof AxiosHeaders ? headers.get('Authorization') : headers?.['Authorization'], + ); + +/** + * A request dispatched before a refresh settled can be answered after it. That 401 describes the + * bearer the request carried, not the one now in use, so the request is replayed with the current + * bearer instead of starting a second refresh for a session that has already recovered. + */ +const getSupersedingToken = (sentToken: string | null) => { + if (!sentToken || getAuthRecoveryState().refreshPromise) { + return null; + } + const currentToken = getBearerToken(); + return currentToken && currentToken !== sentToken ? currentToken : null; +}; + const getJwtExpiryMs = (token: string) => { const payload = token.split('.')[1]; if (!payload) { @@ -430,23 +449,30 @@ const redirectIfTwoFactorSetupRequired = async (response: Response): Promise + response.status === 401 && + !isAuthRecoveryEndpoint(url) && + !isAuthRedirectInProgress() && + getBearerToken() != null; + async function _authenticatedFetch(url: string, options?: RequestInit): Promise { if (typeof window === 'undefined') { return fetch(url, options); } const token = (await refreshBeforeRequest(url)) ?? getBearerToken(); - const response = await fetch(url, withAuthorization(options, token)); - if (await redirectIfTwoFactorSetupRequired(response)) { + let response = await fetch(url, withAuthorization(options, token)); + if ((await redirectIfTwoFactorSetupRequired(response)) || !needsAuthRecovery(response, url)) { return response; } - if ( - response.status !== 401 || - isAuthRecoveryEndpoint(url) || - isAuthRedirectInProgress() || - !getBearerToken() - ) { - return response; + + const supersedingToken = getSupersedingToken(token); + if (supersedingToken) { + await response.body?.cancel().catch(() => undefined); + response = await fetch(url, withAuthorization(options, supersedingToken)); + if ((await redirectIfTwoFactorSetupRequired(response)) || !needsAuthRecovery(response, url)) { + return response; + } } let refreshedToken: string | null; @@ -529,6 +555,14 @@ if (typeof window !== 'undefined') { } if (error.response.status === 401 && !originalRequest._retry) { + const supersedingToken = isRefreshRequest + ? null + : getSupersedingToken(getRequestBearerToken(originalRequest)); + if (supersedingToken) { + setRequestAuthorizationHeader(originalRequest, supersedingToken); + return axios(originalRequest); + } + const hasActiveRecovery = getAuthRecoveryState().refreshPromise != null; if (!hasActiveRecovery) { console.warn('401 error, refreshing token'); diff --git a/packages/data-schemas/src/methods/aclEntry.spec.ts b/packages/data-schemas/src/methods/aclEntry.spec.ts index 33b797391d..c8a9fd400e 100644 --- a/packages/data-schemas/src/methods/aclEntry.spec.ts +++ b/packages/data-schemas/src/methods/aclEntry.spec.ts @@ -520,6 +520,97 @@ describe('AclEntry Model Tests', () => { }); }); + describe('Grants made as a unique entry', () => { + const grantPublic = (uniqueEntry?: boolean) => + methods.grantPermission( + PrincipalType.PUBLIC, + null, + ResourceType.SHARED_LINK, + resourceId, + PermissionBits.VIEW, + grantedById, + undefined, + undefined, + undefined, + uniqueEntry, + ); + const grantUser = (principalId: mongoose.Types.ObjectId | string) => + methods.grantPermission( + PrincipalType.USER, + principalId, + ResourceType.SHARED_LINK, + resourceId, + PermissionBits.VIEW, + grantedById, + undefined, + undefined, + undefined, + true, + ); + const publicEntries = () => + AclEntry.find({ principalType: PrincipalType.PUBLIC, resourceId }).lean(); + const duplicateKey = () => { + throw Object.assign(new Error('E11000 duplicate key error'), { code: 11000 }); + }; + + test('names the entry after the principal and the resource', async () => { + const first = await grantPublic(true); + await AclEntry.deleteMany({}); + const again = await grantPublic(true); + const owner = await grantUser(userId); + await AclEntry.deleteOne({ _id: owner?._id }); + const ownerByString = await grantUser(userId.toString()); + const otherUser = await grantUser(new mongoose.Types.ObjectId()); + + expect(again?._id.toString()).toBe(first?._id.toString()); + expect(ownerByString?._id.toString()).toBe(owner?._id.toString()); + expect(new Set([first, owner, otherUser].map((entry) => entry?._id.toString())).size).toBe(3); + }); + + test('updates an entry that already exists under another id', async () => { + const existing = await grantPublic(); + + const entry = await grantPublic(true); + + expect(entry?._id.toString()).toBe(existing?._id.toString()); + expect(await publicEntries()).toHaveLength(1); + }); + + /** + * Without the option every one of these finds no entry and inserts its own, because the + * upsert matches on fields no unique index covers. + */ + test('leaves one entry when the same grant runs concurrently', async () => { + const entries = await Promise.all(Array.from({ length: 16 }, () => grantPublic(true))); + + expect(new Set(entries.map((entry) => entry?._id.toString())).size).toBe(1); + expect(await publicEntries()).toHaveLength(1); + }); + + test('replays the grant as an update when another writer inserted the entry first', async () => { + const existing = await grantPublic(true); + const findOneAndUpdate = jest.spyOn(AclEntry, 'findOneAndUpdate'); + findOneAndUpdate.mockImplementationOnce(duplicateKey); + + const entry = await grantPublic(true); + + expect(findOneAndUpdate).toHaveBeenCalledTimes(2); + expect(entry?._id.toString()).toBe(existing?._id.toString()); + expect(await publicEntries()).toHaveLength(1); + findOneAndUpdate.mockRestore(); + }); + + test('does not replay a duplicate key for an ordinary grant', async () => { + const findOneAndUpdate = jest.spyOn(AclEntry, 'findOneAndUpdate'); + findOneAndUpdate.mockImplementationOnce(duplicateKey); + + await expect(grantPublic()).rejects.toMatchObject({ code: 11000 }); + + expect(findOneAndUpdate).toHaveBeenCalledTimes(1); + findOneAndUpdate.mockRestore(); + }); + }); + describe('Resource Access Queries', () => { test('should find accessible resources', async () => { /** Create multiple resources with different permissions */ diff --git a/packages/data-schemas/src/methods/aclEntry.tenant.spec.ts b/packages/data-schemas/src/methods/aclEntry.tenant.spec.ts index a216ce9e63..467a7d5c0e 100644 --- a/packages/data-schemas/src/methods/aclEntry.tenant.spec.ts +++ b/packages/data-schemas/src/methods/aclEntry.tenant.spec.ts @@ -2,9 +2,9 @@ import mongoose from 'mongoose'; import { MongoMemoryServer } from 'mongodb-memory-server'; import { PrincipalType, PrincipalModel, PermissionBits } from 'librechat-data-provider'; import type { IAclEntry } from '..'; +import { tenantStorage } from '../config/tenantContext'; import { createAclEntryMethods } from './aclEntry'; import { createModels } from '../models'; -import { tenantStorage } from '../config/tenantContext'; jest.mock('~/config/winston', () => ({ error: jest.fn(), @@ -112,3 +112,28 @@ describe('AclEntry resource lookups are scoped to the active tenant', () => { expect(bPublic.map(String)).toEqual([String(publicB)]); }); }); + +describe('AclEntry grants made as a unique entry', () => { + it('create one entry in the active tenant when the same grant runs concurrently', async () => { + const resourceId = new mongoose.Types.ObjectId(); + const grant = () => + methods.grantPermission( + PrincipalType.PUBLIC, + null, + RESOURCE_TYPE, + resourceId, + PermissionBits.VIEW, + undefined, + undefined, + undefined, + undefined, + true, + ); + + await runAs(TENANT_A, () => Promise.all(Array.from({ length: 8 }, grant))); + + const entries = await runAs(TENANT_A, () => AclEntry.find({ resourceId }).lean()); + expect(entries).toHaveLength(1); + expect(entries[0].tenantId).toBe(TENANT_A); + }); +}); diff --git a/packages/data-schemas/src/methods/aclEntry.ts b/packages/data-schemas/src/methods/aclEntry.ts index 221091944b..9449978571 100644 --- a/packages/data-schemas/src/methods/aclEntry.ts +++ b/packages/data-schemas/src/methods/aclEntry.ts @@ -1,4 +1,5 @@ import { Types } from 'mongoose'; +import { createHash } from 'node:crypto'; import { ResourceType, PrincipalType, @@ -30,6 +31,21 @@ const EMPTY_SUPERSETS: readonly number[] = Object.freeze([]); const supersetCache = new Map(); +function isDuplicateKeyError(error: unknown): boolean { + return typeof error === 'object' && error != null && (error as { code?: unknown }).code === 11000; +} + +/** Names an entry after the grant it records, so two inserts of the same grant collide on `_id`. */ +function grantEntryId( + principalType: string, + principalId: string | Types.ObjectId | null | undefined, + resourceType: string, + resourceId: string | Types.ObjectId, +): Types.ObjectId { + const grant = [resourceType, resourceId, principalType, principalId ?? ''].join(':'); + return new Types.ObjectId(createHash('sha256').update(grant).digest().subarray(0, 12)); +} + /** * Enumerates every `permBits` value (in the range `[0, MAX_PERM_BITS]`) whose * set bits include all bits in `requiredBits`. Used with a `$in` filter to push @@ -172,6 +188,7 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): { session?: ClientSession, roleId?: string | Types.ObjectId, expiredAt?: Date, + uniqueEntry?: boolean, ) => Promise; modifyPermissionBits: ( principalType: string, @@ -402,6 +419,10 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): { * @param grantedBy - The ID of the user granting the permission * @param session - Optional MongoDB session for transactions * @param roleId - Optional role ID to associate with this permission + * @param uniqueEntry - Derive the `_id` of a newly created entry from the principal and the + * resource. The upsert matches on those fields, which no unique index covers, so two grants + * that both find nothing each insert a row. Callers that can race set this: the second insert + * then collides on `_id` and is replayed as an update of the first. * @returns The created or updated ACL entry */ async function grantPermission( @@ -414,6 +435,7 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): { session?: ClientSession, roleId?: string | Types.ObjectId, expiredAt?: Date, + uniqueEntry?: boolean, ): Promise { const AclEntry = mongoose.models.AclEntry as Model; const query: Record = { @@ -444,6 +466,16 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): { ...(roleId && { roleId }), ...(expiredAt && { expiredAt }), }, + ...(uniqueEntry && { + $setOnInsert: { + _id: grantEntryId( + principalType, + query.principalId as string | Types.ObjectId | undefined, + resourceType, + resourceId, + ), + }, + }), }; const options = { @@ -452,7 +484,15 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): { ...(session ? { session } : {}), }; - return await AclEntry.findOneAndUpdate(query, update, options); + try { + return await AclEntry.findOneAndUpdate(query, update, options); + } catch (error) { + /** A duplicate key aborts a transaction, so only a standalone write can be replayed. */ + if (!uniqueEntry || session?.inTransaction() || !isDuplicateKeyError(error)) { + throw error; + } + return await AclEntry.findOneAndUpdate(query, update, options); + } } /**