Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🪐 fix: Replace `$bitsAllSet` ACL Queries for Azure Cosmos DB Compatibility (#12736)

Danny Avila3bd268127280
diff --git a/packages/api/src/acl/accessControlService.ts b/packages/api/src/acl/accessControlService.ts
index 98bc939c24..57d072561a 100644
--- a/packages/api/src/acl/accessControlService.ts
+++ b/packages/api/src/acl/accessControlService.ts
@@ -174,16 +174,7 @@ export class AccessControlService {
this.validateResourceType(resourceType);
- // Find all public ACL entries where the public principal has at least the required permission bits
- const entries = await this._aclModel
- .find({
- principalType: PrincipalType.PUBLIC,
- resourceType,
- permBits: { $bitsAllSet: requiredPermissions },
- })
- .distinct('resourceId');
-
- return entries;
+ return await this._dbMethods.findPublicResourceIds(resourceType, requiredPermissions);
} catch (error) {
if (error instanceof Error) {
logger.error(`[PermissionService.findPubliclyAccessibleResources] Error: ${error.message}`);
diff --git a/packages/api/src/apiKeys/permissions.spec.ts b/packages/api/src/apiKeys/permissions.spec.ts
new file mode 100644
index 0000000000..69441fa800
--- /dev/null
+++ b/packages/api/src/apiKeys/permissions.spec.ts
@@ -0,0 +1,181 @@
+import { Types } from 'mongoose';
+import {
+ ResourceType,
+ PrincipalType,
+ PermissionBits,
+ AccessRoleIds,
+} from 'librechat-data-provider';
+import { permissionBitSupersets } from '@librechat/data-schemas';
+import { enrichRemoteAgentPrincipals } from './permissions';
+import type { EnricherDependencies, Principal } from './permissions';
+
+/**
+ * Tests for `enrichRemoteAgentPrincipals`.
+ *
+ * The function is purely dependency-injected; we stub `aggregateAclEntries`.
+ * Two concerns are covered:
+ * (a) Pipeline shape — the `$match` must filter permBits via
+ * `$in: permissionBitSupersets(SHARE)` (not `$bitsAllSet`) so Cosmos DB
+ * for MongoDB can evaluate it.
+ * (b) Enrichment behavior on pre-filtered rows — given the rows the DB
+ * returns, non-null userInfo is mapped into a REMOTE_AGENT_OWNER
+ * principal and duplicates against the caller-supplied list are skipped.
+ */
+describe('enrichRemoteAgentPrincipals', () => {
+ const resourceId = new Types.ObjectId();
+ const ownerUserId = new Types.ObjectId();
+
+ function makeUserInfo(id: Types.ObjectId, overrides: Record<string, unknown> = {}) {
+ return {
+ _id: id,
+ name: `user-${id.toString().slice(-4)}`,
+ email: `${id.toString().slice(-4)}@test.local`,
+ avatar: 'avatar.png',
+ idOnTheSource: id.toString(),
+ ...overrides,
+ };
+ }
+
+ function makeDeps(aggregateResult: Record<string, unknown>[]): EnricherDependencies {
+ return {
+ aggregateAclEntries: jest.fn().mockResolvedValue(aggregateResult),
+ bulkWriteAclEntries: jest.fn(),
+ findRoleByIdentifier: jest.fn(),
+ logger: { error: jest.fn() },
+ };
+ }
+
+ describe('pipeline shape (Cosmos DB compatibility)', () => {
+ test('$match filters permBits via $in of SHARE supersets, not $bitsAllSet', async () => {
+ const aggregateAclEntries = jest.fn().mockResolvedValue([]);
+ const deps: EnricherDependencies = {
+ aggregateAclEntries,
+ bulkWriteAclEntries: jest.fn(),
+ findRoleByIdentifier: jest.fn(),
+ logger: { error: jest.fn() },
+ };
+
+ await enrichRemoteAgentPrincipals(deps, resourceId, []);
+
+ const pipeline = aggregateAclEntries.mock.calls[0][0];
+ const matchStage = pipeline[0].$match;
+ expect(matchStage.resourceType).toBe(ResourceType.AGENT);
+ expect(matchStage.principalType).toBe(PrincipalType.USER);
+ expect(matchStage.resourceId).toBeInstanceOf(Types.ObjectId);
+ expect((matchStage.resourceId as Types.ObjectId).toString()).toBe(resourceId.toString());
+
+ /** Regression guard: no `$bitsAllSet` — Cosmos DB does not implement it. */
+ expect(matchStage.permBits).not.toHaveProperty('$bitsAllSet');
+
+ /** The filter must be the `$in` expansion of SHARE supersets. */
+ expect(matchStage.permBits).toEqual({
+ $in: permissionBitSupersets(PermissionBits.SHARE),
+ });
+ });
+
+ test('$in list contains exactly the permBits values whose bits include SHARE', async () => {
+ const values = permissionBitSupersets(PermissionBits.SHARE);
+ for (const v of values) {
+ expect((v & PermissionBits.SHARE) === PermissionBits.SHARE).toBe(true);
+ }
+ for (let v = 0; v <= 15; v++) {
+ const expectedIncluded = (v & PermissionBits.SHARE) === PermissionBits.SHARE;
+ expect(values.includes(v)).toBe(expectedIncluded);
+ }
+ });
+
+ test('accepts resourceId as a 24-char hex string and passes an ObjectId to the aggregation', async () => {
+ const hexId = new Types.ObjectId().toString();
+ const aggregateAclEntries = jest.fn().mockResolvedValue([]);
+ const deps: EnricherDependencies = {
+ aggregateAclEntries,
+ bulkWriteAclEntries: jest.fn(),
+ findRoleByIdentifier: jest.fn(),
+ logger: { error: jest.fn() },
+ };
+
+ await enrichRemoteAgentPrincipals(deps, hexId, []);
+
+ const matchStage = aggregateAclEntries.mock.calls[0][0][0].$match;
+ expect(matchStage.resourceId).toBeInstanceOf(Types.ObjectId);
+ expect((matchStage.resourceId as Types.ObjectId).toString()).toBe(hexId);
+ });
+ });
+
+ describe('enrichment behavior', () => {
+ test('enriches a principal for each pre-filtered row with valid userInfo', async () => {
+ const deps = makeDeps([
+ {
+ principalId: ownerUserId,
+ userInfo: makeUserInfo(ownerUserId),
+ },
+ ]);
+
+ const result = await enrichRemoteAgentPrincipals(deps, resourceId, []);
+
+ expect(result.principals).toHaveLength(1);
+ expect(result.principals[0].id).toBe(ownerUserId.toString());
+ expect(result.principals[0].accessRoleId).toBe(AccessRoleIds.REMOTE_AGENT_OWNER);
+ expect(result.principals[0].isImplicit).toBe(true);
+ expect(result.principals[0].source).toBe('local');
+ expect(result.entriesToBackfill).toHaveLength(1);
+ expect(result.entriesToBackfill[0].toString()).toBe(ownerUserId.toString());
+ });
+
+ test('skips rows whose userInfo lookup came back null', async () => {
+ const deps = makeDeps([
+ {
+ principalId: ownerUserId,
+ userInfo: null,
+ },
+ ]);
+
+ const result = await enrichRemoteAgentPrincipals(deps, resourceId, []);
+
+ expect(result.principals).toHaveLength(0);
+ expect(result.entriesToBackfill).toHaveLength(0);
+ });
+
+ test('does not duplicate a principal already present in the input list', async () => {
+ const existing: Principal = {
+ type: PrincipalType.USER,
+ id: ownerUserId.toString(),
+ name: 'already-there',
+ accessRoleId: AccessRoleIds.REMOTE_AGENT_OWNER,
+ };
+ const deps = makeDeps([
+ {
+ principalId: ownerUserId,
+ userInfo: makeUserInfo(ownerUserId),
+ },
+ ]);
+
+ const result = await enrichRemoteAgentPrincipals(deps, resourceId, [existing]);
+
+ expect(result.principals).toHaveLength(1);
+ expect(result.principals[0].name).toBe('already-there');
+ expect(result.entriesToBackfill).toHaveLength(0);
+ });
+
+ test('prepends newly discovered owners to the supplied principals list', async () => {
+ const stranger: Principal = {
+ type: PrincipalType.USER,
+ id: new Types.ObjectId().toString(),
+ name: 'stranger',
+ accessRoleId: 'other_role',
+ };
+ const deps = makeDeps([
+ {
+ principalId: ownerUserId,
+ userInfo: makeUserInfo(ownerUserId),
+ },
+ ]);
+
+ const result = await enrichRemoteAgentPrincipals(deps, resourceId, [stranger]);
+
+ expect(result.principals).toHaveLength(2);
+ expect(result.principals[0].id).toBe(ownerUserId.toString());
+ expect(result.principals[1].id).toBe(stranger.id);
+ });
+ });
+});
diff --git a/packages/api/src/apiKeys/permissions.ts b/packages/api/src/apiKeys/permissions.ts
index b617b0a892..4055f88920 100644
--- a/packages/api/src/apiKeys/permissions.ts
+++ b/packages/api/src/apiKeys/permissions.ts
@@ -5,6 +5,7 @@ import {
PermissionBits,
AccessRoleIds,
} from 'librechat-data-provider';
+import { permissionBitSupersets } from '@librechat/data-schemas';
import type { PipelineStage, AnyBulkWriteOperation } from 'mongoose';
export interface Principal {
@@ -47,13 +48,18 @@ export async function enrichRemoteAgentPrincipals(
? Types.ObjectId.createFromHexString(resourceId)
: resourceId;
+ /**
+ * Filter `permBits` with `$in: permissionBitSupersets(SHARE)` instead of
+ * `$bitsAllSet` for Cosmos DB for MongoDB compatibility. `$in` is indexable
+ * and, for the current 4-bit permission set, expands to at most 8 values.
+ */
const agentOwnerEntries = await deps.aggregateAclEntries([
{
$match: {
resourceType: ResourceType.AGENT,
resourceId: resourceObjectId,
principalType: PrincipalType.USER,
- permBits: { $bitsAllSet: PermissionBits.SHARE },
+ permBits: { $in: permissionBitSupersets(PermissionBits.SHARE) },
},
},
{
diff --git a/packages/data-schemas/misc/ferretdb/aclBitops.ferretdb.spec.ts b/packages/data-schemas/misc/ferretdb/aclBitops.ferretdb.spec.ts
index d8fb4ec84b..5759396ae0 100644
--- a/packages/data-schemas/misc/ferretdb/aclBitops.ferretdb.spec.ts
+++ b/packages/data-schemas/misc/ferretdb/aclBitops.ferretdb.spec.ts
@@ -5,10 +5,13 @@ import { createAclEntryMethods } from '~/methods/aclEntry';
import aclEntrySchema from '~/schema/aclEntry';
/**
- * Integration tests for $bit and $bitsAllSet on FerretDB.
+ * Integration tests for ACL bitwise operations on FerretDB.
*
- * Validates that modifyPermissionBits (using atomic $bit)
- * and $bitsAllSet queries work identically on both MongoDB and FerretDB.
+ * Validates that `modifyPermissionBits` (using the atomic `$bit` operator) and
+ * the application-layer bitwise filtering used by `hasPermission` /
+ * `findAccessibleResources` behave identically on both MongoDB and FerretDB.
+ * The query methods no longer use `$bitsAllSet` — see #12729 for the Cosmos DB
+ * compatibility fix that moved the bit mask into application code.
*
* Run against FerretDB:
* FERRETDB_URI="mongodb://ferretdb:[email protected]:27020/aclbit_test" npx jest aclBitops.ferretdb
@@ -282,7 +285,7 @@ describeIfFerretDB('ACL bitwise operations - FerretDB compatibility', () => {
});
});
- describe('$bitsAllSet queries (hasPermission + findAccessibleResources)', () => {
+ describe('Bitwise permission queries (hasPermission + findAccessibleResources)', () => {
it('should find entries with specific bits set via hasPermission', async () => {
const resourceId = new mongoose.Types.ObjectId();
diff --git a/packages/data-schemas/src/common/index.ts b/packages/data-schemas/src/common/index.ts
index e990985eb2..89505ebd72 100644
--- a/packages/data-schemas/src/common/index.ts
+++ b/packages/data-schemas/src/common/index.ts
@@ -1,2 +1,3 @@
export * from './enum';
export * from './pagination';
+export * from './permissions';
diff --git a/packages/data-schemas/src/common/permissions.ts b/packages/data-schemas/src/common/permissions.ts
new file mode 100644
index 0000000000..e66221b04a
--- /dev/null
+++ b/packages/data-schemas/src/common/permissions.ts
@@ -0,0 +1,53 @@
+import { PermissionBits } from 'librechat-data-provider';
+
+/**
+ * Upper bound for any stored `permBits` value. Computed as the bitwise OR of
+ * every numeric member of `PermissionBits`. Used by:
+ *
+ * - the `permBits` schema validator (rejects writes above this bound)
+ * - `permissionBitSupersets` (enumerates `$in` candidates within this range)
+ * - every ACL read path (via `permissionBitSupersets`)
+ *
+ * The shared definition keeps the read-side enumeration and the write-side
+ * bound locked together: adding a new member to `PermissionBits` auto-expands
+ * both at once. See issue #12729 for the Cosmos DB / `$bitsAllSet` fix.
+ */
+export const MAX_PERM_BITS: number = Object.values(PermissionBits)
+ .filter((v): v is number => typeof v === 'number')
+ .reduce((acc, v) => acc | v, 0);
+
+/**
+ * Fails loudly at module load if `PermissionBits` is ever refactored to a
+ * `const` object, string enum, or all-string shape — any of those would make
+ * `Object.values(...).filter(isNumber)` return `[]`, producing
+ * `MAX_PERM_BITS === 0`. That would silently make the schema reject every
+ * non-zero write AND make `permissionBitSupersets` return `[0]` for every
+ * input, denying every permission check. Crashing at startup is strictly
+ * better than either silent failure mode.
+ */
+if (MAX_PERM_BITS === 0) {
+ throw new Error(
+ 'MAX_PERM_BITS is 0 — `PermissionBits` did not yield any numeric members. ' +
+ 'This typically means the enum was refactored to a `const` object, a ' +
+ 'string enum, or an all-string shape; rewrite the reducer above to ' +
+ 'extract the numeric bits from the new shape, or give ' +
+ '`permissionBitSupersets` an explicit bit-width parameter.',
+ );
+}
+
+/**
+ * `permissionBitSupersets` enumerates `[0, MAX_PERM_BITS]` — size `2^n` where
+ * `n` is the number of permission bits. At 4 bits that's 16 values; at 8 bits
+ * 256; at 16 bits 65,536. Above a few hundred the resulting `$in` list would
+ * degrade query plans and balloon document transfer, so fail loudly if the
+ * enum grows past a safe ceiling. Lifting this limit requires a different
+ * bit-matching strategy (e.g. `$expr` with `$bitAnd` where supported).
+ */
+if (MAX_PERM_BITS > 255) {
+ throw new Error(
+ `MAX_PERM_BITS=${MAX_PERM_BITS} exceeds the $in-enumeration ceiling of 255. ` +
+ 'The current permissionBitSupersets approach would emit more than 256 ' +
+ 'candidates, degrading query plans. Replace the enumeration strategy ' +
+ 'before raising this limit.',
+ );
+}
diff --git a/packages/data-schemas/src/index.ts b/packages/data-schemas/src/index.ts
index 1139f83f17..4156559658 100644
--- a/packages/data-schemas/src/index.ts
+++ b/packages/data-schemas/src/index.ts
@@ -14,6 +14,7 @@ export {
cacheTokenValues,
premiumTokenValues,
defaultRate,
+ permissionBitSupersets,
} from './methods';
export type * from './types';
export type * from './methods';
diff --git a/packages/data-schemas/src/methods/aclEntry.parity.spec.ts b/packages/data-schemas/src/methods/aclEntry.parity.spec.ts
new file mode 100644
index 0000000000..2c2e4b7f46
--- /dev/null
+++ b/packages/data-schemas/src/methods/aclEntry.parity.spec.ts
@@ -0,0 +1,406 @@
+import mongoose from 'mongoose';
+import { performance } from 'node:perf_hooks';
+import {
+ ResourceType,
+ PrincipalType,
+ PrincipalModel,
+ PermissionBits,
+} from 'librechat-data-provider';
+import { MongoMemoryServer } from 'mongodb-memory-server';
+import type * as t from '~/types';
+import { createAclEntryMethods } from './aclEntry';
+import aclEntrySchema from '~/schema/aclEntry';
+
+/**
+ * Parity spec — verifies the `$in`-based queries added in #12729 are behaviorally
+ * equivalent to the legacy `$bitsAllSet` queries on MongoDB, and measures whether
+ * the new path is competitive on wall-clock time.
+ *
+ * Uses `mongodb-memory-server`, which supports both `$bitsAllSet` (legacy) and
+ * `$in` (new). Cosmos DB for MongoDB supports only the latter — this spec proves
+ * the rewrite produces identical results on the backend we can actually run in
+ * CI, then leaves the Cosmos-only behavior to manual smoke testing against a
+ * real Cosmos instance.
+ */
+
+let mongoServer: MongoMemoryServer;
+let AclEntry: mongoose.Model<t.IAclEntry>;
+let methods: ReturnType<typeof createAclEntryMethods>;
+
+/** Enough entries to exercise real query planning without bloating CI runtime. */
+const FIXTURE_SIZE = 800;
+/** Enough iterations for a reasonably stable median; still finishes in <2s total. */
+const PERF_ITERATIONS = 20;
+
+beforeAll(async () => {
+ mongoServer = await MongoMemoryServer.create();
+ const mongoUri = mongoServer.getUri();
+ AclEntry = mongoose.models.AclEntry || mongoose.model('AclEntry', aclEntrySchema);
+ methods = createAclEntryMethods(mongoose);
+ await mongoose.connect(mongoUri);
+});
+
+afterAll(async () => {
+ await mongoose.disconnect();
+ await mongoServer.stop();
+});
+
+beforeEach(async () => {
+ await mongoose.connection.dropDatabase();
+});
+
+function idsToSortedStrings(ids: mongoose.Types.ObjectId[]): string[] {
+ return ids.map((id) => id.toString()).sort();
+}
+
+function buildPrincipalsQuery(
+ principals: Array<{ principalType: string; principalId?: mongoose.Types.ObjectId }>,
+) {
+ return principals.map((p) => ({
+ principalType: p.principalType,
+ ...(p.principalType !== PrincipalType.PUBLIC && { principalId: p.principalId }),
+ }));
+}
+
+async function seedVariedPermissions(
+ userId: mongoose.Types.ObjectId,
+ grantedBy: mongoose.Types.ObjectId,
+ count: number,
+): Promise<void> {
+ /** Every permBits value from 0..15 appears roughly `count/16` times, giving
+ * a uniform distribution for parity + perf assertions. */
+ const docs: Partial<t.IAclEntry>[] = [];
+ for (let i = 0; i < count; i++) {
+ docs.push({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ principalModel: PrincipalModel.USER,
+ resourceType: ResourceType.AGENT,
+ resourceId: new mongoose.Types.ObjectId(),
+ permBits: i % 16,
+ grantedBy,
+ });
+ }
+ await AclEntry.insertMany(docs);
+}
+
+async function median<T>(fn: () => Promise<T>, iterations: number): Promise<number> {
+ const samples: number[] = [];
+ for (let i = 0; i < iterations; i++) {
+ const t0 = performance.now();
+ await fn();
+ samples.push(performance.now() - t0);
+ }
+ samples.sort((a, b) => a - b);
+ return samples[Math.floor(samples.length / 2)];
+}
+
+describe('ACL $bitsAllSet vs $in parity (issue #12729)', () => {
+ const userId = new mongoose.Types.ObjectId();
+ const grantedById = new mongoose.Types.ObjectId();
+ const principalsList = [{ principalType: PrincipalType.USER, principalId: userId }];
+
+ describe('correctness', () => {
+ test.each([
+ PermissionBits.VIEW,
+ PermissionBits.EDIT,
+ PermissionBits.DELETE,
+ PermissionBits.SHARE,
+ PermissionBits.VIEW | PermissionBits.EDIT,
+ PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE,
+ PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE,
+ ])(
+ 'findAccessibleResources returns the same set as `$bitsAllSet` for bits=%i',
+ async (bits) => {
+ await seedVariedPermissions(userId, grantedById, FIXTURE_SIZE);
+
+ const legacy = await AclEntry.find({
+ $or: buildPrincipalsQuery(principalsList),
+ resourceType: ResourceType.AGENT,
+ permBits: { $bitsAllSet: bits },
+ }).distinct('resourceId');
+
+ const current = await methods.findAccessibleResources(
+ principalsList,
+ ResourceType.AGENT,
+ bits,
+ );
+
+ expect(idsToSortedStrings(current)).toEqual(idsToSortedStrings(legacy));
+ },
+ );
+
+ test.each([
+ PermissionBits.VIEW,
+ PermissionBits.EDIT | PermissionBits.DELETE,
+ PermissionBits.SHARE,
+ ])('findPublicResourceIds returns the same set as `$bitsAllSet` for bits=%i', async (bits) => {
+ /** Public entries have no principalId — seed those separately. */
+ const docs: Partial<t.IAclEntry>[] = [];
+ for (let i = 0; i < FIXTURE_SIZE; i++) {
+ docs.push({
+ principalType: PrincipalType.PUBLIC,
+ resourceType: ResourceType.AGENT,
+ resourceId: new mongoose.Types.ObjectId(),
+ permBits: i % 16,
+ grantedBy: grantedById,
+ });
+ }
+ await AclEntry.insertMany(docs);
+
+ const legacy = await AclEntry.find({
+ principalType: PrincipalType.PUBLIC,
+ resourceType: ResourceType.AGENT,
+ permBits: { $bitsAllSet: bits },
+ }).distinct('resourceId');
+
+ const current = await methods.findPublicResourceIds(ResourceType.AGENT, bits);
+
+ expect(idsToSortedStrings(current)).toEqual(idsToSortedStrings(legacy));
+ });
+
+ test('hasPermission returns the same boolean as `$bitsAllSet` across all permBits patterns', async () => {
+ const sharedResourceId = new mongoose.Types.ObjectId();
+ /** One entry per permBits value (0..15) on the same resource. */
+ for (let permBits = 0; permBits <= 15; permBits++) {
+ await AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalId: new mongoose.Types.ObjectId(),
+ principalModel: PrincipalModel.USER,
+ resourceType: ResourceType.AGENT,
+ resourceId: sharedResourceId,
+ permBits,
+ grantedBy: grantedById,
+ });
+ }
+
+ /** For each required bit, enumerate which principalIds satisfy the mask
+ * via legacy and current and verify they match. */
+ for (const required of [
+ PermissionBits.VIEW,
+ PermissionBits.EDIT,
+ PermissionBits.DELETE,
+ PermissionBits.SHARE,
+ PermissionBits.VIEW | PermissionBits.EDIT,
+ PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE,
+ ]) {
+ const legacyMatches = await AclEntry.find({
+ resourceType: ResourceType.AGENT,
+ resourceId: sharedResourceId,
+ permBits: { $bitsAllSet: required },
+ })
+ .select('principalId')
+ .lean();
+
+ for (const entry of legacyMatches) {
+ const pid = entry.principalId as mongoose.Types.ObjectId;
+ const current = await methods.hasPermission(
+ [{ principalType: PrincipalType.USER, principalId: pid }],
+ ResourceType.AGENT,
+ sharedResourceId,
+ required,
+ );
+ expect(current).toBe(true);
+ }
+
+ const allEntries = await AclEntry.find({
+ resourceType: ResourceType.AGENT,
+ resourceId: sharedResourceId,
+ })
+ .select('principalId permBits')
+ .lean();
+ const matchingIds = new Set(
+ legacyMatches.map((e) => (e.principalId as mongoose.Types.ObjectId).toString()),
+ );
+ for (const entry of allEntries) {
+ if (matchingIds.has((entry.principalId as mongoose.Types.ObjectId).toString())) continue;
+ const current = await methods.hasPermission(
+ [
+ {
+ principalType: PrincipalType.USER,
+ principalId: entry.principalId as mongoose.Types.ObjectId,
+ },
+ ],
+ ResourceType.AGENT,
+ sharedResourceId,
+ required,
+ );
+ expect(current).toBe(false);
+ }
+ }
+ });
+
+ test('getSoleOwnedResourceIds returns the same set as the legacy aggregation', async () => {
+ /** Seed a mixed fixture where `userId` owns (has DELETE on) some resources
+ * solely, shares ownership of others, and lacks DELETE on a third group. */
+ const soleOwnedA = new mongoose.Types.ObjectId();
+ const soleOwnedB = new mongoose.Types.ObjectId();
+ const sharedOwned = new mongoose.Types.ObjectId();
+ const nonOwnedView = new mongoose.Types.ObjectId();
+
+ const otherUserId = new mongoose.Types.ObjectId();
+
+ await AclEntry.insertMany([
+ {
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ principalModel: PrincipalModel.USER,
+ resourceType: ResourceType.AGENT,
+ resourceId: soleOwnedA,
+ permBits: PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE,
+ grantedBy: grantedById,
+ },
+ {
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ principalModel: PrincipalModel.USER,
+ resourceType: ResourceType.AGENT,
+ resourceId: soleOwnedB,
+ permBits: PermissionBits.DELETE | PermissionBits.SHARE,
+ grantedBy: grantedById,
+ },
+ {
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ principalModel: PrincipalModel.USER,
+ resourceType: ResourceType.AGENT,
+ resourceId: sharedOwned,
+ permBits: PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE,
+ grantedBy: grantedById,
+ },
+ {
+ principalType: PrincipalType.USER,
+ principalId: otherUserId,
+ principalModel: PrincipalModel.USER,
+ resourceType: ResourceType.AGENT,
+ resourceId: sharedOwned,
+ permBits: PermissionBits.VIEW | PermissionBits.DELETE,
+ grantedBy: grantedById,
+ },
+ {
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ principalModel: PrincipalModel.USER,
+ resourceType: ResourceType.AGENT,
+ resourceId: nonOwnedView,
+ permBits: PermissionBits.VIEW | PermissionBits.EDIT,
+ grantedBy: grantedById,
+ },
+ ]);
+
+ /** Legacy reference: the original two-pass algorithm from #11830. */
+ const legacyOwned = await AclEntry.find({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: { $in: [ResourceType.AGENT] },
+ permBits: { $bitsAllSet: PermissionBits.DELETE },
+ })
+ .select('resourceId')
+ .lean();
+ const legacyIds = legacyOwned.map((e) => e.resourceId);
+ const legacyOthers = await AclEntry.aggregate([
+ {
+ $match: {
+ resourceType: { $in: [ResourceType.AGENT] },
+ resourceId: { $in: legacyIds },
+ permBits: { $bitsAllSet: PermissionBits.DELETE },
+ $or: [{ principalId: { $ne: userId } }, { principalType: { $ne: PrincipalType.USER } }],
+ },
+ },
+ { $group: { _id: '$resourceId' } },
+ ]);
+ const legacyMultiOwner = new Set(
+ legacyOthers.map((doc: { _id: mongoose.Types.ObjectId }) => doc._id.toString()),
+ );
+ const legacyResult = legacyIds.filter((id) => !legacyMultiOwner.has(id.toString()));
+
+ const current = await methods.getSoleOwnedResourceIds(userId, ResourceType.AGENT);
+
+ expect(idsToSortedStrings(current)).toEqual(idsToSortedStrings(legacyResult));
+ expect(idsToSortedStrings(current)).toEqual(
+ [soleOwnedA.toString(), soleOwnedB.toString()].sort(),
+ );
+ });
+ });
+
+ describe('performance (wall-clock, median over 20 runs)', () => {
+ /**
+ * These tests don't assert on absolute timings (CI variance) — they log
+ * numbers so reviewers can verify no gross regression and, if curious,
+ * see the `$in` path is typically at least as fast as `$bitsAllSet`
+ * because `$in` is indexable while `$bitsAllSet` is not.
+ *
+ * The `expect` guard is `Math.max(legacyMs * 5, 50)` — a multiplicative
+ * ceiling of 5× with an absolute floor of 50ms. The earlier
+ * `legacyMs * 3 + 50` form was dominated by the `+ 50` additive term at
+ * sub-ms latencies and would have let a 50× regression pass silently.
+ */
+ test('findAccessibleResources: $bitsAllSet vs $in', async () => {
+ await seedVariedPermissions(userId, grantedById, FIXTURE_SIZE);
+ const requiredBits = PermissionBits.VIEW | PermissionBits.EDIT;
+
+ const legacyMs = await median(
+ () =>
+ AclEntry.find({
+ $or: buildPrincipalsQuery(principalsList),
+ resourceType: ResourceType.AGENT,
+ permBits: { $bitsAllSet: requiredBits },
+ })
+ .distinct('resourceId')
+ .then(() => void 0),
+ PERF_ITERATIONS,
+ );
+ const currentMs = await median(
+ () =>
+ methods
+ .findAccessibleResources(principalsList, ResourceType.AGENT, requiredBits)
+ .then(() => void 0),
+ PERF_ITERATIONS,
+ );
+
+ console.log(
+ `[perf] findAccessibleResources — legacy $bitsAllSet: ${legacyMs.toFixed(2)}ms, ` +
+ `current $in: ${currentMs.toFixed(2)}ms (median of ${PERF_ITERATIONS} runs, ${FIXTURE_SIZE} entries)`,
+ );
+ expect(currentMs).toBeLessThan(Math.max(legacyMs * 5, 50));
+ });
+
+ test('findPublicResourceIds: $bitsAllSet vs $in', async () => {
+ const docs: Partial<t.IAclEntry>[] = [];
+ for (let i = 0; i < FIXTURE_SIZE; i++) {
+ docs.push({
+ principalType: PrincipalType.PUBLIC,
+ resourceType: ResourceType.AGENT,
+ resourceId: new mongoose.Types.ObjectId(),
+ permBits: i % 16,
+ grantedBy: grantedById,
+ });
+ }
+ await AclEntry.insertMany(docs);
+
+ const requiredBits = PermissionBits.VIEW;
+
+ const legacyMs = await median(
+ () =>
+ AclEntry.find({
+ principalType: PrincipalType.PUBLIC,
+ resourceType: ResourceType.AGENT,
+ permBits: { $bitsAllSet: requiredBits },
+ })
+ .distinct('resourceId')
+ .then(() => void 0),
+ PERF_ITERATIONS,
+ );
+ const currentMs = await median(
+ () => methods.findPublicResourceIds(ResourceType.AGENT, requiredBits).then(() => void 0),
+ PERF_ITERATIONS,
+ );
+
+ console.log(
+ `[perf] findPublicResourceIds — legacy $bitsAllSet: ${legacyMs.toFixed(2)}ms, ` +
+ `current $in: ${currentMs.toFixed(2)}ms (median of ${PERF_ITERATIONS} runs, ${FIXTURE_SIZE} entries)`,
+ );
+ expect(currentMs).toBeLessThan(Math.max(legacyMs * 5, 50));
+ });
+ });
+});
diff --git a/packages/data-schemas/src/methods/aclEntry.spec.ts b/packages/data-schemas/src/methods/aclEntry.spec.ts
index df59268db4..da92405c4a 100644
--- a/packages/data-schemas/src/methods/aclEntry.spec.ts
+++ b/packages/data-schemas/src/methods/aclEntry.spec.ts
@@ -7,7 +7,7 @@ import {
} from 'librechat-data-provider';
import { MongoMemoryServer } from 'mongodb-memory-server';
import type * as t from '~/types';
-import { createAclEntryMethods } from './aclEntry';
+import { createAclEntryMethods, permissionBitSupersets } from './aclEntry';
import aclEntrySchema from '~/schema/aclEntry';
let mongoServer: MongoMemoryServer;
@@ -1240,4 +1240,547 @@ describe('AclEntry Model Tests', () => {
expect(results).toEqual([]);
});
});
+
+ /**
+ * These cases exercise the application-layer bitwise filtering that replaced
+ * the `$bitsAllSet` query operator (which is not supported by MongoDB forks
+ * such as Azure Cosmos DB for MongoDB). They verify logical equivalence:
+ * a query for bit B must match entries whose `permBits` are a superset of B,
+ * and must not match subset or disjoint entries.
+ */
+ describe('Application-layer bitwise filtering (Cosmos DB compatibility)', () => {
+ describe('hasPermission', () => {
+ test('returns true when entry has exact required bit', async () => {
+ await methods.grantPermission(
+ PrincipalType.USER,
+ userId,
+ ResourceType.AGENT,
+ resourceId,
+ PermissionBits.VIEW,
+ grantedById,
+ );
+ const result = await methods.hasPermission(
+ [{ principalType: PrincipalType.USER, principalId: userId }],
+ ResourceType.AGENT,
+ resourceId,
+ PermissionBits.VIEW,
+ );
+ expect(result).toBe(true);
+ });
+
+ test('returns true when entry has superset of required bits', async () => {
+ await methods.grantPermission(
+ PrincipalType.USER,
+ userId,
+ ResourceType.AGENT,
+ resourceId,
+ PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE,
+ grantedById,
+ );
+ const result = await methods.hasPermission(
+ [{ principalType: PrincipalType.USER, principalId: userId }],
+ ResourceType.AGENT,
+ resourceId,
+ PermissionBits.VIEW | PermissionBits.EDIT,
+ );
+ expect(result).toBe(true);
+ });
+
+ test('returns false when entry has only subset of required bits', async () => {
+ await methods.grantPermission(
+ PrincipalType.USER,
+ userId,
+ ResourceType.AGENT,
+ resourceId,
+ PermissionBits.VIEW,
+ grantedById,
+ );
+ const result = await methods.hasPermission(
+ [{ principalType: PrincipalType.USER, principalId: userId }],
+ ResourceType.AGENT,
+ resourceId,
+ PermissionBits.VIEW | PermissionBits.EDIT,
+ );
+ expect(result).toBe(false);
+ });
+
+ test('returns false when no entries match', async () => {
+ const result = await methods.hasPermission(
+ [{ principalType: PrincipalType.USER, principalId: userId }],
+ ResourceType.AGENT,
+ resourceId,
+ PermissionBits.VIEW,
+ );
+ expect(result).toBe(false);
+ });
+ });
+
+ describe('findAccessibleResources', () => {
+ test('returns deduplicated resource IDs across multiple matching entries', async () => {
+ const shared = new mongoose.Types.ObjectId();
+ await methods.grantPermission(
+ PrincipalType.USER,
+ userId,
+ ResourceType.AGENT,
+ shared,
+ PermissionBits.VIEW,
+ grantedById,
+ );
+ await methods.grantPermission(
+ PrincipalType.GROUP,
+ groupId,
+ ResourceType.AGENT,
+ shared,
+ PermissionBits.VIEW | PermissionBits.EDIT,
+ grantedById,
+ );
+
+ const result = await methods.findAccessibleResources(
+ [
+ { principalType: PrincipalType.USER, principalId: userId },
+ { principalType: PrincipalType.GROUP, principalId: groupId },
+ ],
+ ResourceType.AGENT,
+ PermissionBits.VIEW,
+ );
+ expect(result).toHaveLength(1);
+ expect(result[0].toString()).toBe(shared.toString());
+ });
+
+ test('excludes resources whose entries only hold subset bits', async () => {
+ const viewOnly = new mongoose.Types.ObjectId();
+ const viewEdit = new mongoose.Types.ObjectId();
+ await methods.grantPermission(
+ PrincipalType.USER,
+ userId,
+ ResourceType.AGENT,
+ viewOnly,
+ PermissionBits.VIEW,
+ grantedById,
+ );
+ await methods.grantPermission(
+ PrincipalType.USER,
+ userId,
+ ResourceType.AGENT,
+ viewEdit,
+ PermissionBits.VIEW | PermissionBits.EDIT,
+ grantedById,
+ );
+
+ const result = await methods.findAccessibleResources(
+ [{ principalType: PrincipalType.USER, principalId: userId }],
+ ResourceType.AGENT,
+ PermissionBits.EDIT,
+ );
+ expect(result).toHaveLength(1);
+ expect(result[0].toString()).toBe(viewEdit.toString());
+ });
+ });
+
+ describe('findPublicResourceIds', () => {
+ test('returns the public resource ID when required bits are present', async () => {
+ const shared = new mongoose.Types.ObjectId();
+ await methods.grantPermission(
+ PrincipalType.PUBLIC,
+ null,
+ ResourceType.AGENT,
+ shared,
+ PermissionBits.VIEW | PermissionBits.EDIT,
+ grantedById,
+ );
+
+ const result = await methods.findPublicResourceIds(
+ ResourceType.AGENT,
+ PermissionBits.VIEW | PermissionBits.EDIT,
+ );
+ expect(result).toHaveLength(1);
+ expect(result[0].toString()).toBe(shared.toString());
+ });
+
+ test('deduplicates when duplicate public entries exist for the same resource', async () => {
+ /**
+ * `grantPermission` upserts, so duplicates are not reachable through the
+ * public API. Bypass it with `AclEntry.create` to confirm the
+ * application-layer dedup logic handles the defensive case.
+ */
+ const shared = new mongoose.Types.ObjectId();
+ await AclEntry.create([
+ {
+ principalType: PrincipalType.PUBLIC,
+ resourceType: ResourceType.AGENT,
+ resourceId: shared,
+ permBits: PermissionBits.VIEW,
+ grantedBy: grantedById,
+ },
+ {
+ principalType: PrincipalType.PUBLIC,
+ resourceType: ResourceType.AGENT,
+ resourceId: shared,
+ permBits: PermissionBits.VIEW | PermissionBits.EDIT,
+ grantedBy: grantedById,
+ },
+ ]);
+
+ const result = await methods.findPublicResourceIds(ResourceType.AGENT, PermissionBits.VIEW);
+ expect(result).toHaveLength(1);
+ expect(result[0].toString()).toBe(shared.toString());
+ });
+ });
+
+ describe('getSoleOwnedResourceIds', () => {
+ test('returns resources where the user is the only DELETE holder', async () => {
+ const soleRes = new mongoose.Types.ObjectId();
+ await methods.grantPermission(
+ PrincipalType.USER,
+ userId,
+ ResourceType.AGENT,
+ soleRes,
+ PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE,
+ grantedById,
+ );
+
+ const result = await methods.getSoleOwnedResourceIds(userId, ResourceType.AGENT);
+ expect(result).toHaveLength(1);
+ expect(result[0].toString()).toBe(soleRes.toString());
+ });
+
+ test('excludes resources where another principal also holds DELETE', async () => {
+ const sharedRes = new mongoose.Types.ObjectId();
+ await methods.grantPermission(
+ PrincipalType.USER,
+ userId,
+ ResourceType.AGENT,
+ sharedRes,
+ PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE,
+ grantedById,
+ );
+ await methods.grantPermission(
+ PrincipalType.GROUP,
+ groupId,
+ ResourceType.AGENT,
+ sharedRes,
+ PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE,
+ grantedById,
+ );
+
+ const result = await methods.getSoleOwnedResourceIds(userId, ResourceType.AGENT);
+ expect(result).toHaveLength(0);
+ });
+
+ test('ignores other principals that lack the DELETE bit', async () => {
+ const soleRes = new mongoose.Types.ObjectId();
+ await methods.grantPermission(
+ PrincipalType.USER,
+ userId,
+ ResourceType.AGENT,
+ soleRes,
+ PermissionBits.VIEW | PermissionBits.DELETE,
+ grantedById,
+ );
+ await methods.grantPermission(
+ PrincipalType.GROUP,
+ groupId,
+ ResourceType.AGENT,
+ soleRes,
+ PermissionBits.VIEW,
+ grantedById,
+ );
+
+ const result = await methods.getSoleOwnedResourceIds(userId, ResourceType.AGENT);
+ expect(result).toHaveLength(1);
+ expect(result[0].toString()).toBe(soleRes.toString());
+ });
+
+ test('excludes resources where the user entry lacks DELETE', async () => {
+ const noDelete = new mongoose.Types.ObjectId();
+ await methods.grantPermission(
+ PrincipalType.USER,
+ userId,
+ ResourceType.AGENT,
+ noDelete,
+ PermissionBits.VIEW | PermissionBits.EDIT,
+ grantedById,
+ );
+
+ const result = await methods.getSoleOwnedResourceIds(userId, ResourceType.AGENT);
+ expect(result).toHaveLength(0);
+ });
+
+ test('handles an array of resource types', async () => {
+ const agentRes = new mongoose.Types.ObjectId();
+ const mcpRes = new mongoose.Types.ObjectId();
+ await methods.grantPermission(
+ PrincipalType.USER,
+ userId,
+ ResourceType.AGENT,
+ agentRes,
+ PermissionBits.VIEW | PermissionBits.DELETE,
+ grantedById,
+ );
+ await methods.grantPermission(
+ PrincipalType.USER,
+ userId,
+ ResourceType.MCPSERVER,
+ mcpRes,
+ PermissionBits.VIEW | PermissionBits.DELETE,
+ grantedById,
+ );
+
+ const result = await methods.getSoleOwnedResourceIds(userId, [
+ ResourceType.AGENT,
+ ResourceType.MCPSERVER,
+ ]);
+ expect(result).toHaveLength(2);
+ const idStrings = result.map((id) => id.toString()).sort();
+ expect(idStrings).toEqual([agentRes.toString(), mcpRes.toString()].sort());
+ });
+
+ test('returns empty array when no owned entries exist', async () => {
+ const result = await methods.getSoleOwnedResourceIds(userId, ResourceType.AGENT);
+ expect(result).toEqual([]);
+ });
+ });
+ });
+
+ /**
+ * Focused unit tests for the `permissionBitSupersets` helper. The helper is
+ * the single point of correctness for every ACL read path (every query uses
+ * `permBits: { $in: permissionBitSupersets(X) }`), so it warrants direct
+ * coverage independent of the higher-level parity and behavior specs.
+ */
+ describe('permissionBitSupersets', () => {
+ test('requiredBits=0 matches every permBits value in [0, 15]', () => {
+ const result = permissionBitSupersets(0);
+ expect(result).toHaveLength(16);
+ expect([...result].sort((a, b) => a - b)).toEqual([
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+ ]);
+ });
+
+ test('requiredBits=15 (all four bits) matches only [15]', () => {
+ const result = permissionBitSupersets(
+ PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE,
+ );
+ expect([...result].sort((a, b) => a - b)).toEqual([15]);
+ });
+
+ test('every returned value is a bitwise superset of requiredBits', () => {
+ for (const required of [
+ PermissionBits.VIEW,
+ PermissionBits.EDIT,
+ PermissionBits.DELETE,
+ PermissionBits.SHARE,
+ PermissionBits.VIEW | PermissionBits.EDIT,
+ PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE,
+ ]) {
+ const result = permissionBitSupersets(required);
+ for (const v of result) {
+ expect((v & required) === required).toBe(true);
+ }
+ }
+ });
+
+ test('returns exactly the values satisfying $bitsAllSet semantics', () => {
+ /**
+ * Parity check against the literal definition: for every required mask,
+ * the returned set must equal the set of all v in [0,15] whose bits
+ * include `required`.
+ */
+ for (let required = 0; required <= 15; required++) {
+ const expected: number[] = [];
+ for (let v = 0; v <= 15; v++) {
+ if ((v & required) === required) {
+ expected.push(v);
+ }
+ }
+ expect([...permissionBitSupersets(required)].sort((a, b) => a - b)).toEqual(expected);
+ }
+ });
+
+ test('memoizes: repeat calls return the same frozen reference', () => {
+ const first = permissionBitSupersets(PermissionBits.SHARE);
+ const second = permissionBitSupersets(PermissionBits.SHARE);
+ expect(second).toBe(first);
+ expect(Object.isFrozen(first)).toBe(true);
+ });
+
+ test('frozen result throws on mutation attempts in strict mode', () => {
+ const result = permissionBitSupersets(PermissionBits.VIEW);
+ /**
+ * `Object.freeze` in strict mode (TypeScript compiles to strict) causes
+ * mutation attempts to throw rather than silently corrupt the cache.
+ */
+ expect(() => {
+ (result as number[]).push(99);
+ }).toThrow(TypeError);
+ });
+
+ /**
+ * Controllers forward user input directly into this path (e.g.
+ * `req.query.requiredPermission` in agents/v1.js is parsed by `parseInt`
+ * and passed to `findAccessibleResources`). Without a guard, attacker-
+ * supplied unique integers would grow the process-global `supersetCache`
+ * indefinitely (a DoS vector). Verify the function rejects every
+ * out-of-range shape without touching the cache.
+ */
+ describe('rejection of out-of-range inputs (cache-growth safety)', () => {
+ const MAX =
+ PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE;
+ const SHARED_EMPTY = permissionBitSupersets(MAX + 1);
+
+ test('returns a frozen empty array for requiredBits above MAX_PERM_BITS', () => {
+ expect(permissionBitSupersets(MAX + 1)).toEqual([]);
+ expect(Object.isFrozen(permissionBitSupersets(MAX + 1))).toBe(true);
+ });
+
+ test('returns the same shared empty instance for every rejected input', () => {
+ /**
+ * Shared reference identity means rejected inputs do not each allocate
+ * a fresh array on every call — key to avoiding GC churn under load.
+ */
+ expect(permissionBitSupersets(MAX + 1)).toBe(SHARED_EMPTY);
+ expect(permissionBitSupersets(MAX + 100)).toBe(SHARED_EMPTY);
+ expect(permissionBitSupersets(-1)).toBe(SHARED_EMPTY);
+ expect(permissionBitSupersets(Number.MAX_SAFE_INTEGER)).toBe(SHARED_EMPTY);
+ expect(permissionBitSupersets(NaN)).toBe(SHARED_EMPTY);
+ expect(permissionBitSupersets(1.5)).toBe(SHARED_EMPTY);
+ });
+
+ test('rejects inputs with bits above MAX_PERM_BITS even if some in-range bits are set', () => {
+ /**
+ * `permBits = 17 = 0b10001` has VIEW set AND bit 4 (out of range). A
+ * stored `permBits` can never be both ≤ 15 and have bit 4 set, so the
+ * match set is necessarily empty — reject before caching.
+ */
+ expect(permissionBitSupersets(MAX + PermissionBits.VIEW)).toBe(SHARED_EMPTY);
+ });
+
+ test('does NOT cache rejected inputs (reference identity)', () => {
+ /**
+ * Fire a burst of unique attacker-supplied integers and verify that
+ * none of them can be retrieved from the cache via a legitimate call
+ * — i.e., they were never cached. We do this by asserting shared
+ * reference identity across repeated calls with varied bogus values.
+ * If any of these were being cached, repeat calls would return
+ * distinct frozen arrays.
+ */
+ const ref = permissionBitSupersets(MAX + 1);
+ for (let i = 0; i < 1000; i++) {
+ expect(permissionBitSupersets(MAX + 1 + i)).toBe(ref);
+ }
+ for (let i = 0; i < 1000; i++) {
+ expect(permissionBitSupersets(-(i + 1))).toBe(ref);
+ }
+ });
+
+ test('does NOT call `supersetCache.set` for rejected inputs (Map-write probe)', () => {
+ /**
+ * Stronger guarantee than reference identity alone: spy on
+ * `Map.prototype.set` and assert zero invocations during a burst of
+ * rejected inputs. This closes the hypothetical gap where a future
+ * regression like `supersetCache.set(requiredBits, EMPTY_SUPERSETS)`
+ * could pass the reference-identity check while still leaking memory
+ * one entry per attacker request.
+ *
+ * The spy is global (it intercepts every `Map.prototype.set` call),
+ * so we snapshot the call count before and after and assert the
+ * delta is zero. The body does no async work and no other Map
+ * writes, so any delta would come from `permissionBitSupersets`.
+ */
+ const setSpy = jest.spyOn(Map.prototype, 'set');
+ try {
+ const before = setSpy.mock.calls.length;
+ for (let i = 0; i < 500; i++) {
+ permissionBitSupersets(MAX + 1 + i);
+ permissionBitSupersets(-(i + 1));
+ permissionBitSupersets(i + 0.5);
+ }
+ const delta = setSpy.mock.calls.length - before;
+ expect(delta).toBe(0);
+ } finally {
+ setSpy.mockRestore();
+ }
+ });
+
+ test('in-range inputs are still cached normally (memoized reference)', () => {
+ const first = permissionBitSupersets(PermissionBits.EDIT);
+ const second = permissionBitSupersets(PermissionBits.EDIT);
+ expect(second).toBe(first);
+ expect(Object.isFrozen(first)).toBe(true);
+ expect(first).not.toBe(SHARED_EMPTY);
+ });
+ });
+ });
+
+ /**
+ * These tests enforce the invariant that `permBits` stays within the
+ * `[0, MAX_PERM_BITS]` range that `permissionBitSupersets` enumerates. Rows
+ * with out-of-range bits would be silently excluded from the `$in` filter
+ * (false permission denials), so the schema rejects them at write time.
+ * See the second review pass on issue #12729.
+ */
+ describe('permBits schema bounds', () => {
+ const MAX_PERM_BITS =
+ PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE;
+
+ test('accepts permBits at the upper bound (all enum bits set)', async () => {
+ const resource = new mongoose.Types.ObjectId();
+ await expect(
+ AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ principalModel: PrincipalModel.USER,
+ resourceType: ResourceType.AGENT,
+ resourceId: resource,
+ permBits: MAX_PERM_BITS,
+ grantedBy: grantedById,
+ }),
+ ).resolves.toBeDefined();
+ });
+
+ test('rejects permBits above MAX_PERM_BITS', async () => {
+ const resource = new mongoose.Types.ObjectId();
+ await expect(
+ AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ principalModel: PrincipalModel.USER,
+ resourceType: ResourceType.AGENT,
+ resourceId: resource,
+ permBits: MAX_PERM_BITS + 1,
+ grantedBy: grantedById,
+ }),
+ ).rejects.toThrow(mongoose.Error.ValidationError);
+ });
+
+ test('rejects negative permBits', async () => {
+ const resource = new mongoose.Types.ObjectId();
+ await expect(
+ AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ principalModel: PrincipalModel.USER,
+ resourceType: ResourceType.AGENT,
+ resourceId: resource,
+ permBits: -1,
+ grantedBy: grantedById,
+ }),
+ ).rejects.toThrow(mongoose.Error.ValidationError);
+ });
+
+ test('rejects non-integer permBits', async () => {
+ const resource = new mongoose.Types.ObjectId();
+ await expect(
+ AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ principalModel: PrincipalModel.USER,
+ resourceType: ResourceType.AGENT,
+ resourceId: resource,
+ permBits: 1.5,
+ grantedBy: grantedById,
+ }),
+ ).rejects.toThrow(mongoose.Error.ValidationError);
+ });
+ });
});
diff --git a/packages/data-schemas/src/methods/aclEntry.ts b/packages/data-schemas/src/methods/aclEntry.ts
index d93693641c..c44b2453f2 100644
--- a/packages/data-schemas/src/methods/aclEntry.ts
+++ b/packages/data-schemas/src/methods/aclEntry.ts
@@ -8,8 +8,73 @@ import type {
Model,
} from 'mongoose';
import type { AclEntry, IAclEntry } from '~/types';
+import { MAX_PERM_BITS } from '~/common/permissions';
import { tenantSafeBulkWrite } from '~/utils/tenantBulkWrite';
+/**
+ * Empty frozen array shared by every rejection path. Returning a single
+ * instance keeps the hot path allocation-free and freezes a known-safe value
+ * so it can never mutate into a "match everything" list.
+ */
+const EMPTY_SUPERSETS: readonly number[] = Object.freeze([]);
+
+const supersetCache = new Map<number, readonly number[]>();
+
+/**
+ * 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
+ * permission-mask matching down to the database without relying on the
+ * `$bitsAllSet` query operator, which is not supported by Azure Cosmos DB for
+ * MongoDB (see issue #12729).
+ *
+ * **Invariant:** stored `permBits` values must lie in `[0, MAX_PERM_BITS]`.
+ * Values with higher-order bits set would never appear in the emitted `$in`
+ * list and would silently produce false permission denials. The aclEntry
+ * schema enforces this with a `max` validator; if the `PermissionBits` enum
+ * grows, `MAX_PERM_BITS` auto-expands from the new enum values.
+ *
+ * **Cache safety:** callers sometimes forward user input directly (e.g.
+ * `req.query.requiredPermission` is parsed and passed through without a range
+ * check). To prevent the process-global cache from growing unboundedly from
+ * attacker-supplied integers, any `requiredBits` outside `[0, MAX_PERM_BITS]`
+ * or with bits set above the max returns a shared frozen empty array and is
+ * NOT added to the cache. An empty `$in` list correctly matches zero rows,
+ * which is the right behavior for a request asking for bits the system does
+ * not recognize.
+ *
+ * For the current 4-bit `PermissionBits` enum the worst case is `required = 0`
+ * which expands to 16 values; the best case (all bits required) expands to 1.
+ * Results are memoized per `requiredBits` so the expansion runs at most once
+ * per distinct mask over the process lifetime.
+ */
+export function permissionBitSupersets(requiredBits: number): readonly number[] {
+ if (
+ !Number.isInteger(requiredBits) ||
+ requiredBits < 0 ||
+ (requiredBits & ~MAX_PERM_BITS) !== 0
+ ) {
+ return EMPTY_SUPERSETS;
+ }
+ const cached = supersetCache.get(requiredBits);
+ if (cached !== undefined) {
+ return cached;
+ }
+ const supersets: number[] = [];
+ for (let v = 0; v <= MAX_PERM_BITS; v++) {
+ if ((v & requiredBits) === requiredBits) {
+ supersets.push(v);
+ }
+ }
+ /**
+ * Freeze the cached array so a future caller cannot mutate the shared cache
+ * entry. All current callers only forward this to Mongoose's `$in`, which
+ * does not mutate — freezing is cheap and prevents silent corruption.
+ */
+ const frozen = Object.freeze(supersets);
+ supersetCache.set(requiredBits, frozen);
+ return frozen;
+}
+
export function createAclEntryMethods(mongoose: typeof import('mongoose')) {
/**
* Find ACL entries for a specific principal (user or group)
@@ -71,7 +136,8 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')) {
}
/**
- * Check if a set of principals has a specific permission on a resource
+ * Check if a set of principals has a specific permission on a resource.
+ * See {@link permissionBitSupersets} for the Cosmos-compatible bit filter.
* @param principalsList - List of principals, each containing { principalType, principalId }
* @param resourceType - The type of resource
* @param resourceId - The ID of the resource
@@ -94,8 +160,10 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')) {
$or: principalsQuery,
resourceType,
resourceId,
- permBits: { $bitsAllSet: permissionBit },
- }).lean();
+ permBits: { $in: permissionBitSupersets(permissionBit) },
+ })
+ .select('_id')
+ .lean();
return !!entry;
}
@@ -330,7 +398,8 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')) {
}
/**
- * Find all resources of a specific type that a set of principals has access to
+ * Find all resources of a specific type that a set of principals has access to.
+ * See {@link permissionBitSupersets} for the Cosmos-compatible bit filter.
* @param principalsList - List of principals, each containing { principalType, principalId }
* @param resourceType - The type of resource
* @param requiredPermBit - Required permission bit (use PermissionBits enum)
@@ -347,13 +416,11 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')) {
...(p.principalType !== PrincipalType.PUBLIC && { principalId: p.principalId }),
}));
- const entries = await AclEntry.find({
+ return await AclEntry.find({
$or: principalsQuery,
resourceType,
- permBits: { $bitsAllSet: requiredPermBit },
+ permBits: { $in: permissionBitSupersets(requiredPermBit) },
}).distinct('resourceId');
-
- return entries;
}
/**
@@ -384,6 +451,7 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')) {
/**
* Finds all publicly accessible resource IDs for a given resource type.
+ * See {@link permissionBitSupersets} for the Cosmos-compatible bit filter.
* @param resourceType - The type of resource
* @param requiredPermissions - Required permission bits
*/
@@ -392,10 +460,10 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')) {
requiredPermissions: number,
): Promise<Types.ObjectId[]> {
const AclEntry = mongoose.models.AclEntry as Model<IAclEntry>;
- return AclEntry.find({
+ return await AclEntry.find({
principalType: PrincipalType.PUBLIC,
resourceType,
- permBits: { $bitsAllSet: requiredPermissions },
+ permBits: { $in: permissionBitSupersets(requiredPermissions) },
}).distinct('resourceId');
}
@@ -411,6 +479,7 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')) {
/**
* Returns resource IDs solely owned by the given user (no other principals
* hold DELETE on the same resource). Handles both single and array resource types.
+ * See {@link permissionBitSupersets} for the Cosmos-compatible bit filter.
*/
async function getSoleOwnedResourceIds(
userObjectId: Types.ObjectId,
@@ -418,12 +487,13 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')) {
): Promise<Types.ObjectId[]> {
const AclEntry = mongoose.models.AclEntry as Model<IAclEntry>;
const types = Array.isArray(resourceTypes) ? resourceTypes : [resourceTypes];
+ const deleteSupersets = permissionBitSupersets(PermissionBits.DELETE);
const ownedEntries = await AclEntry.find({
principalType: PrincipalType.USER,
principalId: userObjectId,
resourceType: { $in: types },
- permBits: { $bitsAllSet: PermissionBits.DELETE },
+ permBits: { $in: deleteSupersets },
})
.select('resourceId')
.lean();
@@ -439,7 +509,7 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')) {
$match: {
resourceType: { $in: types },
resourceId: { $in: ownedIds },
- permBits: { $bitsAllSet: PermissionBits.DELETE },
+ permBits: { $in: deleteSupersets },
$or: [
{ principalId: { $ne: userObjectId } },
{ principalType: { $ne: PrincipalType.USER } },
diff --git a/packages/data-schemas/src/methods/index.ts b/packages/data-schemas/src/methods/index.ts
index 830d88ff4c..c2f6f7cb82 100644
--- a/packages/data-schemas/src/methods/index.ts
+++ b/packages/data-schemas/src/methods/index.ts
@@ -18,7 +18,7 @@ import { createPluginAuthMethods, type PluginAuthMethods } from './pluginAuth';
/* Permissions */
import { createAccessRoleMethods, type AccessRoleMethods } from './accessRole';
import { createUserGroupMethods, type UserGroupMethods } from './userGroup';
-import { createAclEntryMethods, type AclEntryMethods } from './aclEntry';
+import { createAclEntryMethods, permissionBitSupersets, type AclEntryMethods } from './aclEntry';
import { createSystemGrantMethods, type SystemGrantMethods } from './systemGrant';
import { createShareMethods, type ShareMethods } from './share';
/* Tier 1 — Simple CRUD */
@@ -52,6 +52,7 @@ import { createConfigMethods, type ConfigMethods } from './config';
export { RoleConflictError, DEFAULT_REFRESH_TOKEN_EXPIRY, DEFAULT_SESSION_EXPIRY };
export { tokenValues, cacheTokenValues, premiumTokenValues, defaultRate };
+export { permissionBitSupersets };
export type AllMethods = UserMethods &
SessionMethods &
diff --git a/packages/data-schemas/src/schema/aclEntry.ts b/packages/data-schemas/src/schema/aclEntry.ts
index e58cb1a424..c612ee2886 100644
--- a/packages/data-schemas/src/schema/aclEntry.ts
+++ b/packages/data-schemas/src/schema/aclEntry.ts
@@ -1,6 +1,7 @@
import { Schema } from 'mongoose';
import { PrincipalType, PrincipalModel, ResourceType } from 'librechat-data-provider';
import type { IAclEntry } from '~/types';
+import { MAX_PERM_BITS } from '~/common/permissions';
const aclEntrySchema = new Schema<IAclEntry>(
{
@@ -37,6 +38,12 @@ const aclEntrySchema = new Schema<IAclEntry>(
permBits: {
type: Number,
default: 1,
+ min: 0,
+ max: MAX_PERM_BITS,
+ validate: {
+ validator: Number.isInteger,
+ message: '`permBits` must be an integer',
+ },
},
roleId: {
type: Schema.Types.ObjectId,