🪢 fix: Resolve the Races Behind Four Intermittent Session and Scenario E2E Tests (#18061)

* 🔑 fix: Replay a Request Rejected for a Superseded Bearer Instead of Refreshing Again

A burst of requests leaves with one bearer. The first 401 starts a refresh and the
rest share it only while it is in flight: a 401 delivered after the refresh settled
found no recovery running and started a second one, although the session had already
recovered and the response described a bearer that was no longer in use.

Compare the bearer the rejected request carried with the current one. When it has
been replaced and no recovery is running, replay the request with the current
bearer. A replay that is rejected again carries the current bearer, so it takes the
ordinary refresh path. The fetch transport follows the same rule.

This is what failed "recovers from an expired bearer during app bootstrap without
redirect looping": 9 of the 21 bootstrap 401s were delivered after the first
recovery finished, so the test counted a third refresh and a second recovery cycle.

* 🔊 test: Play Decodable Audio and Hold the Reply's Button in the Read-Aloud Replay Scenario

The fixture answered the speech request with four bytes the MP3 parser rejects, so
every playback failed. A failed playback cancels its request, and the audio is
cached only once the response has been read to the end, so the replay was served
from memory only when the response finished before the decoder gave up. When the
decoder won, the replay issued the second request the scenario forbids.

The test also located the button by its name. While a message is read aloud its
button is named "Stop", so the locator resolved to the user message's read-aloud
button: the wait for playback to end passed at once, and the second click could
land on a different message.

Serve a third of a second of silent MPEG frames so playback succeeds and ends on
its own, and locate the reply's button by its test id so the wait and the replay
address the same control.

* 📅 test: Wait for the Schedule Save to Land Before Reloading

The edit scenario clicked Save and reloaded the page in the next step. A reload
discards requests still in flight, so when it won the race the PATCH was cancelled
before the server answered and the edited schedule never appeared. Await the PATCH
response, and require it to succeed, before reloading.

* 🔗 fix: Grant a Legacy Shared Link's Permissions Once When Its First Views Race

The share page requests a link's config and its messages together, and each request
migrates a legacy link on the way in. Both find no grant and both write one. The
grant is an upsert matched on the principal and resource, which no unique index
covers, so the two writes inserted two rows: a second public entry, a second owner
entry, or both.

`grantPermission` now accepts the `_id` to give the entry if the grant creates it.
The migration derives that id from the link and the principal, so the second insert
collides on `_id` and is replayed as an update of the first entry. It holds across
processes because the database enforces it. Grants that pass no id are unchanged.

"manages a shared-link snapshot and preserves legacy public links through runtime
migration" asserts one public entry and saw two.

* 🔑 fix: Refresh When a Replayed Fetch Is Rejected With the Current Bearer

The fetch transport replayed a request whose bearer had been superseded and
returned whatever came back. A second 401 there means the current bearer is not
accepted either, which is the case the refresh exists for, and the axios path
already handles it that way. Replay first, then fall through to the ordinary
recovery when the replay is rejected too.

* 🔗 refactor: Derive a Unique Grant's Entry Id in the Data Layer

`AccessControlService.grantPermission` took the entry's `_id` as a Mongoose
`ObjectId`, which put a storage type in an exported `packages/api` signature. The
service now takes `uniqueEntry: true`, and `grantPermission` in data-schemas
derives the id from the principal and resource it already matches on. A caller can
no longer pass an id that names a different grant.
This commit is contained in:
Danny Avila 2026-11-11 16:22:39 -05:00 • committed by GitHub
parent fb3d77d52a
commit 5ca49b5f4e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 423 additions and 19 deletions

View file

@ -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());

View file

@ -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);

View file

@ -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<IAclEntry | null> {
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(

View file

@ -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<string, number>();
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', () => {

View file

@ -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<void> {
const shareId = share._id;
if (!shareId) {
@ -62,6 +67,7 @@ export async function autoMigrateLegacyLink(share: RawSharedLink): Promise<void>
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<void>
accessRoleId: AccessRoleIds.SHARED_LINK_VIEWER,
grantedBy: share.user,
expiredAt: share.expiredAt,
uniqueEntry: true,
});
publicGranted = true;
} catch (err) {

View file

@ -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<void>();
const sentBearers: Record<string, string[]> = {};
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<void>();
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<Response>();
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<Response>();
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));

View file

@ -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<boo
);
};
const needsAuthRecovery = (response: Response, url: string) =>
response.status === 401 &&
!isAuthRecoveryEndpoint(url) &&
!isAuthRedirectInProgress() &&
getBearerToken() != null;
async function _authenticatedFetch(url: string, options?: RequestInit): Promise<Response> {
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');

View file

@ -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 */

View file

@ -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);
});
});

View file

@ -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<number, readonly number[]>();
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<IAclEntry | null>;
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<IAclEntry | null> {
const AclEntry = mongoose.models.AclEntry as Model<IAclEntry>;
const query: Record<string, unknown> = {
@ -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);
}
}
/**