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: Resolve Tenant Profiles in Their Own Partition and Keep Role Operations in the Caller's (#17417)

Danny Avila080e5f500c0d
diff --git a/api/server/routes/__tests__/grants.spec.js b/api/server/routes/__tests__/grants.spec.js
index c7b5b6bdda..87ee14b53c 100644
--- a/api/server/routes/__tests__/grants.spec.js
+++ b/api/server/routes/__tests__/grants.spec.js
@@ -65,7 +65,7 @@ function createApp(user) {
hasCapabilityForPrincipals: db.hasCapabilityForPrincipals,
getHeldCapabilities: db.getHeldCapabilities,
getCachedPrincipals,
- checkRoleExists: async (name) => (await db.getRoleByName(name)) != null,
+ checkRoleExists: async (name) => (await db.getPartitionRole(name)) != null,
});
const app = express();
@@ -168,6 +168,29 @@ describe('Admin Grants Routes — Integration', () => {
expect(res.body.error).toBe('Role not found');
});
+ it('POST / returns 400 for a role only a tenant holds, as the roles API addresses it', async () => {
+ const { tenantStorage } = require('@librechat/data-schemas');
+ await tenantStorage.run({ tenantId: 'tenant-a' }, () =>
+ db.createRoleByName({ name: 'tenant-only-role' }),
+ );
+ const app = createApp(adminUser);
+
+ const res = await request(app)
+ .post('/api/admin/grants')
+ .send({
+ principalType: PrincipalType.ROLE,
+ principalId: 'tenant-only-role',
+ capability: 'read:users',
+ })
+ .expect(400);
+
+ expect(res.body.error).toBe('Role not found');
+ expect(
+ await mongoose.models.SystemGrant.countDocuments({ principalId: 'tenant-only-role' }),
+ ).toBe(0);
+ await mongoose.models.Role.deleteMany({ name: 'tenant-only-role' });
+ });
+
it('POST / returns 401 without authenticated user', async () => {
const app = createApp(undefined);
diff --git a/api/server/routes/admin/config.js b/api/server/routes/admin/config.js
index 4e21a8a836..2b0e9a5de3 100644
--- a/api/server/routes/admin/config.js
+++ b/api/server/routes/admin/config.js
@@ -64,7 +64,7 @@ const readHandlers = createAdminConfigReadHandlers({
hasCapability,
resolveConfigLayers,
principalExists: db.principalExists,
- findPartitionUser: db.findPartitionUser,
+ findPrincipalUser: db.findPrincipalUser,
getUserPrincipals: db.getUserPrincipals,
getApplicableConfigs: db.getApplicableConfigs,
});
@@ -81,6 +81,7 @@ const catalogHandlers = createAdminConfigCatalogHandlers({
toolManifest: availableTools,
toolkits,
principalExists: db.principalExists,
+ findConfigByPrincipal: db.findConfigByPrincipal,
listAllConfigs: db.listAllConfigs,
overrideEnvAllowlist: process.env.CONFIG_OVERRIDE_ENV_ALLOWLIST,
});
diff --git a/api/server/routes/admin/config.test.js b/api/server/routes/admin/config.test.js
index c36bf34e28..9d777c9d53 100644
--- a/api/server/routes/admin/config.test.js
+++ b/api/server/routes/admin/config.test.js
@@ -35,7 +35,7 @@ const mockDb = {
toggleConfigActiveTracked: jest.fn(),
recordAuditEntry: jest.fn(),
principalExists: jest.fn(async () => true),
- findPartitionUser: jest.fn(async () => null),
+ findPrincipalUser: jest.fn(async () => null),
getUserPrincipals: jest.fn(async () => []),
getApplicableConfigs: jest.fn(async () => []),
};
diff --git a/api/server/routes/admin/grants.js b/api/server/routes/admin/grants.js
index 9986e17229..8056894f2c 100644
--- a/api/server/routes/admin/grants.js
+++ b/api/server/routes/admin/grants.js
@@ -25,7 +25,7 @@ const handlers = createAdminGrantsHandlers({
hasCapabilityForPrincipals: db.hasCapabilityForPrincipals,
getHeldCapabilities: db.getHeldCapabilities,
getCachedPrincipals,
- checkRoleExists: async (name) => (await db.getRoleByName(name)) != null,
+ checkRoleExists: async (name) => (await db.getPartitionRole(name)) != null,
recordAuditEntry: db.recordAuditEntry,
auditFailClosed: isAuditFailClosed(),
lease: {
diff --git a/api/server/routes/admin/roles.js b/api/server/routes/admin/roles.js
index dd2197e2bb..f6c4b73896 100644
--- a/api/server/routes/admin/roles.js
+++ b/api/server/routes/admin/roles.js
@@ -15,7 +15,7 @@ const requireManageRoles = requireCapability(SystemCapabilities.MANAGE_ROLES);
const handlers = createAdminRolesHandlers({
listRoles: db.listRoles,
countRoles: db.countRoles,
- getRoleByName: db.getRoleByName,
+ getRoleByName: db.getPartitionRole,
createRoleByName: db.createRoleByName,
updateRoleByName: db.updateRoleByName,
updateAccessPermissions: db.updateAccessPermissions,
@@ -28,7 +28,7 @@ const handlers = createAdminRolesHandlers({
listUsersByRole: db.listUsersByRole,
countUsersByRole: db.countUsersByRole,
deleteConfig: db.deleteConfig,
- deleteAclEntries: db.deleteAclEntries,
+ deleteAclEntries: db.deletePrincipalAclEntries,
deleteGrantsForPrincipal: db.deleteGrantsForPrincipal,
restoreConfig: db.restoreConfig,
findConfigByPrincipal: db.findConfigByPrincipal,
diff --git a/packages/api/src/admin/cascade.integration.spec.ts b/packages/api/src/admin/cascade.integration.spec.ts
index 1612c5df13..ceba20c3d4 100644
--- a/packages/api/src/admin/cascade.integration.spec.ts
+++ b/packages/api/src/admin/cascade.integration.spec.ts
@@ -164,7 +164,7 @@ function roleHandlers(overrides: Partial<AdminRolesDeps>) {
return createAdminRolesHandlers({
listRoles: methods.listRoles,
countRoles: methods.countRoles,
- getRoleByName: methods.getRoleByName,
+ getRoleByName: methods.getPartitionRole,
createRoleByName: methods.createRoleByName,
updateRoleByName: methods.updateRoleByName,
updateAccessPermissions: methods.updateAccessPermissions,
@@ -177,9 +177,7 @@ function roleHandlers(overrides: Partial<AdminRolesDeps>) {
listUsersByRole: methods.listUsersByRole,
countUsersByRole: methods.countUsersByRole,
deleteConfig: methods.deleteConfig,
- deleteAclEntries: async (filter) => {
- await methods.deleteAclEntries(filter);
- },
+ deleteAclEntries: methods.deletePrincipalAclEntries,
deleteGrantsForPrincipal: methods.deleteGrantsForPrincipal,
restoreConfig: methods.restoreConfig,
findConfigByPrincipal: methods.findConfigByPrincipal,
diff --git a/packages/api/src/admin/catalog.ts b/packages/api/src/admin/catalog.ts
index 95b848c5ec..30422034da 100644
--- a/packages/api/src/admin/catalog.ts
+++ b/packages/api/src/admin/catalog.ts
@@ -50,6 +50,7 @@ import {
collectDefaultEnvReferenceSections,
} from '~/app/allowlist';
import { resolveServedCustomEndpoints } from '~/endpoints/custom/config';
+import { getConfigPartition, getActivePartition } from './partition';
import { listAvailableTools } from '~/tools/available';
import { getSafeErrorMetadata } from '~/utils/errors';
import { resolveConfigSecret } from './secrets';
@@ -98,6 +99,16 @@ export interface AdminConfigCatalogDeps {
toolkits?: TPlugin[];
/** Whether the principal exists in the caller's tenant partition (`principalExists`). */
principalExists?: (principalType: PrincipalType, principalId: string) => Promise<boolean>;
+ /**
+ * A principal's config document, active or not. A group or user scope resolves in the tenant
+ * partition that stores its profile, as `GET /resolved` resolves it; without this lookup every
+ * scope resolves in the caller's.
+ */
+ findConfigByPrincipal?: (
+ principalType: PrincipalType,
+ principalId: string,
+ options?: { includeInactive?: boolean },
+ ) => Promise<ConfigRecord | null>;
/** Every config document of the caller's partition, for the env names profiles reference. */
listAllConfigs?: () => Promise<ConfigRecord[]>;
/** `CONFIG_OVERRIDE_ENV_ALLOWLIST`, as the app config service is given it. */
@@ -348,6 +359,7 @@ export function createAdminConfigCatalogHandlers(deps: AdminConfigCatalogDeps):
toolManifest = [],
toolkits = [],
principalExists,
+ findConfigByPrincipal,
listAllConfigs,
overrideEnvAllowlist,
} = deps;
@@ -473,11 +485,38 @@ export function createAdminConfigCatalogHandlers(deps: AdminConfigCatalogDeps):
}).map(toCatalogTool);
}
+ /**
+ * Whether a scope can be resolved, and the tenant partition it resolves in: the caller's, or for
+ * a group or user profile a caller without a tenant reads from a tenant, the tenant that stores
+ * it. A scope without a profile must exist in the caller's partition.
+ */
+ async function locateScope(
+ principalType: PrincipalType,
+ principalId: string,
+ isBase: boolean,
+ ): Promise<{ exists: boolean; tenantId: string | undefined }> {
+ const activePartition = getActivePartition();
+ if (isBase) {
+ return { exists: true, tenantId: activePartition };
+ }
+ const [stored, exists] = await Promise.all([
+ principalType !== PrincipalType.ROLE && findConfigByPrincipal
+ ? findConfigByPrincipal(principalType, principalId, { includeInactive: true })
+ : null,
+ principalExists ? principalExists(principalType, principalId) : true,
+ ]);
+ if (stored) {
+ return { exists: true, tenantId: getConfigPartition(stored) };
+ }
+ return { exists, tenantId: activePartition };
+ }
+
/**
* GET /catalog?principalType=&principalId= — the endpoints, models, MCP servers and tools a
* scope serves (Base when no principal is named), resolved as `getAppConfig` resolves it for
- * that scope from the stored documents, never the override cache. Model lists are never loaded
- * with a user's stored key. A part is left out unless the caller can read its section.
+ * that scope from the stored documents, never the override cache, in the partition the scope's
+ * profile merges in (`locateScope`). Model lists are never loaded with a user's stored key. A
+ * part is left out unless the caller can read its section.
*/
async function getConfigCatalog(req: ServerRequest, res: Response): Promise<Response> {
try {
@@ -501,24 +540,24 @@ export function createAdminConfigCatalogHandlers(deps: AdminConfigCatalogDeps):
return forbiddenResponse(res);
}
const isBase = isBaseConfigPrincipal({ principalType, principalId });
- const [readable, exists] = await Promise.all([
+ const [readable, scope] = await Promise.all([
getReadableConfigSections(user, [
'endpoints',
'mcpServers',
'filteredTools',
'includedTools',
]),
- isBase || !principalExists ? true : principalExists(principalType, principalId),
+ locateScope(principalType, principalId, isBase),
]);
- if (!exists) {
+ if (!scope.exists) {
return principalNotFoundResponse(res);
}
- const config = await getAppConfig(toScopeOptions(principalType, principalId, user.tenantId));
+ const config = await getAppConfig(toScopeOptions(principalType, principalId, scope.tenantId));
const request: CatalogScopeRequest = {
config,
user: {
- tenantId: user.tenantId,
+ tenantId: scope.tenantId,
...(principalType === PrincipalType.ROLE && !isBase && { role: principalId }),
},
};
diff --git a/packages/api/src/admin/config.ts b/packages/api/src/admin/config.ts
index 22b2cc4dc1..cdd9587043 100644
--- a/packages/api/src/admin/config.ts
+++ b/packages/api/src/admin/config.ts
@@ -16,9 +16,7 @@ import {
import {
logger,
getAtPath,
- getTenantId,
unsetAtPath,
- tenantStorage,
isPlainRecord,
isDotFreePath,
isSegmentPrefix,
@@ -64,7 +62,6 @@ import {
MAX_CONFIG_PATH_DEPTH,
getDefaultConfigPriority,
BASE_CONFIG_PRINCIPAL_ID,
- SYSTEM_TENANT_ID,
isConfigRevisionConflict,
ConfigRevisionConflictError,
isConfigOverrideStateEmpty,
@@ -177,6 +174,7 @@ import {
isWebSearchBindingPath,
getWebSearchReentryIssues,
} from './binding';
+import { getConfigPartition, getActivePartition, runInPartition } from './partition';
import { buildAdminConfigMeta, getCatalogModelsTtlMs } from './meta';
import { createAdminAuditEmitter, configTarget } from './audit';
import { DEFAULT_OVERRIDE_CACHE_TTL } from '~/app/service';
@@ -1452,21 +1450,6 @@ interface WriteScope {
activeTenantId: string | undefined;
}
-/** The tenant partition a stored document belongs to; `null` and `''` are tenantless. */
-function getConfigPartition(record: Pick<ConfigRecord, 'tenantId'>): string | undefined {
- return record.tenantId || undefined;
-}
-
-/**
- * The partition the config store reads and writes role documents in for this request
- * (`tenantPartition`): the active tenant's, or the deployment's own outside a tenant and under
- * the system context.
- */
-function getActivePartition(): string | undefined {
- const tenantId = getTenantId();
- return tenantId && tenantId !== SYSTEM_TENANT_ID ? tenantId : undefined;
-}
-
/**
* Why a planned unset or tombstone wrote nothing: no document to unset, no principal to create
* one for, or a stored credential it would send elsewhere without entering it again.
@@ -3061,11 +3044,9 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
* Base is read in that tenant's context; the partition rules themselves stay the store's.
*/
function readActiveBase(tenantId: string | undefined): Promise<ConfigRecord | null> {
- const read = () => findConfigByPrincipal(PrincipalType.ROLE, BASE_CONFIG_PRINCIPAL_ID);
- if (tenantId === getActivePartition()) {
- return read();
- }
- return tenantStorage.run({ ...tenantStorage.getStore(), tenantId }, read);
+ return runInPartition(tenantId, () =>
+ findConfigByPrincipal(PrincipalType.ROLE, BASE_CONFIG_PRINCIPAL_ID),
+ );
}
/**
diff --git a/packages/api/src/admin/meta.spec.ts b/packages/api/src/admin/meta.spec.ts
index 7945be46d0..6f67f9ad2b 100644
--- a/packages/api/src/admin/meta.spec.ts
+++ b/packages/api/src/admin/meta.spec.ts
@@ -1972,7 +1972,7 @@ const FEATURE_PROBES: Record<AdminConfigFeatureFlag, () => Promise<boolean>> = {
}),
hasCapability: async () => true,
resolveConfigLayers: service.resolveConfigLayers,
- findPartitionUser: async (id) => (id === 'member' ? { id, role: 'r1' } : null),
+ findPrincipalUser: async (id) => (id === 'member' ? { id, role: 'r1' } : null),
getUserPrincipals: async () => [{ principalType: PrincipalType.ROLE, principalId: 'r1' }],
getApplicableConfigs: async () => [role],
});
diff --git a/packages/api/src/admin/partition.spec.ts b/packages/api/src/admin/partition.spec.ts
new file mode 100644
index 0000000000..666ecf59d7
--- /dev/null
+++ b/packages/api/src/admin/partition.spec.ts
@@ -0,0 +1,41 @@
+import { getTenantId, tenantStorage, SYSTEM_TENANT_ID } from '@librechat/data-schemas';
+import { runInPartition } from './partition';
+
+/** The tenant context a read runs in. */
+const readContext = jest.fn(async () => getTenantId());
+
+const inContext = <T>(tenantId: string, run: () => Promise<T>): Promise<T> =>
+ tenantStorage.run({ tenantId }, run);
+
+beforeEach(() => {
+ readContext.mockClear();
+});
+
+describe('runInPartition', () => {
+ it("runs in the request's own context when that is the partition", async () => {
+ expect(await runInPartition(undefined, readContext)).toBeUndefined();
+ expect(await inContext('tenant-a', () => runInPartition('tenant-a', readContext))).toBe(
+ 'tenant-a',
+ );
+ expect(await inContext(SYSTEM_TENANT_ID, () => runInPartition(undefined, readContext))).toBe(
+ SYSTEM_TENANT_ID,
+ );
+ });
+
+ it('moves a read from outside a tenant into the tenant partition it names', async () => {
+ expect(await runInPartition('tenant-a', readContext)).toBe('tenant-a');
+ expect(await inContext(SYSTEM_TENANT_ID, () => runInPartition('tenant-a', readContext))).toBe(
+ 'tenant-a',
+ );
+ });
+
+ it('refuses to leave an active tenant, for the platform or another tenant, without reading', async () => {
+ await expect(
+ inContext('tenant-a', () => runInPartition(undefined, readContext)),
+ ).rejects.toThrow('cannot leave the active tenant partition');
+ await expect(
+ inContext('tenant-a', () => runInPartition('tenant-b', readContext)),
+ ).rejects.toThrow('cannot leave the active tenant partition');
+ expect(readContext).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/api/src/admin/partition.ts b/packages/api/src/admin/partition.ts
new file mode 100644
index 0000000000..47fdcebb82
--- /dev/null
+++ b/packages/api/src/admin/partition.ts
@@ -0,0 +1,50 @@
+import { getTenantId, tenantStorage, SYSTEM_TENANT_ID } from '@librechat/data-schemas';
+import type { ConfigRecord } from '@librechat/data-schemas';
+
+/**
+ * The tenant partitions the admin config API reads and judges in. The config store addresses
+ * role documents (whose ids are names every tenant reuses) in the active partition, and group
+ * and user documents by id, so an admin without a tenant reaches a tenant's group or user
+ * profile. Such a profile merges in its own tenant: librechat.yaml as that tenant resolves it,
+ * that tenant's `__base__`, and, for a user, that tenant's roles and groups. Reads and writes
+ * of it run there (`runInPartition`); the partition rules themselves stay the store's.
+ */
+
+/** The tenant partition a stored document belongs to; `null` and `''` are tenantless. */
+export function getConfigPartition(record: Pick<ConfigRecord, 'tenantId'>): string | undefined {
+ return record.tenantId || undefined;
+}
+
+/**
+ * The partition the config store reads and writes role documents in for this request
+ * (`tenantPartition`): the active tenant's, or the deployment's own outside a tenant and under
+ * the system context.
+ */
+export function getActivePartition(): string | undefined {
+ const tenantId = getTenantId();
+ return tenantId && tenantId !== SYSTEM_TENANT_ID ? tenantId : undefined;
+}
+
+/**
+ * Runs `read` in tenant partition `tenantId` (`undefined`: the deployment's own): in the
+ * request's own context when that is the partition, otherwise in that tenant's context, so every
+ * store read it makes lands there. Only a request outside a tenant moves: inside one, leaving it
+ * would read another tenant, or with `undefined` no tenant context at all, which the tenant plugin
+ * scopes to nothing outside strict mode, so that rejects. Capability checks never run inside it:
+ * they judge the caller, in the caller's own tenant.
+ */
+export function runInPartition<T>(
+ tenantId: string | undefined,
+ read: () => Promise<T>,
+): Promise<T> {
+ const active = getActivePartition();
+ if (tenantId === active) {
+ return read();
+ }
+ if (active !== undefined) {
+ return Promise.reject(
+ new Error('[runInPartition] A read cannot leave the active tenant partition'),
+ );
+ }
+ return tenantStorage.run({ ...tenantStorage.getStore(), tenantId }, read);
+}
diff --git a/packages/api/src/admin/resolved.integration.spec.ts b/packages/api/src/admin/resolved.integration.spec.ts
index 87f7d6bb2f..b31eb10be4 100644
--- a/packages/api/src/admin/resolved.integration.spec.ts
+++ b/packages/api/src/admin/resolved.integration.spec.ts
@@ -92,7 +92,7 @@ function readHandlers(extra: Partial<ReadDeps> = {}) {
hasCapability: async () => true,
resolveConfigLayers: service.resolveConfigLayers,
principalExists: methods.principalExists,
- findPartitionUser: methods.findPartitionUser,
+ findPrincipalUser: methods.findPrincipalUser,
getUserPrincipals: methods.getUserPrincipals,
getApplicableConfigs: methods.getApplicableConfigs,
...extra,
@@ -460,3 +460,194 @@ describe('GET /effective?userId=', () => {
expect((await getEffective(new mongoose.Types.ObjectId().toString())).statusCode).toBe(404);
});
});
+
+describe("a tenant's profile read by an admin without a tenant", () => {
+ const TENANT = 'tenant-a';
+ const inTenant = <T>(run: () => Promise<T>): Promise<T> =>
+ dataSchemas.tenantStorage.run({ tenantId: TENANT }, run);
+ /** librechat.yaml with a custom endpoint only tenant-a resolves. */
+ const TENANT_YAML: DeepPartial<TCustomConfig> = {
+ ...YAML,
+ endpoints: {
+ custom: [
+ ...(YAML.endpoints?.custom ?? []),
+ {
+ name: 'Regional',
+ tenantId: TENANT,
+ apiKey: 'regional-literal-key',
+ baseURL: 'https://regional.example.com/v1',
+ models: { default: ['regional-1'] },
+ } as NonNullable<NonNullable<TCustomConfig['endpoints']>['custom']>[number],
+ ],
+ },
+ };
+ let tenantService: AppConfigService;
+
+ beforeAll(async () => {
+ const { createAppConfigService } = await import('~/app/service');
+ const appConfig: AppConfig = await dataSchemas.AppService({
+ config: structuredClone(TENANT_YAML),
+ });
+ const store = new Map<string, unknown>();
+ tenantService = createAppConfigService({
+ loadBaseConfig: async () => structuredClone(appConfig),
+ setCachedTools: async () => undefined,
+ getCache: () => ({
+ get: async (key: string) => store.get(key),
+ set: async (key: string, value: unknown) => {
+ store.set(key, value);
+ },
+ delete: async (key: string) => store.delete(key),
+ opts: { store: { keys: () => store.keys() } },
+ }),
+ cacheKeys: { APP_CONFIG: 'app_config' },
+ getApplicableConfigs: methods.getApplicableConfigs,
+ getUserPrincipals: methods.getUserPrincipals,
+ });
+ });
+
+ const customNames = (tree: Partial<TCustomConfig>) =>
+ (tree.endpoints?.custom ?? []).map(({ name }) => name);
+
+ /** Base documents that tell the partitions apart, and a tenant-a user in a tenant-a group. */
+ async function seedPartitions(): Promise<{ groupId: string; userId: string }> {
+ await patch(ROLE, dataSchemas.BASE_CONFIG_PRINCIPAL_ID, [
+ { fieldPath: 'interface.customWelcome', value: 'Platform Base' },
+ { fieldPath: 'registration.socialLogins', value: ['platform'] },
+ ]);
+ await new mongoose.models.Role({ name: 'EDITOR' }).save();
+ await patch(ROLE, 'EDITOR', [{ fieldPath: 'interface.modelSelect', value: true }]);
+ return inTenant(async () => {
+ await patch(ROLE, dataSchemas.BASE_CONFIG_PRINCIPAL_ID, [
+ { fieldPath: 'interface.customWelcome', value: 'Tenant Base' },
+ ]);
+ await new mongoose.models.Role({ name: 'EDITOR' }).save();
+ await patch(ROLE, 'EDITOR', [{ fieldPath: 'interface.modelSelect', value: false }]);
+ const userId = await createUser('[email protected]', 'EDITOR');
+ const groupId = await createGroup('Tenant Engineering', [userId]);
+ await patch(PrincipalType.GROUP, groupId, [
+ { fieldPath: 'registration.socialLogins', value: ['tenant-group'] },
+ ]);
+ return { groupId, userId };
+ });
+ }
+
+ it("resolves a group profile on that tenant's librechat.yaml and Base, as its members get it", async () => {
+ const { groupId } = await seedPartitions();
+ const tenantBase = await inTenant(() =>
+ methods.findConfigByPrincipal(ROLE, dataSchemas.BASE_CONFIG_PRINCIPAL_ID),
+ );
+
+ const res = await getResolved(PrincipalType.GROUP, groupId, {
+ resolveConfigLayers: tenantService.resolveConfigLayers,
+ });
+ const body = res.body as AdminResolvedConfigResponse;
+
+ expect(res.statusCode).toBe(200);
+ expect(body.layers.map(({ principalType, revision }) => [principalType, revision])).toEqual([
+ [ROLE, tenantBase && dataSchemas.getConfigRevision(tenantBase)],
+ [PrincipalType.GROUP, expect.any(String)],
+ ]);
+ expect(body.resolved.interface?.customWelcome).toBe('Tenant Base');
+ expect(body.resolved.registration?.socialLogins).toEqual(['tenant-group']);
+ expect(customNames(body.yaml)).toEqual(['Gateway', 'Regional']);
+ expect(customNames(body.resolved)).toEqual(['Gateway', 'Regional']);
+
+ const served = await inTenant(() =>
+ tenantService.getAppConfig({
+ resolvedPrincipals: [{ principalType: PrincipalType.GROUP, principalId: groupId }],
+ bypassOverrideCache: true,
+ }),
+ );
+ expect(served.interfaceConfig?.customWelcome).toBe(body.resolved.interface?.customWelcome);
+ expect(served.registration?.socialLogins).toEqual(body.resolved.registration?.socialLogins);
+
+ /** Another tenant's admin still cannot read it. */
+ const other = await dataSchemas.tenantStorage.run({ tenantId: 'tenant-b' }, () =>
+ getResolved(
+ PrincipalType.GROUP,
+ groupId,
+ { resolveConfigLayers: tenantService.resolveConfigLayers },
+ { id: 'admin-b', role: 'ADMIN', tenantId: 'tenant-b' },
+ ),
+ );
+ expect(other.statusCode).toBe(404);
+ });
+
+ it("resolves a tenant's user over that tenant's role, groups and Base, as their requests do", async () => {
+ const { groupId, userId } = await seedPartitions();
+
+ const res = await getEffective(userId, {
+ resolveConfigLayers: tenantService.resolveConfigLayers,
+ });
+ const body = res.body as AdminEffectiveConfigResponse;
+
+ expect(res.statusCode).toBe(200);
+ expect(body.principals).toEqual(
+ expect.arrayContaining([
+ { principalType: ROLE, principalId: 'EDITOR' },
+ { principalType: PrincipalType.GROUP, principalId: groupId },
+ ]),
+ );
+ const tenantDocuments = await inTenant(() =>
+ methods.getApplicableConfigs([
+ { principalType: ROLE, principalId: 'EDITOR' },
+ { principalType: PrincipalType.GROUP, principalId: groupId },
+ ]),
+ );
+ expect(body.layers.map(({ revision }) => revision)).toEqual(
+ tenantDocuments.map(dataSchemas.getConfigRevision),
+ );
+ expect(body.resolved.interface?.customWelcome).toBe('Tenant Base');
+ expect(body.resolved.interface?.modelSelect).toBe(false);
+ expect(body.resolved.registration?.socialLogins).toEqual(['tenant-group']);
+ expect(customNames(body.yaml)).toEqual(['Gateway', 'Regional']);
+
+ const served = await inTenant(() =>
+ tenantService.getAppConfig({ role: 'EDITOR', userId, bypassOverrideCache: true }),
+ );
+ expect(served.interfaceConfig?.customWelcome).toBe(body.resolved.interface?.customWelcome);
+ expect(served.interfaceConfig?.modelSelect).toBe(body.resolved.interface?.modelSelect);
+ expect(served.registration?.socialLogins).toEqual(body.resolved.registration?.socialLogins);
+ });
+
+ it("lists the catalog of a group profile from that tenant's librechat.yaml and Base", async () => {
+ const { groupId } = await seedPartitions();
+ await patch(ROLE, dataSchemas.BASE_CONFIG_PRINCIPAL_ID, [
+ { fieldPath: 'mcpServers.platform-tools.url', value: 'https://platform.example.com/mcp' },
+ ]);
+ await inTenant(() =>
+ patch(ROLE, dataSchemas.BASE_CONFIG_PRINCIPAL_ID, [
+ { fieldPath: 'mcpServers.tenant-tools.url', value: 'https://tenant.example.com/mcp' },
+ ]),
+ );
+ const { createAdminConfigCatalogHandlers } = await import('./catalog');
+ const getAppConfig = jest.fn(tenantService.getAppConfig);
+ const handlers = createAdminConfigCatalogHandlers({
+ hasAnyConfigReadAccess: async () => true,
+ getReadableConfigSections: async () => ({
+ broad: false,
+ sections: new Set(['endpoints', 'mcpServers']),
+ }),
+ hasConfigCapability: async () => true,
+ getAppConfig,
+ getEndpointsConfig: async () => ({}),
+ loadDefaultModels: async () => ({}),
+ loadConfigModels: async () => ({}),
+ principalExists: methods.principalExists,
+ findConfigByPrincipal: methods.findConfigByPrincipal,
+ });
+ const res = mockRes();
+
+ await handlers.getConfigCatalog(
+ mockReq({ query: { principalType: PrincipalType.GROUP, principalId: groupId } }),
+ res,
+ );
+ const body = res.body as { endpoints?: Record<string, unknown>; mcpServers?: unknown[] };
+
+ expect(res.statusCode).toBe(200);
+ expect(getAppConfig).toHaveBeenCalledWith(expect.objectContaining({ tenantId: TENANT }));
+ expect(Object.keys(body.endpoints ?? {})).toEqual(expect.arrayContaining(['Regional']));
+ expect(body.mcpServers).toEqual([expect.objectContaining({ name: 'tenant-tools' })]);
+ });
+});
diff --git a/packages/api/src/admin/resolved.ts b/packages/api/src/admin/resolved.ts
index c184ffeae0..d85296a0db 100644
--- a/packages/api/src/admin/resolved.ts
+++ b/packages/api/src/admin/resolved.ts
@@ -34,6 +34,7 @@ import {
filterSectionsByReadAccess,
filterConfigDocForReadAccess,
} from './config';
+import { getConfigPartition, getActivePartition, runInPartition } from './partition';
import { redactConfigSecrets, redactResolvedConfigSecrets } from './secrets';
import { getSafeErrorMetadata } from '~/utils/errors';
@@ -62,17 +63,24 @@ export interface AdminConfigReadDeps {
resolveConfigLayers?: (options: ResolveConfigLayersOptions) => Promise<ResolvedConfigLayers>;
/** Whether the principal exists in the caller's tenant partition (`principalExists`). */
principalExists?: (principalType: PrincipalType, principalId: string) => Promise<boolean>;
- /** A user of the caller's tenant partition, with what principal resolution reads of them. */
- findPartitionUser?: (
- userId: string,
- ) => Promise<{ id: string; role?: string; idOnTheSource?: string | null } | null>;
- /** The principals a user resolves to: the user, their role and their groups. */
+ /**
+ * A user the caller addresses by id (`findPrincipalUser`), with what principal resolution reads
+ * of them and the tenant that holds them: inside a tenant only that tenant's users, outside one
+ * any tenant's, as group and user profiles are addressed.
+ */
+ findPrincipalUser?: (userId: string) => Promise<{
+ id: string;
+ role?: string;
+ idOnTheSource?: string | null;
+ tenantId?: string;
+ } | null>;
+ /** The principals a user resolves to in the active tenant: the user, their role and groups. */
getUserPrincipals?: (params: {
userId: string;
role?: string | null;
idOnTheSource?: string | null;
}) => Promise<ResolvedPrincipal[]>;
- /** Base and the principals' active documents, from the caller's tenant partition. */
+ /** Base and the principals' active documents, from the active tenant partition. */
getApplicableConfigs?: (
principals: Array<{ principalType: string; principalId?: string }>,
) => Promise<ConfigRecord[]>;
@@ -167,17 +175,33 @@ export function createAdminConfigReadHandlers(deps: AdminConfigReadDeps): {
hasCapability,
resolveConfigLayers,
principalExists,
- findPartitionUser,
+ findPrincipalUser,
getUserPrincipals,
getApplicableConfigs,
} = deps;
+ /** The Base document of one tenant partition, active or not; none for Base itself. */
+ function readBase(isBase: boolean, tenantId: string | undefined): Promise<ConfigRecord | null> {
+ if (isBase) {
+ return Promise.resolve(null);
+ }
+ return runInPartition(tenantId, () =>
+ findConfigByPrincipal(PrincipalType.ROLE, BASE_CONFIG_PRINCIPAL_ID, {
+ includeInactive: true,
+ }),
+ );
+ }
+
/**
* GET /resolved/:principalType/:principalId — what a profile resolves to over librechat.yaml
* and the Base document (Base alone for Base), in librechat.yaml shape, with each document and
* what the merge does not apply of it. The profile's other principals vary per user and are
* left out; `GET /effective` resolves a user. A principal with no document resolves to Base,
* unless it does not exist in the caller's tenant (404 `PRINCIPAL_NOT_FOUND`).
+ *
+ * It resolves in the partition the profile merges in, as writes judge it (`resolveWriteScope`):
+ * the caller's, or for a group or user profile a caller without a tenant reads from a tenant,
+ * that tenant's librechat.yaml and Base, read once the document names it.
*/
async function getResolvedConfig(req: ServerRequest, res: Response): Promise<Response> {
try {
@@ -200,12 +224,9 @@ export function createAdminConfigReadHandlers(deps: AdminConfigReadDeps): {
}
const isBase = isBaseConfigPrincipal({ principalType, principalId });
- const [base, target] = await Promise.all([
- isBase
- ? null
- : findConfigByPrincipal(PrincipalType.ROLE, BASE_CONFIG_PRINCIPAL_ID, {
- includeInactive: true,
- }),
+ const activePartition = getActivePartition();
+ const [activeBase, target] = await Promise.all([
+ readBase(isBase, activePartition),
findConfigByPrincipal(principalType, principalId, { includeInactive: true }),
]);
if (
@@ -216,9 +237,11 @@ export function createAdminConfigReadHandlers(deps: AdminConfigReadDeps): {
) {
return principalNotFoundResponse(res);
}
+ const partition = target ? getConfigPartition(target) : activePartition;
+ const base = partition === activePartition ? activeBase : await readBase(isBase, partition);
const records = [base, target].filter((record): record is ConfigRecord => record != null);
const resolution = await resolveConfigLayers({
- tenantId: user.tenantId,
+ tenantId: partition,
configs: records.filter((record) => record.isActive),
});
const body: AdminResolvedConfigResponse = {
@@ -236,8 +259,12 @@ export function createAdminConfigReadHandlers(deps: AdminConfigReadDeps): {
/**
* GET /effective?userId= — what one user's requests resolve to: Base, then the active profiles
* of their role, groups and their own, in merge order. Needs `read:users` and `read:groups`
- * besides config read access, since it shows the user's role and group memberships. A user who
- * is not in the caller's tenant answers 404 `USER_NOT_FOUND`.
+ * besides config read access, since it shows the user's role and group memberships. A user the
+ * caller cannot address answers 404 `USER_NOT_FOUND`: inside a tenant, one of another tenant.
+ *
+ * It resolves in the user's own tenant, as their requests do: their role and groups, that
+ * tenant's documents, librechat.yaml as it resolves it. Inside a tenant that is the caller's;
+ * a caller without a tenant reads a tenant's user there.
*/
async function getEffectiveConfig(req: ServerRequest, res: Response): Promise<Response> {
try {
@@ -259,30 +286,33 @@ export function createAdminConfigReadHandlers(deps: AdminConfigReadDeps): {
}
if (
!resolveConfigLayers ||
- !findPartitionUser ||
+ !findPrincipalUser ||
!getUserPrincipals ||
!getApplicableConfigs
) {
return res.status(501).json({ error: 'Effective config is not available' });
}
- const target = await findPartitionUser(userId);
+ const target = await findPrincipalUser(userId);
if (!target) {
return res.status(404).json({ error: 'User not found', code: 'USER_NOT_FOUND' });
}
- const principals = await getUserPrincipals({
- userId: target.id,
- role: target.role ?? null,
- idOnTheSource: target.idOnTheSource ?? null,
- });
- const named = principals.flatMap((principal) => {
- const id = toPrincipalId(principal);
- return id == null
- ? []
- : [{ principalType: principal.principalType as PrincipalType, principalId: id }];
+ const partition = getConfigPartition(target);
+ const { named, records } = await runInPartition(partition, async () => {
+ const principals = await getUserPrincipals({
+ userId: target.id,
+ role: target.role ?? null,
+ idOnTheSource: target.idOnTheSource ?? null,
+ });
+ const resolvedNamed = principals.flatMap((principal) => {
+ const id = toPrincipalId(principal);
+ return id == null
+ ? []
+ : [{ principalType: principal.principalType as PrincipalType, principalId: id }];
+ });
+ return { named: resolvedNamed, records: await getApplicableConfigs(resolvedNamed) };
});
- const records = await getApplicableConfigs(named);
- const resolution = await resolveConfigLayers({ tenantId: user.tenantId, configs: records });
+ const resolution = await resolveConfigLayers({ tenantId: partition, configs: records });
const body: AdminEffectiveConfigResponse = {
userId: target.id,
principals: named,
diff --git a/packages/api/src/admin/roles.rename.spec.ts b/packages/api/src/admin/roles.rename.spec.ts
index 1fb65fb5c7..0ebcb7beef 100644
--- a/packages/api/src/admin/roles.rename.spec.ts
+++ b/packages/api/src/admin/roles.rename.spec.ts
@@ -86,7 +86,7 @@ function createHandlers(overrides: Partial<AdminRolesDeps> = {}) {
return createAdminRolesHandlers({
listRoles: methods.listRoles,
countRoles: methods.countRoles,
- getRoleByName: methods.getRoleByName,
+ getRoleByName: methods.getPartitionRole,
createRoleByName: methods.createRoleByName,
updateRoleByName: methods.updateRoleByName,
updateAccessPermissions: methods.updateAccessPermissions,
@@ -99,9 +99,7 @@ function createHandlers(overrides: Partial<AdminRolesDeps> = {}) {
listUsersByRole: methods.listUsersByRole,
countUsersByRole: methods.countUsersByRole,
deleteConfig: methods.deleteConfig,
- deleteAclEntries: async (filter) => {
- await methods.deleteAclEntries(filter);
- },
+ deleteAclEntries: methods.deletePrincipalAclEntries,
deleteGrantsForPrincipal: methods.deleteGrantsForPrincipal,
restoreConfig: methods.restoreConfig,
findConfigByPrincipal: methods.findConfigByPrincipal,
@@ -195,14 +193,22 @@ async function seedRole(name: string, description = 'Writes things') {
return { userId: userId.toString(), resourceId };
}
-/** Everything keyed by `name`: its role document, members, profile, grants and ACL entries. */
+/**
+ * Everything keyed by `name` in the active tenant partition (platform-level outside a tenant):
+ * its role document, members, profile, grants and ACL entries.
+ */
async function keyedBy(name: string) {
+ const tenantId = dataSchemas.getTenantId();
const [role, members, profile, grants, aclEntries] = await Promise.all([
- methods.getRoleByName(name),
+ methods.getPartitionRole(name),
methods.findUserIdsByRole(name),
methods.findConfigByPrincipal(PrincipalType.ROLE, name, { includeInactive: true }),
- methods.findGrantsForPrincipal(PrincipalType.ROLE, name),
- mongoose.models.AclEntry.find({ principalType: PrincipalType.ROLE, principalId: name })
+ methods.findGrantsForPrincipal(PrincipalType.ROLE, name, { tenantId }),
+ mongoose.models.AclEntry.find({
+ principalType: PrincipalType.ROLE,
+ principalId: name,
+ tenantId: tenantId ?? { $in: [null, ''] },
+ })
.select('resourceId')
.lean<Array<{ resourceId: Types.ObjectId }>>(),
]);
@@ -694,6 +700,189 @@ describe('role rename without a tenant', () => {
});
});
+describe('role operations without a tenant keep to the platform role', () => {
+ /** A tenant-a role of `name` with one member, created in that tenant. */
+ async function seedTenantRole(name: string, description: string): Promise<string> {
+ return inTenant('tenant-a', async () => {
+ await methods.createRoleByName({ name, description, permissions: {} });
+ const userId = await methods.createUser(
+ { email: `tenant-${name}@example.com`, name, provider: 'local', role: name },
+ undefined,
+ true,
+ );
+ await setWelcome(name, `tenant ${name}`);
+ await methods.grantCapability({
+ principalType: PrincipalType.ROLE,
+ principalId: name,
+ capability: dataSchemas.SystemCapabilities.READ_CONFIGS,
+ tenantId: 'tenant-a',
+ });
+ await methods.grantPermission(
+ PrincipalType.ROLE,
+ name,
+ ResourceType.AGENT,
+ new Types.ObjectId(),
+ PermissionBits.VIEW,
+ );
+ return userId.toString();
+ });
+ }
+
+ /** What tenant-a holds for `name`, read in that tenant. */
+ const tenantKeyedBy = (name: string) => inTenant('tenant-a', () => keyedBy(name));
+
+ async function remove(name: string, tenantId?: string): Promise<MockRes> {
+ const res = mockRes();
+ const req = {
+ params: { name },
+ body: {},
+ query: {},
+ user: { _id: new Types.ObjectId(), id: 'admin', role: 'ADMIN', tenantId },
+ } as Partial<ServerRequest> as ServerRequest;
+ const run = () => createHandlers().deleteRole(req, res);
+ await (tenantId ? inTenant(tenantId, run) : run());
+ return res;
+ }
+
+ it("migrates and renames only the platform role and its members, never a tenant's role", async () => {
+ const { userId } = await seedRole('editor');
+ const tenantUserId = await seedTenantRole('editor', 'Tenant editors');
+ const tenantBefore = await tenantKeyedBy('editor');
+
+ const res = await rename(createHandlers(), 'editor', { name: 'writer', description: 'New' });
+
+ expect(res.statusCode).toBe(200);
+ expect(await keyedBy('writer')).toMatchObject({
+ role: { name: 'writer', description: 'New' },
+ members: [userId],
+ });
+ expect(tenantBefore.members).toEqual([tenantUserId]);
+ expect(await tenantKeyedBy('editor')).toEqual(tenantBefore);
+ expect(await inTenant('tenant-a', () => keyedBy('writer'))).toEqual(nothing);
+ });
+
+ it("serves a platform role created or renamed after a tenant's role of its name to the platform's permission checks", async () => {
+ await seedTenantRole('editor', 'Tenant editors');
+ await seedTenantRole('tenant-only', 'Tenant only');
+ await seedRole('writer');
+ const params: Record<string, string> = {};
+ const body: Record<string, unknown> = { name: 'editor', description: 'Platform editors' };
+ const created = mockRes();
+ await createHandlers().createRole(
+ {
+ params,
+ body,
+ query: {},
+ user: { _id: new Types.ObjectId(), id: 'admin', role: 'ADMIN' },
+ } as Partial<ServerRequest> as ServerRequest,
+ created,
+ );
+ const renamed = await rename(createHandlers(), 'writer', { name: 'tenant-only' });
+ /** `getRoleByName` as every request's permission checks read it, with no cached role. */
+ const served = async (name: string) => (await methods.getRoleByName(name))?.description;
+
+ expect(created.statusCode).toBe(201);
+ expect(renamed.statusCode).toBe(200);
+ expect(await served('editor')).toBe('Platform editors');
+ expect(await served('tenant-only')).toBe('Writes things');
+ expect(await inTenant('tenant-a', () => served('editor'))).toBe('Tenant editors');
+ expect(await inTenant('tenant-a', () => served('tenant-only'))).toBe('Tenant only');
+ });
+
+ it('answers 404 for a role only a tenant holds, renaming nothing in that tenant', async () => {
+ await seedTenantRole('tenant-editor', 'Tenant only');
+ const before = await tenantKeyedBy('tenant-editor');
+
+ const res = await rename(createHandlers(), 'tenant-editor', { name: 'renamed' });
+
+ expect(res.statusCode).toBe(404);
+ expect(await tenantKeyedBy('tenant-editor')).toEqual(before);
+ expect(await inTenant('tenant-a', () => keyedBy('renamed'))).toEqual(nothing);
+ });
+
+ it("deletes only the platform role and what it holds, never a tenant role's members, grants or ACL entries", async () => {
+ await seedRole('editor');
+ await seedTenantRole('editor', 'Tenant editors');
+ const tenantBefore = await tenantKeyedBy('editor');
+
+ const res = await remove('editor');
+
+ expect(res.statusCode).toBe(200);
+ expect(await keyedBy('editor')).toEqual(nothing);
+ expect(await tenantKeyedBy('editor')).toEqual(tenantBefore);
+ expect(tenantBefore).toMatchObject({
+ role: { name: 'editor', description: 'Tenant editors' },
+ grants: [dataSchemas.SystemCapabilities.READ_CONFIGS],
+ aclEntries: [expect.any(String)],
+ });
+ });
+
+ it('answers 404 for a deletion of a role only a tenant holds, removing nothing there', async () => {
+ await seedTenantRole('tenant-editor', 'Tenant only');
+ const before = await tenantKeyedBy('tenant-editor');
+
+ const res = await remove('tenant-editor');
+
+ expect(res.statusCode).toBe(404);
+ expect(await tenantKeyedBy('tenant-editor')).toEqual(before);
+ });
+
+ it("lists, adds and removes only the platform's users as the platform role's members", async () => {
+ const { userId } = await seedRole('editor');
+ const tenantMember = await seedTenantRole('editor', 'Tenant editors');
+ const tenantUser = await inTenant('tenant-a', async () =>
+ (
+ await methods.createUser(
+ { email: '[email protected]', name: 'tu', provider: 'local', role: 'USER' },
+ undefined,
+ true,
+ )
+ ).toString(),
+ );
+ const handlers = createHandlers();
+ const call = async (
+ handler: 'getRoleMembers' | 'addRoleMember' | 'removeRoleMember',
+ params: Record<string, string>,
+ body: Record<string, unknown> = {},
+ ): Promise<MockRes> => {
+ const res = mockRes();
+ const req = {
+ params,
+ body,
+ query: {},
+ user: { _id: new Types.ObjectId(), id: 'admin', role: 'ADMIN' },
+ } as Partial<ServerRequest> as ServerRequest;
+ await handlers[handler](req, res);
+ return res;
+ };
+ const roleOf = async (id: string) =>
+ (await mongoose.models.User.collection.findOne({ _id: new Types.ObjectId(id) }))?.role;
+
+ const members = await call('getRoleMembers', { name: 'editor' });
+ const added = await call('addRoleMember', { name: 'editor' }, { userId: tenantUser });
+ const removed = await call('removeRoleMember', { name: 'editor', userId: tenantMember });
+
+ expect(members.statusCode).toBe(200);
+ expect(members.body).toMatchObject({ members: [{ userId }], total: 1 });
+ expect(added.statusCode).toBe(404);
+ expect(removed.statusCode).toBe(404);
+ expect(await roleOf(tenantUser)).toBe('USER');
+ expect(await roleOf(tenantMember)).toBe('editor');
+ });
+
+ it("deletes only the active tenant's role inside it, leaving the platform role", async () => {
+ await seedRole('editor');
+ await seedTenantRole('editor', 'Tenant editors');
+ const platformBefore = await keyedBy('editor');
+
+ const res = await remove('editor', 'tenant-a');
+
+ expect(res.statusCode).toBe(200);
+ expect(await tenantKeyedBy('editor')).toEqual(nothing);
+ expect(await keyedBy('editor')).toEqual(platformBefore);
+ });
+});
+
describe('role rename inside a tenant', () => {
it("moves only that tenant's profile, never the platform role's of the same name", async () => {
await seedRole('editor');
diff --git a/packages/api/src/admin/roles.spec.ts b/packages/api/src/admin/roles.spec.ts
index e3e77c088e..13f4359d1c 100644
--- a/packages/api/src/admin/roles.spec.ts
+++ b/packages/api/src/admin/roles.spec.ts
@@ -442,8 +442,9 @@ describe('createAdminRolesHandlers', () => {
describe('updateRole', () => {
it('updates role and returns 200', async () => {
const role = mockRole({ name: 'senior-editor' });
+ const existing = mockRole({ _id: new Types.ObjectId() } as Partial<IRole>);
const deps = createDeps({
- getRoleByName: jest.fn().mockResolvedValueOnce(mockRole()).mockResolvedValueOnce(null),
+ getRoleByName: jest.fn().mockResolvedValueOnce(existing).mockResolvedValueOnce(null),
updateRoleByName: jest.fn().mockResolvedValue(role),
});
const handlers = createAdminRolesHandlers(deps);
@@ -456,7 +457,12 @@ describe('createAdminRolesHandlers', () => {
expect(status).toHaveBeenCalledWith(200);
expect(json).toHaveBeenCalledWith({ role });
- expect(deps.updateRoleByName).toHaveBeenCalledWith('editor', { name: 'senior-editor' });
+ /** The rename writes the role document it read, not another tenant's of that name. */
+ expect(deps.updateRoleByName).toHaveBeenCalledWith(
+ 'editor',
+ { name: 'senior-editor' },
+ { id: String(existing._id) },
+ );
});
it('writes and audits nothing when the description already matches', async () => {
@@ -493,7 +499,7 @@ describe('createAdminRolesHandlers', () => {
await handlers.updateRole(req, res);
- expect(deps.updateRoleByName).toHaveBeenCalledWith('editor', { name: 'trimmed' });
+ expect(deps.updateRoleByName).toHaveBeenCalledWith('editor', { name: 'trimmed' }, undefined);
});
it('migrates users before renaming role', async () => {
@@ -579,10 +585,11 @@ describe('createAdminRolesHandlers', () => {
expect(status).toHaveBeenCalledWith(200);
expect(json).toHaveBeenCalledWith({ role });
expect(deps.updateUsersByRole).toHaveBeenCalledWith('editor', 'senior-editor');
- expect(deps.updateRoleByName).toHaveBeenCalledWith('editor', {
- name: 'senior-editor',
- description: 'Updated desc',
- });
+ expect(deps.updateRoleByName).toHaveBeenCalledWith(
+ 'editor',
+ { name: 'senior-editor', description: 'Updated desc' },
+ undefined,
+ );
});
it('returns 403 when renaming a system role', async () => {
@@ -1400,8 +1407,7 @@ describe('createAdminRolesHandlers', () => {
it('scopes each cascade audit entry to the removed grant’s own tenant', async () => {
const recordAuditEntry = jest.fn().mockResolvedValue(undefined);
const deps = deleteDeps({
- // a platform admin (no tenantId) deletes a role holding both a
- // platform-level grant and a tenant-scoped one
+ // each removed grant names its own scope, whatever the caller's
deleteGrantsForPrincipal: jest
.fn()
.mockResolvedValue([
diff --git a/packages/api/src/admin/roles.ts b/packages/api/src/admin/roles.ts
index f49f506207..94a2fd39d1 100644
--- a/packages/api/src/admin/roles.ts
+++ b/packages/api/src/admin/roles.ts
@@ -24,6 +24,7 @@ import type { CascadeStep } from './cascade';
import { createAdminAuditEmitter, diffRolePermissions, configTarget } from './audit';
import { cascadeStep, runCascade, invalidatingConfigStore } from './cascade';
import { getSafeErrorMetadata } from '~/utils/errors';
+import { getActivePartition } from './partition';
import { parsePagination } from './pagination';
const systemRoleValues = new Set<string>(Object.values(SystemRoles));
@@ -119,19 +120,37 @@ interface RoleMemberParams extends RoleNameParams {
export type RoleListItem = { _id: Types.ObjectId | string; name: string; description?: string };
+/**
+ * Role ids are names every tenant reuses, so every role operation here addresses the role of the
+ * caller's tenant partition and what it holds there (members, profile, grants and ACL entries):
+ * the active tenant's, or for an admin without a tenant only the platform-level ones, never each
+ * tenant's own role of the same name. The routes wire the data-schemas methods that keep to that
+ * partition, and a member added or removed by id must be a user of it too.
+ */
export interface AdminRolesDeps {
+ /** The roles of the caller's tenant partition (`listRoles`). */
listRoles: (options?: { limit?: number; offset?: number }) => Promise<RoleListItem[]>;
countRoles: () => Promise<number>;
+ /**
+ * The role of exactly this name in the caller's tenant partition, read as stored
+ * (`getPartitionRole`); a missing system role is created there.
+ */
getRoleByName: (name: string, fields?: string | string[] | null) => Promise<IRole | null>;
createRoleByName: (roleData: Partial<IRole>) => Promise<IRole>;
- updateRoleByName: (name: string, updates: Partial<IRole>) => Promise<IRole | null>;
+ /** With `options.id`, updates only the role document with that `_id`. */
+ updateRoleByName: (
+ name: string,
+ updates: Partial<IRole>,
+ options?: { id?: string },
+ ) => Promise<IRole | null>;
updateAccessPermissions: (
name: string,
perms: Record<string, Record<string, boolean>>,
roleData?: IRole,
) => Promise<void>;
/** With `options.id`, deletes only the role that still has that `_id`, so a role recreated
- * under the same name is never removed by a request that targeted the original. */
+ * under the same name is never removed by a request that targeted the original. Reassigns the
+ * role's members in the caller's partition to USER. */
deleteRoleByName: (name: string, options?: { id?: string }) => Promise<IRole | null>;
findUser: (
criteria: FilterQuery<IUser>,
@@ -143,7 +162,9 @@ export interface AdminRolesDeps {
data: Partial<IUser>,
expectedState?: Record<string, unknown>,
) => Promise<IUser | null>;
+ /** Moves the role's members in the caller's partition to `newRole` (a rename's migration). */
updateUsersByRole: (oldRole: string, newRole: string) => Promise<void>;
+ /** The ids of the role's members in the caller's partition. */
findUserIdsByRole: (roleName: string) => Promise<string[]>;
/** With `fromRole`, only users whose role is still that one change. */
updateUsersRoleByIds: (
@@ -161,15 +182,16 @@ export interface AdminRolesDeps {
principalType: PrincipalType,
principalId: string | Types.ObjectId,
) => Promise<ConfigRecord | null>;
- /** Removes all ACL entries scoped to this principal. */
+ /** Removes the role's ACL entries in the caller's partition (`deletePrincipalAclEntries`). */
deleteAclEntries: (filter: {
principalType: PrincipalType;
principalId: string | Types.ObjectId;
}) => Promise<void>;
/** Drops cached prompt group access IDs; role deletion can remove PROMPTGROUP grants. */
invalidatePromptGroupAccessContext?: () => Promise<void>;
- /** Removes all system capability grants held by this principal and returns
- * the removed grants so each can be audited. */
+ /** Removes the system capability grants this principal holds in one scope (exactly
+ * `tenantId`, or platform-level ones without it) and returns the removed grants so each can be
+ * audited. */
deleteGrantsForPrincipal: (
principalType: PrincipalType,
principalId: string | Types.ObjectId,
@@ -258,6 +280,20 @@ function roleTarget(name: string) {
return { type: 'role', id: name, name };
}
+/**
+ * Whether a user belongs to the caller's tenant partition, the one a role name addresses. Outside
+ * a tenant a user is found by id in any tenant, but a tenant user's `role` names that tenant's own
+ * role, so the platform role's member routes never change it.
+ */
+function isPartitionUser(user: Pick<IUser, 'tenantId'>): boolean {
+ return (user.tenantId || undefined) === getActivePartition();
+}
+
+/** The document a role was read as, so a write changes that role and no other of its name. */
+function roleIdentity(role: Pick<IRole, '_id'>): { id: string } | undefined {
+ return role._id != null ? { id: String(role._id) } : undefined;
+}
+
/** What a role rename moved to the new name along with the role. */
interface RoleDependentsMoved {
/** The profile as the new name now holds it; `null` when the role had none. */
@@ -358,9 +394,8 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
severity: 'warning',
target: { type: PrincipalType.ROLE, id: roleName, name: roleName },
metadata: { capability: grant.capability },
- /** Scope each entry to the removed grant's own tenant: a platform
- * admin's role deletion can remove tenant-scoped grants, and those
- * removals must land in the affected tenant's chain, not the caller's. */
+ /** Scope each entry to the removed grant's own tenant, so a removal
+ * always lands in the chain of the tenant whose grant it was. */
tenantId: grant.tenantId,
});
}
@@ -479,7 +514,7 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
}
}
try {
- await updateRoleByName(newName, revert);
+ await updateRoleByName(newName, revert, roleIdentity(existing));
} catch (revertError) {
logger.error(
`[adminRoles] CRITICAL: rename rollback failed — role "${currentName}" is still named "${newName}"`,
@@ -649,7 +684,7 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
let role: IRole | null;
try {
const updates: Partial<IRole> = { name: newName, ...extraUpdates };
- role = await updateRoleByName(currentName, updates);
+ role = await updateRoleByName(currentName, updates, roleIdentity(existing));
} catch (error) {
await rollbackMigratedUsers(migratedIds, currentName, newName);
throw error;
@@ -760,7 +795,7 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
return res.status(200).json({ role });
}
- const role = await updateRoleByName(name, updates);
+ const role = await updateRoleByName(name, updates, roleIdentity(existing));
if (!role) {
return res.status(404).json({ error: 'Role not found' });
}
@@ -780,10 +815,8 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
}
/**
- * The re-fetch via `getRoleByName` after `updateAccessPermissions` depends on the
- * callee having written the updated document to the role cache. If the cache layer
- * is refactored to stop writing from within `updateAccessPermissions`, this handler
- * must be updated to perform an explicit uncached DB read.
+ * The re-fetch via `getRoleByName` after `updateAccessPermissions` reads the role as
+ * stored (`getPartitionRole` reads no cache), so it returns what the update wrote.
*/
async function updateRolePermissionsHandler(req: ServerRequest, res: Response) {
try {
@@ -1113,7 +1146,7 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
}
const user = await findUser({ _id: userId });
- if (!user) {
+ if (!user || !isPartitionUser(user)) {
return res.status(404).json({ error: 'User not found' });
}
@@ -1200,7 +1233,7 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
}
const user = await findUser({ _id: userId });
- if (!user) {
+ if (!user || !isPartitionUser(user)) {
return res.status(404).json({ error: 'User not found' });
}
diff --git a/packages/data-schemas/src/app/changes.spec.ts b/packages/data-schemas/src/app/changes.spec.ts
index c715dd1564..2e6e3c1903 100644
--- a/packages/data-schemas/src/app/changes.spec.ts
+++ b/packages/data-schemas/src/app/changes.spec.ts
@@ -414,6 +414,25 @@ describe('applyConfigChange: rename', () => {
);
});
+ it.each([
+ ['an unsafe name', '$where'],
+ ['a reserved name', '__proto__'],
+ ['a name past the length limit', 'k'.repeat(257)],
+ ])(
+ 'refuses %s for an entry of a collection merged by key, as the admin route does',
+ (_label, to) => {
+ const stored = deepFreeze(
+ state({ endpoints: { custom: [endpoint('a')] } }, ['endpoints.custom["a"].headers.X']),
+ );
+
+ const refused = errorOf(() =>
+ applyConfigChange(stored, { op: 'rename', segments: CUSTOM, from: 'a', to }),
+ );
+
+ expect(isConfigEntryError(refused) && refused.reason).toBe('invalid_entry');
+ },
+ );
+
it('lets a renamed entry be edited by its new name later in the same batch', () => {
const { state: next, changed } = applyConfigChanges(
state({ endpoints: { custom: [endpoint('old', { apiKey: 'v3:cipher' })] } }),
diff --git a/packages/data-schemas/src/app/changes.ts b/packages/data-schemas/src/app/changes.ts
index 9e93ea28ee..6cafe2025c 100644
--- a/packages/data-schemas/src/app/changes.ts
+++ b/packages/data-schemas/src/app/changes.ts
@@ -9,12 +9,6 @@ import {
getWriteClearedTombstones,
renameConfigEntryTombstones,
} from './mutations';
-import {
- getConfigEntryIdentity,
- getConfigArrayMergeKey,
- isConfigEntryTombstone,
- getConfigTombstoneSegments,
-} from './collections';
import {
getAtPath,
setAtPath,
@@ -22,8 +16,15 @@ import {
isPlainRecord,
ConfigPathError,
isSegmentPrefix,
+ isConfigEntryKey,
pruneEmptyAncestors,
} from './paths';
+import {
+ getConfigEntryIdentity,
+ getConfigArrayMergeKey,
+ isConfigEntryTombstone,
+ getConfigTombstoneSegments,
+} from './collections';
import { combineFoldedConfigEntries } from './resolution';
/**
@@ -366,9 +367,13 @@ function applyRename(
throw new ConfigEntryError([...segments], 'invalid_entry');
}
const keyField = getConfigArrayMergeKey(segments);
- return keyField
- ? renameKeyedEntry(state, segments, keyField, from, to)
- : renameRecordKey(state, segments, from, to);
+ if (!keyField) {
+ return renameRecordKey(state, segments, from, to);
+ }
+ if (!isConfigEntryKey(to)) {
+ throw new ConfigEntryError([...segments], 'invalid_entry');
+ }
+ return renameKeyedEntry(state, segments, keyField, from, to);
}
/**
diff --git a/packages/data-schemas/src/app/mutations.spec.ts b/packages/data-schemas/src/app/mutations.spec.ts
index 9b39dbfabf..ef2afe387b 100644
--- a/packages/data-schemas/src/app/mutations.spec.ts
+++ b/packages/data-schemas/src/app/mutations.spec.ts
@@ -391,4 +391,28 @@ describe('keyed locations: entries of an array merged by key', () => {
renameConfigEntriesTombstones(input, [{ segments: CUSTOM, from: 'ollama', to: 'new' }]),
).toEqual(moved);
});
+
+ it.each([
+ ['an unsafe new name', CUSTOM, '$where'],
+ ['a reserved new name', CUSTOM, 'constructor'],
+ ['a new name past the length limit', CUSTOM, 'k'.repeat(257)],
+ ['a record rather than an array merged by key', ['mcpServers'], 'new'],
+ ])('refuses %s instead of moving tombstones no path can address', (_label, segments, to) => {
+ const input = state({}, ['endpoints.custom["old"].headers.A']);
+ const refused = (run: () => unknown) => {
+ try {
+ run();
+ } catch (caught) {
+ return isConfigPathError(caught) && caught.reason;
+ }
+ return 'applied';
+ };
+
+ expect(refused(() => renameConfigEntryTombstones(input, segments, 'old', to))).toBe(
+ 'keyed_path',
+ );
+ expect(
+ refused(() => renameConfigEntriesTombstones(input, [{ segments, from: 'old', to }])),
+ ).toBe('keyed_path');
+ });
});
diff --git a/packages/data-schemas/src/app/mutations.ts b/packages/data-schemas/src/app/mutations.ts
index 67ba2f989a..5c09d610c8 100644
--- a/packages/data-schemas/src/app/mutations.ts
+++ b/packages/data-schemas/src/app/mutations.ts
@@ -314,7 +314,10 @@ export function renameConfigEntriesTombstones(
* Moves the keyed tombstones of entry `from` of the merged-by-key array at `segments` to entry
* `to`, as a rename of the principal's own entry carries what it hides: each keeps its path
* inside the entry. The tombstone that hides `to` whole goes, since the principal's own entry
- * now has that key, and a moved tombstone that `to` already has is kept once.
+ * now has that key, and a moved tombstone that `to` already has is kept once. A `to` no keyed
+ * path can address (`isConfigEntryKey`), or `segments` that are not an array merged by key,
+ * throw a `ConfigPathError` (`requireEntryLocation`), as the admin routes refuse such a rename:
+ * a moved tombstone would name a path no read or removal can address.
*/
export function renameConfigEntryTombstones(
state: ConfigOverrideState,
@@ -322,6 +325,7 @@ export function renameConfigEntryTombstones(
from: string,
to: string,
): ConfigOverrideState {
+ requireEntryLocation({ segments, entry: { key: to, rest: [] } });
const fromIdentity = getConfigEntryIdentity(segments, from);
const tombstones: string[] = [];
let changed = false;
diff --git a/packages/data-schemas/src/methods/aclEntry.spec.ts b/packages/data-schemas/src/methods/aclEntry.spec.ts
index 71ce1b9f78..33b797391d 100644
--- a/packages/data-schemas/src/methods/aclEntry.spec.ts
+++ b/packages/data-schemas/src/methods/aclEntry.spec.ts
@@ -964,6 +964,65 @@ describe('AclEntry Model Tests', () => {
});
});
+ describe('deletePrincipalAclEntries', () => {
+ const grantTo = (principalType: PrincipalType, principalId: string | mongoose.Types.ObjectId) =>
+ methods.grantPermission(
+ principalType,
+ principalId,
+ ResourceType.AGENT,
+ new mongoose.Types.ObjectId(),
+ PermissionBits.VIEW,
+ grantedById,
+ );
+ const remainingIds = async () =>
+ (await AclEntry.find({}).select('_id').lean()).map(({ _id }) => _id.toString()).sort();
+
+ it("removes a role's platform-level entries outside a tenant, never a tenant role's of that name", async () => {
+ await grantTo(PrincipalType.ROLE, 'editor');
+ const unclaimed = await grantTo(PrincipalType.ROLE, 'editor');
+ const tenant = await grantTo(PrincipalType.ROLE, 'editor');
+ const other = await grantTo(PrincipalType.ROLE, 'other');
+ await AclEntry.collection.updateOne({ _id: unclaimed?._id }, { $set: { tenantId: '' } });
+ await AclEntry.collection.updateOne({ _id: tenant?._id }, { $set: { tenantId: 'tenant-a' } });
+
+ await methods.deletePrincipalAclEntries({
+ principalType: PrincipalType.ROLE,
+ principalId: 'editor',
+ });
+
+ expect(await remainingIds()).toEqual([tenant?._id.toString(), other?._id.toString()].sort());
+ });
+
+ it("removes only the active tenant's role entries inside it", async () => {
+ const platform = await grantTo(PrincipalType.ROLE, 'editor');
+ const tenant = await grantTo(PrincipalType.ROLE, 'editor');
+ await AclEntry.collection.updateOne({ _id: tenant?._id }, { $set: { tenantId: 'tenant-a' } });
+
+ await tenantStorage.run({ tenantId: 'tenant-a' }, () =>
+ methods.deletePrincipalAclEntries({
+ principalType: PrincipalType.ROLE,
+ principalId: 'editor',
+ }),
+ );
+
+ expect(await remainingIds()).toEqual([platform?._id.toString()]);
+ });
+
+ it('removes a group principal entries by id, whichever tenant holds them', async () => {
+ const groupId = new mongoose.Types.ObjectId();
+ const tenant = await grantTo(PrincipalType.GROUP, groupId);
+ const other = await grantTo(PrincipalType.GROUP, new mongoose.Types.ObjectId());
+ await AclEntry.collection.updateOne({ _id: tenant?._id }, { $set: { tenantId: 'tenant-a' } });
+
+ await methods.deletePrincipalAclEntries({
+ principalType: PrincipalType.GROUP,
+ principalId: groupId,
+ });
+
+ expect(await remainingIds()).toEqual([other?._id.toString()]);
+ });
+ });
+
describe('moveAclEntriesToPrincipal', () => {
const grantToRole = (roleName: string, bits: number) =>
methods.grantPermission(
diff --git a/packages/data-schemas/src/methods/aclEntry.ts b/packages/data-schemas/src/methods/aclEntry.ts
index b379d1b018..6efb23cf60 100644
--- a/packages/data-schemas/src/methods/aclEntry.ts
+++ b/packages/data-schemas/src/methods/aclEntry.ts
@@ -191,6 +191,10 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): {
filter: Record<string, unknown>,
options?: { session?: ClientSession },
) => Promise<DeleteResult>;
+ deletePrincipalAclEntries: (principal: {
+ principalType: PrincipalType;
+ principalId: string | Types.ObjectId;
+ }) => Promise<void>;
moveAclEntriesToPrincipal: (
principalType: PrincipalType,
fromPrincipalId: string,
@@ -552,6 +556,27 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): {
return AclEntry.deleteMany(filter, options || {});
}
+ /**
+ * Removes every ACL entry a principal holds, as the principal's deletion does. A role is keyed
+ * by a name every tenant reuses, so only its entries in the caller's tenant partition
+ * (`tenantPartitionFilter`) go: that tenant's, or without a tenant only platform-level ones,
+ * never those of each tenant's own role that shares the name (as `moveAclEntriesToPrincipal`
+ * moves them on a rename). A group or user is addressed by id, passed as stored (an ObjectId).
+ */
+ async function deletePrincipalAclEntries(principal: {
+ principalType: PrincipalType;
+ principalId: string | Types.ObjectId;
+ }): Promise<void> {
+ const AclEntry = mongoose.models.AclEntry as Model<IAclEntry>;
+ const { principalType, principalId } = principal;
+ await AclEntry.deleteMany({
+ principalType,
+ principalId,
+ ...(principalType === PrincipalType.ROLE &&
+ tenantPartitionFilter('deletePrincipalAclEntries')),
+ });
+ }
+
/**
* Re-keys a role principal's entries to another name (a role rename) and returns the ids it
* moved; with `ids`, moves only those (how a caller undoes a move). Entries keep their
@@ -892,6 +917,7 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): {
modifyPermissionBits,
findAccessibleResources,
deleteAclEntries,
+ deletePrincipalAclEntries,
replaceRoleBits,
bulkWriteAclEntries,
findPublicResourceIds,
diff --git a/packages/data-schemas/src/methods/principal.spec.ts b/packages/data-schemas/src/methods/principal.spec.ts
index ee043796ea..49baa51a1f 100644
--- a/packages/data-schemas/src/methods/principal.spec.ts
+++ b/packages/data-schemas/src/methods/principal.spec.ts
@@ -140,8 +140,8 @@ describe('principalExists', () => {
});
});
-describe('findPartitionUser', () => {
- it('returns what principal resolution reads, only for a user of the caller partition', async () => {
+describe('findPrincipalUser', () => {
+ it('returns what principal resolution reads and the tenant that holds the user', async () => {
const platform = await seedPrincipals('platform');
const tenant = await inTenant('tenant-a', async () => {
const user = await new mongoose.models.User({
@@ -152,26 +152,51 @@ describe('findPartitionUser', () => {
}).save();
return user._id.toString();
});
+ const tenantUser = {
+ id: tenant,
+ role: 'EDITOR',
+ idOnTheSource: 'entra-oid',
+ tenantId: 'tenant-a',
+ };
- expect(await methods.findPartitionUser(platform.userId)).toEqual({
+ expect(await methods.findPrincipalUser(platform.userId)).toEqual({
id: platform.userId,
role: SystemRoles.USER,
idOnTheSource: null,
});
- expect(await methods.findPartitionUser(tenant)).toBeNull();
- expect(await inTenant('tenant-a', () => methods.findPartitionUser(tenant))).toEqual({
- id: tenant,
- role: 'EDITOR',
- idOnTheSource: 'entra-oid',
- });
- expect(await inTenant('tenant-b', () => methods.findPartitionUser(tenant))).toBeNull();
- expect(await inTenant('tenant-a', () => methods.findPartitionUser(platform.userId))).toBeNull();
+ /** Outside a tenant a user is addressed by id, as group and user profiles are. */
+ expect(await methods.findPrincipalUser(tenant)).toEqual(tenantUser);
+ expect(await inTenant('tenant-a', () => methods.findPrincipalUser(tenant))).toEqual(tenantUser);
+ expect(await inTenant('tenant-b', () => methods.findPrincipalUser(tenant))).toBeNull();
+ expect(await inTenant('tenant-a', () => methods.findPrincipalUser(platform.userId))).toBeNull();
+ });
+
+ it('treats an unclaimed user (null or empty tenant) as platform-level', async () => {
+ const [unset, empty] = await Promise.all(
+ [null, ''].map(async (tenantId, index) => {
+ const { insertedId } = await mongoose.models.User.collection.insertOne({
+ email: `unclaimed-${index}@example.com`,
+ provider: 'local',
+ role: 'USER',
+ tenantId,
+ });
+ return insertedId.toString();
+ }),
+ );
+
+ for (const userId of [unset, empty]) {
+ expect(await methods.findPrincipalUser(userId)).toEqual({
+ id: userId,
+ role: 'USER',
+ idOnTheSource: null,
+ });
+ }
});
it('answers null without a query for an id that cannot name a user', async () => {
const findOne = jest.spyOn(mongoose.models.User, 'findOne');
- expect(await methods.findPartitionUser('not-an-id')).toBeNull();
- expect(await methods.findPartitionUser('F6E5D4C3B2A1F6E5D4C3B2A1')).toBeNull();
+ expect(await methods.findPrincipalUser('not-an-id')).toBeNull();
+ expect(await methods.findPrincipalUser('F6E5D4C3B2A1F6E5D4C3B2A1')).toBeNull();
expect(findOne).not.toHaveBeenCalled();
findOne.mockRestore();
});
diff --git a/packages/data-schemas/src/methods/principal.ts b/packages/data-schemas/src/methods/principal.ts
index cc3152f962..dbccb7c193 100644
--- a/packages/data-schemas/src/methods/principal.ts
+++ b/packages/data-schemas/src/methods/principal.ts
@@ -5,19 +5,23 @@ import { isCanonicalObjectIdString } from '~/utils/objectId';
const systemRoleNames: ReadonlySet<string> = new Set(Object.values(SystemRoles));
-/** What principal resolution reads of a user: their role and external identity. */
-export interface PartitionUser {
+/**
+ * What principal resolution reads of a user (their role and external identity), and the tenant
+ * that holds them (absent for a platform-level user).
+ */
+export interface PrincipalUser {
id: string;
role?: string;
idOnTheSource?: string | null;
+ tenantId?: string;
}
export interface PrincipalMethods {
principalExists: (principalType: PrincipalType, principalId: string) => Promise<boolean>;
- findPartitionUser: (userId: string) => Promise<PartitionUser | null>;
+ findPrincipalUser: (userId: string) => Promise<PrincipalUser | null>;
}
-/** Principal lookups that stay in the caller's tenant partition. */
+/** Principal lookups for the admin API, in the caller's tenant partition or by id. */
export function createPrincipalMethods(mongoose: typeof import('mongoose')): PrincipalMethods {
async function existsInPartition(
modelName: 'Role' | 'Group' | 'User',
@@ -62,24 +66,33 @@ export function createPrincipalMethods(mongoose: typeof import('mongoose')): Pri
}
/**
- * A user of the caller's tenant partition (`tenantPartitionFilter`), by canonical ObjectId, with
- * the fields principal resolution reads (`getUserPrincipals`); `null` when the partition holds
- * no such user, as for a user of another tenant.
+ * A user the caller addresses by canonical ObjectId, with the fields principal resolution reads
+ * (`getUserPrincipals`) and the tenant that holds them. Users are addressed by id the way their
+ * config documents are: inside a tenant only that tenant's (the tenant plugin scopes the read),
+ * and outside one any tenant's, so their profile resolves in their own tenant. Strict mode
+ * refuses the read without a tenant context, as every query does. `null` when the caller sees
+ * no such user, as for a user of another tenant inside a tenant.
*/
- async function findPartitionUser(userId: string): Promise<PartitionUser | null> {
+ async function findPrincipalUser(userId: string): Promise<PrincipalUser | null> {
if (!isCanonicalObjectIdString(userId)) {
return null;
}
- const model = mongoose.models.User as Model<{ role?: string; idOnTheSource?: string | null }>;
- const user = await model
- .findOne({ _id: userId, ...tenantPartitionFilter('findPartitionUser') })
- .select('role idOnTheSource')
- .lean();
+ const model = mongoose.models.User as Model<{
+ role?: string;
+ idOnTheSource?: string | null;
+ tenantId?: string | null;
+ }>;
+ const user = await model.findOne({ _id: userId }).select('role idOnTheSource tenantId').lean();
if (user == null) {
return null;
}
- return { id: userId, role: user.role, idOnTheSource: user.idOnTheSource ?? null };
+ return {
+ id: userId,
+ role: user.role,
+ idOnTheSource: user.idOnTheSource ?? null,
+ ...(user.tenantId ? { tenantId: user.tenantId } : {}),
+ };
}
- return { principalExists, findPartitionUser };
+ return { principalExists, findPrincipalUser };
}
diff --git a/packages/data-schemas/src/methods/role.cache.spec.ts b/packages/data-schemas/src/methods/role.cache.spec.ts
index 512c47ea88..bf73d31d21 100644
--- a/packages/data-schemas/src/methods/role.cache.spec.ts
+++ b/packages/data-schemas/src/methods/role.cache.spec.ts
@@ -1,10 +1,10 @@
import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
-import { PermissionTypes, Permissions } from 'librechat-data-provider';
+import { PermissionTypes, Permissions, SystemRoles } from 'librechat-data-provider';
import type { IRole } from '..';
+import { runAsSystem, tenantStorage } from '../config/tenantContext';
import { createRoleMethods } from './role';
import { createModels } from '../models';
-import { tenantStorage } from '../config/tenantContext';
jest.mock('~/config/winston', () => ({
error: jest.fn(),
@@ -120,11 +120,44 @@ describe('getRoleByName cache is scoped to the active tenant', () => {
findOneSpy.mockRestore();
});
+ it('serves the platform role outside a tenant when an older tenant role has its name', async () => {
+ await seedRole(TENANT_A, false);
+ await new Role({
+ name: ROLE_NAME,
+ permissions: { [PermissionTypes.PROMPTS]: { [Permissions.USE]: true } },
+ }).save();
+
+ const platform = await getRoleByName(ROLE_NAME);
+ const system = await runAsSystem(() => getRoleByName(ROLE_NAME));
+ const tenant = await runAs(TENANT_A, () => getRoleByName(ROLE_NAME));
+
+ expect(platform?.tenantId).toBeUndefined();
+ expect(usePromptsPermission(platform)).toBe(true);
+ expect(usePromptsPermission(system)).toBe(true);
+ expect(usePromptsPermission(cache.store.get(ROLE_NAME) as IRole)).toBe(true);
+ expect(usePromptsPermission(tenant)).toBe(false);
+ });
+
+ it('finds no role outside a tenant that only a tenant holds, and creates a missing system role at platform level', async () => {
+ await seedRole(TENANT_A, true);
+ await runAs(TENANT_A, () => new Role({ name: SystemRoles.USER }).save());
+
+ const tenantOnly = await getRoleByName(ROLE_NAME);
+ const user = await getRoleByName(SystemRoles.USER);
+
+ expect(tenantOnly).toBeNull();
+ expect(user?.tenantId).toBeUndefined();
+ expect(await Role.collection.countDocuments({ name: SystemRoles.USER })).toBe(2);
+ });
+
it('uses the unscoped key when no tenant context is active (single-tenant)', async () => {
const previousDefault = process.env.DEFAULT_TENANT_ID;
delete process.env.DEFAULT_TENANT_ID;
try {
- await seedRole(TENANT_A, true);
+ await new Role({
+ name: ROLE_NAME,
+ permissions: { [PermissionTypes.PROMPTS]: { [Permissions.USE]: true } },
+ }).save();
const role = await getRoleByName(ROLE_NAME);
expect(usePromptsPermission(role)).toBe(true);
diff --git a/packages/data-schemas/src/methods/role.methods.spec.ts b/packages/data-schemas/src/methods/role.methods.spec.ts
index 1e9c40bfc9..434d1408f3 100644
--- a/packages/data-schemas/src/methods/role.methods.spec.ts
+++ b/packages/data-schemas/src/methods/role.methods.spec.ts
@@ -44,6 +44,8 @@ let countUsersByRole: ReturnType<typeof createRoleMethods>['countUsersByRole'];
let updateRoleByName: ReturnType<typeof createRoleMethods>['updateRoleByName'];
let listRoles: ReturnType<typeof createRoleMethods>['listRoles'];
let countRoles: ReturnType<typeof createRoleMethods>['countRoles'];
+let getPartitionRole: ReturnType<typeof createRoleMethods>['getPartitionRole'];
+let findUserIdsByRole: ReturnType<typeof createRoleMethods>['findUserIdsByRole'];
let mongoServer: MongoMemoryServer;
beforeAll(async () => {
@@ -67,6 +69,8 @@ beforeAll(async () => {
countUsersByRole = methods.countUsersByRole;
listRoles = methods.listRoles;
countRoles = methods.countRoles;
+ getPartitionRole = methods.getPartitionRole;
+ findUserIdsByRole = methods.findUserIdsByRole;
});
afterAll(async () => {
@@ -1303,3 +1307,222 @@ describe('createRoleByName - duplicate key race', () => {
insertSpy.mockRestore();
});
});
+
+describe('role-name-keyed operations stay in the caller tenant partition', () => {
+ const inTenant = <T>(tenantId: string, run: () => Promise<T>): Promise<T> =>
+ tenantStorage.run({ tenantId }, run);
+
+ /** An `editor` role and member at platform level and in tenant-a, and a tenant-only role. */
+ async function seed() {
+ const platformRole = await Role.create({ name: 'editor', description: 'platform' });
+ const platformUser = await User.create({ email: '[email protected]', role: 'editor' });
+ const tenant = await inTenant('tenant-a', async () => ({
+ role: await Role.create({ name: 'editor', description: 'tenant' }),
+ user: await User.create({ email: '[email protected]', role: 'editor' }),
+ only: await Role.create({ name: 'tenant-only' }),
+ }));
+ return {
+ platformRoleId: platformRole._id.toString(),
+ platformUserId: platformUser._id.toString(),
+ tenantRoleId: tenant.role._id.toString(),
+ tenantUserId: tenant.user._id.toString(),
+ };
+ }
+
+ const userRole = async (id: string) =>
+ (await User.collection.findOne({ _id: new mongoose.Types.ObjectId(id) }))?.role;
+ const roleDescription = async (id: string) =>
+ (await Role.collection.findOne({ _id: new mongoose.Types.ObjectId(id) }))?.description;
+
+ it('reads and lists only the platform roles and members outside a tenant', async () => {
+ const ids = await seed();
+
+ expect(String((await getPartitionRole('editor'))?._id)).toBe(ids.platformRoleId);
+ expect(await getPartitionRole('tenant-only')).toBeNull();
+ expect((await listRoles()).map(({ name }) => name)).toEqual(['editor']);
+ expect(await countRoles()).toBe(1);
+ expect(await findUserIdsByRole('editor')).toEqual([ids.platformUserId]);
+ expect((await listUsersByRole('editor')).map(({ _id }) => String(_id))).toEqual([
+ ids.platformUserId,
+ ]);
+ expect(await countUsersByRole('editor')).toBe(1);
+ });
+
+ it("reads and lists only the active tenant's roles and members inside it", async () => {
+ const ids = await seed();
+
+ const found = await inTenant('tenant-a', async () => ({
+ role: await getPartitionRole('editor'),
+ roles: (await listRoles()).map(({ name }) => name).sort(),
+ members: await findUserIdsByRole('editor'),
+ count: await countUsersByRole('editor'),
+ }));
+
+ expect(String(found.role?._id)).toBe(ids.tenantRoleId);
+ expect(found.roles).toEqual(['editor', 'tenant-only']);
+ expect(found.members).toEqual([ids.tenantUserId]);
+ expect(found.count).toBe(1);
+ });
+
+ it('creates a missing system role in the partition that reads it, never reading the role cache', async () => {
+ await inTenant('tenant-a', () => Role.create({ name: SystemRoles.USER }));
+
+ const platform = await getPartitionRole(SystemRoles.USER);
+
+ expect(platform?.name).toBe(SystemRoles.USER);
+ expect(platform?.tenantId).toBeUndefined();
+ expect(await Role.collection.countDocuments({ name: SystemRoles.USER })).toBe(2);
+ expect(mockCache.get).not.toHaveBeenCalled();
+ });
+
+ it("renames and migrates only the platform role and its members, leaving the tenant's", async () => {
+ const ids = await seed();
+ const platform = await getPartitionRole('editor');
+
+ await updateUsersByRole('editor', 'writer');
+ const renamed = await updateRoleByName(
+ 'editor',
+ { name: 'writer', description: 'moved' },
+ { id: String(platform?._id) },
+ );
+
+ expect(String(renamed._id)).toBe(ids.platformRoleId);
+ expect(await userRole(ids.platformUserId)).toBe('writer');
+ expect(await userRole(ids.tenantUserId)).toBe('editor');
+ expect(await roleDescription(ids.tenantRoleId)).toBe('tenant');
+ expect(
+ (await Role.collection.findOne({ _id: new mongoose.Types.ObjectId(ids.tenantRoleId) }))?.name,
+ ).toBe('editor');
+ });
+
+ it("creates a platform role whose name a tenant's role holds, and refuses one the partition holds", async () => {
+ await seed();
+
+ const created = await createRoleByName({ name: 'tenant-only' });
+
+ expect(created.tenantId).toBeUndefined();
+ await expect(createRoleByName({ name: 'editor' })).rejects.toThrow(/already exists/);
+ await expect(
+ inTenant('tenant-a', () => createRoleByName({ name: 'tenant-only' })),
+ ).rejects.toThrow(/already exists/);
+ });
+
+ it('updates only the role document an id names, and nothing once it no longer has the name', async () => {
+ const tenantRole = await inTenant('tenant-a', () =>
+ Role.create({ name: 'editor', description: 'tenant' }),
+ );
+ const platformRole = await Role.create({ name: 'editor', description: 'platform' });
+
+ const updated = await updateRoleByName(
+ 'editor',
+ { description: 'changed' },
+ { id: String(platformRole._id) },
+ );
+ const missed = await updateRoleByName(
+ 'writer',
+ { description: 'never' },
+ { id: String(platformRole._id) },
+ );
+
+ expect(String(updated._id)).toBe(String(platformRole._id));
+ expect(missed).toBeNull();
+ expect(await roleDescription(String(platformRole._id))).toBe('changed');
+ expect(await roleDescription(String(tenantRole._id))).toBe('tenant');
+ });
+
+ it('writes access permissions to the role document it was given, never another of its name', async () => {
+ const tenantRole = await inTenant('tenant-a', () =>
+ Role.create({ name: 'editor', permissions: {} }),
+ );
+ await Role.create({ name: 'editor', permissions: {} });
+ const platform = await getPartitionRole('editor');
+
+ await updateAccessPermissions(
+ 'editor',
+ { [PermissionTypes.BOOKMARKS]: { [Permissions.USE]: true } },
+ platform as IRole,
+ );
+
+ const stored = await Role.collection
+ .find({ name: 'editor' })
+ .project({ tenantId: 1, permissions: 1 })
+ .toArray();
+ const byTenant = new Map(stored.map((role) => [role.tenantId ?? '-', role.permissions]));
+ expect(byTenant.get('-')?.[PermissionTypes.BOOKMARKS]).toEqual({ [Permissions.USE]: true });
+ expect(byTenant.get('tenant-a')?.[PermissionTypes.BOOKMARKS]).toBeUndefined();
+ expect(String(tenantRole._id)).not.toBe(String(platform?._id));
+ });
+
+ it('reads and writes by name alone the platform role outside a tenant, though an older tenant role has its name', async () => {
+ const tenantRole = await inTenant('tenant-a', () =>
+ Role.create({ name: 'editor', description: 'tenant', permissions: {} }),
+ );
+ const platformRole = await Role.create({
+ name: 'editor',
+ description: 'platform',
+ permissions: {},
+ });
+
+ const read = await getRoleByName('editor');
+ const updated = await updateRoleByName('editor', { description: 'changed' });
+ await updateAccessPermissions('editor', {
+ [PermissionTypes.BOOKMARKS]: { [Permissions.USE]: true },
+ });
+ /** A role read without its `_id`, as `GET /api/roles/:roleName` reads (and caches) it. */
+ const withoutId = await getRoleByName('editor', '-_id -__v');
+ await updateAccessPermissions(
+ 'editor',
+ { [PermissionTypes.PROMPTS]: { [Permissions.USE]: false } },
+ withoutId,
+ );
+
+ expect(String(read._id)).toBe(String(platformRole._id));
+ expect(String(updated._id)).toBe(String(platformRole._id));
+ expect(withoutId._id).toBeUndefined();
+ const stored = async (id: unknown) =>
+ Role.collection.findOne({ _id: new mongoose.Types.ObjectId(String(id)) });
+ expect(await stored(platformRole._id)).toMatchObject({
+ description: 'changed',
+ permissions: {
+ [PermissionTypes.BOOKMARKS]: { [Permissions.USE]: true },
+ [PermissionTypes.PROMPTS]: { [Permissions.USE]: false },
+ },
+ });
+ const tenantStored = await stored(tenantRole._id);
+ expect(tenantStored?.description).toBe('tenant');
+ expect(tenantStored?.permissions?.[PermissionTypes.BOOKMARKS]).toBeUndefined();
+ expect(tenantStored?.permissions?.[PermissionTypes.PROMPTS]).toBeUndefined();
+ });
+
+ it("deletes only the platform role and reassigns only its members, leaving the tenant's", async () => {
+ const ids = await seed();
+
+ const deleted = await deleteRoleByName('editor');
+ const refused = await deleteRoleByName('editor', { id: ids.tenantRoleId });
+
+ expect(String(deleted?._id)).toBe(ids.platformRoleId);
+ expect(refused).toBeNull();
+ expect(await userRole(ids.platformUserId)).toBe(SystemRoles.USER);
+ expect(await userRole(ids.tenantUserId)).toBe('editor');
+ expect(await roleDescription(ids.tenantRoleId)).toBe('tenant');
+ });
+
+ it("deletes and renames only the active tenant's role and members inside it", async () => {
+ const ids = await seed();
+
+ await inTenant('tenant-a', async () => {
+ await updateUsersByRole('editor', 'writer');
+ await updateRoleByName('editor', { name: 'writer' });
+ await deleteRoleByName('tenant-only');
+ });
+
+ expect(await userRole(ids.tenantUserId)).toBe('writer');
+ expect(await userRole(ids.platformUserId)).toBe('editor');
+ expect(await roleDescription(ids.platformRoleId)).toBe('platform');
+ expect(
+ (await Role.collection.findOne({ _id: new mongoose.Types.ObjectId(ids.platformRoleId) }))
+ ?.name,
+ ).toBe('editor');
+ expect(await Role.collection.countDocuments({ name: 'tenant-only' })).toBe(0);
+ });
+});
diff --git a/packages/data-schemas/src/methods/role.ts b/packages/data-schemas/src/methods/role.ts
index 250bae2777..3074349265 100644
--- a/packages/data-schemas/src/methods/role.ts
+++ b/packages/data-schemas/src/methods/role.ts
@@ -6,9 +6,10 @@ import {
permissionsSchema,
removeNullishValues,
} from 'librechat-data-provider';
-import type { Model } from 'mongoose';
+import type { FilterQuery, Model } from 'mongoose';
import type { CacheStore, IRole, IUser } from '~/types';
import { scopedCacheKey, getTenantId, runAsSystem, SYSTEM_TENANT_ID } from '~/config/tenantContext';
+import { tenantPartitionFilter } from '~/models/plugins/tenantIsolation';
import { escapeRegExp } from '~/utils/string';
import logger from '~/config/winston';
@@ -46,11 +47,16 @@ export function createRoleMethods(
countRoles: () => Promise<number>;
initializeRoles: () => Promise<void>;
getRoleByName: (roleName: string, fieldsToSelect?: string | string[] | null) => Promise<IRole>;
+ getPartitionRole: (roleName: string) => Promise<IRole | null>;
findRolesByNames: (
roleNames: string[],
fieldsToSelect?: string | string[] | null,
) => Promise<IRole[]>;
- updateRoleByName: (roleName: string, updates: Partial<IRole>) => Promise<IRole>;
+ updateRoleByName: (
+ roleName: string,
+ updates: Partial<IRole>,
+ options?: { id?: string },
+ ) => Promise<IRole>;
updateAccessPermissions: (
roleName: string,
permissionsUpdate: Record<string, Record<string, boolean>>,
@@ -71,6 +77,32 @@ export function createRoleMethods(
) => Promise<IUser[]>;
countUsersByRole: (roleName: string) => Promise<number>;
} {
+ /**
+ * The users holding `roleName` in the caller's tenant partition (`tenantPartitionFilter`): the
+ * active tenant's, or outside a tenant only platform-level ones. Role names are reused across
+ * tenants (the role index is unique on name plus `tenantId`), and outside a tenant the tenant
+ * plugin scopes nothing, so a filter on the name alone would reach the members of each
+ * tenant's own role of that name; the role reads and writes by name below keep to the same
+ * partition for the same reason.
+ */
+ function roleMembersFilter(roleName: string, operation: string): FilterQuery<IUser> {
+ return { role: roleName, ...tenantPartitionFilter(operation) };
+ }
+
+ /**
+ * The role named `roleName` in the caller's tenant partition, or with `id` exactly that role
+ * document (which a caller read in its own partition) as long as it still has the name.
+ */
+ function roleDocumentFilter(
+ roleName: string,
+ operation: string,
+ id?: string,
+ ): FilterQuery<IRole> {
+ return id
+ ? { name: roleName, _id: id }
+ : { name: roleName, ...tenantPartitionFilter(operation) };
+ }
+
/**
* Initialize default roles in the system.
* Creates the default roles (ADMIN, USER) if they don't exist in the database.
@@ -139,7 +171,8 @@ export function createRoleMethods(
}
/**
- * List all roles in the system. Returns only name and description (projected).
+ * List the roles of the caller's tenant partition (`tenantPartitionFilter`), the ones a role
+ * name addresses. Returns only name and description (projected).
*/
async function listRoles(options?: {
limit?: number;
@@ -148,7 +181,7 @@ export function createRoleMethods(
const Role = mongoose.models.Role as Model<IRole>;
const limit = options?.limit ?? 50;
const offset = options?.offset ?? 0;
- return await Role.find({})
+ return await Role.find(tenantPartitionFilter('listRoles'))
.select('name description')
.sort({ name: 1 })
.skip(offset)
@@ -156,15 +189,18 @@ export function createRoleMethods(
.lean();
}
+ /** Counts the roles {@link listRoles} lists. */
async function countRoles(): Promise<number> {
const Role = mongoose.models.Role;
- return await Role.countDocuments({});
+ return await Role.countDocuments(tenantPartitionFilter('countRoles'));
}
/**
- * Retrieve a role by name and convert the found role document to a plain object.
- * If the role with the given name doesn't exist and the name is a system defined role,
- * create it and return the lean version.
+ * Retrieve the role named `roleName` in the caller's tenant partition (`tenantPartitionFilter`)
+ * as a plain object: the active tenant's, or outside a tenant (and under the system context)
+ * the platform-level one, never a tenant's role of the same name, which the tenant plugin
+ * would not filter out there. The cache key carries the same partition (`scopedCacheKey`).
+ * If the role doesn't exist there and the name is a system defined role, it is created there.
*/
async function getRoleByName(
roleName: string,
@@ -179,7 +215,7 @@ export function createRoleMethods(
}
}
const Role = mongoose.models.Role;
- let query = Role.findOne({ name: roleName });
+ let query = Role.findOne(roleDocumentFilter(roleName, 'getRoleByName'));
if (fieldsToSelect) {
query = query.select(fieldsToSelect);
}
@@ -201,6 +237,34 @@ export function createRoleMethods(
}
}
+ /**
+ * The role named exactly `roleName` in the caller's tenant partition (`tenantPartitionFilter`),
+ * as the admin roles API addresses it: never a tenant's role of the same name outside that
+ * tenant. A system role with no document there is created there, as {@link getRoleByName}
+ * creates it. Reads no cache, so an admin read never returns another partition's cached role.
+ */
+ async function getPartitionRole(roleName: string): Promise<IRole | null> {
+ const Role = mongoose.models.Role as Model<IRole>;
+ const read = () =>
+ Role.findOne(roleDocumentFilter(roleName, 'getPartitionRole'))
+ .select('-__v')
+ .lean<IRole>()
+ .exec();
+ const role = await read();
+ if (role || !systemRoleValues.has(roleName)) {
+ return role;
+ }
+ try {
+ const created = await new Role(roleDefaults[roleName as keyof typeof roleDefaults]).save();
+ return created.toObject() as IRole;
+ } catch (error) {
+ if (error && typeof error === 'object' && 'code' in error && error.code === 11000) {
+ return read();
+ }
+ throw error;
+ }
+ }
+
/**
* Find roles by name without using or populating the shared role-name cache.
* Use this for tenant-scoped authorization lookups where the active ALS tenant context must control the query.
@@ -252,13 +316,24 @@ export function createRoleMethods(
}
/**
- * Update role values by name.
+ * Update the values of the role named `roleName` in the caller's tenant partition, as
+ * {@link getRoleByName} reads it. With `options.id`, only the role document with that `_id`
+ * changes (`null` when it no longer has the name), so a caller that read one role writes that
+ * role and never another tenant's role of the same name.
*/
- async function updateRoleByName(roleName: string, updates: Partial<IRole>): Promise<IRole> {
+ async function updateRoleByName(
+ roleName: string,
+ updates: Partial<IRole>,
+ options?: { id?: string },
+ ): Promise<IRole> {
const cache = deps.getCache?.(CacheKeys.ROLES);
try {
const Role = mongoose.models.Role;
- const role = await Role.findOneAndUpdate({ name: roleName }, { $set: updates }, { new: true })
+ const role = await Role.findOneAndUpdate(
+ roleDocumentFilter(roleName, 'updateRoleByName', options?.id),
+ { $set: updates },
+ { new: true },
+ )
.select('-__v')
.lean()
.exec();
@@ -314,6 +389,9 @@ export function createRoleMethods(
if (!role) {
return;
}
+ /** The role read is the one written, whichever tenant partition it was read in. */
+ const id = role._id != null ? String(role._id) : undefined;
+ const target = roleDocumentFilter(roleName, 'updateAccessPermissions', id);
const currentPermissions =
((role as unknown as Record<string, unknown>).permissions as Record<
@@ -417,16 +495,13 @@ export function createRoleMethods(
);
try {
- await Role.updateOne(
- { name: roleName },
- {
- $set: updateObj,
- $unset: unsetFields,
- },
- );
+ await Role.updateOne(target, {
+ $set: updateObj,
+ $unset: unsetFields,
+ });
const cache = deps.getCache?.(CacheKeys.ROLES);
- const updatedRole = await Role.findOne({ name: roleName }).select('-__v').lean().exec();
+ const updatedRole = await Role.findOne(target).select('-__v').lean().exec();
if (cache) {
await cache.set(scopedCacheKey(roleName), updatedRole);
}
@@ -437,7 +512,7 @@ export function createRoleMethods(
throw updateError;
}
} else {
- await updateRoleByName(roleName, updateObj as unknown as Partial<IRole>);
+ await updateRoleByName(roleName, updateObj as unknown as Partial<IRole>, { id });
}
logger.info(`Updated '${roleName}' role permissions`);
@@ -449,7 +524,10 @@ export function createRoleMethods(
}
}
- /** Rejects names that match system roles. */
+ /**
+ * Rejects names that match system roles, and a name the caller's tenant partition already holds
+ * (`tenantPartitionFilter`); another tenant's role of that name is a different role.
+ */
async function createRoleByName(roleData: Partial<IRole>): Promise<IRole> {
const { name } = roleData;
if (!name || typeof name !== 'string' || !name.trim()) {
@@ -460,7 +538,7 @@ export function createRoleMethods(
throw new RoleConflictError(`Cannot create role with reserved system name: ${name}`);
}
const Role = mongoose.models.Role;
- const existing = await Role.findOne({ name: trimmed }).lean();
+ const existing = await Role.findOne(roleDocumentFilter(trimmed, 'createRoleByName')).lean();
if (existing) {
throw new RoleConflictError(`Role "${trimmed}" already exists`);
}
@@ -491,7 +569,9 @@ export function createRoleMethods(
}
/**
- * Guards against deleting system roles. Reassigns affected users back to USER.
+ * Guards against deleting system roles. Reassigns affected users back to USER. Only the role
+ * of the caller's tenant partition and its members there are touched
+ * (`tenantPartitionFilter`).
*
* No existence pre-check is performed: for a nonexistent role the `updateMany`
* is a harmless no-op and `findOneAndDelete` returns null. This makes the
@@ -512,16 +592,19 @@ export function createRoleMethods(
throw new Error(`Cannot delete system role: ${roleName}`);
}
const Role = mongoose.models.Role;
+ const role = { name: roleName, ...tenantPartitionFilter('deleteRoleByName') };
/** A role recreated under this name has another `_id`: leave it and its members alone. */
- if (options?.id && !(await Role.exists({ _id: options.id, name: roleName }))) {
+ if (options?.id && !(await Role.exists({ ...role, _id: options.id }))) {
return null;
}
const User = mongoose.models.User as Model<IUser>;
const affectedUserIds = await findUserIdsByRole(roleName);
- await User.updateMany({ role: roleName }, { $set: { role: SystemRoles.USER } });
+ await User.updateMany(roleMembersFilter(roleName, 'deleteRoleByName'), {
+ $set: { role: SystemRoles.USER },
+ });
await invalidateAuthUserDocCache(affectedUserIds);
const deleted = await Role.findOneAndDelete({
- name: roleName,
+ ...role,
...(options?.id ? { _id: options.id } : {}),
}).lean();
try {
@@ -538,16 +621,22 @@ export function createRoleMethods(
return deleted as IRole | null;
}
+ /** Moves the members of `oldRole` in the caller's tenant partition to `newRole` (a rename). */
async function updateUsersByRole(oldRole: string, newRole: string): Promise<void> {
const User = mongoose.models.User as Model<IUser>;
const affectedUserIds = await findUserIdsByRole(oldRole);
- await User.updateMany({ role: oldRole }, { $set: { role: newRole } });
+ await User.updateMany(roleMembersFilter(oldRole, 'updateUsersByRole'), {
+ $set: { role: newRole },
+ });
await invalidateAuthUserDocCache(affectedUserIds);
}
+ /** The ids of the users holding `roleName` in the caller's tenant partition. */
async function findUserIdsByRole(roleName: string): Promise<string[]> {
const User = mongoose.models.User as Model<IUser>;
- const users = await User.find({ role: roleName }).select('_id').lean();
+ const users = await User.find(roleMembersFilter(roleName, 'findUserIdsByRole'))
+ .select('_id')
+ .lean();
return users.map((u) => u._id.toString());
}
@@ -601,6 +690,7 @@ export function createRoleMethods(
}
}
+ /** The users holding `roleName` in the caller's tenant partition, a page at a time. */
async function listUsersByRole(
roleName: string,
options?: { limit?: number; offset?: number },
@@ -608,7 +698,7 @@ export function createRoleMethods(
const User = mongoose.models.User as Model<IUser>;
const limit = options?.limit ?? 50;
const offset = options?.offset ?? 0;
- return await User.find({ role: roleName })
+ return await User.find(roleMembersFilter(roleName, 'listUsersByRole'))
.select('_id name email avatar')
.sort({ _id: 1 })
.skip(offset)
@@ -616,9 +706,10 @@ export function createRoleMethods(
.lean<IUser[]>();
}
+ /** Counts the users {@link listUsersByRole} lists. */
async function countUsersByRole(roleName: string): Promise<number> {
const User = mongoose.models.User as Model<IUser>;
- return await User.countDocuments({ role: roleName });
+ return await User.countDocuments(roleMembersFilter(roleName, 'countUsersByRole'));
}
return {
@@ -626,6 +717,7 @@ export function createRoleMethods(
countRoles,
initializeRoles,
getRoleByName,
+ getPartitionRole,
findRolesByNames,
updateRoleByName,
updateAccessPermissions,
diff --git a/packages/data-schemas/src/methods/systemGrant.spec.ts b/packages/data-schemas/src/methods/systemGrant.spec.ts
index 82497c4d3f..ba901d10ea 100644
--- a/packages/data-schemas/src/methods/systemGrant.spec.ts
+++ b/packages/data-schemas/src/methods/systemGrant.spec.ts
@@ -843,7 +843,7 @@ describe('systemGrant methods', () => {
);
});
- it('moves only platform-level grants when no tenant is given, unlike the delete cascade', async () => {
+ it('moves only platform-level grants when no tenant is given, as the delete cascade removes them', async () => {
await grant('editor', SystemCapabilities.READ_USERS, 'tenant-a');
await grant('editor', SystemCapabilities.READ_CONFIGS);
await grant('writer', SystemCapabilities.READ_USERS, 'tenant-a');
@@ -1113,7 +1113,7 @@ describe('systemGrant methods', () => {
expect(caps).toEqual([SystemCapabilities.READ_GROUPS, SystemCapabilities.READ_USERS]);
});
- it('without tenantId deletes all grants across all tenants', async () => {
+ it("without tenantId deletes only platform-level grants, never a tenant's own role's", async () => {
await methods.grantCapability({
principalType: PrincipalType.ROLE,
principalId: 'temp-role',
@@ -1126,13 +1126,18 @@ describe('systemGrant methods', () => {
tenantId: 'tenant-a',
});
- await methods.deleteGrantsForPrincipal(PrincipalType.ROLE, 'temp-role');
+ const found = await methods.findGrantsForPrincipal(PrincipalType.ROLE, 'temp-role');
+ const removed = await methods.deleteGrantsForPrincipal(PrincipalType.ROLE, 'temp-role');
- const remaining = await SystemGrant.countDocuments({
+ expect(found.map((g) => g.capability)).toEqual([SystemCapabilities.READ_USERS]);
+ expect(removed.map((g) => g.capability)).toEqual([SystemCapabilities.READ_USERS]);
+ const remaining = await SystemGrant.find({
principalType: PrincipalType.ROLE,
principalId: 'temp-role',
- });
- expect(remaining).toBe(0);
+ }).lean();
+ expect(remaining.map((g) => [g.capability, g.tenantId])).toEqual([
+ [SystemCapabilities.READ_CONFIGS, 'tenant-a'],
+ ]);
});
});
diff --git a/packages/data-schemas/src/methods/systemGrant.ts b/packages/data-schemas/src/methods/systemGrant.ts
index d20a34d9ca..76eea9dad7 100644
--- a/packages/data-schemas/src/methods/systemGrant.ts
+++ b/packages/data-schemas/src/methods/systemGrant.ts
@@ -158,6 +158,11 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
move: SystemGrantMove,
) => Promise<void>;
} {
+ /** The grants of exactly one scope: `tenantId`'s, or the platform-level ones without it. */
+ function grantScope(tenantId?: string): FilterQuery<ISystemGrant> {
+ return tenantId != null ? { tenantId } : { tenantId: { $exists: false } };
+ }
+
function tenantCondition(tenantId?: string): FilterQuery<ISystemGrant> {
return tenantId != null
? { $and: [{ $or: [{ tenantId }, { tenantId: { $exists: false } }] }] }
@@ -581,11 +586,11 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
* Delete system grants for a principal.
* Used for cascade cleanup when a principal (group, role) is deleted.
*
- * When `tenantId` is provided, only grants scoped to **exactly** that
- * tenant are removed — platform-level grants (no tenantId) are left
- * intact so they continue to serve other tenants.
- * When `tenantId` is omitted, ALL grants for the principal are removed
- * regardless of tenant scope.
+ * Only the grants of one scope go, as `moveGrantsToPrincipal` moves them on a rename: with
+ * `tenantId`, those scoped to **exactly** that tenant (platform-level grants, with no
+ * tenantId, are left intact so they continue to serve other tenants); without it, only the
+ * platform-level ones. A role is keyed by a name every tenant reuses, so deleting the
+ * platform's role never removes the grants a tenant's own role of that name holds.
*/
async function deleteGrantsForPrincipal(
principalType: PrincipalType,
@@ -598,7 +603,7 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
const filter: FilterQuery<ISystemGrant> = {
principalType,
principalId: normalizedPrincipalId,
- ...(options?.tenantId != null && { tenantId: options.tenantId }),
+ ...grantScope(options?.tenantId),
};
const queryOptions = options?.session ? { session: options.session } : {};
/** Read the matching grants before deleting so cascade callers (e.g. role
@@ -618,7 +623,7 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
return SystemGrant.find({
principalType,
principalId: normalizePrincipalId(principalId, principalType),
- ...(options?.tenantId != null && { tenantId: options.tenantId }),
+ ...grantScope(options?.tenantId),
}).lean<ISystemGrant[]>();
}
@@ -646,9 +651,9 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
/**
* Re-keys a principal's grants to another id of the same type (a role rename), in one tenant
- * scope: exactly `tenantId` when given, platform-level grants (no `tenantId`) otherwise. A
- * rename re-keys one role, so unlike {@link deleteGrantsForPrincipal} a caller without a
- * tenant never re-keys the grants of each tenant's own role that shares the name. Each grant
+ * scope: exactly `tenantId` when given, platform-level grants (no `tenantId`) otherwise, as
+ * {@link deleteGrantsForPrincipal} removes them. A rename re-keys one role, so a caller without
+ * a tenant never re-keys the grants of each tenant's own role that shares the name. Each grant
* keeps its identity and history. One the target already holds in the same scope is removed
* from the source instead, since the unique index allows one.
*
@@ -665,13 +670,11 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
options?: { tenantId?: string },
): Promise<SystemGrantMove> {
const SystemGrant = mongoose.models.SystemGrant as Model<ISystemGrant>;
- const scope: FilterQuery<ISystemGrant> =
- options?.tenantId != null ? { tenantId: options.tenantId } : { tenantId: { $exists: false } };
const source = normalizePrincipalId(fromPrincipalId, principalType);
const grants = await SystemGrant.find({
principalType,
principalId: source,
- ...scope,
+ ...grantScope(options?.tenantId),
}).lean<ISystemGrant[]>();
if (grants.length === 0) {
return { moved: [], superseded: [] };