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: Base-First Config Precedence, Profile Lifecycle and Role Renames That Keep Their Profile (#17352)

Danny Avila76e3c6b134d7
diff --git a/api/server/routes/__tests__/admin-config-reload.spec.js b/api/server/routes/__tests__/admin-config-reload.spec.js
index 8b59bee242..d846a2c118 100644
--- a/api/server/routes/__tests__/admin-config-reload.spec.js
+++ b/api/server/routes/__tests__/admin-config-reload.spec.js
@@ -51,8 +51,8 @@ function writeYaml(maxMatches) {
fs.writeFileSync(configPath, yaml.dump({ version: Constants.CONFIG_VERSION, filters }));
}
-const principal = '/api/admin/config/user/reload-sentinel';
-
+/** A real user's profile route: a write that creates a profile needs its principal to exist. */
+let principal;
let app;
let mongoServer;
@@ -63,6 +63,11 @@ beforeAll(async () => {
mongoose.set('autoIndex', false);
createModels(mongoose);
await mongoose.models.Config.createIndexes();
+ const user = await mongoose.models.User.create({
+ email: '[email protected]',
+ provider: 'local',
+ });
+ principal = `/api/admin/config/user/${user._id}`;
writeYaml(1);
app = express();
app.use(express.json());
diff --git a/api/server/routes/admin/config.js b/api/server/routes/admin/config.js
index 652f79ffbc..1e5caead2f 100644
--- a/api/server/routes/admin/config.js
+++ b/api/server/routes/admin/config.js
@@ -24,10 +24,11 @@ const handlers = createAdminConfigHandlers({
listAllConfigs: db.listAllConfigs,
findConfigByPrincipal: db.findConfigByPrincipal,
writeConfigDocument: db.writeConfigDocument,
- tombstoneConfigField: db.tombstoneConfigField,
unsetConfigField: db.unsetConfigField,
deleteConfig: db.deleteConfig,
toggleConfigActiveTracked: db.toggleConfigActiveTracked,
+ setConfigPriority: db.setConfigPriority,
+ principalExists: db.principalExists,
hasAnyConfigReadAccess,
getReadableConfigSections,
hasConfigCapability,
@@ -52,5 +53,6 @@ router.delete('/:principalType/:principalId/fields', handlers.deleteConfigField)
router.post('/:principalType/:principalId/changes', handlers.applyConfigChanges);
router.delete('/:principalType/:principalId', handlers.deleteConfigOverrides);
router.patch('/:principalType/:principalId/active', handlers.toggleConfig);
+router.patch('/:principalType/:principalId/priority', handlers.updateConfigPriority);
module.exports = router;
diff --git a/api/server/routes/admin/config.test.js b/api/server/routes/admin/config.test.js
index fe30dda433..951ea44b9c 100644
--- a/api/server/routes/admin/config.test.js
+++ b/api/server/routes/admin/config.test.js
@@ -21,7 +21,6 @@ const mockDb = {
listAllConfigs: jest.fn(),
findConfigByPrincipal: jest.fn(),
writeConfigDocument: jest.fn(),
- tombstoneConfigField: jest.fn(),
unsetConfigField: jest.fn(),
deleteConfig: jest.fn(),
toggleConfigActiveTracked: jest.fn(),
diff --git a/api/server/routes/admin/roles.js b/api/server/routes/admin/roles.js
index 47eae598b4..dd2197e2bb 100644
--- a/api/server/routes/admin/roles.js
+++ b/api/server/routes/admin/roles.js
@@ -2,6 +2,7 @@ const express = require('express');
const { createAdminRolesHandlers } = require('@librechat/api');
const { SystemCapabilities } = require('@librechat/data-schemas');
const { requireCapability } = require('~/server/middleware/roles/capabilities');
+const { invalidateConfigCaches } = require('~/server/services/Config');
const { requireJwtAuth } = require('~/server/middleware');
const db = require('~/models');
@@ -32,6 +33,11 @@ const handlers = createAdminRolesHandlers({
restoreConfig: db.restoreConfig,
findConfigByPrincipal: db.findConfigByPrincipal,
findGrantsForPrincipal: db.findGrantsForPrincipal,
+ renameConfigPrincipal: db.renameConfigPrincipal,
+ moveGrantsToPrincipal: db.moveGrantsToPrincipal,
+ restoreMovedGrants: db.restoreMovedGrants,
+ moveAclEntriesToPrincipal: db.moveAclEntriesToPrincipal,
+ invalidateConfigCaches,
recordAuditEntry: db.recordAuditEntry,
auditFailClosed: process.env.AUDIT_LOG_FAIL_CLOSED === 'true',
invalidatePromptGroupAccessContext: db.invalidatePromptGroupAccessContext,
diff --git a/docs/mcp-overrides.md b/docs/mcp-overrides.md
index a18513c0f5..10325c7ea4 100644
--- a/docs/mcp-overrides.md
+++ b/docs/mcp-overrides.md
@@ -10,6 +10,10 @@ of a record map. All three are tombstones, written and removed with the same two
| POST | `/api/admin/config/:principalType/:principalId/fields/tombstone` | `{ "fieldPath": "mcpServers.…" }` |
| DELETE | `/api/admin/config/:principalType/:principalId/fields` | `?fieldPath=mcpServers.…` |
+Profiles merge in a fixed order, the last winning: `__base__` first whatever its priority, then
+ascending priority, then role, group and user on equal priority. A "higher" profile below is one
+that merges later.
+
`librechat.yaml` stays authoritative for which servers exist. A profile cannot delete or rename a
`librechat.yaml` server; it can only hide it from the principals the profile applies to.
@@ -37,8 +41,10 @@ Two broader tombstones hide more than one server or reach more principals:
- `fieldPath: "mcpServers"` removes the whole section, so it hides every server a profile can hide
(all but the ones listed below) for the profile's principals.
- A tombstone in the `__base__` profile applies to every principal, administrators included.
+ `__base__` merges first, so every other profile is higher than it: a profile that writes fields
+ of a server `__base__` hides brings it back for that profile's principals, as described below.
-Deleting the tombstone shows the server again. A higher-priority profile that writes some fields of
+Deleting the tombstone shows the server again. A higher profile that writes some fields of
a server a lower profile hides also brings it back for its own principals, but not with those
fields. The merge keeps only what the higher profile wrote, which is not a usable server
definition, so those principals get the server as `librechat.yaml` defines it, and the incomplete
@@ -55,7 +61,7 @@ Some servers are never hidden:
- A user's own servers.
The decision comes from the principal's merged configuration (user, role and group memberships, in
-priority order). When that configuration cannot be read, every server a profile could hide is
+merge order). When that configuration cannot be read, every server a profile could hide is
withheld instead of falling back to `librechat.yaml`.
### When a change takes effect
@@ -105,7 +111,7 @@ These tombstones behave as follows:
- `DELETE …/fields?fieldPath=<same path>` removes that tombstone and restores the inherited key.
- `DELETE …/fields?fieldPath=mcpServers.<name>.headers` resets the whole record: it clears the key
tombstones under it as well as the keys the profile wrote.
-- A higher-priority profile can supply the key again.
+- A higher profile can supply the key again.
- Fields of a process-backed server, including `env`, cannot be removed.
- A record key that contains `.` cannot be addressed with a dotted `fieldPath`.
diff --git a/e2e/specs/mock/content-filters.helpers.ts b/e2e/specs/mock/content-filters.helpers.ts
index 59c9cccb8a..6da40585bb 100644
--- a/e2e/specs/mock/content-filters.helpers.ts
+++ b/e2e/specs/mock/content-filters.helpers.ts
@@ -15,7 +15,8 @@ import { getPrimaryE2EUser } from '../../setup/users.mock';
const PROJECT_ROOT = path.resolve(__dirname, '../../..');
const GENERATED_CONFIG_ROOT = path.join(PROJECT_ROOT, 'e2e/.generated');
const RELOAD_SENTINEL = `e2e-content-filter-reload-${process.pid}-${randomUUID()}`;
-const RELOAD_SENTINEL_PATH = `/api/admin/config/user/${encodeURIComponent(RELOAD_SENTINEL)}`;
+const RELOAD_SENTINEL_ROLE_PATH = `/api/admin/roles/${encodeURIComponent(RELOAD_SENTINEL)}`;
+const RELOAD_SENTINEL_PATH = `/api/admin/config/role/${encodeURIComponent(RELOAD_SENTINEL)}`;
const RELOAD_PRIORITY = 10;
type RequestFetchOptions = NonNullable<Parameters<APIRequestContext['fetch']>[1]>;
@@ -179,12 +180,29 @@ function getConfigFromResult(result: RequestResult): RuntimeConfig {
return result.body.config as RuntimeConfig;
}
+/**
+ * The sentinel's profile belongs to a role of its own: config writes need an existing principal,
+ * and no user is a member, so its empty profile changes no one's config.
+ */
+async function ensureReloadSentinelRole(request: APIRequestContext, token: string): Promise<void> {
+ const result = await requestResult(request, {
+ path: '/api/admin/roles',
+ token,
+ method: 'POST',
+ data: { name: RELOAD_SENTINEL },
+ });
+ expect([201, 409], `Expected reload sentinel role to exist: ${result.text}`).toContain(
+ result.status,
+ );
+}
+
/**
* A committed admin config write is what makes the server reload librechat.yaml; a request with
* nothing to write reloads nothing. A PUT that carries `priority` always writes the sentinel,
* and the returned `config` confirms it did (a no-op answers with only a message).
*/
async function triggerConfigReload(request: APIRequestContext, token: string): Promise<void> {
+ await ensureReloadSentinelRole(request, token);
const result = await requestResult(request, {
path: RELOAD_SENTINEL_PATH,
token,
@@ -241,6 +259,14 @@ async function deleteReloadSentinel(request: APIRequestContext, token: string):
expect([200, 404], `Expected reload sentinel cleanup to succeed: ${result.text}`).toContain(
result.status,
);
+ const role = await requestResult(request, {
+ path: RELOAD_SENTINEL_ROLE_PATH,
+ token,
+ method: 'DELETE',
+ });
+ expect([200, 404], `Expected reload sentinel role cleanup to succeed: ${role.text}`).toContain(
+ role.status,
+ );
}
export async function loginAdmin(request: APIRequestContext): Promise<string> {
diff --git a/packages/api/src/admin/audit.ts b/packages/api/src/admin/audit.ts
index f3e97096e2..78265d825f 100644
--- a/packages/api/src/admin/audit.ts
+++ b/packages/api/src/admin/audit.ts
@@ -19,6 +19,16 @@ export type AdminAuditEvent = Omit<RecordAuditEntryInput, 'actor' | 'context'>;
export type AdminAuditEmitter = (req: ServerRequest, event: AdminAuditEvent) => Promise<void>;
+/** Audit target for a principal's override document. Records field paths and
+ * sections only: override values can carry secrets. */
+export function configTarget(
+ principalType: string,
+ principalId: string,
+): { type: 'config'; id: string; name: string } {
+ const key = `${principalType}:${principalId}`;
+ return { type: 'config', id: key, name: key };
+}
+
/**
* Whether resource permission updates fail closed. Their audit entry is written
* before the ACL changes, so a failed write rejects the request with nothing
diff --git a/packages/api/src/admin/config.changes.integration.spec.ts b/packages/api/src/admin/config.changes.integration.spec.ts
index f5961a3468..c9c216b0d8 100644
--- a/packages/api/src/admin/config.changes.integration.spec.ts
+++ b/packages/api/src/admin/config.changes.integration.spec.ts
@@ -94,7 +94,6 @@ function createDeps(overrides: Partial<AdminConfigDeps> = {}): AdminConfigDeps {
listAllConfigs: methods.listAllConfigs,
findConfigByPrincipal: methods.findConfigByPrincipal,
writeConfigDocument: jest.fn(methods.writeConfigDocument),
- tombstoneConfigField: methods.tombstoneConfigField,
unsetConfigField: methods.unsetConfigField,
deleteConfig: methods.deleteConfig,
toggleConfigActiveTracked: methods.toggleConfigActiveTracked,
diff --git a/packages/api/src/admin/config.dotted.integration.spec.ts b/packages/api/src/admin/config.dotted.integration.spec.ts
index 45eba93354..2c9deaaed7 100644
--- a/packages/api/src/admin/config.dotted.integration.spec.ts
+++ b/packages/api/src/admin/config.dotted.integration.spec.ts
@@ -48,7 +48,6 @@ beforeAll(async () => {
listAllConfigs: methods.listAllConfigs,
findConfigByPrincipal: methods.findConfigByPrincipal,
writeConfigDocument: methods.writeConfigDocument,
- tombstoneConfigField: methods.tombstoneConfigField,
unsetConfigField: methods.unsetConfigField,
deleteConfig: methods.deleteConfig,
toggleConfigActiveTracked: methods.toggleConfigActiveTracked,
diff --git a/packages/api/src/admin/config.handler.spec.ts b/packages/api/src/admin/config.handler.spec.ts
index ad031fd439..70c24a2cae 100644
--- a/packages/api/src/admin/config.handler.spec.ts
+++ b/packages/api/src/admin/config.handler.spec.ts
@@ -104,9 +104,6 @@ function createHandlers(overrides = {}) {
async (principalType: string, principalId: string, draft: ConfigDraft, expected: string) =>
writtenDocument(principalType, principalId, draft, expected),
),
- tombstoneConfigField: jest
- .fn()
- .mockResolvedValue({ _id: 'c1', tombstones: ['mcpServers.github'] }),
unsetConfigField: jest.fn().mockResolvedValue({ _id: 'c1', overrides: {} }),
deleteConfig: jest.fn().mockResolvedValue({ _id: 'c1' }),
toggleConfigActiveTracked: jest
@@ -1033,6 +1030,18 @@ describe('createAdminConfigHandlers', () => {
});
describe('tombstoneConfigField', () => {
+ const storedAdmin = {
+ _id: '64b000000000000000000001',
+ principalType: 'role',
+ principalId: 'admin',
+ principalModel: 'Role',
+ priority: 7,
+ configVersion: 3,
+ isActive: false,
+ overrides: { mcpServers: { github: { url: 'https://example.com/mcp' } } },
+ tombstones: ['memory'],
+ };
+
it('writes an explicit tombstone for a valid field path', async () => {
const { handlers, deps } = createHandlers();
const req = mockReq({
@@ -1044,33 +1053,55 @@ describe('createAdminConfigHandlers', () => {
await handlers.tombstoneConfigField(req, res);
expect(res.statusCode).toBe(200);
- expect(deps.tombstoneConfigField).toHaveBeenCalledWith(
- 'role',
- 'admin',
- expect.anything(),
- ['mcpServers.github'],
- undefined,
- undefined,
- { expectedRevision: undefined },
- );
+ expect(deps.writeConfigDocument).toHaveBeenCalledTimes(1);
+ expect(deps.writeConfigDocument.mock.calls[0].slice(0, 2)).toEqual(['role', 'admin']);
+ expect(deps.writeConfigDocument.mock.calls[0][3]).toBe('absent');
+ expect(writtenDraft(deps)).toEqual({
+ principalModel: 'Role',
+ priority: 10,
+ overrides: {},
+ tombstones: ['mcpServers.github'],
+ isActive: true,
+ });
});
- it('lets the store keep the existing priority when priority is omitted', async () => {
- const { handlers, deps } = createHandlers();
- const req = mockReq({
- params: { principalType: 'role', principalId: 'admin' },
- body: { fieldPath: 'mcpServers.github', priority: 42 },
+ it('writes over the stored document, keeping its priority unless one is requested', async () => {
+ const kept = createHandlers({
+ findConfigByPrincipal: jest.fn().mockResolvedValue(storedAdmin),
+ });
+ await kept.handlers.tombstoneConfigField(
+ mockReq({
+ params: { principalType: 'role', principalId: 'admin' },
+ body: { fieldPath: 'mcpServers.github' },
+ }),
+ mockRes(),
+ );
+ expect(kept.deps.writeConfigDocument.mock.calls[0][3]).toBe('64b000000000000000000001:3');
+ expect(writtenDraft(kept.deps)).toEqual({
+ principalModel: 'Role',
+ priority: 7,
+ overrides: {},
+ tombstones: ['memory', 'mcpServers.github'],
+ isActive: false,
});
- const res = mockRes();
-
- await handlers.tombstoneConfigField(req, res);
- expect(deps.tombstoneConfigField.mock.calls[0][4]).toBe(42);
- expect(deps.findConfigByPrincipal).not.toHaveBeenCalled();
+ const requested = createHandlers({
+ findConfigByPrincipal: jest.fn().mockResolvedValue(storedAdmin),
+ });
+ await requested.handlers.tombstoneConfigField(
+ mockReq({
+ params: { principalType: 'role', principalId: 'admin' },
+ body: { fieldPath: 'mcpServers.github', priority: 42 },
+ }),
+ mockRes(),
+ );
+ expect(writtenDraft(requested.deps).priority).toBe(42);
});
it('suppresses a secret and its preview companion in one write', async () => {
- const { handlers, deps } = createHandlers();
+ const { handlers, deps } = createHandlers({
+ findConfigByPrincipal: jest.fn().mockResolvedValue(storedAdmin),
+ });
const req = mockReq({
params: { principalType: 'role', principalId: 'admin' },
body: { fieldPath: 'ocr.apiKey', expectedRevision: '64b000000000000000000001:3' },
@@ -1080,16 +1111,9 @@ describe('createAdminConfigHandlers', () => {
await handlers.tombstoneConfigField(req, res);
expect(res.statusCode).toBe(200);
- expect(deps.tombstoneConfigField).toHaveBeenCalledTimes(1);
- expect(deps.tombstoneConfigField).toHaveBeenCalledWith(
- 'role',
- 'admin',
- expect.anything(),
- ['ocr.apiKey', 'ocr.apiKeyPreview'],
- undefined,
- undefined,
- { expectedRevision: '64b000000000000000000001:3' },
- );
+ expect(deps.writeConfigDocument).toHaveBeenCalledTimes(1);
+ expect(deps.writeConfigDocument.mock.calls[0][3]).toBe('64b000000000000000000001:3');
+ expect(writtenDraft(deps).tombstones).toEqual(['memory', 'ocr.apiKey', 'ocr.apiKeyPreview']);
});
it('ignores tenant-wide Langfuse tombstones through the generic config API', async () => {
@@ -1104,7 +1128,7 @@ describe('createAdminConfigHandlers', () => {
expect(res.statusCode).toBe(200);
expect(res.body).toEqual({ message: 'No actionable field path provided', revision: null });
- expect(deps.tombstoneConfigField).not.toHaveBeenCalled();
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
it('rejects tombstones of the displayed secret key', async () => {
@@ -1118,7 +1142,7 @@ describe('createAdminConfigHandlers', () => {
await handlers.tombstoneConfigField(req, res);
expect(res.statusCode).toBe(400);
- expect(deps.tombstoneConfigField).not.toHaveBeenCalled();
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
it('blocks interface permission paths', async () => {
@@ -1133,7 +1157,7 @@ describe('createAdminConfigHandlers', () => {
expect(res.statusCode).toBe(200);
expect(res.body!.message).toBeDefined();
- expect(deps.tombstoneConfigField).not.toHaveBeenCalled();
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
it('ignores tombstones for base-only filter policy', async () => {
@@ -1148,7 +1172,7 @@ describe('createAdminConfigHandlers', () => {
expect(res.statusCode).toBe(200);
expect(res.body!.message).toBeDefined();
- expect(deps.tombstoneConfigField).not.toHaveBeenCalled();
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
it('rejects unsafe field paths', async () => {
@@ -1162,7 +1186,7 @@ describe('createAdminConfigHandlers', () => {
await handlers.tombstoneConfigField(req, res);
expect(res.statusCode).toBe(400);
- expect(deps.tombstoneConfigField).not.toHaveBeenCalled();
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
});
@@ -1574,8 +1598,17 @@ describe('createAdminConfigHandlers', () => {
expect(res.statusCode).toBe(200);
const priorityArg = writtenDraft(deps).priority;
expect(priorityArg).toBe(999);
- /** Read once to validate the write on top of the stored fields, not for its priority. */
- expect(deps.findConfigByPrincipal).toHaveBeenCalledTimes(1);
+ /**
+ * The target is read once, to validate the write on top of its stored fields (not for its
+ * priority); Base is read beside it (the store keeps role documents to the caller's
+ * partition) as the floor the write lands on, and once more after the write, to see that
+ * the floor did not move.
+ */
+ expect(deps.findConfigByPrincipal).toHaveBeenCalledTimes(3);
+ expect(deps.findConfigByPrincipal).toHaveBeenCalledWith('role', 'admin', {
+ includeInactive: true,
+ });
+ expect(deps.findConfigByPrincipal).toHaveBeenCalledWith('role', '__base__');
});
it('preserves priority 0 when broad caller supplies it', async () => {
@@ -1623,10 +1656,22 @@ describe('createAdminConfigHandlers', () => {
});
describe('tombstoneConfigField: section-scoped priority preservation', () => {
- /** The store keeps the stored priority (or the default on create) when none is passed. */
+ const storedAt = (priority: number) =>
+ jest.fn().mockResolvedValue({
+ _id: 'c1',
+ principalType: 'role',
+ principalId: 'admin',
+ priority,
+ configVersion: 1,
+ isActive: true,
+ overrides: {},
+ tombstones: [],
+ });
+
it('ignores request-supplied priority when caller lacks broad manage:configs', async () => {
const { handlers, deps } = createHandlers({
hasConfigCapability: jest.fn(async (_user, section) => section === 'memory'),
+ findConfigByPrincipal: storedAt(15),
});
const req = mockReq({
params: { principalType: 'role', principalId: 'admin' },
@@ -1637,13 +1682,13 @@ describe('createAdminConfigHandlers', () => {
await handlers.tombstoneConfigField(req, res);
expect(res.statusCode).toBe(200);
- const [, , , , priorityArg] = deps.tombstoneConfigField.mock.calls[0];
- expect(priorityArg).toBeUndefined();
+ expect(writtenDraft(deps).priority).toBe(15);
});
it('honors request-supplied priority when caller holds broad manage:configs', async () => {
const { handlers, deps } = createHandlers({
hasConfigCapability: jest.fn().mockResolvedValue(true),
+ findConfigByPrincipal: storedAt(15),
});
const req = mockReq({
params: { principalType: 'role', principalId: 'admin' },
@@ -1654,9 +1699,7 @@ describe('createAdminConfigHandlers', () => {
await handlers.tombstoneConfigField(req, res);
expect(res.statusCode).toBe(200);
- const [, , , , priorityArg] = deps.tombstoneConfigField.mock.calls[0];
- expect(priorityArg).toBe(999);
- expect(deps.findConfigByPrincipal).not.toHaveBeenCalled();
+ expect(writtenDraft(deps).priority).toBe(999);
});
});
@@ -2126,7 +2169,7 @@ describe('createAdminConfigHandlers', () => {
await handlers.tombstoneConfigField(req, res);
expect(res.statusCode).toBe(403);
- expect(deps.tombstoneConfigField).not.toHaveBeenCalled();
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
it('field delete against __base__ returns 403 for a section-scoped manager', async () => {
@@ -2333,7 +2376,6 @@ describe('createAdminConfigHandlers', () => {
listAllConfigs: jest.fn().mockResolvedValue([]),
findConfigByPrincipal: jest.fn().mockResolvedValue(null),
writeConfigDocument: jest.fn(),
- tombstoneConfigField: jest.fn(),
unsetConfigField: jest.fn(),
deleteConfig: jest.fn().mockResolvedValue({ _id: 'c1' }),
/** The document as it was before the write. */
@@ -2925,7 +2967,6 @@ describe('createAdminConfigHandlers', () => {
expect(fieldRes.statusCode).toBe(200);
expect(removals.map((res) => res.statusCode)).toEqual([200, 200]);
expect(deps.writeConfigDocument).toHaveBeenCalledTimes(1);
- expect(deps.tombstoneConfigField).not.toHaveBeenCalled();
expect(deps.unsetConfigField).not.toHaveBeenCalled();
});
@@ -2951,7 +2992,7 @@ describe('createAdminConfigHandlers', () => {
error: 'Unknown config section',
code: 'UNKNOWN_SECTION',
});
- expect(deps.tombstoneConfigField).not.toHaveBeenCalled();
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
expect(deleteRes.statusCode).toBe(200);
expect(deps.unsetConfigField).toHaveBeenCalledWith(
'role',
@@ -3100,10 +3141,7 @@ describe('createAdminConfigHandlers', () => {
it('records config.created when the first tombstone creates the document', async () => {
const recordAuditEntry = jest.fn().mockResolvedValue(undefined);
- const { handlers } = createHandlers({
- recordAuditEntry,
- tombstoneConfigField: jest.fn().mockResolvedValue({ _id: 'c1', configVersion: 1 }),
- });
+ const { handlers } = createHandlers({ recordAuditEntry });
const res = mockRes();
await handlers.tombstoneConfigField(
@@ -3118,7 +3156,19 @@ describe('createAdminConfigHandlers', () => {
it('records tombstone and unset field operations', async () => {
const recordAuditEntry = jest.fn().mockResolvedValue(undefined);
- const { handlers } = createHandlers({ recordAuditEntry });
+ const { handlers } = createHandlers({
+ recordAuditEntry,
+ findConfigByPrincipal: jest.fn().mockResolvedValue({
+ _id: 'c1',
+ principalType: 'role',
+ principalId: 'editor',
+ priority: 10,
+ configVersion: 2,
+ isActive: true,
+ overrides: {},
+ tombstones: [],
+ }),
+ });
const tombstoneRes = mockRes();
await handlers.tombstoneConfigField(
@@ -3324,7 +3374,6 @@ describe('createAdminConfigHandlers', () => {
expect(res.statusCode).toBe(400);
expect(res.body).toEqual(UNKNOWN_SECTION);
- expect(deps.tombstoneConfigField).not.toHaveBeenCalled();
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
expect(deps.findConfigByPrincipal).not.toHaveBeenCalled();
},
@@ -3601,7 +3650,7 @@ describe('createAdminConfigHandlers', () => {
],
[
'tombstone',
- 'tombstoneConfigField',
+ 'writeConfigDocument',
(h: ReturnType<typeof createHandlers>['handlers'], res: Response) =>
h.tombstoneConfigField(
mockReq({ params, body: { fieldPath: 'endpoints.bedrock' } }),
@@ -3637,7 +3686,6 @@ describe('createAdminConfigHandlers', () => {
hasConfigCapability: scopedCapability(['manage:endpoints']),
getReadableConfigSections: jest.fn().mockRejectedValue(new Error('grant lookup down')),
writeConfigDocument: jest.fn().mockResolvedValue(writtenDoc()),
- tombstoneConfigField: jest.fn().mockResolvedValue(writtenDoc()),
unsetConfigField: jest.fn().mockResolvedValue(writtenDoc()),
recordAuditEntry,
invalidateConfigCaches,
@@ -3683,7 +3731,7 @@ describe('createAdminConfigHandlers', () => {
it('tombstone: a section manager sees only the tombstoned section', async () => {
const { handlers } = createHandlers({
hasConfigCapability: scopedCapability(['manage:memory']),
- tombstoneConfigField: jest.fn().mockResolvedValue(writtenDoc()),
+ writeConfigDocument: jest.fn().mockResolvedValue(writtenDoc()),
});
const res = mockRes();
@@ -3878,10 +3926,14 @@ describe('createAdminConfigHandlers', () => {
it('re-reads and re-validates when a write without a precondition loses a race', async () => {
const rotated = { ...stored, configVersion: 5, overrides: { interface: { a: 1 } } };
- const findConfigByPrincipal = jest
- .fn()
- .mockResolvedValueOnce(stored)
- .mockResolvedValueOnce(rotated);
+ const reads = [stored, rotated];
+ /**
+ * Base (the validation floor) has no document. Each attempt reads it beside the target,
+ * and the committed write reads it once more.
+ */
+ const findConfigByPrincipal = jest.fn(async (_type: string, principalId: string) =>
+ principalId === '__base__' ? null : reads.shift(),
+ );
const writeConfigDocument = jest
.fn()
.mockRejectedValueOnce(new ConfigRevisionConflictError())
@@ -3900,7 +3952,8 @@ describe('createAdminConfigHandlers', () => {
);
expect(res.statusCode).toBe(200);
- expect(findConfigByPrincipal).toHaveBeenCalledTimes(2);
+ expect(reads).toHaveLength(0);
+ expect(findConfigByPrincipal).toHaveBeenCalledTimes(5);
expect(writeConfigDocument).toHaveBeenCalledTimes(2);
expect(writeConfigDocument.mock.calls[1][2].overrides).toEqual({
interface: { a: 1, customWelcome: 'x' },
@@ -3908,6 +3961,34 @@ describe('createAdminConfigHandlers', () => {
expect(writeConfigDocument.mock.calls[1][3]).toBe('64b000000000000000000001:5');
});
+ it('keeps a committed write when Base cannot be read again to check it', async () => {
+ let baseReads = 0;
+ const findConfigByPrincipal = jest.fn(async (_type: string, principalId: string) => {
+ if (principalId !== '__base__') {
+ return stored;
+ }
+ baseReads += 1;
+ if (baseReads > 1) {
+ throw new Error('connection reset');
+ }
+ return null;
+ });
+ const { handlers, deps } = createHandlers({ findConfigByPrincipal });
+ const res = mockRes();
+
+ await handlers.patchConfigField(
+ mockReq({
+ params,
+ body: { entries: [{ fieldPath: 'interface.customWelcome', value: 'kept' }] },
+ }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(baseReads).toBe(2);
+ expect(deps.writeConfigDocument).toHaveBeenCalledTimes(1);
+ });
+
it('answers 409 once the retry budget is spent', async () => {
const findConfigByPrincipal = jest.fn().mockResolvedValue(stored);
const writeConfigDocument = jest.fn().mockRejectedValue(new ConfigRevisionConflictError());
@@ -3926,7 +4007,9 @@ describe('createAdminConfigHandlers', () => {
});
it('passes the precondition through to tombstone, field delete, delete and toggle', async () => {
- const { handlers, deps } = createHandlers();
+ const { handlers, deps } = createHandlers({
+ findConfigByPrincipal: jest.fn().mockResolvedValue(stored),
+ });
await handlers.tombstoneConfigField(
mockReq({ params, body: { fieldPath: 'memory', expectedRevision: storedRevision } }),
@@ -3946,7 +4029,7 @@ describe('createAdminConfigHandlers', () => {
);
const options = { expectedRevision: storedRevision };
- expect(deps.tombstoneConfigField.mock.calls[0][6]).toEqual(options);
+ expect(deps.writeConfigDocument.mock.calls[0][3]).toBe(storedRevision);
expect(deps.unsetConfigField.mock.calls[0][4]).toEqual(options);
expect(deps.deleteConfig.mock.calls[0][3]).toEqual({ expectEmpty: false, ...options });
expect(deps.toggleConfigActiveTracked.mock.calls[0][3]).toEqual({
@@ -3956,7 +4039,7 @@ describe('createAdminConfigHandlers', () => {
});
it.each([
- ['tombstoneConfigField', { body: { fieldPath: 'memory' } }, 'tombstoneConfigField'],
+ ['tombstoneConfigField', { body: { fieldPath: 'memory' } }, 'writeConfigDocument'],
['deleteConfigField', { query: { fieldPath: 'memory' } }, 'unsetConfigField'],
['deleteConfigOverrides', {}, 'deleteConfig'],
['toggleConfig', { body: { isActive: true } }, 'toggleConfigActiveTracked'],
@@ -4042,7 +4125,7 @@ describe('createAdminConfigHandlers', () => {
expect(gone.body?.currentRevision).toBeNull();
for (const deps of [exists.deps, missing.deps]) {
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
- expect(deps.tombstoneConfigField).not.toHaveBeenCalled();
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
expect(deps.unsetConfigField).not.toHaveBeenCalled();
}
},
@@ -4061,7 +4144,12 @@ describe('createAdminConfigHandlers', () => {
);
expect(matched.statusCode).toBe(200);
expect(matched.body?.revision).toBe(storedRevision);
+ },
+ );
+ it.each(noops.filter(([name]) => name !== 'upsertConfigOverrides'))(
+ '%s answers 200 with no revision under absent when there is no document',
+ async (name, location, input) => {
const missing = createHandlers();
const absent = mockRes();
await missing.handlers[name](
@@ -4072,6 +4160,22 @@ describe('createAdminConfigHandlers', () => {
expect(absent.body?.revision).toBeNull();
},
);
+
+ it('upsertConfigOverrides under absent creates the empty profile, as a create-only PUT does', async () => {
+ const missing = createHandlers();
+ const absent = mockRes();
+ await missing.handlers.upsertConfigOverrides(
+ mockReq({ params, body: { overrides: { filters: {} }, expectedRevision: 'absent' } }),
+ absent,
+ );
+ expect(absent.statusCode).toBe(201);
+ expect(missing.deps.writeConfigDocument).toHaveBeenCalledWith(
+ params.principalType,
+ params.principalId,
+ expect.objectContaining({ overrides: {}, tombstones: [], isActive: true }),
+ 'absent',
+ );
+ });
});
it('returns revisions on reads', async () => {
@@ -4270,4 +4374,185 @@ describe('createAdminConfigHandlers', () => {
);
});
});
+
+ describe('updateConfigPriority', () => {
+ const params = { principalType: 'role', principalId: 'editor' };
+ const document = {
+ _id: '64b000000000000000000001',
+ principalType: 'role',
+ principalId: 'editor',
+ priority: 30,
+ overrides: { webSearch: { serperApiKey: 'v3:cipher', serperApiKeyPreview: 'sk-...1234' } },
+ tombstones: [],
+ isActive: true,
+ configVersion: 4,
+ };
+
+ it('rejects a bad principal type, priority or revision before touching anything', async () => {
+ const setConfigPriority = jest.fn();
+ const { handlers } = createHandlers({ setConfigPriority });
+ const cases: Array<[Record<string, unknown>, Record<string, unknown>, string]> = [
+ [{ principalType: 'public', principalId: 'x' }, { priority: 1 }, 'INVALID_PRINCIPAL_TYPE'],
+ [params, {}, 'INVALID_PRIORITY'],
+ [params, { priority: -1 }, 'INVALID_PRIORITY'],
+ [params, { priority: '3' }, 'INVALID_PRIORITY'],
+ [params, { priority: 1, expectedRevision: 'nope' }, 'INVALID_EXPECTED_REVISION'],
+ ];
+
+ for (const [reqParams, body, code] of cases) {
+ const res = mockRes();
+ await handlers.updateConfigPriority(mockReq({ params: reqParams, body }), res);
+ expect(res.statusCode).toBe(400);
+ expect(res.body?.code).toBe(code);
+ }
+ expect(setConfigPriority).not.toHaveBeenCalled();
+ });
+
+ it('requires an authenticated broad manager', async () => {
+ const setConfigPriority = jest.fn();
+ const unauthenticated = mockRes();
+ const { handlers } = createHandlers({ setConfigPriority });
+ await handlers.updateConfigPriority(
+ mockReq({ params, body: { priority: 1 }, user: undefined }),
+ unauthenticated,
+ );
+
+ const sectionScoped = createHandlers({
+ setConfigPriority,
+ hasConfigCapability: jest.fn(async (_user: unknown, section: string | null) => !!section),
+ });
+ const forbidden = mockRes();
+ await sectionScoped.handlers.updateConfigPriority(
+ mockReq({ params, body: { priority: 1 } }),
+ forbidden,
+ );
+
+ expect(unauthenticated.statusCode).toBe(401);
+ expect(forbidden.statusCode).toBe(403);
+ expect(setConfigPriority).not.toHaveBeenCalled();
+ });
+
+ it('answers 501 when the server did not wire the priority write', async () => {
+ const { handlers } = createHandlers();
+ const res = mockRes();
+
+ await handlers.updateConfigPriority(mockReq({ params, body: { priority: 1 } }), res);
+
+ expect(res.statusCode).toBe(501);
+ });
+
+ it('passes the revision through and redacts the stored secrets in the response', async () => {
+ const setConfigPriority = jest
+ .fn()
+ .mockResolvedValue({ config: { ...document, priority: 5 }, changed: true });
+ const { handlers } = createHandlers({ setConfigPriority });
+ const res = mockRes();
+
+ await handlers.updateConfigPriority(
+ mockReq({ params, body: { priority: 5, expectedRevision: '64b000000000000000000001:4' } }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(setConfigPriority).toHaveBeenCalledWith('role', 'editor', 5, {
+ expectedRevision: '64b000000000000000000001:4',
+ });
+ const config = res.body?.config as { overrides: { webSearch: Record<string, unknown> } };
+ expect(config.overrides.webSearch.serperApiKey).toBeUndefined();
+ expect(JSON.stringify(res.body)).not.toContain('v3:cipher');
+ });
+
+ it('answers 409 with the current revision when the precondition is stale', async () => {
+ const setConfigPriority = jest
+ .fn()
+ .mockRejectedValue(new ConfigRevisionConflictError('64b000000000000000000001:5'));
+ const { handlers } = createHandlers({ setConfigPriority });
+ const res = mockRes();
+
+ await handlers.updateConfigPriority(
+ mockReq({ params, body: { priority: 5, expectedRevision: '64b000000000000000000001:4' } }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(409);
+ expect(res.body).toEqual({
+ error: 'Config was modified by another request',
+ code: 'CONFIG_VERSION_CONFLICT',
+ currentRevision: '64b000000000000000000001:5',
+ });
+ });
+ });
+
+ describe('principal existence on create', () => {
+ const entry = { entries: [{ fieldPath: 'interface.customWelcome', value: 'hi' }] };
+
+ it('does not look the principal up when its document already exists', async () => {
+ const principalExists = jest.fn().mockResolvedValue(false);
+ const { handlers } = createHandlers({
+ principalExists,
+ findConfigByPrincipal: jest.fn(async (_type: string, principalId: string) =>
+ principalId === '__base__'
+ ? null
+ : { _id: '64b000000000000000000001', priority: 10, overrides: {}, configVersion: 1 },
+ ),
+ });
+ const res = mockRes();
+
+ await handlers.patchConfigField(
+ mockReq({ params: { principalType: 'role', principalId: 'retired' }, body: entry }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(principalExists).not.toHaveBeenCalled();
+ });
+
+ it('never looks Base up, and refuses a principal the lookup does not find', async () => {
+ const principalExists = jest.fn().mockResolvedValue(false);
+ const { handlers } = createHandlers({ principalExists });
+
+ const base = mockRes();
+ await handlers.patchConfigField(
+ mockReq({ params: { principalType: 'role', principalId: '__base__' }, body: entry }),
+ base,
+ );
+ const group = mockRes();
+ await handlers.patchConfigField(
+ mockReq({
+ params: { principalType: 'group', principalId: 'grp_engineering' },
+ body: entry,
+ }),
+ group,
+ );
+
+ expect(base.statusCode).toBe(200);
+ expect(group.statusCode).toBe(404);
+ expect(group.body?.code).toBe('PRINCIPAL_NOT_FOUND');
+ expect(principalExists).toHaveBeenCalledTimes(1);
+ expect(principalExists).toHaveBeenCalledWith('group', 'grp_engineering');
+ });
+ });
+
+ describe('create-only PUT', () => {
+ it('writes an empty create-only request instead of answering it as a no-op', async () => {
+ const { handlers, deps } = createHandlers();
+ const res = mockRes();
+
+ await handlers.upsertConfigOverrides(
+ mockReq({
+ params: { principalType: 'user', principalId: '64b000000000000000000009' },
+ body: { overrides: {}, expectedRevision: 'absent' },
+ }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(201);
+ expect(deps.writeConfigDocument).toHaveBeenCalledWith(
+ 'user',
+ '64b000000000000000000009',
+ { principalModel: 'User', priority: 100, overrides: {}, tombstones: [], isActive: true },
+ 'absent',
+ );
+ });
+ });
});
diff --git a/packages/api/src/admin/config.integration.spec.ts b/packages/api/src/admin/config.integration.spec.ts
index 490282dff5..3e79f0265c 100644
--- a/packages/api/src/admin/config.integration.spec.ts
+++ b/packages/api/src/admin/config.integration.spec.ts
@@ -71,7 +71,6 @@ function handlersFor(
listAllConfigs: methods.listAllConfigs,
findConfigByPrincipal: methods.findConfigByPrincipal,
writeConfigDocument: methods.writeConfigDocument,
- tombstoneConfigField: methods.tombstoneConfigField,
unsetConfigField: methods.unsetConfigField,
deleteConfig: methods.deleteConfig,
toggleConfigActiveTracked: methods.toggleConfigActiveTracked,
diff --git a/packages/api/src/admin/config.precedence.integration.spec.ts b/packages/api/src/admin/config.precedence.integration.spec.ts
new file mode 100644
index 0000000000..861c516ae4
--- /dev/null
+++ b/packages/api/src/admin/config.precedence.integration.spec.ts
@@ -0,0 +1,1024 @@
+import mongoose, { Types } from 'mongoose';
+import { MongoMemoryServer } from 'mongodb-memory-server';
+import type { TCustomConfig } from 'librechat-data-provider';
+import type { Response } from 'express';
+import type { ServerRequest } from '~/types/http';
+
+process.env.CREDS_KEY =
+ process.env.CREDS_KEY ?? '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
+process.env.CREDS_IV = process.env.CREDS_IV ?? '0123456789abcdef0123456789abcdef';
+
+type DataSchemas = typeof import('@librechat/data-schemas');
+type Methods = ReturnType<DataSchemas['createMethods']>;
+type AdminConfigHandlers = ReturnType<typeof import('./config').createAdminConfigHandlers>;
+type AdminConfigDeps = Parameters<typeof import('./config').createAdminConfigHandlers>[0];
+type Handler = (req: ServerRequest, res: Response) => Promise<Response>;
+
+interface MockRes {
+ statusCode: number;
+ body: undefined | Record<string, unknown>;
+ status: jest.Mock;
+ json: jest.Mock;
+}
+
+interface ConfigBody {
+ _id: string;
+ priority: number;
+ overrides: Record<string, unknown>;
+ tombstones: string[];
+ isActive: boolean;
+ configVersion: number;
+ revision: string;
+}
+
+/**
+ * The admin config handlers on a real Config, Role, Group and User collection: precedence and
+ * default priorities (W2-1), the profile lifecycle (W2-16) and validation on the Base floor
+ * (W2-3).
+ */
+
+let mongoServer: MongoMemoryServer;
+let methods: Methods;
+let dataSchemas: DataSchemas;
+let createAdminConfigHandlers: typeof import('./config').createAdminConfigHandlers;
+
+const LIFECYCLE_TIMEOUT_MS = 180_000;
+
+beforeAll(async () => {
+ const [schemas, handlersModule, server] = await Promise.all([
+ import('@librechat/data-schemas'),
+ import('./config'),
+ MongoMemoryServer.create(),
+ ]);
+ dataSchemas = schemas;
+ mongoServer = server;
+ ({ createAdminConfigHandlers } = handlersModule);
+ jest.spyOn(schemas.logger, 'error').mockReturnValue(schemas.logger);
+ jest.spyOn(schemas.logger, 'warn').mockReturnValue(schemas.logger);
+ jest.spyOn(schemas.logger, 'info').mockReturnValue(schemas.logger);
+
+ await mongoose.connect(mongoServer.getUri());
+ schemas.createModels(mongoose);
+ await mongoose.models.Config.init();
+ methods = schemas.createMethods(mongoose);
+}, LIFECYCLE_TIMEOUT_MS);
+
+afterAll(async () => {
+ await mongoose.disconnect();
+ await mongoServer?.stop();
+}, LIFECYCLE_TIMEOUT_MS);
+
+beforeEach(async () => {
+ await Promise.all(
+ ['Config', 'Role', 'Group', 'User'].map((name) => mongoose.models[name].deleteMany({})),
+ );
+});
+
+function mockReq(overrides: Record<string, unknown> = {}): ServerRequest {
+ return {
+ user: { id: 'u1', role: 'ADMIN', _id: { toString: () => 'u1' } },
+ params: {},
+ body: {},
+ query: {},
+ ...overrides,
+ } as Partial<ServerRequest> as ServerRequest;
+}
+
+function mockRes(): Response & MockRes {
+ const res: MockRes = {
+ statusCode: 200,
+ body: undefined,
+ status: jest.fn((code: number) => {
+ res.statusCode = code;
+ return res;
+ }),
+ json: jest.fn((data: MockRes['body']) => {
+ res.body = data;
+ return res;
+ }),
+ };
+ return res as Partial<Response> as Response & MockRes;
+}
+
+/** Handlers wired the way `api/server/routes/admin/config.js` wires them, over `yaml`. */
+function createHandlers(
+ yaml: Partial<TCustomConfig> = {},
+ overrides: Partial<AdminConfigDeps> = {},
+): AdminConfigHandlers {
+ return createAdminConfigHandlers({
+ listAllConfigs: methods.listAllConfigs,
+ findConfigByPrincipal: methods.findConfigByPrincipal,
+ writeConfigDocument: methods.writeConfigDocument,
+ unsetConfigField: methods.unsetConfigField,
+ deleteConfig: methods.deleteConfig,
+ toggleConfigActiveTracked: methods.toggleConfigActiveTracked,
+ setConfigPriority: methods.setConfigPriority,
+ principalExists: methods.principalExists,
+ hasConfigCapability: async () => true,
+ hasAnyConfigReadAccess: async () => true,
+ hasCapability: async () => true,
+ getAppConfig: async () => ({ config: yaml }) as never,
+ ...overrides,
+ });
+}
+
+async function call(handler: Handler, request: Record<string, unknown>): Promise<MockRes> {
+ const res = mockRes();
+ await handler(mockReq(request), res);
+ return res;
+}
+
+const configOf = (res: MockRes): ConfigBody => res.body?.config as ConfigBody;
+
+const roleParams = (principalId: string) => ({ principalType: 'role', principalId });
+const BASE = roleParams('__base__');
+
+async function createRole(name: string): Promise<void> {
+ await methods.createRoleByName({ name, permissions: {} });
+}
+
+async function createGroup(name: string): Promise<string> {
+ const group = await methods.createGroup({ name, source: 'local' });
+ return group._id.toString();
+}
+
+async function createUser(email: string): Promise<string> {
+ const id = await methods.createUser({ email, name: email, provider: 'local' }, undefined, true);
+ return id.toString();
+}
+
+const stored = (principalType: string, principalId: string) =>
+ methods.findConfigByPrincipal(principalType as never, principalId, { includeInactive: true });
+
+describe('validation on the Base floor (W2-3)', () => {
+ /** librechat.yaml names a memory agent by id. */
+ const agentIdYaml = { memory: { agent: { id: 'agent_1' } } } as Partial<TCustomConfig>;
+ /** librechat.yaml picks a memory provider and model. */
+ const providerYaml = {
+ memory: { agent: { provider: 'openAI', model: 'gpt-4o' } },
+ } as Partial<TCustomConfig>;
+
+ /** Base drops the YAML agent id and picks a provider and model instead. */
+ async function switchBaseToProvider(handlers: AdminConfigHandlers): Promise<void> {
+ const tombstoned = await call(handlers.tombstoneConfigField, {
+ params: BASE,
+ body: { fieldPath: 'memory.agent.id' },
+ });
+ expect(tombstoned.statusCode).toBe(200);
+ const patched = await call(handlers.patchConfigField, {
+ params: BASE,
+ body: {
+ entries: [
+ { fieldPath: 'memory.agent.provider', value: 'openAI' },
+ { fieldPath: 'memory.agent.model', value: 'gpt-4o' },
+ ],
+ },
+ });
+ expect(patched.statusCode).toBe(200);
+ }
+
+ /** Base drops the YAML provider and model and names an agent instead. */
+ async function switchBaseToAgentId(handlers: AdminConfigHandlers): Promise<void> {
+ for (const fieldPath of ['memory.agent.provider', 'memory.agent.model']) {
+ const tombstoned = await call(handlers.tombstoneConfigField, {
+ params: BASE,
+ body: { fieldPath },
+ });
+ expect(tombstoned.statusCode).toBe(200);
+ }
+ const patched = await call(handlers.patchConfigField, {
+ params: BASE,
+ body: { entries: [{ fieldPath: 'memory.agent.id', value: 'agent_9' }] },
+ });
+ expect(patched.statusCode).toBe(200);
+ }
+
+ it('accepts a profile write that is valid on top of Base, though not on the YAML alone', async () => {
+ const handlers = createHandlers(agentIdYaml);
+ await createRole('editor');
+ await switchBaseToProvider(handlers);
+
+ const patched = await call(handlers.patchConfigField, {
+ params: roleParams('editor'),
+ body: { entries: [{ fieldPath: 'memory.agent.model', value: 'gpt-4.1' }] },
+ });
+ const replaced = await call(handlers.upsertConfigOverrides, {
+ params: roleParams('editor'),
+ body: { overrides: { memory: { agent: { model: 'gpt-4.1-mini' } } } },
+ });
+
+ expect(patched.statusCode).toBe(200);
+ expect(replaced.statusCode).toBe(200);
+ expect((await stored('role', 'editor'))?.overrides).toEqual({
+ memory: { agent: { model: 'gpt-4.1-mini' } },
+ });
+ });
+
+ it('refuses a profile write that only fails on top of Base, which the merge would drop', async () => {
+ const handlers = createHandlers(providerYaml);
+ await createRole('editor');
+ await switchBaseToAgentId(handlers);
+
+ const patched = await call(handlers.patchConfigField, {
+ params: roleParams('editor'),
+ body: { entries: [{ fieldPath: 'memory.agent.model', value: 'gpt-4.1' }] },
+ });
+
+ expect(patched.statusCode).toBe(400);
+ expect(patched.body).toEqual({
+ error: 'Invalid config override',
+ code: 'CONFIG_OVERRIDE_INVALID',
+ issues: [
+ {
+ path: 'memory.agent.model',
+ segments: ['memory', 'agent', 'model'],
+ code: 'union_dropped_key',
+ },
+ ],
+ });
+ expect(await stored('role', 'editor')).toBeNull();
+ });
+
+ it('judges a POST /changes batch on the Base floor: valid only on top of Base', async () => {
+ const handlers = createHandlers(agentIdYaml);
+ await createRole('editor');
+ await switchBaseToProvider(handlers);
+
+ const changed = await call(handlers.applyConfigChanges, {
+ params: roleParams('editor'),
+ body: { ops: [{ op: 'set', fieldPath: 'memory.agent.model', value: 'gpt-4.1' }] },
+ });
+
+ expect(changed.statusCode).toBe(200);
+ expect(changed.body?.written).toBe(true);
+ expect((await stored('role', 'editor'))?.overrides).toEqual({
+ memory: { agent: { model: 'gpt-4.1' } },
+ });
+ });
+
+ it('refuses a POST /changes batch that only fails on top of Base', async () => {
+ const handlers = createHandlers(providerYaml);
+ await createRole('editor');
+ await switchBaseToAgentId(handlers);
+
+ const changed = await call(handlers.applyConfigChanges, {
+ params: roleParams('editor'),
+ body: { ops: [{ op: 'set', fieldPath: 'memory.agent.model', value: 'gpt-4.1' }] },
+ });
+
+ expect(changed.statusCode).toBe(400);
+ expect(changed.body).toMatchObject({
+ code: 'CONFIG_OVERRIDE_INVALID',
+ issues: [
+ {
+ path: 'memory.agent.model',
+ segments: ['memory', 'agent', 'model'],
+ code: 'union_dropped_key',
+ },
+ ],
+ });
+ expect(await stored('role', 'editor')).toBeNull();
+ });
+
+ it("validates a caller without a tenant on the platform Base, never on a tenant's Base", async () => {
+ const handlers = createHandlers(providerYaml);
+ await createRole('editor');
+ await dataSchemas.tenantStorage.run({ tenantId: 'tenant-a' }, () =>
+ switchBaseToAgentId(handlers),
+ );
+
+ const patched = await call(handlers.patchConfigField, {
+ params: roleParams('editor'),
+ body: { entries: [{ fieldPath: 'memory.agent.model', value: 'gpt-4.1' }] },
+ });
+
+ expect(patched.statusCode).toBe(200);
+ expect((await stored('role', 'editor'))?.overrides).toEqual({
+ memory: { agent: { model: 'gpt-4.1' } },
+ });
+ });
+
+ it('ignores an inactive Base, which the merge skips too', async () => {
+ const handlers = createHandlers(providerYaml);
+ await createRole('editor');
+ await switchBaseToAgentId(handlers);
+ const toggled = await call(handlers.toggleConfig, {
+ params: BASE,
+ body: { isActive: false },
+ });
+ expect(toggled.statusCode).toBe(200);
+
+ const patched = await call(handlers.patchConfigField, {
+ params: roleParams('editor'),
+ body: { entries: [{ fieldPath: 'memory.agent.model', value: 'gpt-4.1' }] },
+ });
+
+ expect(patched.statusCode).toBe(200);
+ });
+
+ it('validates a Base write on the YAML alone, not on the Base document it replaces', async () => {
+ const handlers = createHandlers(providerYaml);
+ await switchBaseToAgentId(handlers);
+
+ /**
+ * Base switches back to a provider. On its own stored agent id this would be refused (the id
+ * option would drop the provider and model); on the YAML, minus Base's tombstones, it is valid.
+ */
+ const replaced = await call(handlers.upsertConfigOverrides, {
+ params: BASE,
+ body: { overrides: { memory: { agent: { provider: 'anthropic', model: 'claude' } } } },
+ });
+
+ expect(replaced.statusCode).toBe(200);
+ expect(configOf(replaced).overrides).toEqual({
+ memory: { agent: { provider: 'anthropic', model: 'claude' } },
+ });
+ });
+});
+
+describe('validation on the Base the write lands over (W2-3)', () => {
+ const providerYaml = {
+ memory: { agent: { provider: 'openAI', model: 'gpt-4o' } },
+ } as Partial<TCustomConfig>;
+ const editor = roleParams('editor');
+ const setModel = { entries: [{ fieldPath: 'memory.agent.model', value: 'gpt-4.1' }] };
+ const setWelcome = (value: string) => ({
+ entries: [{ fieldPath: 'interface.customWelcome', value }],
+ });
+
+ /** Base drops the YAML provider and model and names an agent, so a profile's model is invalid. */
+ async function switchBaseToAgentId(handlers: AdminConfigHandlers): Promise<void> {
+ const changed = await call(handlers.applyConfigChanges, {
+ params: BASE,
+ body: {
+ ops: [
+ { op: 'tombstone', fieldPath: 'memory.agent.provider' },
+ { op: 'tombstone', fieldPath: 'memory.agent.model' },
+ { op: 'set', fieldPath: 'memory.agent.id', value: 'agent_9' },
+ ],
+ },
+ });
+ expect(changed.statusCode).toBe(200);
+ }
+
+ /**
+ * Handlers whose first write to `editor` runs `before` just before it reaches the store and
+ * `after` once it has committed: what concurrent requests do in between.
+ */
+ function racingHandlers(
+ hooks: { before?: () => Promise<void>; after?: () => Promise<void> },
+ overrides: Partial<AdminConfigDeps> = {},
+ ): AdminConfigHandlers {
+ let raced = false;
+ return createHandlers(providerYaml, {
+ ...overrides,
+ writeConfigDocument: async (principalType, principalId, draft, expected) => {
+ const first = !raced && principalId === 'editor';
+ raced ||= first;
+ if (first) {
+ await hooks.before?.();
+ }
+ const written = await methods.writeConfigDocument(
+ principalType,
+ principalId,
+ draft,
+ expected,
+ );
+ if (first) {
+ await hooks.after?.();
+ }
+ return written;
+ },
+ });
+ }
+
+ it('judges a write that retries after losing a race on the Base it reads again', async () => {
+ const handlers = createHandlers(providerYaml);
+ await createRole('editor');
+ await call(handlers.patchConfigField, { params: editor, body: setWelcome('first') });
+ const racing = racingHandlers({
+ before: async () => {
+ await switchBaseToAgentId(handlers);
+ await call(handlers.patchConfigField, { params: editor, body: setWelcome('concurrent') });
+ },
+ });
+
+ const patched = await call(racing.patchConfigField, { params: editor, body: setModel });
+
+ expect(patched.statusCode).toBe(400);
+ expect(patched.body?.issues).toEqual([expect.objectContaining({ code: 'union_dropped_key' })]);
+ /** Refused before its retry wrote anything: no write landed to be withdrawn again. */
+ expect(await stored('role', 'editor')).toMatchObject({
+ overrides: { interface: { customWelcome: 'concurrent' } },
+ configVersion: 2,
+ });
+ });
+
+ it('withdraws a write Base changed under before it committed, and answers as Base now judges it', async () => {
+ const handlers = createHandlers(providerYaml);
+ await createRole('editor');
+ await call(handlers.patchConfigField, { params: editor, body: setWelcome('first') });
+ const invalidateConfigCaches = jest.fn().mockResolvedValue(undefined);
+ const racing = racingHandlers(
+ { before: () => switchBaseToAgentId(handlers) },
+ { invalidateConfigCaches },
+ );
+
+ const patched = await call(racing.patchConfigField, { params: editor, body: setModel });
+
+ expect(patched.statusCode).toBe(400);
+ expect(patched.body?.issues).toEqual([expect.objectContaining({ code: 'union_dropped_key' })]);
+ expect((await stored('role', 'editor'))?.overrides).toEqual({
+ interface: { customWelcome: 'first' },
+ });
+ expect(invalidateConfigCaches).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ {
+ route: 'POST /changes',
+ send: (handlers: AdminConfigHandlers) =>
+ call(handlers.applyConfigChanges, {
+ params: editor,
+ body: { ops: [{ op: 'set', fieldPath: 'memory.agent.model', value: 'gpt-4.1' }] },
+ }),
+ },
+ {
+ route: 'PUT',
+ send: (handlers: AdminConfigHandlers) =>
+ call(handlers.upsertConfigOverrides, {
+ params: editor,
+ body: { overrides: { memory: { agent: { model: 'gpt-4.1' } } } },
+ }),
+ },
+ ])('$route removes the profile it created on a Base that changed under it', async ({ send }) => {
+ const handlers = createHandlers(providerYaml);
+ await createRole('editor');
+
+ const res = await send(racingHandlers({ before: () => switchBaseToAgentId(handlers) }));
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body?.code).toBe('CONFIG_OVERRIDE_INVALID');
+ expect(await stored('role', 'editor')).toBeNull();
+ });
+
+ it('keeps a write that is still valid on the Base that changed under it', async () => {
+ const handlers = createHandlers(providerYaml);
+ await createRole('editor');
+ const racing = racingHandlers({
+ before: async () => {
+ const based = await call(handlers.patchConfigField, {
+ params: BASE,
+ body: setWelcome('all'),
+ });
+ expect(based.statusCode).toBe(200);
+ },
+ });
+
+ const patched = await call(racing.patchConfigField, { params: editor, body: setModel });
+
+ expect(patched.statusCode).toBe(200);
+ expect((await stored('role', 'editor'))?.overrides).toEqual({
+ memory: { agent: { model: 'gpt-4.1' } },
+ });
+ });
+
+ it('answers 409 and leaves the profile when a later write landed before the withdrawal', async () => {
+ const handlers = createHandlers(providerYaml);
+ await createRole('editor');
+ await call(handlers.patchConfigField, { params: editor, body: setWelcome('first') });
+ const racing = racingHandlers({
+ before: () => switchBaseToAgentId(handlers),
+ after: async () => {
+ await call(handlers.patchConfigField, { params: editor, body: setWelcome('later') });
+ },
+ });
+
+ const patched = await call(racing.patchConfigField, { params: editor, body: setModel });
+
+ const current = await stored('role', 'editor');
+ expect(patched.statusCode).toBe(409);
+ expect(patched.body?.code).toBe('CONFIG_VERSION_CONFLICT');
+ expect(patched.body?.currentRevision).toBe(`${current?._id}:${current?.configVersion}`);
+ expect(current?.overrides).toEqual({
+ interface: { customWelcome: 'later' },
+ memory: { agent: { model: 'gpt-4.1' } },
+ });
+ });
+});
+
+describe('profile lifecycle (W2-16)', () => {
+ it('creates a profile only when none exists: one of two concurrent creates wins', async () => {
+ const handlers = createHandlers();
+ const groupId = await createGroup('Engineering');
+ const create = () =>
+ call(handlers.upsertConfigOverrides, {
+ params: { principalType: 'group', principalId: groupId },
+ body: { overrides: {}, expectedRevision: 'absent' },
+ });
+
+ const results = await Promise.all([create(), create()]);
+ const statuses = results.map((res) => res.statusCode).sort();
+
+ expect(statuses).toEqual([201, 409]);
+ const created = results.find((res) => res.statusCode === 201) as MockRes;
+ const refused = results.find((res) => res.statusCode === 409) as MockRes;
+ expect(configOf(created)).toMatchObject({ priority: 20, overrides: {}, isActive: true });
+ expect(refused.body).toEqual({
+ error: 'Config was modified by another request',
+ code: 'CONFIG_VERSION_CONFLICT',
+ currentRevision: configOf(created).revision,
+ });
+ });
+
+ it('changes only the priority, keeping overrides, tombstones and the inactive state', async () => {
+ const recordAuditEntry = jest.fn().mockResolvedValue(undefined);
+ const invalidateConfigCaches = jest.fn().mockResolvedValue(undefined);
+ const handlers = createHandlers({}, { recordAuditEntry, invalidateConfigCaches });
+ await createRole('editor');
+ const params = roleParams('editor');
+ await call(handlers.patchConfigField, {
+ params,
+ body: { entries: [{ fieldPath: 'interface.customWelcome', value: 'hi' }] },
+ });
+ await call(handlers.tombstoneConfigField, { params, body: { fieldPath: 'memory' } });
+ const toggled = await call(handlers.toggleConfig, { params, body: { isActive: false } });
+ recordAuditEntry.mockClear();
+ invalidateConfigCaches.mockClear();
+
+ const changed = await call(handlers.updateConfigPriority, {
+ params,
+ body: { priority: 40, expectedRevision: configOf(toggled).revision },
+ });
+
+ expect(changed.statusCode).toBe(200);
+ expect(configOf(changed)).toMatchObject({
+ priority: 40,
+ overrides: { interface: { customWelcome: 'hi' } },
+ tombstones: ['memory'],
+ isActive: false,
+ configVersion: configOf(toggled).configVersion + 1,
+ });
+ expect(invalidateConfigCaches).toHaveBeenCalledTimes(1);
+ expect(recordAuditEntry).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: 'config.updated',
+ metadata: { operation: 'priority', priority: 40 },
+ }),
+ );
+
+ recordAuditEntry.mockClear();
+ invalidateConfigCaches.mockClear();
+ const unchanged = await call(handlers.updateConfigPriority, { params, body: { priority: 40 } });
+ expect(unchanged.statusCode).toBe(200);
+ expect(configOf(unchanged).revision).toBe(configOf(changed).revision);
+ expect(recordAuditEntry).not.toHaveBeenCalled();
+ expect(invalidateConfigCaches).not.toHaveBeenCalled();
+
+ const stale = await call(handlers.updateConfigPriority, {
+ params,
+ body: { priority: 41, expectedRevision: configOf(toggled).revision },
+ });
+ expect(stale.statusCode).toBe(409);
+ expect(stale.body?.currentRevision).toBe(configOf(changed).revision);
+ });
+
+ it('keeps the priority route to broad managers and existing profiles', async () => {
+ await createRole('editor');
+ const broad = createHandlers();
+ const params = roleParams('editor');
+
+ const missing = await call(broad.updateConfigPriority, { params, body: { priority: 5 } });
+ expect(missing.statusCode).toBe(404);
+ expect(missing.body?.code).toBe('CONFIG_NOT_FOUND');
+ expect(await stored('role', 'editor')).toBeNull();
+
+ await call(broad.patchConfigField, {
+ params,
+ body: { entries: [{ fieldPath: 'interface.customWelcome', value: 'hi' }] },
+ });
+ const sectionScoped = createHandlers(
+ {},
+ {
+ hasConfigCapability: async (_user, section) => section === 'interface',
+ },
+ );
+ const denied = await call(sectionScoped.updateConfigPriority, {
+ params,
+ body: { priority: 5 },
+ });
+ expect(denied.statusCode).toBe(403);
+ expect((await stored('role', 'editor'))?.priority).toBe(10);
+
+ for (const priority of [-1, '5', null, undefined]) {
+ const invalid = await call(broad.updateConfigPriority, { params, body: { priority } });
+ expect(invalid.statusCode).toBe(400);
+ expect(invalid.body?.code).toBe('INVALID_PRIORITY');
+ }
+ });
+
+ it("changes the priority only in the caller's tenant partition", async () => {
+ const handlers = createHandlers();
+ const inTenant = <T>(tenantId: string, run: () => Promise<T>) =>
+ dataSchemas.tenantStorage.run({ tenantId }, run);
+ const params = roleParams('editor');
+ const reorder = (priority: number) =>
+ call(handlers.updateConfigPriority, { params, body: { priority } });
+ /** Every stored `editor` profile as `tenant:priority`, the platform-level one as `-:…`. */
+ const priorities = async () =>
+ (
+ await mongoose.models.Config.collection
+ .find({ principalType: 'role', principalId: 'editor' })
+ .project<{ priority: number; tenantId?: string }>({ priority: 1, tenantId: 1 })
+ .toArray()
+ )
+ .map((document) => `${document.tenantId ?? '-'}:${document.priority}`)
+ .sort();
+ await inTenant('tenant-a', async () => {
+ await createRole('editor');
+ const created = await call(handlers.patchConfigField, {
+ params,
+ body: { entries: [{ fieldPath: 'interface.customWelcome', value: 'tenant-a' }] },
+ });
+ expect(created.statusCode).toBe(200);
+ });
+
+ const onlyTenant = await reorder(40);
+ expect(onlyTenant.statusCode).toBe(404);
+ expect(onlyTenant.body?.code).toBe('CONFIG_NOT_FOUND');
+ expect(await priorities()).toEqual(['tenant-a:10']);
+
+ await mongoose.models.Config.collection.insertOne({
+ principalType: 'role',
+ principalId: 'editor',
+ principalModel: 'Role',
+ priority: 10,
+ overrides: { interface: { customWelcome: 'platform' } },
+ tombstones: [],
+ isActive: true,
+ configVersion: 1,
+ });
+ const platform = await reorder(40);
+ expect(platform.statusCode).toBe(200);
+ expect(configOf(platform).overrides).toEqual({ interface: { customWelcome: 'platform' } });
+ expect(await priorities()).toEqual(['-:40', 'tenant-a:10']);
+
+ const tenant = await inTenant('tenant-a', () => reorder(30));
+ expect(tenant.statusCode).toBe(200);
+ expect(configOf(tenant).overrides).toEqual({ interface: { customWelcome: 'tenant-a' } });
+ expect(await priorities()).toEqual(['-:40', 'tenant-a:30']);
+ });
+
+ it("answers a priority write that loses a race with the revision in the caller's partition", async () => {
+ const handlers = createHandlers();
+ const params = roleParams('editor');
+ await dataSchemas.tenantStorage.run({ tenantId: 'tenant-a' }, async () => {
+ await createRole('editor');
+ const created = await call(handlers.patchConfigField, {
+ params,
+ body: { entries: [{ fieldPath: 'interface.customWelcome', value: 'tenant-a' }] },
+ });
+ expect(created.statusCode).toBe(200);
+ });
+ const collection = mongoose.models.Config.collection;
+ const { insertedId } = await collection.insertOne({
+ principalType: 'role',
+ principalId: 'editor',
+ principalModel: 'Role',
+ priority: 10,
+ overrides: { interface: { customWelcome: 'platform' } },
+ tombstones: [],
+ isActive: true,
+ configVersion: 1,
+ });
+ const findOneAndUpdate = collection.findOneAndUpdate.bind(collection);
+ /** Another platform admin deletes the profile between this request's read and its write. */
+ jest.spyOn(collection, 'findOneAndUpdate').mockImplementationOnce((async (
+ ...args: Parameters<typeof findOneAndUpdate>
+ ) => {
+ await collection.deleteOne({ _id: insertedId });
+ return findOneAndUpdate(...args);
+ }) as unknown as typeof collection.findOneAndUpdate);
+
+ const lost = await call(handlers.updateConfigPriority, {
+ params,
+ body: { priority: 40, expectedRevision: `${insertedId}:1` },
+ });
+
+ expect(lost.statusCode).toBe(409);
+ expect(lost.body).toEqual({
+ error: 'Config was modified by another request',
+ code: 'CONFIG_VERSION_CONFLICT',
+ currentRevision: null,
+ });
+ });
+
+ it('refuses to create a profile for a role, group or user that does not exist', async () => {
+ const handlers = createHandlers();
+ const missingObjectId = new Types.ObjectId().toString();
+ const writes: Array<[Handler, Record<string, unknown>, Record<string, unknown>]> = [
+ [handlers.upsertConfigOverrides, roleParams('ghost'), { overrides: {}, priority: 5 }],
+ [
+ handlers.patchConfigField,
+ { principalType: 'group', principalId: 'grp_engineering' },
+ { entries: [{ fieldPath: 'interface.customWelcome', value: 'hi' }] },
+ ],
+ [
+ handlers.patchConfigField,
+ { principalType: 'group', principalId: missingObjectId },
+ { entries: [{ fieldPath: 'interface.customWelcome', value: 'hi' }] },
+ ],
+ [
+ handlers.tombstoneConfigField,
+ { principalType: 'user', principalId: missingObjectId },
+ { fieldPath: 'memory' },
+ ],
+ ];
+
+ for (const [handler, params, body] of writes) {
+ const res = await call(handler, { params, body });
+ expect(res.statusCode).toBe(404);
+ expect(res.body).toEqual({ error: 'Principal not found', code: 'PRINCIPAL_NOT_FOUND' });
+ }
+ expect(await methods.listAllConfigs()).toEqual([]);
+ });
+
+ it('refuses a POST /changes batch that would create a document for a missing principal', async () => {
+ const handlers = createHandlers();
+ const missingObjectId = new Types.ObjectId().toString();
+ const set = [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' }];
+ const batches: Array<[Record<string, unknown>, Record<string, unknown>]> = [
+ [roleParams('ghost'), { ops: set }],
+ /** A batch that changes nothing but the priority would otherwise create a document. */
+ [
+ { principalType: 'group', principalId: missingObjectId },
+ { ops: [{ op: 'unset', fieldPath: 'interface.customWelcome' }], priority: 30 },
+ ],
+ [
+ { principalType: 'user', principalId: missingObjectId },
+ { ops: [{ op: 'tombstone', fieldPath: 'memory' }], dryRun: true },
+ ],
+ [{ principalType: 'group', principalId: 'grp_engineering' }, { ops: set }],
+ ];
+
+ for (const [params, body] of batches) {
+ const res = await call(handlers.applyConfigChanges, { params, body });
+ expect(res.statusCode).toBe(404);
+ expect(res.body).toEqual({ error: 'Principal not found', code: 'PRINCIPAL_NOT_FOUND' });
+ }
+ expect(await methods.listAllConfigs()).toEqual([]);
+ });
+
+ it('creates first documents through POST /changes at the type default priority', async () => {
+ const handlers = createHandlers();
+ await createRole('editor');
+ const groupId = await createGroup('Engineering');
+ const userId = await createUser('[email protected]');
+ const ops = [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' }];
+
+ const results = await Promise.all(
+ [
+ roleParams('editor'),
+ { principalType: 'group', principalId: groupId },
+ { principalType: 'user', principalId: userId },
+ BASE,
+ ].map((params) => call(handlers.applyConfigChanges, { params, body: { ops } })),
+ );
+
+ expect(results.map((res) => res.statusCode)).toEqual([200, 200, 200, 200]);
+ expect(results.map((res) => configOf(res).priority)).toEqual([10, 20, 100, 0]);
+ });
+
+ it('lets a priority-only POST /changes batch create the document of a principal that exists', async () => {
+ const handlers = createHandlers();
+ const userId = await createUser('[email protected]');
+
+ const res = await call(handlers.applyConfigChanges, {
+ params: { principalType: 'user', principalId: userId },
+ body: { ops: [{ op: 'unset', fieldPath: 'interface.customWelcome' }], priority: 30 },
+ });
+
+ expect(res.statusCode).toBe(200);
+ expect(configOf(res)).toMatchObject({ priority: 30, overrides: {}, tombstones: [] });
+ });
+
+ it('creates a first document at the type default when tombstoning a web search URL', async () => {
+ const handlers = createHandlers();
+ const groupId = await createGroup('Engineering');
+ const userId = await createUser('[email protected]');
+
+ const results = await Promise.all(
+ [
+ { principalType: 'group', principalId: groupId },
+ { principalType: 'user', principalId: userId },
+ ].map((params) =>
+ call(handlers.tombstoneConfigField, {
+ params,
+ body: { fieldPath: 'webSearch.jinaApiUrl' },
+ }),
+ ),
+ );
+
+ expect(results.map((res) => res.statusCode)).toEqual([200, 200]);
+ expect(results.map((res) => configOf(res).priority)).toEqual([20, 100]);
+ expect(results.map((res) => configOf(res).tombstones)).toEqual([
+ ['webSearch.jinaApiUrl'],
+ ['webSearch.jinaApiUrl'],
+ ]);
+ });
+
+ it('creates profiles for principals that exist, at their type default priority', async () => {
+ const handlers = createHandlers();
+ await createRole('editor');
+ const groupId = await createGroup('Engineering');
+ const userId = await createUser('[email protected]');
+ const entry = { entries: [{ fieldPath: 'interface.customWelcome', value: 'hi' }] };
+
+ const results = await Promise.all([
+ call(handlers.patchConfigField, { params: roleParams('editor'), body: entry }),
+ call(handlers.patchConfigField, {
+ params: { principalType: 'group', principalId: groupId },
+ body: entry,
+ }),
+ call(handlers.tombstoneConfigField, {
+ params: { principalType: 'user', principalId: userId },
+ body: { fieldPath: 'memory' },
+ }),
+ call(handlers.patchConfigField, { params: BASE, body: entry }),
+ ]);
+
+ expect(results.map((res) => res.statusCode)).toEqual([200, 200, 200, 200]);
+ expect(results.map((res) => configOf(res).priority)).toEqual([10, 20, 100, 0]);
+ });
+
+ it('checks the principal only when a write would create its first document', async () => {
+ const handlers = createHandlers();
+ /** A profile left behind by a role deleted before cleanup existed. */
+ await methods.patchConfigFields('role' as never, 'retired', 'Role' as never, {
+ 'interface.customWelcome': 'old',
+ });
+
+ const patched = await call(handlers.patchConfigField, {
+ params: roleParams('retired'),
+ body: { entries: [{ fieldPath: 'interface.customWelcome', value: 'new' }] },
+ });
+
+ expect(patched.statusCode).toBe(200);
+ });
+
+ it('checks the principal on the document a tombstone writes over, not on an earlier read', async () => {
+ const orphans = ['retired', 'retired-search'];
+ for (const principalId of orphans) {
+ /** A profile left behind by a role renamed or deleted before its profile moved with it. */
+ await methods.patchConfigFields('role' as never, principalId, 'Role' as never, {
+ 'interface.customWelcome': 'old',
+ });
+ }
+ /** A concurrent DELETE of each orphan lands after the tombstone read it, before it writes. */
+ const removed = new Set<string>();
+ const handlers = createHandlers(
+ {},
+ {
+ findConfigByPrincipal: async (principalType, principalId, options) => {
+ const found = await methods.findConfigByPrincipal(principalType, principalId, options);
+ if (found && !removed.has(principalId)) {
+ removed.add(principalId);
+ await methods.deleteConfig(principalType, principalId);
+ }
+ return found;
+ },
+ },
+ );
+
+ const results = await Promise.all([
+ call(handlers.tombstoneConfigField, {
+ params: roleParams('retired'),
+ body: { fieldPath: 'memory' },
+ }),
+ call(handlers.tombstoneConfigField, {
+ params: roleParams('retired-search'),
+ body: { fieldPath: 'webSearch.jinaApiUrl' },
+ }),
+ ]);
+
+ expect([...removed].sort()).toEqual(orphans);
+ for (const res of results) {
+ expect(res.statusCode).toBe(404);
+ expect(res.body).toEqual({ error: 'Principal not found', code: 'PRINCIPAL_NOT_FOUND' });
+ }
+ expect(await methods.listAllConfigs()).toEqual([]);
+ });
+
+ it('looks principals up in the caller tenant only', async () => {
+ const handlers = createHandlers();
+ const inTenant = <T>(tenantId: string, run: () => Promise<T>) =>
+ dataSchemas.tenantStorage.run({ tenantId }, run);
+ await inTenant('tenant-a', () => createRole('tenant-role'));
+ const write = () =>
+ call(handlers.patchConfigField, {
+ params: roleParams('tenant-role'),
+ body: { entries: [{ fieldPath: 'interface.customWelcome', value: 'hi' }] },
+ });
+
+ const elsewhere = await inTenant('tenant-b', write);
+ const home = await inTenant('tenant-a', write);
+
+ expect(elsewhere.statusCode).toBe(404);
+ expect(home.statusCode).toBe(200);
+ });
+
+ it('looks principals up at platform level for a caller without a tenant', async () => {
+ const handlers = createHandlers();
+ const tenantPrincipals = await dataSchemas.tenantStorage.run(
+ { tenantId: 'tenant-a' },
+ async () => {
+ await createRole('tenant-role');
+ return {
+ groupId: await createGroup('Tenant Engineering'),
+ userId: await createUser('[email protected]'),
+ };
+ },
+ );
+ await createRole('Editor');
+ const entry = { entries: [{ fieldPath: 'interface.customWelcome', value: 'hi' }] };
+ const write = (principalType: string, principalId: string) =>
+ call(handlers.patchConfigField, { params: { principalType, principalId }, body: entry });
+
+ const refused = await Promise.all([
+ write('role', 'tenant-role'),
+ write('group', tenantPrincipals.groupId),
+ write('user', tenantPrincipals.userId),
+ write('role', 'editor'),
+ ]);
+
+ expect(refused.map((res) => res.body?.code)).toEqual(Array(4).fill('PRINCIPAL_NOT_FOUND'));
+ expect(await methods.listAllConfigs()).toEqual([]);
+ expect((await write('role', 'Editor')).statusCode).toBe(200);
+ });
+
+ it('treats the system roles as existing without creating their role documents', async () => {
+ const handlers = createHandlers();
+
+ const res = await call(handlers.patchConfigField, {
+ params: roleParams('USER'),
+ body: { entries: [{ fieldPath: 'interface.customWelcome', value: 'hi' }] },
+ });
+
+ expect(res.statusCode).toBe(200);
+ expect(configOf(res).priority).toBe(10);
+ expect(await mongoose.models.Role.countDocuments({})).toBe(0);
+ });
+});
+
+describe('priority on writes (W2-1)', () => {
+ it('keeps the stored priority when a broad PUT does not send one', async () => {
+ const handlers = createHandlers();
+ const groupId = await createGroup('Engineering');
+ const params = { principalType: 'group', principalId: groupId };
+ await call(handlers.patchConfigField, {
+ params,
+ body: { entries: [{ fieldPath: 'interface.customWelcome', value: 'hi' }] },
+ });
+
+ const replaced = await call(handlers.upsertConfigOverrides, {
+ params,
+ body: { overrides: { interface: { customWelcome: 'replaced' } } },
+ });
+
+ expect(replaced.statusCode).toBe(200);
+ expect(configOf(replaced).priority).toBe(20);
+ const reprioritized = await call(handlers.upsertConfigOverrides, {
+ params,
+ body: { overrides: { interface: { customWelcome: 'again' } }, priority: 7 },
+ });
+ expect(configOf(reprioritized).priority).toBe(7);
+ });
+
+ it('lists profiles in the order they merge: Base first, then priority, type and identity', async () => {
+ const handlers = createHandlers();
+ await createRole('editor');
+ const groupId = await createGroup('Engineering');
+ const userId = await createUser('[email protected]');
+ const entry = { entries: [{ fieldPath: 'interface.customWelcome', value: 'hi' }] };
+ for (const params of [
+ { principalType: 'user', principalId: userId },
+ { principalType: 'group', principalId: groupId },
+ roleParams('editor'),
+ BASE,
+ ]) {
+ await call(handlers.patchConfigField, { params, body: entry });
+ }
+ await call(handlers.updateConfigPriority, { params: BASE, body: { priority: 500 } });
+ await call(handlers.updateConfigPriority, {
+ params: { principalType: 'group', principalId: groupId },
+ body: { priority: 10 },
+ });
+
+ const listed = await call(handlers.listConfigs, {});
+ const order = (listed.body?.configs as Array<{ principalType: string; priority: number }>).map(
+ ({ principalType, priority }) => `${principalType}:${priority}`,
+ );
+
+ expect(order).toEqual(['role:500', 'role:10', 'group:10', 'user:100']);
+ });
+});
diff --git a/packages/api/src/admin/config.store.spec.ts b/packages/api/src/admin/config.store.spec.ts
index f9d9baf1f0..89415b6ba1 100644
--- a/packages/api/src/admin/config.store.spec.ts
+++ b/packages/api/src/admin/config.store.spec.ts
@@ -56,7 +56,6 @@ function createHandlers(overrides: Partial<AdminConfigDeps> = {}): AdminConfigHa
listAllConfigs: methods.listAllConfigs,
findConfigByPrincipal: methods.findConfigByPrincipal,
writeConfigDocument: methods.writeConfigDocument,
- tombstoneConfigField: methods.tombstoneConfigField,
unsetConfigField: methods.unsetConfigField,
deleteConfig: methods.deleteConfig,
toggleConfigActiveTracked: methods.toggleConfigActiveTracked,
@@ -180,14 +179,21 @@ describe('admin config handlers on the portable store (real Config collection)',
body: { entries: [{ fieldPath: 'webSearch.serperApiKey', value: 'sk-rotated-secret' }] },
});
- /** The stale admin's read happens before the rotation; its write lands after it. */
- const findConfigByPrincipal = jest
- .fn<
- ReturnType<Methods['findConfigByPrincipal']>,
- Parameters<Methods['findConfigByPrincipal']>
- >()
- .mockResolvedValueOnce(beforeRotation)
- .mockImplementation(methods.findConfigByPrincipal);
+ /**
+ * The stale admin's read of the profile happens before the rotation; its write lands after
+ * it. Other reads (Base, the validation floor) go to the store.
+ */
+ let staleReads = 1;
+ const findConfigByPrincipal = jest.fn<
+ ReturnType<Methods['findConfigByPrincipal']>,
+ Parameters<Methods['findConfigByPrincipal']>
+ >(async (principalType, principalId, options) => {
+ if (principalId === params.principalId && staleReads > 0) {
+ staleReads -= 1;
+ return beforeRotation;
+ }
+ return methods.findConfigByPrincipal(principalType, principalId, options);
+ });
const stale = createHandlers({ findConfigByPrincipal });
const echoed = await call(stale.patchConfigField, {
params,
@@ -199,7 +205,12 @@ describe('admin config handlers on the portable store (real Config collection)',
});
expect(echoed.statusCode).toBe(200);
- expect(findConfigByPrincipal).toHaveBeenCalledTimes(2);
+ expect(staleReads).toBe(0);
+ expect(
+ findConfigByPrincipal.mock.calls.filter(
+ ([, principalId]) => principalId === params.principalId,
+ ),
+ ).toHaveLength(2);
const stored = await raw().findOne({ principalId: params.principalId });
expect(decryptV3(stored!.overrides.webSearch.serperApiKey)).toBe('sk-rotated-secret');
expect(stored!.overrides.webSearch.scraperTimeout).toBe(9000);
diff --git a/packages/api/src/admin/config.ts b/packages/api/src/admin/config.ts
index 216c0bdd1a..95960b279c 100644
--- a/packages/api/src/admin/config.ts
+++ b/packages/api/src/admin/config.ts
@@ -40,6 +40,7 @@ import {
isSameConfigValue,
isConfigRevision,
isConfigPathError,
+ resolveRawConfig,
isFieldNameRejection,
getDottedSectionIssues,
runConfigMutation,
@@ -47,15 +48,18 @@ import {
toConfigOverrideState,
tombstoneConfigPaths,
applyConfigTombstones,
+ isBaseConfigPrincipal,
+ ABSENT_CONFIG_REVISION,
replaceConfigOverrides,
parseConfigPathSegments,
getConfigOverrideIssues,
getExpectedRevision,
MAX_CONFIG_PATH_DEPTH,
- DEFAULT_CONFIG_PRIORITY,
+ getDefaultConfigPriority,
BASE_CONFIG_PRINCIPAL_ID,
isConfigRevisionConflict,
isConfigOverrideStateEmpty,
+ toConfigDraft,
} from '@librechat/data-schemas';
import type {
AppConfig,
@@ -63,6 +67,7 @@ import type {
ConfigChange,
ConfigRecord,
ConfigSection,
+ ConfigWriteOutcome,
ConfigRevision,
ConfigFieldWrite,
SystemCapability,
@@ -79,13 +84,14 @@ import type {
AdminConfigChangesResponse,
AdminConfigChangeErrorResponse,
ConfigMutationOutcome,
+ ConfigMutationPlan,
} from '@librechat/data-schemas';
import type { TCustomConfig } from 'librechat-data-provider';
import type { Response } from 'express';
-import type { AdminAuditEvent, RecordAuditEntry } from './audit';
import type { CapabilityUser } from '~/middleware/capabilities';
import type { SecretReentryIssue } from './binding';
import type { ServerRequest } from '~/types/http';
+import type { RecordAuditEntry } from './audit';
import {
encryptConfigSecretFields,
encryptConfigSecrets,
@@ -108,9 +114,9 @@ import {
getRemovalReentryIssues,
getReplaceReentryIssues,
} from './binding';
+import { createAdminAuditEmitter, configTarget } from './audit';
import { DEFAULT_OVERRIDE_CACHE_TTL } from '~/app/service';
import { getSafeErrorMetadata } from '~/utils/errors';
-import { createAdminAuditEmitter } from './audit';
import { buildAdminConfigMeta } from './meta';
const UNSAFE_SEGMENTS = /(?:^|\.)(__[\w]*|constructor|prototype)(?:\.|$)/;
@@ -538,9 +544,9 @@ export interface AdminConfigDeps {
) => Promise<ConfigRecord | null>;
/**
* Writes the principal's whole document when it is still at `expected` (`absent`: only when
- * none exists), or throws a `ConfigRevisionConflictError`. PUT and PATCH plan the next
- * document from the one they read, so validation and secret preservation see exactly what the
- * write replaces.
+ * none exists), or throws a `ConfigRevisionConflictError`. PUT, PATCH, POST `/changes`,
+ * tombstones and web search unsets plan the next document from the one they read, so
+ * validation, the principal check and secret preservation see exactly what the write replaces.
*/
writeConfigDocument: (
principalType: PrincipalType,
@@ -548,16 +554,6 @@ export interface AdminConfigDeps {
draft: ConfigDraft,
expected: ConfigRevision,
) => Promise<ConfigRecord>;
- /** Tombstones every path in one write; an omitted `priority` keeps the stored one. */
- tombstoneConfigField: (
- principalType: PrincipalType,
- principalId: string,
- principalModel: PrincipalModel,
- fieldPaths: ConfigPathInputs,
- priority?: number,
- session?: NoSession,
- options?: ConfigWriteOptions,
- ) => Promise<ConfigRecord>;
/**
* Removes every path (dotted, or `{ segments }` for keys that contain dots) in one write,
* pruning parents left empty; `null` when there is no document.
@@ -582,6 +578,26 @@ export interface AdminConfigDeps {
isActive: boolean,
options?: ConfigLifecycleOptions,
) => Promise<{ config: ConfigRecord; changed: boolean } | null>;
+ /**
+ * Sets only the document's priority in the caller's tenant partition (platform-level without
+ * a tenant, never a tenant's document for the same principal); resolves to it and whether
+ * this write changed it, or `null` when the principal has none there. Without it the priority
+ * route answers 501.
+ */
+ setConfigPriority?: (
+ principalType: PrincipalType,
+ principalId: string,
+ priority: number,
+ options?: ConfigWriteOptions,
+ ) => Promise<ConfigWriteOutcome | null>;
+ /**
+ * Whether the role (exact name), group or user (ObjectId) exists in the caller's tenant
+ * partition: the caller's tenant, or without one only platform-level principals. A write that
+ * would create a principal's first document refuses one that does not (404
+ * `PRINCIPAL_NOT_FOUND`), since that profile would never apply to anyone. Without this
+ * lookup nothing is checked.
+ */
+ principalExists?: (principalType: PrincipalType, principalId: string) => Promise<boolean>;
hasConfigCapability: (
user: CapabilityUser,
section: ConfigSection | null,
@@ -617,13 +633,6 @@ export interface AdminConfigDeps {
overrideCacheTtlMs?: number;
}
-/** Audit target for a principal's override document. Records field paths and
- * sections only: override values can carry secrets. */
-function configTarget(principalType: string, principalId: string): AdminAuditEvent['target'] {
- const key = `${principalType}:${principalId}`;
- return { type: 'config', id: key, name: key };
-}
-
// ── Validation helpers ───────────────────────────────────────────────
const CONFIG_PRINCIPAL_TYPES = new Set([
@@ -636,6 +645,20 @@ function validatePrincipalType(value: string): value is PrincipalType {
return CONFIG_PRINCIPAL_TYPES.has(value as PrincipalType);
}
+const INVALID_PRIORITY_ERROR = 'priority must be a non-negative number';
+
+function isValidPriority(value: unknown): value is number {
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
+}
+
+function invalidPriorityResponse(res: Response): Response {
+ return res.status(400).json({ error: INVALID_PRIORITY_ERROR, code: 'INVALID_PRIORITY' });
+}
+
+function principalNotFoundResponse(res: Response): Response {
+ return res.status(404).json({ error: 'Principal not found', code: 'PRINCIPAL_NOT_FOUND' });
+}
+
function principalModel(type: PrincipalType): PrincipalModel {
switch (type) {
case PrincipalType.USER:
@@ -892,6 +915,20 @@ function secretReentryResponse(res: Response, issues: SecretReentryIssue[]): Res
});
}
+/** Why a planned unset or tombstone wrote nothing. */
+type RemovalStop =
+ | { status: 404; missing: 'config' | 'principal' }
+ | { status: 400; reentry: SecretReentryIssue[] };
+
+function removalStopResponse(res: Response, stop: RemovalStop): Response {
+ if (stop.status === 400) {
+ return secretReentryResponse(res, stop.reentry);
+ }
+ return stop.missing === 'principal'
+ ? principalNotFoundResponse(res)
+ : res.status(404).json({ error: 'Config not found' });
+}
+
const INVALID_EXPECTED_REVISION_ERROR =
'expectedRevision must be "absent" or a revision returned by the config API';
@@ -1443,15 +1480,17 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
applyConfigChanges: (req: ServerRequest, res: Response) => Promise<Response>;
deleteConfigOverrides: (req: ServerRequest, res: Response) => Promise<Response>;
toggleConfig: (req: ServerRequest, res: Response) => Promise<Response>;
+ updateConfigPriority: (req: ServerRequest, res: Response) => Promise<Response>;
} {
const {
listAllConfigs,
findConfigByPrincipal,
writeConfigDocument,
- tombstoneConfigField: writeConfigTombstone,
unsetConfigField,
deleteConfig,
toggleConfigActiveTracked,
+ setConfigPriority,
+ principalExists,
hasConfigCapability,
hasAnyConfigReadAccess = async () => false,
getReadableConfigSections = async (u, sections) => {
@@ -1542,7 +1581,11 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
});
}
- /** Maps the expected failures of a write to their responses; anything else is rethrown. */
+ /**
+ * Maps the expected failures of a write to their responses; anything else is rethrown. A
+ * conflict that does not carry the current revision rereads it from the document the write
+ * addressed (for a role, in the caller's tenant partition).
+ */
async function writeFailureResponse(
res: Response,
error: unknown,
@@ -1559,33 +1602,37 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
/**
- * Unsets or tombstones a web search URL (or the whole section) in a write planned from the
- * document it replaces, so the re-entry check judges exactly the revision the write lands on.
- * A write that lands in between is re-read and re-checked, or answers 409 under
- * `expectedRevision`. Stops with the re-entry issues, or with `null` when an unset finds no
- * document.
+ * Unsets or tombstones a dot-free path (a secret together with its preview) in a write
+ * planned from the document it replaces, so each check judges exactly the revision the write
+ * lands on: a tombstone that creates the principal's first document needs the principal
+ * (`canCreateFor`), and removing a web search URL needs its stored key entered again. A
+ * write that lands in between is re-read and re-checked, or answers 409 under
+ * `expectedRevision`. An unset stops when there is no document.
*/
- function removeWebSearchBinding(
+ function removeConfigPath(
principalType: PrincipalType,
principalId: string,
fieldPath: string,
removal: { tombstone: true; priority?: number } | { tombstone: false },
expectedRevision: ConfigRevision | undefined,
- ): Promise<ConfigMutationOutcome<SecretReentryIssue[] | null>> {
+ ): Promise<ConfigMutationOutcome<RemovalStop>> {
const paths = getConfigSecretMutationPaths(fieldPath).map(parseFieldPath);
- return runConfigMutation<SecretReentryIssue[] | null>(
+ return runConfigMutation<RemovalStop>(
{
read: () => readStoredConfig(principalType, principalId),
write: (draft, revision) =>
writeConfigDocument(principalType, principalId, draft, revision),
},
- (stored) => {
+ async (stored) => {
if (!stored && !removal.tombstone) {
- return { draft: null, result: null };
+ return { draft: null, result: { status: 404, missing: 'config' } };
+ }
+ if (!stored && !(await canCreateFor(principalType, principalId))) {
+ return { draft: null, result: { status: 404, missing: 'principal' } };
}
const reentry = getRemovalReentryIssues(stored, fieldPath, removal.tombstone);
if (reentry.length > 0) {
- return { draft: null, result: reentry };
+ return { draft: null, result: { status: 400, reentry } };
}
const current = toConfigOverrideState(stored);
const state = removal.tombstone
@@ -1597,7 +1644,7 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
priority:
(removal.tombstone ? removal.priority : undefined) ??
stored?.priority ??
- DEFAULT_CONFIG_PRIORITY,
+ getDefaultConfigPriority({ principalType, principalId }),
overrides: state.overrides,
tombstones: state.tombstones,
isActive: stored?.isActive ?? true,
@@ -1617,6 +1664,139 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
return appConfig?.config ?? {};
}
+ /**
+ * The active Base document, from the caller's tenant partition (platform-level without one),
+ * as the config store addresses every role document.
+ */
+ function readActiveBase(): Promise<ConfigRecord | null> {
+ return findConfigByPrincipal(PrincipalType.ROLE, BASE_CONFIG_PRINCIPAL_ID);
+ }
+
+ /**
+ * Takes back a write this request made, only while the document is still at the revision the
+ * write produced: the document it replaced is written back, or the one it created removed. A
+ * write that landed since throws a revision conflict, and is left as it is.
+ */
+ async function withdrawWrite(
+ principalType: PrincipalType,
+ principalId: string,
+ written: ConfigRecord,
+ previous: ConfigRecord | null,
+ ): Promise<ConfigRecord | null> {
+ const revision = getConfigRevision(written);
+ if (previous) {
+ return writeConfigDocument(principalType, principalId, toConfigDraft(previous), revision);
+ }
+ await deleteConfig(principalType, principalId, undefined, { expectedRevision: revision });
+ return null;
+ }
+
+ /**
+ * Reads Base again after a profile write committed and, when it is no longer `read` (the Base
+ * the write was planned on), judges the request on it. `null` when Base did not move, or when
+ * that cannot be told: the committed write then stands, as it would had Base moved just after
+ * it, and is never turned into a failure.
+ */
+ async function judgeOnLandedBase<T>(
+ read: ConfigRecord | null,
+ judge: (landed: ConfigRecord | null) => Promise<ConfigMutationPlan<T>>,
+ ): Promise<ConfigMutationPlan<T> | null> {
+ try {
+ const landed = await readActiveBase();
+ if ((landed && getConfigRevision(landed)) === (read && getConfigRevision(read))) {
+ return null;
+ }
+ return await judge(landed);
+ } catch (error) {
+ logger.warn(
+ '[adminConfig] A profile write could not be checked on the Base it landed over; it stands',
+ getSafeErrorMetadata(error),
+ );
+ return null;
+ }
+ }
+
+ /**
+ * Runs a write that validates on the config the principal's overrides land on, before its own
+ * tombstones (the floor): `librechat.yaml` with the active Base document resolved over it,
+ * exactly as the merge layers Base under every profile (Base always merges first), or
+ * `librechat.yaml` alone for Base itself. The principal's other profiles vary per user and
+ * are left to the merge. Base is read from the caller's tenant partition, so a caller without
+ * a tenant validates on the platform-level Base and never on a tenant's. With `yaml` `null`
+ * the write does not validate on the floor, and `plan` gets an empty one.
+ *
+ * Base is its own document, which the profile's compare-and-swap does not cover. So each
+ * attempt reads Base beside the profile (a retry never reuses a Base a concurrent write has
+ * replaced), and once the write commits Base is read again. When it moved meanwhile, the
+ * request is judged once more, `plan` on the document the write replaced, on the Base the
+ * write landed over (`judgeOnLandedBase`): a write still valid there stands, and one that is
+ * not is withdrawn (`withdrawWrite`) and answered with that judgement.
+ */
+ async function runOnValidationFloor<T>(
+ principalType: PrincipalType,
+ principalId: string,
+ tenantId: string | undefined,
+ yaml: Partial<TCustomConfig> | null,
+ plan: (
+ stored: ConfigRecord | null,
+ floor: Partial<TCustomConfig>,
+ ) => Promise<ConfigMutationPlan<T>>,
+ expectedRevision: ConfigRevision | undefined,
+ ): Promise<ConfigMutationOutcome<T>> {
+ const readsBase = yaml != null && !isBaseConfigPrincipal({ principalType, principalId });
+ const attempt: { base: ConfigRecord | null } = { base: null };
+ const floorOver = (base: ConfigRecord | null): Partial<TCustomConfig> => {
+ if (yaml == null) {
+ return {};
+ }
+ return base ? resolveRawConfig(yaml, [base]) : yaml;
+ };
+ const outcome = await runConfigMutation<T>(
+ {
+ read: async () => {
+ const [stored, base] = await Promise.all([
+ readStoredConfig(principalType, principalId),
+ readsBase ? readActiveBase() : null,
+ ]);
+ attempt.base = base;
+ return stored;
+ },
+ write: (draft, revision) =>
+ writeConfigDocument(principalType, principalId, draft, revision),
+ },
+ (stored) => plan(stored, floorOver(attempt.base)),
+ { expectedRevision },
+ );
+ if (!outcome.written || !readsBase) {
+ return outcome;
+ }
+ const judged = await judgeOnLandedBase(attempt.base, (landed) =>
+ plan(outcome.previous, floorOver(landed)),
+ );
+ if (judged == null || judged.draft != null) {
+ return outcome;
+ }
+ const current = await withdrawWrite(
+ principalType,
+ principalId,
+ outcome.record,
+ outcome.previous,
+ );
+ await invalidateCaches(tenantId, 'withdrawn write');
+ return { written: false, current, result: judged.result };
+ }
+
+ /**
+ * Whether a write may create the principal's first document: it must exist in the caller's
+ * tenant partition. Base always may, and nothing is checked without `principalExists`.
+ */
+ async function canCreateFor(principalType: PrincipalType, principalId: string): Promise<boolean> {
+ if (!principalExists || isBaseConfigPrincipal({ principalType, principalId })) {
+ return true;
+ }
+ return principalExists(principalType, principalId);
+ }
+
/**
* Resolves which sections a write's response may show: the ones the caller can read. Those
* already include each section it manages, because the grant layer resolves
@@ -1809,8 +1989,8 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
return res.status(400).json({ error: LANGFUSE_HEADERS_CONFIG_ERROR });
}
- if (priority != null && (typeof priority !== 'number' || priority < 0)) {
- return res.status(400).json({ error: 'priority must be a non-negative number' });
+ if (priority != null && !isValidPriority(priority)) {
+ return invalidPriorityResponse(res);
}
const user = getCapabilityUser(req);
@@ -1877,8 +2057,10 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
const overrideSections = Object.keys(filteredOverrides);
+ /** A create-only request is a lifecycle write even when it carries nothing. */
+ const createOnly = expected.value === ABSENT_CONFIG_REVISION;
- if (overrideSections.length === 0 && priority == null) {
+ if (overrideSections.length === 0 && priority == null && !createOnly) {
return noopResponse(
res,
'No actionable override sections provided',
@@ -1909,21 +2091,24 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
const encryptedOverrides = encryptConfigSecrets(filteredOverrides);
- const baseYaml = overrideSections.length > 0 ? await getBaseYamlConfig(user.tenantId) : {};
+ const yaml = overrideSections.length > 0 ? await getBaseYamlConfig(user.tenantId) : null;
type PutStop =
| { status: 403 }
+ | { status: 404 }
| { status: 400; issues: ConfigOverrideIssue[] }
| { status: 400; reentry: SecretReentryIssue[] };
let outcome;
try {
- outcome = await runConfigMutation<PutStop>(
- {
- read: () => readStoredConfig(principalType, principalId),
- write: (draft, revision) =>
- writeConfigDocument(principalType, principalId, draft, revision),
- },
- (stored) => {
+ outcome = await runOnValidationFloor<PutStop>(
+ principalType,
+ principalId,
+ user.tenantId,
+ yaml,
+ async (stored, floor) => {
+ if (!stored && !(await canCreateFor(principalType, principalId))) {
+ return { draft: null, result: { status: 404 } };
+ }
/** Assign-only callers manage the profile's lifecycle, never its contents. */
if (
!hasBroadManage &&
@@ -1937,7 +2122,7 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
/** A full replace keeps the principal's tombstones, so they shape its base. */
const issues = getConfigOverrideIssues(
preserved,
- applyConfigTombstones(baseYaml, stored?.tombstones),
+ applyConfigTombstones(floor, stored?.tombstones),
);
if (issues.length > 0) {
return { draft: null, result: { status: 400, issues } };
@@ -1962,19 +2147,22 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
toConfigOverrideState(stored),
next as Partial<TCustomConfig>,
);
+ /** An omitted priority keeps the stored one, so a replace never reorders profiles. */
+ const requestedPriority = hasBroadManage ? priority : undefined;
return {
draft: {
principalModel: principalModel(principalType),
- priority: hasBroadManage
- ? (priority ?? DEFAULT_CONFIG_PRIORITY)
- : (stored?.priority ?? DEFAULT_CONFIG_PRIORITY),
+ priority:
+ requestedPriority ??
+ stored?.priority ??
+ getDefaultConfigPriority({ principalType, principalId }),
overrides: state.overrides,
tombstones: state.tombstones,
isActive: true,
},
};
},
- { expectedRevision: expected.value },
+ expected.value,
);
} catch (error) {
return await writeFailureResponse(res, error, principalType, principalId);
@@ -1985,6 +2173,9 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
if (stop.status === 403) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
+ if (stop.status === 404) {
+ return principalNotFoundResponse(res);
+ }
if ('reentry' in stop) {
return secretReentryResponse(res, stop.reentry);
}
@@ -2041,8 +2232,8 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
priority?: number;
};
- if (priority != null && (typeof priority !== 'number' || priority < 0)) {
- return res.status(400).json({ error: 'priority must be a non-negative number' });
+ if (priority != null && !isValidPriority(priority)) {
+ return invalidPriorityResponse(res);
}
const expected = readExpectedRevision(
@@ -2157,7 +2348,7 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
const requestedPriority = hasBroadManage ? priority : undefined;
- const [baseYaml, access] = await Promise.all([
+ const [yaml, access] = await Promise.all([
getBaseYamlConfig(user.tenantId),
resolveWriteReadAccess(user, hasBroadManage, writtenSections),
]);
@@ -2167,42 +2358,50 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
value,
}));
- type PatchStop = { issues: ConfigOverrideIssue[] } | { reentry: SecretReentryIssue[] };
+ type PatchStop =
+ | { status: 404 }
+ | { status: 400; issues: ConfigOverrideIssue[] }
+ | { status: 400; reentry: SecretReentryIssue[] };
let outcome;
try {
- outcome = await runConfigMutation<PatchStop>(
- {
- read: () => readStoredConfig(principalType, principalId),
- write: (draft, revision) =>
- writeConfigDocument(principalType, principalId, draft, revision),
- },
- (stored) => {
+ outcome = await runOnValidationFloor<PatchStop>(
+ principalType,
+ principalId,
+ user.tenantId,
+ yaml,
+ async (stored, floor) => {
+ if (!stored && !(await canCreateFor(principalType, principalId))) {
+ return { draft: null, result: { status: 404 } };
+ }
/** Secrets an object omits are kept before validation sees the document. */
const writes = toOrderedWrites(
validEntries,
preservePatchedConfigSecretFields(encryptedFields, stored?.overrides),
);
- const fieldIssues = getConfigFieldIssues(writes, baseYaml, stored);
+ const fieldIssues = getConfigFieldIssues(writes, floor, stored);
if (fieldIssues.length > 0) {
- return { draft: null, result: { issues: fieldIssues } };
+ return { draft: null, result: { status: 400, issues: fieldIssues } };
}
const state = setConfigFields(toConfigOverrideState(stored), writes);
/** A changed URL beside a stored key that stays needs that key entered again. */
const reentry = getPatchReentryIssues(stored, requested, state);
if (reentry.length > 0) {
- return { draft: null, result: { reentry } };
+ return { draft: null, result: { status: 400, reentry } };
}
return {
draft: {
principalModel: principalModel(principalType),
- priority: requestedPriority ?? stored?.priority ?? DEFAULT_CONFIG_PRIORITY,
+ priority:
+ requestedPriority ??
+ stored?.priority ??
+ getDefaultConfigPriority({ principalType, principalId }),
overrides: state.overrides,
tombstones: state.tombstones,
isActive: stored?.isActive ?? true,
},
};
},
- { expectedRevision: expected.value },
+ expected.value,
);
} catch (error) {
return await writeFailureResponse(res, error, principalType, principalId);
@@ -2210,6 +2409,9 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
if (!outcome.written) {
const stop = outcome.result;
+ if (stop.status === 404) {
+ return principalNotFoundResponse(res);
+ }
return 'reentry' in stop
? secretReentryResponse(res, stop.reentry)
: invalidOverrideResponse(res, stop.issues);
@@ -2263,8 +2465,8 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
return res.status(400).json({ error: 'fieldPath is required' });
}
- if (priority != null && (typeof priority !== 'number' || priority < 0)) {
- return res.status(400).json({ error: 'priority must be a non-negative number' });
+ if (priority != null && !isValidPriority(priority)) {
+ return invalidPriorityResponse(res);
}
const expected = readExpectedRevision(
@@ -2335,39 +2537,26 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
const requestedPriority = hasBroadManage ? priority : undefined;
- let config: ConfigRecord;
+ let outcome: ConfigMutationOutcome<RemovalStop>;
try {
- if (isWebSearchBindingPath(fieldPath)) {
- const outcome = await removeWebSearchBinding(
- principalType,
- principalId,
- fieldPath,
- { tombstone: true, priority: requestedPriority },
- expected.value,
- );
- if (!outcome.written) {
- return secretReentryResponse(res, outcome.result ?? []);
- }
- config = outcome.record;
- } else {
- /** A secret and its preview companion are suppressed together, in one write. */
- config = await writeConfigTombstone(
- principalType,
- principalId,
- principalModel(principalType),
- getConfigSecretMutationPaths(fieldPath),
- requestedPriority,
- undefined,
- { expectedRevision: expected.value },
- );
- }
+ outcome = await removeConfigPath(
+ principalType,
+ principalId,
+ fieldPath,
+ { tombstone: true, priority: requestedPriority },
+ expected.value,
+ );
} catch (error) {
return await writeFailureResponse(res, error, principalType, principalId);
}
+ if (!outcome.written) {
+ return removalStopResponse(res, outcome.result);
+ }
+ const { record: config, previous } = outcome;
await invalidateCaches(user.tenantId, 'field tombstone');
await emitAudit(req, {
- action: config.configVersion === 1 ? 'config.created' : 'config.updated',
+ action: previous == null ? 'config.created' : 'config.updated',
target: configTarget(principalType, principalId),
metadata: { operation: 'tombstone', fieldPath },
});
@@ -2459,17 +2648,17 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
let config: ConfigRecord | null;
try {
if (target.dotFree && isWebSearchBindingPath(fieldPath)) {
- const outcome = await removeWebSearchBinding(
+ const outcome = await removeConfigPath(
principalType,
principalId,
fieldPath,
{ tombstone: false },
expected.value,
);
- if (!outcome.written && outcome.result) {
- return secretReentryResponse(res, outcome.result);
+ if (!outcome.written) {
+ return removalStopResponse(res, outcome.result);
}
- config = outcome.written ? outcome.record : null;
+ config = outcome.record;
} else {
/**
* A secret and its preview companion are removed together, in one write. A path with
@@ -2536,13 +2725,8 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
};
const { ops, priority } = body;
- if (
- priority != null &&
- (typeof priority !== 'number' || !Number.isFinite(priority) || priority < 0)
- ) {
- return res
- .status(400)
- .json({ error: 'priority must be a non-negative number', code: 'INVALID_PRIORITY' });
+ if (priority != null && !isValidPriority(priority)) {
+ return invalidPriorityResponse(res);
}
if (body.dryRun !== undefined && typeof body.dryRun !== 'boolean') {
@@ -2656,14 +2840,19 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
appliedChanges: PreparedChange[];
}
type ChangesStop =
+ | { kind: 'principal' }
| { kind: 'issues'; issues: ConfigOverrideIssue[] }
| { kind: 'reentry'; issues: SecretReentryIssue[] }
| { kind: 'change'; failure: ChangeFailure };
type ChangesResult = { report: ChangesReport; stop?: never } | { stop: ChangesStop };
- const plan = (
+ const plan = async (
stored: ConfigRecord | null,
- ): { draft: ConfigDraft | null; result: ChangesResult } => {
+ floor: Partial<TCustomConfig>,
+ ): Promise<ConfigMutationPlan<ChangesResult>> => {
+ if (!stored && !(await canCreateFor(principalType, principalId))) {
+ return { draft: null, result: { stop: { kind: 'principal' } } };
+ }
const report: ChangesReport = {
applied: [],
unchanged: [],
@@ -2732,14 +2921,15 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
report.ignored = [];
report.appliedChanges = [];
}
- /** As on PUT, a priority for a principal without a document creates one that holds it. */
+ /** As on PUT, a priority for an existing principal without a document creates one that
+ * holds it. */
const priorityChanged = requestedPriority != null && requestedPriority !== stored?.priority;
if (!documentChanged && !priorityChanged) {
return { draft: null, result: { report } };
}
if (documentChanged) {
const written = getConfigBatchWrittenPaths(appliedSteps, state, storedState);
- const issues = getConfigChangeIssues(state, baseYaml, stored, written);
+ const issues = getConfigChangeIssues(state, floor, stored, written);
if (issues.length > 0) {
return { draft: null, result: { stop: { kind: 'issues', issues } } };
}
@@ -2761,7 +2951,10 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
return {
draft: {
principalModel: principalModel(principalType),
- priority: requestedPriority ?? stored?.priority ?? DEFAULT_CONFIG_PRIORITY,
+ priority:
+ requestedPriority ??
+ stored?.priority ??
+ getDefaultConfigPriority({ principalType, principalId }),
overrides: state.overrides,
tombstones: state.tombstones,
isActive: stored?.isActive ?? true,
@@ -2772,20 +2965,22 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
let outcome;
try {
- outcome = await runConfigMutation<ChangesResult>(
- {
- read: () => readStoredConfig(principalType, principalId),
- write: (draft, revision) =>
- writeConfigDocument(principalType, principalId, draft, revision),
- },
+ outcome = await runOnValidationFloor<ChangesResult>(
+ principalType,
+ principalId,
+ user.tenantId,
+ baseYaml,
plan,
- { expectedRevision: expected.value },
+ expected.value,
);
} catch (error) {
return await writeFailureResponse(res, error, principalType, principalId);
}
const result = outcome.result as ChangesResult;
+ if (result.stop?.kind === 'principal') {
+ return principalNotFoundResponse(res);
+ }
if (result.stop?.kind === 'change') {
return res.status(400).json(result.stop.failure);
}
@@ -2907,6 +3102,82 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
}
+ /**
+ * PATCH /:principalType/:principalId/priority — Set only the document's priority.
+ *
+ * Overrides, tombstones and `isActive` stay as stored, so a priority change never re-sends
+ * (and so never risks clobbering) a profile's contents. Broad `manage:configs` only, like
+ * every other priority change. An unchanged priority is not written or audited. Only the
+ * caller's tenant partition is addressed, so a caller without a tenant reorders a
+ * platform-level profile and gets 404 for one that only a tenant holds.
+ */
+ async function updateConfigPriority(req: ServerRequest, res: Response): Promise<Response> {
+ try {
+ const { principalType, principalId } = req.params as {
+ principalType: string;
+ principalId: string;
+ };
+
+ if (!validatePrincipalType(principalType)) {
+ return res.status(400).json({
+ error: `Invalid principalType: ${principalType}`,
+ code: 'INVALID_PRINCIPAL_TYPE',
+ });
+ }
+
+ const { priority } = req.body as { priority?: unknown };
+ if (!isValidPriority(priority)) {
+ return invalidPriorityResponse(res);
+ }
+
+ const expected = readExpectedRevision(
+ (req.body as { expectedRevision?: unknown }).expectedRevision,
+ );
+ if (!expected.ok) {
+ return invalidExpectedRevisionResponse(res);
+ }
+
+ const user = getCapabilityUser(req);
+ if (!user) {
+ return res.status(401).json({ error: 'Authentication required', code: 'AUTH_REQUIRED' });
+ }
+
+ if (!(await hasConfigCapability(user, null, 'manage'))) {
+ return res.status(403).json({ error: 'Insufficient permissions', code: 'FORBIDDEN' });
+ }
+
+ if (!setConfigPriority) {
+ return res.status(501).json({ error: 'Priority updates are not configured' });
+ }
+
+ let updated: ConfigWriteOutcome | null;
+ try {
+ updated = await setConfigPriority(principalType, principalId, priority, {
+ expectedRevision: expected.value,
+ });
+ } catch (error) {
+ return await writeFailureResponse(res, error, principalType, principalId);
+ }
+ if (!updated) {
+ return res.status(404).json({ error: 'Config not found', code: 'CONFIG_NOT_FOUND' });
+ }
+
+ const { config, changed } = updated;
+ if (changed) {
+ await invalidateCaches(user.tenantId, 'priority');
+ await emitAudit(req, {
+ action: 'config.updated',
+ target: configTarget(principalType, principalId),
+ metadata: { operation: 'priority', priority: config.priority },
+ });
+ }
+ return res.status(200).json({ config: redactConfigForResponse(config) });
+ } catch (error) {
+ logger.error('[adminConfig] updateConfigPriority error:', getSafeErrorMetadata(error));
+ return res.status(500).json({ error: 'Failed to update config priority' });
+ }
+ }
+
/**
* PATCH /:principalType/:principalId/active — Toggle isActive.
*/
@@ -3007,5 +3278,6 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
applyConfigChanges: applyChanges,
deleteConfigOverrides,
toggleConfig,
+ updateConfigPriority,
};
}
diff --git a/packages/api/src/admin/langfuse.handler.spec.ts b/packages/api/src/admin/langfuse.handler.spec.ts
index a955cf7d37..6a97d9b63a 100644
--- a/packages/api/src/admin/langfuse.handler.spec.ts
+++ b/packages/api/src/admin/langfuse.handler.spec.ts
@@ -829,7 +829,8 @@ describe('createAdminLangfuseHandlers', () => {
expect(deps.findConfigByPrincipal).toHaveBeenCalledWith('role', '__base__', {
includeInactive: true,
});
- expect(deps.patchConfigFields.mock.calls[0][4]).toBe(42);
+ /** No priority is sent, so the store keeps the stored 42. */
+ expect(deps.patchConfigFields.mock.calls[0][4]).toBeUndefined();
expect(deps.toggleConfigActive).toHaveBeenCalledWith('role', '__base__', true);
expect(res.body).toMatchObject({ configured: true, enabled: true });
});
diff --git a/packages/api/src/admin/langfuse.ts b/packages/api/src/admin/langfuse.ts
index e693853073..d519718485 100644
--- a/packages/api/src/admin/langfuse.ts
+++ b/packages/api/src/admin/langfuse.ts
@@ -31,7 +31,6 @@ import { getSafeErrorMetadata } from '~/utils/errors';
import { createAdminAuditEmitter } from './audit';
import { mergeHeaders } from '~/utils/headers';
-const DEFAULT_PRIORITY = 10;
const ENCRYPTED_PREFIX = 'v3:';
const LANGFUSE_VERIFICATION_TIMEOUT_MS = 10_000;
@@ -61,13 +60,16 @@ export interface AdminLangfuseDeps {
principalId: string,
options?: { includeInactive?: boolean },
) => Promise<ConfigRecord | null>;
- /** Sets the fields in one compare-and-swap write, re-reading on a concurrent change. */
+ /**
+ * Sets the fields in one compare-and-swap write, re-reading on a concurrent change. An
+ * omitted priority keeps the stored one (Base merges first whatever its priority).
+ */
patchConfigFields: (
principalType: PrincipalType,
principalId: string,
principalModel: PrincipalModel,
fields: Record<string, unknown>,
- priority: number,
+ priority?: number,
) => Promise<ConfigRecord | null>;
toggleConfigActive: (
principalType: PrincipalType,
@@ -455,7 +457,6 @@ export function createAdminLangfuseHandlers(deps: AdminLangfuseDeps): {
BASE_CONFIG_PRINCIPAL_ID,
PrincipalModel.ROLE,
encryptConfigSecretFields(fields),
- existing?.priority ?? DEFAULT_PRIORITY,
);
/** The patch has committed by now, so a failed activation must not skip the cache
* invalidation or the audit entry; it is rethrown once both have started. */
diff --git a/packages/api/src/admin/meta.spec.ts b/packages/api/src/admin/meta.spec.ts
index 26a6670156..754ee8b1e9 100644
--- a/packages/api/src/admin/meta.spec.ts
+++ b/packages/api/src/admin/meta.spec.ts
@@ -4,12 +4,15 @@ import { readFileSync } from 'fs';
import mongoSanitize from 'express-mongo-sanitize';
import {
AppService,
+ getConfigRevision,
loadWebSearchConfig,
mergeConfigOverrides,
+ ABSENT_CONFIG_REVISION,
createConfigOperations,
getConfigOverrideIssues,
BASE_CONFIG_PRINCIPAL_ID,
isConfigOverrideStateEmpty,
+ ConfigRevisionConflictError,
} from '@librechat/data-schemas';
import {
Constants,
@@ -31,16 +34,19 @@ import {
import type {
AdminConfigFeatureFlag,
ConfigOverrideLayer,
+ ConfigPrincipal,
AdminConfigMeta,
ConfigRecord,
ConfigStore,
ConfigDraft,
AppConfig,
+ IRole,
} from '@librechat/data-schemas';
import type { MCPOptions } from 'librechat-data-provider';
import type { Request, Response } from 'express';
import type { ServerRequest } from '~/types/http';
import type { AdminConfigDeps } from './config';
+import type { AdminRolesDeps } from './roles';
import { createRequestSanitizer, rejectUnsafeConfigKeys } from '~/middleware/sanitize';
import { resolvePreAuthAppConfig, resolvePreLoginAppConfig } from '~/app/resolve';
import { redactConfigSecrets, encryptConfigSecretFields } from './secrets';
@@ -49,6 +55,7 @@ import { createMCPPolicyResolver } from '~/mcp/registry/policy';
import { resolveTitleConfig } from '~/endpoints/config';
import { createAppConfigService } from '~/app/service';
import { createAdminConfigHandlers } from './config';
+import { createAdminRolesHandlers } from './roles';
import { ADMIN_CONFIG_FEATURES } from './meta';
import { loadWebSearchAuth } from '~/web';
@@ -101,7 +108,6 @@ function createHandlers(overrides: Partial<AdminConfigDeps> = {}) {
async (_type: string, _id: string, draft: ConfigDraft): Promise<ConfigRecord> =>
storedConfig(draft.overrides ?? {}),
),
- tombstoneConfigField: jest.fn().mockResolvedValue(null),
unsetConfigField: jest.fn().mockResolvedValue(null),
deleteConfig: jest.fn().mockResolvedValue(null),
toggleConfigActiveTracked: jest.fn().mockResolvedValue(null),
@@ -185,6 +191,58 @@ function getIn(target: object, path: string): unknown {
);
}
+/**
+ * A config store over a map, for probes that run the store contract's real operations: whole
+ * document writes under a revision precondition, and removals.
+ */
+function createMapStore(): ConfigStore {
+ const documents = new Map<string, ConfigRecord>();
+ let sequence = 0;
+ const keyOf = ({ principalType, principalId }: ConfigPrincipal) =>
+ `${principalType}:${principalId}`;
+ const revisionOf = (record?: ConfigRecord) =>
+ record ? getConfigRevision(record) : ABSENT_CONFIG_REVISION;
+ return {
+ read: async (principal) => documents.get(keyOf(principal)) ?? null,
+ list: async () => [...documents.values()],
+ listActive: async () => [...documents.values()].filter((record) => record.isActive),
+ async write(principal, draft, expected) {
+ const current = documents.get(keyOf(principal));
+ if (expected !== revisionOf(current)) {
+ throw new ConfigRevisionConflictError(current ? revisionOf(current) : null);
+ }
+ sequence += 1;
+ const record: ConfigRecord = {
+ ...draft,
+ ...principal,
+ _id: current?._id ?? String(sequence).padStart(24, '0'),
+ configVersion: (current?.configVersion ?? 0) + 1,
+ };
+ documents.set(keyOf(principal), record);
+ return record;
+ },
+ async remove(principal, expected) {
+ const current = documents.get(keyOf(principal));
+ if (expected !== undefined && expected !== revisionOf(current)) {
+ throw new ConfigRevisionConflictError(current ? revisionOf(current) : null);
+ }
+ documents.delete(keyOf(principal));
+ return current ?? null;
+ },
+ restore: async () => false,
+ };
+}
+
+/** Config handler deps that read and write `store` through the admin API's own calls. */
+function storeDeps(store: ConfigStore): Partial<AdminConfigDeps> {
+ return {
+ findConfigByPrincipal: (principalType, principalId) =>
+ store.read({ principalType, principalId: principalId.toString() }),
+ writeConfigDocument: (principalType, principalId, draft, expected) =>
+ store.write({ principalType, principalId }, draft, expected),
+ };
+}
+
describe('GET /api/admin/config/meta', () => {
it('answers 401 without a user and 403 without any config read access', async () => {
const anonymous = mockRes();
@@ -216,11 +274,15 @@ describe('GET /api/admin/config/meta', () => {
expect(Object.keys(meta.features).sort()).toEqual([
'awaitedInvalidation',
'changesBatch',
+ 'deterministicPrecedence',
'dottedKeys',
'expectedRevision',
'preAuthBaseOverrides',
+ 'principalCheck',
+ 'priorityRoute',
'prunesEmptyParents',
'readFilteredWriteResponses',
+ 'roleRenameMovesProfile',
'sectionAllowlist',
'webSearchStoredKeys',
'yamlMcpHide',
@@ -260,6 +322,10 @@ describe('GET /api/admin/config/meta', () => {
awaitedInvalidation: true,
changesBatch: true,
yamlMcpHide: true,
+ deterministicPrecedence: true,
+ priorityRoute: true,
+ principalCheck: true,
+ roleRenameMovesProfile: true,
});
});
@@ -465,7 +531,6 @@ const FEATURE_PROBES: Record<AdminConfigFeatureFlag, () => Promise<boolean>> = {
return { broad: false, sections: new Set<string>() };
}),
writeConfigDocument: commit,
- tombstoneConfigField: commit,
unsetConfigField: commit,
};
};
@@ -688,6 +753,309 @@ const FEATURE_PROBES: Record<AdminConfigFeatureFlag, () => Promise<boolean>> = {
return held && res.statusCode === 200 && bypassed && dropsStaleMerge;
},
+ async deterministicPrecedence() {
+ const layer = (
+ principalType: PrincipalType,
+ principalId: string,
+ priority: number,
+ _id: string,
+ ): ConfigOverrideLayer => ({
+ principalType,
+ principalId,
+ priority,
+ _id,
+ overrides: { interface: { customWelcome: principalId } },
+ });
+ const winner = (...configs: ConfigOverrideLayer[]) =>
+ mergeConfigOverrides({ config: {} } as AppConfig, configs).interfaceConfig?.customWelcome;
+ const base = layer(PrincipalType.ROLE, '__base__', 50, 'a3');
+ const role = layer(PrincipalType.ROLE, 'r1', 5, 'a2');
+ const group = layer(PrincipalType.GROUP, 'g1', 5, 'a1');
+ const user = layer(PrincipalType.USER, 'u1', 5, 'a0');
+ const later = layer(PrincipalType.GROUP, 'g2', 5, 'a4');
+ const ordered =
+ winner(role, base) === 'r1' &&
+ winner(base, role) === 'r1' &&
+ winner(group, role) === 'g1' &&
+ winner(role, group) === 'g1' &&
+ winner(user, group, role) === 'u1' &&
+ winner(later, group) === 'g2' &&
+ winner(group, later) === 'g2';
+
+ const store = createMapStore();
+ const handlers = createHandlers(storeDeps(store));
+ const put = async (principalType: PrincipalType, principalId: string, body: object) => {
+ await handlers.upsertConfigOverrides(
+ mockReq({ params: { principalType, principalId }, body }),
+ mockRes(),
+ );
+ return (await store.read({ principalType, principalId }))?.priority;
+ };
+ const overrides = { interface: { customWelcome: 'hi' } };
+ const defaults = await Promise.all([
+ put(PrincipalType.ROLE, 'r1', { overrides }),
+ put(PrincipalType.GROUP, 'g1', { overrides }),
+ put(PrincipalType.USER, 'u1', { overrides }),
+ ]);
+ await put(PrincipalType.ROLE, 'r1', { overrides, priority: 33 });
+ const kept = await put(PrincipalType.ROLE, 'r1', {
+ overrides: { interface: { customWelcome: 'again' } },
+ });
+ await handlers.applyConfigChanges(
+ mockReq({
+ params: { principalType: PrincipalType.GROUP, principalId: 'g0' },
+ body: { ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' }] },
+ }),
+ mockRes(),
+ );
+ const batchDefault = (
+ await store.read({ principalType: PrincipalType.GROUP, principalId: 'g0' })
+ )?.priority;
+
+ const operations = createConfigOperations(store);
+ await operations.setFields(
+ { principalType: PrincipalType.ROLE, principalId: '__base__' },
+ PrincipalModel.ROLE,
+ { 'interface.customWelcome': 'base' },
+ 500,
+ );
+ await operations.setPriority({ principalType: PrincipalType.GROUP, principalId: 'g0' }, 33);
+ const listed = mockRes();
+ await createHandlers({ listAllConfigs: () => operations.listConfigs() }).listConfigs(
+ mockReq(),
+ listed,
+ );
+ const listOrder = (listed.body?.configs as ConfigRecord[] | undefined)
+ ?.map(({ principalId }) => principalId)
+ .join();
+
+ /** Statuses of a PATCH `/fields` and a dry-run batch setting `memory.agent.model` on a role
+ * over `yaml`, with Base tombstoning `tombstones` and setting `fields`. */
+ const floorStatuses = async (
+ yaml: object,
+ tombstones: string[],
+ fields: Record<string, unknown>,
+ ) => {
+ const floorStore = createMapStore();
+ const floorOperations = createConfigOperations(floorStore);
+ const base = { principalType: PrincipalType.ROLE, principalId: '__base__' };
+ await floorOperations.tombstoneFields(base, PrincipalModel.ROLE, tombstones);
+ await floorOperations.setFields(base, PrincipalModel.ROLE, fields);
+ const floorHandlers = createHandlers({
+ ...storeDeps(floorStore),
+ getAppConfig: jest.fn().mockResolvedValue({ config: yaml }),
+ });
+ const params = { principalType: PrincipalType.ROLE, principalId: 'r2' };
+ const batch = mockRes();
+ await floorHandlers.applyConfigChanges(
+ mockReq({
+ params,
+ body: {
+ ops: [{ op: 'set', fieldPath: 'memory.agent.model', value: 'gpt-4.1' }],
+ dryRun: true,
+ },
+ }),
+ batch,
+ );
+ const patched = await patch([{ fieldPath: 'memory.agent.model', value: 'gpt-4.1' }], {
+ ...storeDeps(floorStore),
+ getAppConfig: jest.fn().mockResolvedValue({ config: yaml }),
+ });
+ return `${patched.statusCode},${batch.statusCode}`;
+ };
+ const validOnlyOverBase = await floorStatuses(
+ { memory: { agent: { id: 'agent_1' } } },
+ ['memory.agent.id'],
+ { 'memory.agent.provider': 'openAI', 'memory.agent.model': 'gpt-4o' },
+ );
+ const invalidOnlyOverBase = await floorStatuses(
+ { memory: { agent: { provider: 'openAI', model: 'gpt-4o' } } },
+ ['memory.agent.provider', 'memory.agent.model'],
+ { 'memory.agent.id': 'agent_9' },
+ );
+
+ return (
+ ordered &&
+ defaults.join() === '10,20,100' &&
+ kept === 33 &&
+ batchDefault === 20 &&
+ listOrder === '__base__,g1,r1,g0,u1' &&
+ validOnlyOverBase === '200,200' &&
+ invalidOnlyOverBase === '400,400'
+ );
+ },
+ async priorityRoute() {
+ const store = createMapStore();
+ const operations = createConfigOperations(store);
+ const principal = { principalType: PrincipalType.ROLE, principalId: 'r1' };
+ await operations.setFields(principal, PrincipalModel.ROLE, { 'interface.customWelcome': 'x' });
+ await operations.tombstoneFields(principal, PrincipalModel.ROLE, 'memory.agent');
+ await operations.setActive(principal, false);
+ const before = await store.read(principal);
+
+ const setConfigPriority: AdminConfigDeps['setConfigPriority'] = (type, id, priority, options) =>
+ operations.setPriority({ principalType: type, principalId: id }, priority, options);
+ const route = async (
+ principalId: string,
+ body: object,
+ deps: Partial<AdminConfigDeps> = {},
+ ) => {
+ const res = mockRes();
+ await createHandlers({ setConfigPriority, ...deps }).updateConfigPriority(
+ mockReq({ params: { principalType: PrincipalType.ROLE, principalId }, body }),
+ res,
+ );
+ return res;
+ };
+ const updated = await route('r1', { priority: 42 });
+ const after = await store.read(principal);
+ const missing = await route('nobody', { priority: 1 });
+ const invalid = await route('r1', { priority: -1 });
+ const sectionScoped = await route(
+ 'r1',
+ { priority: 7 },
+ { hasConfigCapability: jest.fn(async (_user, section) => section != null) },
+ );
+ return (
+ updated.statusCode === 200 &&
+ after?.priority === 42 &&
+ JSON.stringify(after.overrides) === JSON.stringify(before?.overrides) &&
+ JSON.stringify(after.tombstones) === JSON.stringify(before?.tombstones) &&
+ after.isActive === false &&
+ missing.statusCode === 404 &&
+ missing.body?.code === 'CONFIG_NOT_FOUND' &&
+ invalid.statusCode === 400 &&
+ invalid.body?.code === 'INVALID_PRIORITY' &&
+ sectionScoped.statusCode === 403 &&
+ (await store.read(principal))?.priority === 42
+ );
+ },
+ async principalCheck() {
+ const store = createMapStore();
+ const principalExists = jest.fn(async (_type: PrincipalType, id: string) => id === 'editor');
+ const handlers = createHandlers({ ...storeDeps(store), principalExists });
+ const write = async (
+ handler:
+ | 'upsertConfigOverrides'
+ | 'patchConfigField'
+ | 'tombstoneConfigField'
+ | 'applyConfigChanges',
+ principalId: string,
+ body: object,
+ ) => {
+ const res = mockRes();
+ await handlers[handler](
+ mockReq({ params: { principalType: PrincipalType.ROLE, principalId }, body }),
+ res,
+ );
+ return res;
+ };
+ const refused = await Promise.all([
+ write('upsertConfigOverrides', 'ghost', { overrides: { interface: { customWelcome: 'x' } } }),
+ write('patchConfigField', 'ghost', {
+ entries: [{ fieldPath: 'interface.customWelcome', value: 'x' }],
+ }),
+ write('tombstoneConfigField', 'ghost', { fieldPath: 'interface.customWelcome' }),
+ write('applyConfigChanges', 'ghost', {
+ ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'x' }],
+ }),
+ write('applyConfigChanges', 'ghost', {
+ ops: [{ op: 'unset', fieldPath: 'interface.customWelcome' }],
+ priority: 5,
+ }),
+ ]);
+ const created = await write('upsertConfigOverrides', 'editor', {
+ overrides: {},
+ expectedRevision: ABSENT_CONFIG_REVISION,
+ });
+ const again = await write('upsertConfigOverrides', 'editor', {
+ overrides: {},
+ expectedRevision: ABSENT_CONFIG_REVISION,
+ });
+
+ /** A tombstone checks the document it writes over: here a DELETE lands after its read. */
+ const retired = { principalType: PrincipalType.ROLE, principalId: 'retired' };
+ await createConfigOperations(store).setFields(retired, PrincipalModel.ROLE, {
+ 'interface.customWelcome': 'old',
+ });
+ let removedConcurrently = false;
+ const raced = mockRes();
+ await createHandlers({
+ ...storeDeps(store),
+ principalExists,
+ findConfigByPrincipal: async (principalType, principalId) => {
+ const found = await store.read({ principalType, principalId });
+ if (found && !removedConcurrently) {
+ removedConcurrently = true;
+ await store.remove({ principalType, principalId });
+ }
+ return found;
+ },
+ }).tombstoneConfigField(
+ mockReq({ params: retired, body: { fieldPath: 'interface.customWelcome' } }),
+ raced,
+ );
+
+ return (
+ refused.every((res) => res.statusCode === 404 && res.body?.code === 'PRINCIPAL_NOT_FOUND') &&
+ (await store.read({ principalType: PrincipalType.ROLE, principalId: 'ghost' })) === null &&
+ created.statusCode === 201 &&
+ again.statusCode === 409 &&
+ again.body?.code === 'CONFIG_VERSION_CONFLICT' &&
+ removedConcurrently &&
+ raced.statusCode === 404 &&
+ raced.body?.code === 'PRINCIPAL_NOT_FOUND' &&
+ (await store.read(retired)) === null
+ );
+ },
+ async roleRenameMovesProfile() {
+ const store = createMapStore();
+ const operations = createConfigOperations(store);
+ const role = (principalId: string) => ({ principalType: PrincipalType.ROLE, principalId });
+ await operations.setFields(role('editor'), PrincipalModel.ROLE, {
+ 'interface.customWelcome': 'moved',
+ });
+ await operations.setFields(role('taken'), PrincipalModel.ROLE, {
+ 'interface.customWelcome': 'kept',
+ });
+ const moveGrantsToPrincipal = jest.fn().mockResolvedValue({ moved: [], superseded: [] });
+ const moveAclEntriesToPrincipal = jest.fn().mockResolvedValue([]);
+ const deps: Partial<AdminRolesDeps> = {
+ getRoleByName: jest.fn(async (name: string) =>
+ name === 'editor' ? ({ name } as IRole) : null,
+ ),
+ updateRoleByName: jest.fn(async (_name: string, updates: Partial<IRole>) => updates as IRole),
+ findUserIdsByRole: jest.fn().mockResolvedValue([]),
+ updateUsersByRole: jest.fn().mockResolvedValue(undefined),
+ findConfigByPrincipal: (type, id) => store.read({ principalType: type, principalId: id }),
+ renameConfigPrincipal: (_type, from, to) => operations.movePrincipal(role(from), role(to)),
+ moveGrantsToPrincipal,
+ moveAclEntriesToPrincipal,
+ };
+ const handlers = createAdminRolesHandlers(deps as AdminRolesDeps);
+ const rename = async (name: string) => {
+ const res = mockRes();
+ await handlers.updateRole(mockReq({ params: { name: 'editor' }, body: { name } }), res);
+ return res;
+ };
+ const conflict = await rename('taken');
+ const reserved = await rename('__base__');
+ const renamed = await rename('reviewer');
+ const moved = await store.read(role('reviewer'));
+ return (
+ conflict.statusCode === 409 &&
+ conflict.body?.code === 'ROLE_CONFIG_CONFLICT' &&
+ reserved.statusCode === 400 &&
+ reserved.body?.code === 'ROLE_NAME_RESERVED' &&
+ renamed.statusCode === 200 &&
+ (await store.read(role('editor'))) === null &&
+ getIn(moved?.overrides ?? {}, 'interface.customWelcome') === 'moved' &&
+ getIn((await store.read(role('taken')))?.overrides ?? {}, 'interface.customWelcome') ===
+ 'kept' &&
+ moveGrantsToPrincipal.mock.calls[0]?.slice(0, 3).join() === 'role,editor,reviewer' &&
+ moveAclEntriesToPrincipal.mock.calls[0]?.slice(0, 3).join() === 'role,editor,reviewer'
+ );
+ },
async changesBatch() {
const writeConfigDocument = jest.fn(
async (_type: string, _id: string, draft: ConfigDraft): Promise<ConfigRecord> => ({
@@ -745,27 +1113,19 @@ const FEATURE_PROBES: Record<AdminConfigFeatureFlag, () => Promise<boolean>> = {
const yaml = { docs, local };
const principal = { id: 'u1', role: 'USER' };
- const stored = memoryConfigOperations(storedConfig({}));
+ const store = createMapStore();
const written = mockRes();
- await createHandlers({
- tombstoneConfigField: (type, id, model, paths, priority, _session, options) =>
- stored.operations.tombstoneFields(
- { principalType: type, principalId: id },
- model,
- paths,
- priority,
- options,
- ),
- }).tombstoneConfigField(
+ await createHandlers(storeDeps(store)).tombstoneConfigField(
mockReq({
params: { principalType: 'role', principalId: 'r1' },
body: { fieldPath: 'mcpServers.docs' },
}),
written,
);
- const record = stored.current();
- const storesTombstone =
- written.statusCode === 200 && record.tombstones.includes('mcpServers.docs');
+ const record = await store.read({ principalType: PrincipalType.ROLE, principalId: 'r1' });
+ if (written.statusCode !== 200 || !record?.tombstones.includes('mcpServers.docs')) {
+ return false;
+ }
const merged = mergeConfigOverrides(
{ config: { mcpServers: yaml }, mcpConfig: yaml } as Partial<AppConfig> as AppConfig,
@@ -797,7 +1157,7 @@ const FEATURE_PROBES: Record<AdminConfigFeatureFlag, () => Promise<boolean>> = {
unreadable.setYamlServerOptions(yaml);
const failsClosed = (await unreadable.resolveHiddenServerNames({ userId: 'u2' })).has('docs');
- return storesTombstone && withheld && refusesCheckout && !hidden.has('local') && failsClosed;
+ return withheld && refusesCheckout && !hidden.has('local') && failsClosed;
},
};
diff --git a/packages/api/src/admin/meta.ts b/packages/api/src/admin/meta.ts
index 1998f46d7a..efbcd4647d 100644
--- a/packages/api/src/admin/meta.ts
+++ b/packages/api/src/admin/meta.ts
@@ -30,6 +30,10 @@ export const ADMIN_CONFIG_FEATURES: Readonly<AdminConfigFeatures> = {
awaitedInvalidation: true,
changesBatch: true,
yamlMcpHide: true,
+ deterministicPrecedence: true,
+ priorityRoute: true,
+ principalCheck: true,
+ roleRenameMovesProfile: true,
};
/**
diff --git a/packages/api/src/admin/roles.rename.spec.ts b/packages/api/src/admin/roles.rename.spec.ts
new file mode 100644
index 0000000000..1fb65fb5c7
--- /dev/null
+++ b/packages/api/src/admin/roles.rename.spec.ts
@@ -0,0 +1,761 @@
+import mongoose, { Types } from 'mongoose';
+import { MongoMemoryServer } from 'mongodb-memory-server';
+import {
+ PrincipalType,
+ PrincipalModel,
+ ResourceType,
+ PermissionBits,
+} from 'librechat-data-provider';
+import type { Response } from 'express';
+import type { ServerRequest } from '~/types/http';
+
+type DataSchemas = typeof import('@librechat/data-schemas');
+type Methods = ReturnType<DataSchemas['createMethods']>;
+type AdminRolesDeps = Parameters<typeof import('./roles').createAdminRolesHandlers>[0];
+
+interface MockRes {
+ statusCode: number;
+ body: undefined | Record<string, unknown>;
+ status: jest.Mock;
+ json: jest.Mock;
+}
+
+/**
+ * Role rename on real collections (BE-20): the config profile, system grants and ACL entries
+ * keyed by the role's name move with it, and a rename that cannot finish leaves everything as
+ * it was.
+ */
+
+let mongoServer: MongoMemoryServer;
+let methods: Methods;
+let dataSchemas: DataSchemas;
+let createAdminRolesHandlers: typeof import('./roles').createAdminRolesHandlers;
+
+const LIFECYCLE_TIMEOUT_MS = 180_000;
+
+beforeAll(async () => {
+ const [schemas, rolesModule, server] = await Promise.all([
+ import('@librechat/data-schemas'),
+ import('./roles'),
+ MongoMemoryServer.create(),
+ ]);
+ dataSchemas = schemas;
+ mongoServer = server;
+ ({ createAdminRolesHandlers } = rolesModule);
+ jest.spyOn(schemas.logger, 'error').mockReturnValue(schemas.logger);
+ jest.spyOn(schemas.logger, 'warn').mockReturnValue(schemas.logger);
+ jest.spyOn(schemas.logger, 'info').mockReturnValue(schemas.logger);
+
+ await mongoose.connect(mongoServer.getUri());
+ schemas.createModels(mongoose);
+ await Promise.all(['Config', 'SystemGrant'].map((name) => mongoose.models[name].init()));
+ methods = schemas.createMethods(mongoose);
+}, LIFECYCLE_TIMEOUT_MS);
+
+afterAll(async () => {
+ await mongoose.disconnect();
+ await mongoServer?.stop();
+}, LIFECYCLE_TIMEOUT_MS);
+
+beforeEach(async () => {
+ await Promise.all(
+ ['Config', 'Role', 'User', 'SystemGrant', 'AclEntry'].map((name) =>
+ mongoose.models[name].deleteMany({}),
+ ),
+ );
+});
+
+function mockRes(): Response & MockRes {
+ const res: MockRes = {
+ statusCode: 200,
+ body: undefined,
+ status: jest.fn((code: number) => {
+ res.statusCode = code;
+ return res;
+ }),
+ json: jest.fn((data: MockRes['body']) => {
+ res.body = data;
+ return res;
+ }),
+ };
+ return res as Partial<Response> as Response & MockRes;
+}
+
+/** Handlers wired the way `api/server/routes/admin/roles.js` wires them. */
+function createHandlers(overrides: Partial<AdminRolesDeps> = {}) {
+ return createAdminRolesHandlers({
+ listRoles: methods.listRoles,
+ countRoles: methods.countRoles,
+ getRoleByName: methods.getRoleByName,
+ createRoleByName: methods.createRoleByName,
+ updateRoleByName: methods.updateRoleByName,
+ updateAccessPermissions: methods.updateAccessPermissions,
+ deleteRoleByName: methods.deleteRoleByName,
+ findUser: methods.findUser,
+ updateUser: methods.updateUser,
+ updateUsersByRole: methods.updateUsersByRole,
+ findUserIdsByRole: methods.findUserIdsByRole,
+ updateUsersRoleByIds: methods.updateUsersRoleByIds,
+ listUsersByRole: methods.listUsersByRole,
+ countUsersByRole: methods.countUsersByRole,
+ deleteConfig: methods.deleteConfig,
+ deleteAclEntries: async (filter) => {
+ await methods.deleteAclEntries(filter);
+ },
+ deleteGrantsForPrincipal: methods.deleteGrantsForPrincipal,
+ restoreConfig: methods.restoreConfig,
+ findConfigByPrincipal: methods.findConfigByPrincipal,
+ findGrantsForPrincipal: methods.findGrantsForPrincipal,
+ renameConfigPrincipal: methods.renameConfigPrincipal,
+ moveGrantsToPrincipal: methods.moveGrantsToPrincipal,
+ restoreMovedGrants: methods.restoreMovedGrants,
+ moveAclEntriesToPrincipal: methods.moveAclEntriesToPrincipal,
+ ...overrides,
+ });
+}
+
+/** Runs `run` in a tenant's context, as the tenant middleware does for that tenant's requests. */
+function inTenant<T>(tenantId: string, run: () => Promise<T>): Promise<T> {
+ return dataSchemas.tenantStorage.run({ tenantId }, run);
+}
+
+/** Renames as an admin without a tenant, or as one of `tenantId` inside its context. */
+async function rename(
+ handlers: ReturnType<typeof createHandlers>,
+ from: string,
+ body: Record<string, unknown>,
+ tenantId?: string,
+): Promise<MockRes> {
+ const res = mockRes();
+ const req = {
+ params: { name: from },
+ body,
+ query: {},
+ user: { _id: new Types.ObjectId(), id: 'admin', role: 'ADMIN', tenantId },
+ } as Partial<ServerRequest> as ServerRequest;
+ const run = () => handlers.updateRole(req, res);
+ await (tenantId ? inTenant(tenantId, run) : run());
+ return res;
+}
+
+/** Every stored role profile as `tenant/name: welcome`, platform-level ones as `-/name: …`. */
+async function profileLayout(): Promise<string[]> {
+ const documents = await mongoose.connection
+ .db!.collection('configs')
+ .find({ principalType: PrincipalType.ROLE })
+ .toArray();
+ return documents
+ .map(
+ (document) =>
+ `${document.tenantId || '-'}/${document.principalId}: ${document.overrides?.interface?.customWelcome}`,
+ )
+ .sort();
+}
+
+/** Every stored role grant as `tenant/name: capability`, platform-level ones as `-/name: …`. */
+async function grantLayout(): Promise<string[]> {
+ const grants = await mongoose.models.SystemGrant.find({ principalType: PrincipalType.ROLE })
+ .select('principalId capability tenantId')
+ .lean<Array<{ principalId: string; capability: string; tenantId?: string }>>();
+ return grants
+ .map((grant) => `${grant.tenantId || '-'}/${grant.principalId}: ${grant.capability}`)
+ .sort();
+}
+
+const setWelcome = (name: string, welcome: string) =>
+ methods.patchConfigFields(PrincipalType.ROLE, name, PrincipalModel.ROLE, {
+ 'interface.customWelcome': welcome,
+ });
+
+/** A role with a member, a config profile, a grant and an ACL entry, all keyed by its name. */
+async function seedRole(name: string, description = 'Writes things') {
+ await methods.createRoleByName({ name, description, permissions: {} });
+ const userId = await methods.createUser(
+ { email: `${name}@example.com`, name, provider: 'local', role: name },
+ undefined,
+ true,
+ );
+ await methods.patchConfigFields(PrincipalType.ROLE, name, PrincipalModel.ROLE, {
+ 'interface.customWelcome': `hello ${name}`,
+ });
+ await methods.setConfigPriority(PrincipalType.ROLE, name, 15);
+ await methods.grantCapability({
+ principalType: PrincipalType.ROLE,
+ principalId: name,
+ capability: dataSchemas.SystemCapabilities.READ_USERS,
+ });
+ const resourceId = new Types.ObjectId();
+ await methods.grantPermission(
+ PrincipalType.ROLE,
+ name,
+ ResourceType.AGENT,
+ resourceId,
+ PermissionBits.VIEW,
+ );
+ return { userId: userId.toString(), resourceId };
+}
+
+/** Everything keyed by `name`: its role document, members, profile, grants and ACL entries. */
+async function keyedBy(name: string) {
+ const [role, members, profile, grants, aclEntries] = await Promise.all([
+ methods.getRoleByName(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 })
+ .select('resourceId')
+ .lean<Array<{ resourceId: Types.ObjectId }>>(),
+ ]);
+ return {
+ role: role ? { name: role.name, description: role.description } : null,
+ members,
+ profile: profile
+ ? { overrides: profile.overrides, priority: profile.priority, isActive: profile.isActive }
+ : null,
+ grants: grants.map((grant) => grant.capability),
+ aclEntries: aclEntries.map((entry) => entry.resourceId.toString()),
+ };
+}
+
+const nothing = { role: null, members: [], profile: null, grants: [], aclEntries: [] };
+
+describe('role rename moves what is keyed by the role name', () => {
+ it('moves the profile, grants and ACL entries with the role and its members', async () => {
+ const recordAuditEntry = jest.fn().mockResolvedValue(undefined);
+ const invalidateConfigCaches = jest.fn().mockResolvedValue(undefined);
+ const invalidatePromptGroupAccessContext = jest.fn().mockResolvedValue(undefined);
+ const handlers = createHandlers({
+ recordAuditEntry,
+ invalidateConfigCaches,
+ invalidatePromptGroupAccessContext,
+ });
+ const { userId, resourceId } = await seedRole('editor');
+ const before = await keyedBy('editor');
+
+ const res = await rename(handlers, 'editor', { name: 'writer' });
+
+ expect(res.statusCode).toBe(200);
+ expect(await keyedBy('editor')).toEqual(nothing);
+ expect(await keyedBy('writer')).toEqual({
+ ...before,
+ role: { name: 'writer', description: 'Writes things' },
+ members: [userId],
+ aclEntries: [resourceId.toString()],
+ });
+ expect(invalidateConfigCaches).toHaveBeenCalledTimes(1);
+ expect(invalidatePromptGroupAccessContext).toHaveBeenCalledTimes(1);
+ expect(recordAuditEntry.mock.calls.map(([entry]) => [entry.action, entry.target.id])).toEqual([
+ ['role.updated', 'writer'],
+ ['config.deleted', 'role:editor'],
+ ['config.created', 'role:writer'],
+ ]);
+ expect(recordAuditEntry.mock.calls.map(([entry]) => entry.metadata)).toEqual([
+ {
+ previousName: 'editor',
+ descriptionChanged: false,
+ configMoved: true,
+ grantsMoved: 1,
+ grantCapabilities: dataSchemas.SystemCapabilities.READ_USERS,
+ aclEntriesMoved: 1,
+ },
+ { cause: 'role_renamed', movedTo: 'role:writer' },
+ { operation: 'move', cause: 'role_renamed', movedFrom: 'role:editor', priority: 15 },
+ ]);
+ });
+
+ it('renames a role without a profile, grants or ACL entries, auditing no config move', async () => {
+ const recordAuditEntry = jest.fn().mockResolvedValue(undefined);
+ const handlers = createHandlers({ recordAuditEntry });
+ await methods.createRoleByName({ name: 'plain', permissions: {} });
+
+ const res = await rename(handlers, 'plain', { name: 'simple' });
+
+ expect(res.statusCode).toBe(200);
+ expect((await keyedBy('simple')).role?.name).toBe('simple');
+ expect((await keyedBy('plain')).role).toBeNull();
+ expect(recordAuditEntry.mock.calls.map(([entry]) => entry.action)).toEqual(['role.updated']);
+ });
+
+ it('refuses with 409 before changing anything when the new name already has a profile', async () => {
+ const handlers = createHandlers();
+ await seedRole('editor');
+ await methods.patchConfigFields(PrincipalType.ROLE, 'writer', PrincipalModel.ROLE, {
+ 'interface.customWelcome': 'orphaned',
+ });
+ const before = await keyedBy('editor');
+
+ const res = await rename(handlers, 'editor', { name: 'writer' });
+
+ expect(res.statusCode).toBe(409);
+ expect(res.body).toEqual({
+ error: 'A config profile already exists for role "writer"',
+ code: 'ROLE_CONFIG_CONFLICT',
+ });
+ expect(await keyedBy('editor')).toEqual(before);
+ expect((await keyedBy('writer')).profile?.overrides).toEqual({
+ interface: { customWelcome: 'orphaned' },
+ });
+ });
+
+ it('rolls everything back with 409 when a profile for the new name appears mid-rename', async () => {
+ await seedRole('editor');
+ const before = await keyedBy('editor');
+ /** The profile lands after the pre-check, between the role update and the profile move. */
+ const handlers = createHandlers({
+ renameConfigPrincipal: async (principalType, from, to) => {
+ await methods.patchConfigFields(principalType, to, PrincipalModel.ROLE, {
+ 'interface.customWelcome': 'racer',
+ });
+ return methods.renameConfigPrincipal(principalType, from, to);
+ },
+ });
+
+ const res = await rename(handlers, 'editor', { name: 'writer', description: 'Renamed' });
+
+ expect(res.statusCode).toBe(409);
+ expect(res.body?.code).toBe('ROLE_CONFIG_CONFLICT');
+ expect(await keyedBy('editor')).toEqual(before);
+ const writer = await keyedBy('writer');
+ expect(writer.role).toBeNull();
+ expect(writer.grants).toEqual([]);
+ expect(writer.aclEntries).toEqual([]);
+ });
+
+ it('reports a profile move that kept losing races as a failed rename, not a conflict', async () => {
+ await seedRole('editor');
+ const before = await keyedBy('editor');
+ const handlers = createHandlers({
+ renameConfigPrincipal: async () => {
+ throw new dataSchemas.ConfigRevisionConflictError();
+ },
+ });
+
+ const res = await rename(handlers, 'editor', { name: 'writer' });
+
+ expect(res.statusCode).toBe(500);
+ expect(res.body?.code).toBe('ROLE_RENAME_FAILED');
+ expect(await keyedBy('editor')).toEqual(before);
+ expect(await keyedBy('writer')).toEqual(nothing);
+ });
+
+ it('undoes the ACL move without taking the entries the new name already had', async () => {
+ await seedRole('editor');
+ const writerResource = new Types.ObjectId();
+ await methods.grantPermission(
+ PrincipalType.ROLE,
+ 'writer',
+ ResourceType.AGENT,
+ writerResource,
+ PermissionBits.EDIT,
+ );
+ const before = await keyedBy('editor');
+ const handlers = createHandlers({
+ moveGrantsToPrincipal: async () => {
+ throw new Error('grant write failed');
+ },
+ });
+
+ const res = await rename(handlers, 'editor', { name: 'writer' });
+
+ expect(res.statusCode).toBe(500);
+ expect(res.body?.code).toBe('ROLE_RENAME_FAILED');
+ expect(await keyedBy('editor')).toEqual(before);
+ expect(await keyedBy('writer')).toEqual({
+ ...nothing,
+ aclEntries: [writerResource.toString()],
+ });
+ });
+
+ it('rolls everything back when moving a dependent fails', async () => {
+ const invalidateConfigCaches = jest.fn().mockResolvedValue(undefined);
+ await seedRole('editor');
+ const before = await keyedBy('editor');
+ const handlers = createHandlers({
+ invalidateConfigCaches,
+ moveAclEntriesToPrincipal: async () => {
+ throw new Error('acl write failed');
+ },
+ });
+
+ const res = await rename(handlers, 'editor', { name: 'writer', description: 'Renamed' });
+
+ expect(res.statusCode).toBe(500);
+ expect(res.body).toEqual({
+ error: 'Failed to move the role profile, grants or permissions; the role was not renamed',
+ code: 'ROLE_RENAME_FAILED',
+ });
+ expect(await keyedBy('editor')).toEqual(before);
+ expect(await keyedBy('writer')).toEqual(nothing);
+ expect(invalidateConfigCaches).toHaveBeenCalledTimes(1);
+ });
+
+ it('takes back the new description of a role stored without one when the rename rolls back', async () => {
+ await mongoose.models.Role.collection.insertOne({ name: 'legacy', permissions: {} });
+ expect((await keyedBy('legacy')).role).toEqual({ name: 'legacy', description: undefined });
+ const handlers = createHandlers({
+ moveAclEntriesToPrincipal: async () => {
+ throw new Error('acl write failed');
+ },
+ });
+
+ const res = await rename(handlers, 'legacy', { name: 'modern', description: 'Renamed' });
+
+ expect(res.statusCode).toBe(500);
+ expect(res.body?.code).toBe('ROLE_RENAME_FAILED');
+ expect((await keyedBy('legacy')).role).toEqual({ name: 'legacy', description: '' });
+ expect((await keyedBy('modern')).role).toBeNull();
+ });
+});
+
+describe('a rename that rolls back undoes only what it changed', () => {
+ /** The ACL move fails; every other move still finishes before the rollback starts. */
+ const failingAclMove = async (): Promise<string[]> => {
+ throw new Error('acl write failed');
+ };
+ const failAcl = (meanwhile: () => Promise<unknown>) =>
+ createHandlers({
+ moveAclEntriesToPrincipal: async () => {
+ await meanwhile();
+ return failingAclMove();
+ },
+ });
+
+ it('never re-creates a moved grant that another admin revoked before the rollback', async () => {
+ await seedRole('editor');
+ await methods.grantCapability({
+ principalType: PrincipalType.ROLE,
+ principalId: 'editor',
+ capability: dataSchemas.SystemCapabilities.READ_CONFIGS,
+ });
+ /** The grants move, then another admin revokes one of them from the role's new name. */
+ const handlers = createHandlers({
+ moveGrantsToPrincipal: async (...args) => {
+ const move = await methods.moveGrantsToPrincipal(...args);
+ await methods.revokeCapability({
+ principalType: PrincipalType.ROLE,
+ principalId: 'writer',
+ capability: dataSchemas.SystemCapabilities.READ_USERS,
+ });
+ return move;
+ },
+ moveAclEntriesToPrincipal: failingAclMove,
+ });
+
+ const res = await rename(handlers, 'editor', { name: 'writer' });
+
+ expect(res.statusCode).toBe(500);
+ expect(res.body?.code).toBe('ROLE_RENAME_FAILED');
+ expect(await grantLayout()).toEqual([
+ `-/editor: ${dataSchemas.SystemCapabilities.READ_CONFIGS}`,
+ ]);
+ });
+
+ it('moves back only the profile it moved, never one another admin put at the new name', async () => {
+ await seedRole('editor');
+ /** Another admin removes the moved profile and writes one of their own for the new name. */
+ const handlers = createHandlers({
+ renameConfigPrincipal: async (principalType, from, to, options) => {
+ const moved = await methods.renameConfigPrincipal(principalType, from, to, options);
+ if (!options) {
+ await methods.deleteConfig(principalType, to);
+ await setWelcome(to, 'theirs');
+ }
+ return moved;
+ },
+ moveAclEntriesToPrincipal: failingAclMove,
+ });
+
+ const res = await rename(handlers, 'editor', { name: 'writer' });
+
+ expect(res.statusCode).toBe(500);
+ expect((await keyedBy('editor')).role?.name).toBe('editor');
+ expect(await profileLayout()).toEqual(['-/writer: theirs']);
+ });
+
+ it('brings the moved profile back with an edit made to it meanwhile', async () => {
+ await seedRole('editor');
+ const handlers = createHandlers({
+ renameConfigPrincipal: async (principalType, from, to, options) => {
+ const moved = await methods.renameConfigPrincipal(principalType, from, to, options);
+ if (!options) {
+ await setWelcome(to, 'edited');
+ }
+ return moved;
+ },
+ moveAclEntriesToPrincipal: failingAclMove,
+ });
+
+ const res = await rename(handlers, 'editor', { name: 'writer' });
+
+ expect(res.statusCode).toBe(500);
+ expect(await profileLayout()).toEqual(['-/editor: edited']);
+ expect((await keyedBy('editor')).profile?.priority).toBe(15);
+ });
+
+ it('leaves a member another admin reassigned during the rename on their new role', async () => {
+ const { userId } = await seedRole('editor');
+ const otherId = await methods.createUser(
+ { email: '[email protected]', name: 'second', provider: 'local', role: 'editor' },
+ undefined,
+ true,
+ );
+ const handlers = failAcl(() => methods.updateUser(userId, { role: 'REVIEWER' }));
+
+ const res = await rename(handlers, 'editor', { name: 'writer' });
+
+ expect(res.statusCode).toBe(500);
+ expect((await keyedBy('editor')).members).toEqual([otherId.toString()]);
+ expect(await methods.findUserIdsByRole('REVIEWER')).toEqual([userId]);
+ expect(await methods.findUserIdsByRole('writer')).toEqual([]);
+ });
+
+ it('keeps a description another admin set during the rename', async () => {
+ await seedRole('editor');
+ const handlers = failAcl(() =>
+ methods.updateRoleByName('writer', { description: 'Edited meanwhile' }),
+ );
+
+ const res = await rename(handlers, 'editor', { name: 'writer', description: 'Renamed' });
+
+ expect(res.statusCode).toBe(500);
+ expect((await keyedBy('editor')).role).toEqual({
+ name: 'editor',
+ description: 'Edited meanwhile',
+ });
+ });
+
+ it('finishes the rename when the profile copy committed but its acknowledgement was lost', async () => {
+ await seedRole('editor');
+ const collection = mongoose.models.Config.collection;
+ const findOneAndUpdate = collection.findOneAndUpdate.bind(collection);
+ jest.spyOn(collection, 'findOneAndUpdate').mockImplementationOnce((async (
+ ...args: Parameters<typeof findOneAndUpdate>
+ ) => {
+ await findOneAndUpdate(...args);
+ throw new mongoose.mongo.MongoNetworkError('connection reset after the write applied');
+ }) as unknown as typeof collection.findOneAndUpdate);
+
+ const res = await rename(createHandlers(), 'editor', { name: 'writer' });
+
+ expect(res.statusCode).toBe(200);
+ expect(await profileLayout()).toEqual(['-/writer: hello editor']);
+ expect((await keyedBy('writer')).profile?.priority).toBe(15);
+ });
+});
+
+describe('role names never reach the Base config document', () => {
+ const BASE = '__base__';
+
+ async function seedBase(customWelcome: string) {
+ await methods.patchConfigFields(PrincipalType.ROLE, BASE, PrincipalModel.ROLE, {
+ 'interface.customWelcome': customWelcome,
+ });
+ return methods.findConfigByPrincipal(PrincipalType.ROLE, BASE, { includeInactive: true });
+ }
+
+ function request(params: Record<string, string>, body: Record<string, unknown> = {}) {
+ return {
+ params,
+ body,
+ query: {},
+ user: { _id: new Types.ObjectId(), id: 'admin', role: 'ADMIN' },
+ } as Partial<ServerRequest> as ServerRequest;
+ }
+
+ it('refuses to create a role named after the Base principal', async () => {
+ const res = mockRes();
+
+ await createHandlers().createRole(request({}, { name: BASE }), res);
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toEqual({
+ error: 'name is reserved for the base config',
+ code: 'ROLE_NAME_RESERVED',
+ });
+ expect(await methods.getRoleByName(BASE)).toBeNull();
+ });
+
+ it('refuses to rename a role onto the Base principal, so its profile never becomes Base', async () => {
+ await seedRole('promoted');
+ const before = await keyedBy('promoted');
+
+ const res = await rename(createHandlers(), 'promoted', { name: BASE });
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toEqual({
+ error: 'name is reserved for the base config',
+ code: 'ROLE_NAME_RESERVED',
+ });
+ expect(await keyedBy('promoted')).toEqual(before);
+ expect(await methods.findConfigByPrincipal(PrincipalType.ROLE, BASE)).toBeNull();
+ });
+
+ it('renames a role that already had the name without moving Base off it', async () => {
+ const base = await seedBase('everyone');
+ await methods.createRoleByName({ name: BASE, permissions: {} });
+ await methods.grantCapability({
+ principalType: PrincipalType.ROLE,
+ principalId: BASE,
+ capability: dataSchemas.SystemCapabilities.READ_USERS,
+ });
+
+ const res = await rename(createHandlers(), BASE, { name: 'legacy' });
+
+ expect(res.statusCode).toBe(200);
+ expect(await methods.findConfigByPrincipal(PrincipalType.ROLE, BASE)).toEqual(base);
+ const legacy = await keyedBy('legacy');
+ expect(legacy.role?.name).toBe('legacy');
+ expect(legacy.profile).toBeNull();
+ expect(legacy.grants).toEqual([dataSchemas.SystemCapabilities.READ_USERS]);
+ });
+
+ it('deletes a role that already had the name without deleting Base', async () => {
+ const base = await seedBase('everyone');
+ await methods.createRoleByName({ name: BASE, permissions: {} });
+ const res = mockRes();
+
+ await createHandlers().deleteRole(request({ name: BASE }), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(await methods.getRoleByName(BASE)).toBeNull();
+ expect(await methods.findConfigByPrincipal(PrincipalType.ROLE, BASE)).toEqual(base);
+ });
+});
+
+describe('role rename without a tenant', () => {
+ it('moves platform-level grants and ACL entries only, never a tenant role of the same name', async () => {
+ await seedRole('editor');
+ await dataSchemas.tenantStorage.run({ tenantId: 'tenant-a' }, async () => {
+ await methods.grantCapability({
+ principalType: PrincipalType.ROLE,
+ principalId: 'editor',
+ capability: dataSchemas.SystemCapabilities.READ_CONFIGS,
+ tenantId: 'tenant-a',
+ });
+ await methods.grantPermission(
+ PrincipalType.ROLE,
+ 'editor',
+ ResourceType.AGENT,
+ new Types.ObjectId(),
+ PermissionBits.VIEW,
+ );
+ });
+ const tenantKeyed = () =>
+ dataSchemas.tenantStorage.run({ tenantId: 'tenant-a' }, async () => ({
+ grants: (
+ await methods.findGrantsForPrincipal(PrincipalType.ROLE, 'editor', {
+ tenantId: 'tenant-a',
+ })
+ ).map((grant) => grant.capability),
+ aclEntries: await mongoose.models.AclEntry.countDocuments({
+ principalType: PrincipalType.ROLE,
+ principalId: 'editor',
+ }),
+ }));
+ const tenantBefore = await tenantKeyed();
+
+ const res = await rename(createHandlers(), 'editor', { name: 'writer' });
+
+ expect(res.statusCode).toBe(200);
+ expect(tenantBefore).toEqual({
+ grants: [dataSchemas.SystemCapabilities.READ_CONFIGS],
+ aclEntries: 1,
+ });
+ expect(await tenantKeyed()).toEqual(tenantBefore);
+ const writer = await keyedBy('writer');
+ expect(writer.grants).toEqual([dataSchemas.SystemCapabilities.READ_USERS]);
+ expect(writer.aclEntries).toHaveLength(1);
+ });
+
+ it("leaves a tenant role's profile in its tenant when the platform role has none", async () => {
+ const recordAuditEntry = jest.fn().mockResolvedValue(undefined);
+ await methods.createRoleByName({ name: 'editor', permissions: {} });
+ await inTenant('tenant-a', async () => {
+ await methods.createRoleByName({ name: 'editor', permissions: {} });
+ await setWelcome('editor', 'tenant-a');
+ });
+
+ const res = await rename(createHandlers({ recordAuditEntry }), 'editor', { name: 'writer' });
+
+ expect(res.statusCode).toBe(200);
+ expect(await profileLayout()).toEqual(['tenant-a/editor: tenant-a']);
+ expect(recordAuditEntry.mock.calls.map(([entry]) => entry.action)).toEqual(['role.updated']);
+ expect(recordAuditEntry.mock.calls[0][0].metadata.configMoved).toBe(false);
+ });
+
+ it('moves the platform profile and is not refused by a tenant profile at the new name', async () => {
+ await seedRole('editor');
+ await inTenant('tenant-a', () => setWelcome('writer', 'tenant-a'));
+
+ const res = await rename(createHandlers(), 'editor', { name: 'writer' });
+
+ expect(res.statusCode).toBe(200);
+ expect(await profileLayout()).toEqual(['-/writer: hello editor', 'tenant-a/writer: tenant-a']);
+ });
+});
+
+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');
+ await inTenant('tenant-a', async () => {
+ await methods.createRoleByName({ name: 'editor', permissions: {} });
+ await setWelcome('editor', 'tenant-a');
+ });
+
+ const res = await rename(createHandlers(), 'editor', { name: 'writer' }, 'tenant-a');
+
+ expect(res.statusCode).toBe(200);
+ expect(await profileLayout()).toEqual(['-/editor: hello editor', 'tenant-a/writer: tenant-a']);
+ expect((await keyedBy('editor')).profile?.overrides).toEqual({
+ interface: { customWelcome: 'hello editor' },
+ });
+ });
+
+ it("moves only that tenant's grants, never the platform role's of the same name", async () => {
+ await seedRole('editor');
+ await inTenant('tenant-a', async () => {
+ await methods.createRoleByName({ name: 'editor', permissions: {} });
+ await methods.grantCapability({
+ principalType: PrincipalType.ROLE,
+ principalId: 'editor',
+ capability: dataSchemas.SystemCapabilities.READ_CONFIGS,
+ tenantId: 'tenant-a',
+ });
+ });
+ const recordAuditEntry = jest.fn().mockResolvedValue(undefined);
+
+ const res = await rename(
+ createHandlers({ recordAuditEntry }),
+ 'editor',
+ { name: 'writer' },
+ 'tenant-a',
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(await grantLayout()).toEqual([
+ `-/editor: ${dataSchemas.SystemCapabilities.READ_USERS}`,
+ `tenant-a/writer: ${dataSchemas.SystemCapabilities.READ_CONFIGS}`,
+ ]);
+ expect(recordAuditEntry.mock.calls[0][0].metadata).toMatchObject({
+ grantsMoved: 1,
+ grantCapabilities: dataSchemas.SystemCapabilities.READ_CONFIGS,
+ });
+ });
+
+ it("answers 409 for a profile at the new name in the caller's tenant", async () => {
+ await inTenant('tenant-a', async () => {
+ await methods.createRoleByName({ name: 'editor', permissions: {} });
+ await setWelcome('editor', 'tenant-a');
+ await setWelcome('writer', 'orphaned');
+ });
+
+ const res = await rename(createHandlers(), 'editor', { name: 'writer' }, 'tenant-a');
+
+ expect(res.statusCode).toBe(409);
+ expect(res.body?.code).toBe('ROLE_CONFIG_CONFLICT');
+ expect(await profileLayout()).toEqual([
+ 'tenant-a/editor: tenant-a',
+ 'tenant-a/writer: orphaned',
+ ]);
+ });
+});
diff --git a/packages/api/src/admin/roles.spec.ts b/packages/api/src/admin/roles.spec.ts
index 6647cdf4f5..e3e77c088e 100644
--- a/packages/api/src/admin/roles.spec.ts
+++ b/packages/api/src/admin/roles.spec.ts
@@ -297,7 +297,25 @@ describe('createAdminRolesHandlers', () => {
await handlers.createRole(req, res);
expect(status).toHaveBeenCalledWith(400);
- expect(json).toHaveBeenCalledWith({ error: 'name is a reserved path segment' });
+ expect(json).toHaveBeenCalledWith({
+ error: 'name is a reserved path segment',
+ code: 'ROLE_NAME_RESERVED',
+ });
+ expect(deps.createRoleByName).not.toHaveBeenCalled();
+ });
+
+ it('returns 400 when name is the base config principal id', async () => {
+ const deps = createDeps();
+ const handlers = createAdminRolesHandlers(deps);
+ const { req, res, status, json } = createReqRes({ body: { name: ' __base__ ' } });
+
+ await handlers.createRole(req, res);
+
+ expect(status).toHaveBeenCalledWith(400);
+ expect(json).toHaveBeenCalledWith({
+ error: 'name is reserved for the base config',
+ code: 'ROLE_NAME_RESERVED',
+ });
expect(deps.createRoleByName).not.toHaveBeenCalled();
});
@@ -706,7 +724,9 @@ describe('createAdminRolesHandlers', () => {
expect(json).toHaveBeenCalledWith({ error: 'Role not found' });
expect(deps.updateUsersByRole).toHaveBeenCalledTimes(1);
expect(deps.updateUsersByRole).toHaveBeenCalledWith('editor', 'new-name');
- expect(deps.updateUsersRoleByIds).toHaveBeenCalledWith(ids, 'editor');
+ expect(deps.updateUsersRoleByIds).toHaveBeenCalledWith(ids, 'editor', {
+ fromRole: 'new-name',
+ });
});
it('rolls back user migration when rename throws', async () => {
@@ -727,7 +747,9 @@ describe('createAdminRolesHandlers', () => {
expect(status).toHaveBeenCalledWith(500);
expect(deps.updateUsersByRole).toHaveBeenCalledTimes(1);
expect(deps.updateUsersByRole).toHaveBeenCalledWith('editor', 'new-name');
- expect(deps.updateUsersRoleByIds).toHaveBeenCalledWith(ids, 'editor');
+ expect(deps.updateUsersRoleByIds).toHaveBeenCalledWith(ids, 'editor', {
+ fromRole: 'new-name',
+ });
});
it('logs rollback failure and still returns 500', async () => {
@@ -2297,7 +2319,14 @@ describe('admin role audit entries', () => {
expect.objectContaining({
action: 'role.updated',
target: { type: 'role', id: 'writer', name: 'writer' },
- metadata: { previousName: 'editor', descriptionChanged: false },
+ metadata: {
+ previousName: 'editor',
+ descriptionChanged: false,
+ configMoved: false,
+ grantsMoved: 0,
+ grantCapabilities: null,
+ aclEntriesMoved: 0,
+ },
}),
);
});
diff --git a/packages/api/src/admin/roles.ts b/packages/api/src/admin/roles.ts
index 60de35dabc..7606ca20d2 100644
--- a/packages/api/src/admin/roles.ts
+++ b/packages/api/src/admin/roles.ts
@@ -1,5 +1,11 @@
import { PrincipalType, SystemRoles } from 'librechat-data-provider';
-import { logger, isValidObjectIdString, RoleConflictError } from '@librechat/data-schemas';
+import {
+ logger,
+ RoleConflictError,
+ isConfigMoveRefused,
+ isValidObjectIdString,
+ BASE_CONFIG_PRINCIPAL_ID,
+} from '@librechat/data-schemas';
import type {
IRole,
IUser,
@@ -7,12 +13,15 @@ import type {
AdminMember,
ISystemGrant,
AuditSeverity,
+ SystemGrantMove,
+ ConfigMoveOptions,
} from '@librechat/data-schemas';
import type { FilterQuery, Types } from 'mongoose';
import type { Response } from 'express';
import type { ServerRequest } from '~/types/http';
import type { RecordAuditEntry } from './audit';
-import { createAdminAuditEmitter, diffRolePermissions } from './audit';
+import type { CascadeStep } from './cascade';
+import { createAdminAuditEmitter, diffRolePermissions, configTarget } from './audit';
import { getSafeErrorMetadata } from '~/utils/errors';
import { cascadeStep, runCascade } from './cascade';
import { parsePagination } from './pagination';
@@ -35,6 +44,16 @@ const CONTROL_CHAR_RE = /\p{Cc}/u;
*/
const RESERVED_ROLE_NAMES = new Set(['members', 'permissions']);
+/**
+ * Whether a role name keys its own config profile. The tenant-wide Base document is keyed
+ * `role` / `__base__`, so a role by that name (reserved now, but one may predate that) must
+ * never move or delete it: that would let `manage:roles` rewrite what every user gets, which
+ * otherwise needs broad `manage:configs`.
+ */
+function hasOwnConfigProfile(roleName: string): boolean {
+ return roleName !== BASE_CONFIG_PRINCIPAL_ID;
+}
+
function validateNameParam(name: string): string | null {
if (!name || typeof name !== 'string') {
return 'name parameter is required';
@@ -48,22 +67,31 @@ function validateNameParam(name: string): string | null {
return null;
}
-function validateRoleName(name: unknown, required: boolean): string | null {
+/** A rejected role name as the 400 body; a reserved name carries a code the client can map. */
+interface RoleNameError {
+ error: string;
+ code?: 'ROLE_NAME_RESERVED';
+}
+
+function validateRoleName(name: unknown, required: boolean): RoleNameError | null {
if (name === undefined) {
- return required ? 'name is required' : null;
+ return required ? { error: 'name is required' } : null;
}
if (typeof name !== 'string' || !name.trim()) {
- return required ? 'name is required' : 'name must be a non-empty string';
+ return { error: required ? 'name is required' : 'name must be a non-empty string' };
}
const trimmed = name.trim();
if (trimmed.length > MAX_NAME_LENGTH) {
- return `name must not exceed ${MAX_NAME_LENGTH} characters`;
+ return { error: `name must not exceed ${MAX_NAME_LENGTH} characters` };
}
if (CONTROL_CHAR_RE.test(trimmed)) {
- return 'name contains invalid characters';
+ return { error: 'name contains invalid characters' };
}
if (RESERVED_ROLE_NAMES.has(trimmed)) {
- return 'name is a reserved path segment';
+ return { error: 'name is a reserved path segment', code: 'ROLE_NAME_RESERVED' };
+ }
+ if (!hasOwnConfigProfile(trimmed)) {
+ return { error: 'name is reserved for the base config', code: 'ROLE_NAME_RESERVED' };
}
return null;
}
@@ -117,7 +145,12 @@ export interface AdminRolesDeps {
) => Promise<IUser | null>;
updateUsersByRole: (oldRole: string, newRole: string) => Promise<void>;
findUserIdsByRole: (roleName: string) => Promise<string[]>;
- updateUsersRoleByIds: (userIds: string[], newRole: string) => Promise<void>;
+ /** With `fromRole`, only users whose role is still that one change. */
+ updateUsersRoleByIds: (
+ userIds: string[],
+ newRole: string,
+ options?: { fromRole?: string },
+ ) => Promise<void>;
listUsersByRole: (
roleName: string,
options?: { limit?: number; offset?: number },
@@ -152,6 +185,8 @@ export interface AdminRolesDeps {
principalId: string,
options?: { tenantId?: string },
) => Promise<ISystemGrant[]>;
+ /** A role's profile in the caller's tenant partition (platform-level without a tenant), the
+ * partition `renameConfigPrincipal` moves in. */
findConfigByPrincipal?: (
principalType: PrincipalType,
principalId: string,
@@ -160,6 +195,48 @@ export interface AdminRolesDeps {
/** Re-creates a deleted config document in full, only if none exists. Resolves
* to whether it inserted. */
restoreConfig?: (snapshot: ConfigRecord) => Promise<boolean>;
+ /**
+ * Role rename moves what is keyed by the role's name (this config profile, and the grants
+ * and ACL entries below), so it follows the role instead of applying to nobody, and to any
+ * later role that reuses the old name. Each move is undone if the rename cannot complete; a
+ * dependent without its mover stays where it is.
+ *
+ * Moves the config profile within the caller's tenant partition (platform-level without a
+ * tenant, never a tenant's role of the same name); `null` when there is none. Throws
+ * `ConfigMoveRefusedError`, changing nothing, when the new name already has one in that
+ * partition (`CONFIG_PRINCIPAL_EXISTS`) or either name is the Base principal id. With
+ * `identity`, moves only that document, and resolves to `null` when the source holds another.
+ */
+ renameConfigPrincipal?: (
+ principalType: PrincipalType,
+ fromPrincipalId: string,
+ toPrincipalId: string,
+ options?: ConfigMoveOptions,
+ ) => Promise<ConfigRecord | null>;
+ /** Moves the system grants of exactly `tenantId`, or platform-level ones without it; returns what it changed. */
+ moveGrantsToPrincipal?: (
+ principalType: PrincipalType,
+ fromPrincipalId: string,
+ toPrincipalId: string,
+ options?: { tenantId?: string },
+ ) => Promise<SystemGrantMove>;
+ /** Undoes exactly what `moveGrantsToPrincipal` returned it changed; a grant revoked since stays revoked. */
+ restoreMovedGrants?: (
+ principalType: PrincipalType,
+ fromPrincipalId: string,
+ toPrincipalId: string,
+ move: SystemGrantMove,
+ ) => Promise<void>;
+ /** Moves the ACL entries of the request's tenant (platform-level ones without a tenant) and
+ * returns their ids; with `ids`, moves only those (the undo). */
+ moveAclEntriesToPrincipal?: (
+ principalType: PrincipalType,
+ fromPrincipalId: string,
+ toPrincipalId: string,
+ options?: { ids?: readonly string[] },
+ ) => Promise<string[]>;
+ /** Clears merged-config caches keyed by role name after a rename moved a profile. */
+ invalidateConfigCaches?: (tenantId?: string) => Promise<void>;
/** Optional audit emission for role mutations and the grants removed by the
* role-deletion cascade. Failure is logged unless `auditFailClosed` is set. */
recordAuditEntry?: RecordAuditEntry;
@@ -180,6 +257,39 @@ function roleTarget(name: string) {
return { type: 'role', id: name, name };
}
+/** 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. */
+ config: ConfigRecord | null;
+ /** The grants that now apply under the new name: re-keyed, or already held there. */
+ grants: ISystemGrant[];
+ aclEntries: number;
+}
+
+type RoleRenameResult =
+ | { ok: true; role: IRole; moved: RoleDependentsMoved }
+ | { ok: false; code: 'ROLE_NOT_FOUND' | 'ROLE_CONFIG_CONFLICT' | 'ROLE_RENAME_FAILED' };
+
+function renameFailureResponse(
+ res: Response,
+ code: Extract<RoleRenameResult, { ok: false }>['code'],
+ newName: string,
+): Response {
+ if (code === 'ROLE_NOT_FOUND') {
+ return res.status(404).json({ error: 'Role not found' });
+ }
+ if (code === 'ROLE_CONFIG_CONFLICT') {
+ return res.status(409).json({
+ error: `A config profile already exists for role "${newName}"`,
+ code,
+ });
+ }
+ return res.status(500).json({
+ error: 'Failed to move the role profile, grants or permissions; the role was not renamed',
+ code,
+ });
+}
+
export function createAdminRolesHandlers(deps: AdminRolesDeps): {
listRoles: (req: ServerRequest, res: Response) => Promise<Response>;
getRole: (req: ServerRequest, res: Response) => Promise<Response>;
@@ -212,6 +322,11 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
restoreConfig,
findConfigByPrincipal,
findGrantsForPrincipal,
+ renameConfigPrincipal,
+ moveGrantsToPrincipal,
+ restoreMovedGrants,
+ moveAclEntriesToPrincipal,
+ invalidateConfigCaches,
recordAuditEntry,
auditFailClosed,
invalidatePromptGroupAccessContext,
@@ -288,7 +403,7 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
};
const nameError = validateRoleName(name, true);
if (nameError) {
- return res.status(400).json({ error: nameError });
+ return res.status(400).json(nameError);
}
const descError = validateDescription(description);
if (descError) {
@@ -333,7 +448,7 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
return;
}
try {
- await updateUsersRoleByIds(migratedIds, currentName);
+ await updateUsersRoleByIds(migratedIds, currentName, { fromRole: newName });
} catch (rollbackError) {
logger.error(
`[adminRoles] CRITICAL: rename rollback failed — ${migratedIds.length} users have dangling role "${newName}": [${migratedIds.join(', ')}]`,
@@ -343,7 +458,178 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
}
/**
- * Renames a role by migrating users to the new name and updating the role document.
+ * Puts the role document back under its old name (and description) after a failed rename.
+ * The description goes back only while it is still the one this rename set, so an edit made
+ * meanwhile is kept. A role stored without a description gets the schema default (`''`)
+ * back: the update only sets fields, and an undefined one would be dropped, keeping the new
+ * description.
+ */
+ async function revertRoleUpdate(
+ existing: IRole,
+ currentName: string,
+ newName: string,
+ extraUpdates?: Partial<IRole>,
+ ): Promise<void> {
+ const revert: Partial<IRole> = { name: currentName };
+ if (extraUpdates?.description !== undefined) {
+ const renamed = await getRoleByName(newName).catch(() => null);
+ if (renamed?.description === extraUpdates.description) {
+ revert.description = existing.description ?? '';
+ }
+ }
+ try {
+ await updateRoleByName(newName, revert);
+ } catch (revertError) {
+ logger.error(
+ `[adminRoles] CRITICAL: rename rollback failed — role "${currentName}" is still named "${newName}"`,
+ getSafeErrorMetadata(revertError),
+ );
+ }
+ }
+
+ /**
+ * Moves what is keyed by the role's name, concurrently, and undoes every completed move when
+ * any fails. `configConflict` reports that the new name already had a profile; any other
+ * failure of the profile move (it kept changing, or a copy could not be withdrawn) is a
+ * failed rename, not a conflict at the new name.
+ */
+ async function moveRoleDependents(
+ currentName: string,
+ newName: string,
+ tenantId: string | undefined,
+ ): Promise<
+ | { ok: true; moved: RoleDependentsMoved }
+ | { ok: false; code: 'ROLE_CONFIG_CONFLICT' | 'ROLE_RENAME_FAILED' }
+ > {
+ let configConflict = false;
+ const steps: CascadeStep[] = [];
+ if (renameConfigPrincipal && hasOwnConfigProfile(currentName)) {
+ steps.push(
+ cascadeStep(
+ 'config',
+ async () => {
+ try {
+ return await renameConfigPrincipal(PrincipalType.ROLE, currentName, newName);
+ } catch (error) {
+ configConflict = isConfigMoveRefused(error, 'CONFIG_PRINCIPAL_EXISTS');
+ throw error;
+ }
+ },
+ async (moved: ConfigRecord | null) => {
+ if (!moved) {
+ return;
+ }
+ /** Only the profile this rename moved goes back, with any edit made to it since. */
+ const restored = await renameConfigPrincipal(PrincipalType.ROLE, newName, currentName, {
+ identity: moved._id,
+ });
+ if (!restored) {
+ logger.warn(
+ `[adminRoles] rename rollback left role "${newName}"'s profile in place: it is no longer the one the rename moved`,
+ );
+ }
+ },
+ ),
+ );
+ }
+ if (moveGrantsToPrincipal) {
+ steps.push(
+ cascadeStep(
+ 'grants',
+ () => moveGrantsToPrincipal(PrincipalType.ROLE, currentName, newName, { tenantId }),
+ restoreMovedGrants
+ ? (move: SystemGrantMove) =>
+ restoreMovedGrants(PrincipalType.ROLE, currentName, newName, move)
+ : undefined,
+ ),
+ );
+ }
+ if (moveAclEntriesToPrincipal) {
+ steps.push(
+ cascadeStep(
+ 'acl',
+ () => moveAclEntriesToPrincipal(PrincipalType.ROLE, currentName, newName),
+ async (ids: string[]) => {
+ await moveAclEntriesToPrincipal(PrincipalType.ROLE, newName, currentName, { ids });
+ },
+ ),
+ );
+ }
+ if (steps.length === 0) {
+ return { ok: true, moved: { config: null, grants: [], aclEntries: 0 } };
+ }
+ const cascade = await runCascade(steps, '[adminRoles] rename');
+ if (cascade.failed.length > 0) {
+ await cascade.compensate();
+ return { ok: false, code: configConflict ? 'ROLE_CONFIG_CONFLICT' : 'ROLE_RENAME_FAILED' };
+ }
+ const { config, grants, acl } = cascade.removed as {
+ config?: ConfigRecord | null;
+ grants?: SystemGrantMove;
+ acl?: string[];
+ };
+ return {
+ ok: true,
+ moved: {
+ config: config ?? null,
+ grants: grants ? [...grants.moved, ...grants.superseded] : [],
+ aclEntries: acl?.length ?? 0,
+ },
+ };
+ }
+
+ /**
+ * Records a profile a rename moved in the config trail of both principals, so neither
+ * chain starts or ends without a cause: deleted from the old name, created at the new one.
+ */
+ async function emitProfileMove(
+ req: ServerRequest,
+ previousName: string,
+ newName: string,
+ profile: ConfigRecord | null,
+ ): Promise<void> {
+ if (!profile) {
+ return;
+ }
+ const from = configTarget(PrincipalType.ROLE, previousName);
+ const to = configTarget(PrincipalType.ROLE, newName);
+ await emitAudit(req, {
+ action: 'config.deleted',
+ target: from,
+ metadata: { cause: 'role_renamed', movedTo: to.id },
+ });
+ await emitAudit(req, {
+ action: 'config.created',
+ target: to,
+ metadata: {
+ operation: 'move',
+ cause: 'role_renamed',
+ movedFrom: from.id,
+ priority: profile.priority,
+ },
+ });
+ }
+
+ /** Clears what a rename's moves (or their undo) leave stale; failures are logged, not thrown. */
+ async function invalidateRenamedRole(tenantId: string | undefined): Promise<void> {
+ const results = await Promise.allSettled([
+ invalidateConfigCaches?.(tenantId),
+ invalidatePromptGroupAccessContext?.(),
+ ]);
+ for (const result of results) {
+ if (result.status === 'rejected') {
+ logger.error(
+ '[adminRoles] cache invalidation after rename failed:',
+ getSafeErrorMetadata(result.reason),
+ );
+ }
+ }
+ }
+
+ /**
+ * Renames a role: migrates its users, renames the role document, then moves the config
+ * profile, grants and ACL entries keyed by the old name. A failure at any step undoes the
+ * earlier ones, so the role is either fully renamed or left as it was.
*
* The ID snapshot from `findUserIdsByRole` is a point-in-time read. Users assigned
* to `currentName` between the snapshot and the bulk `updateUsersByRole` write will
@@ -351,23 +637,33 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
* and only relevant under concurrent admin operations during a rename.
*/
async function renameRole(
+ existing: IRole,
currentName: string,
newName: string,
+ tenantId: string | undefined,
extraUpdates?: Partial<IRole>,
- ): Promise<IRole | null> {
+ ): Promise<RoleRenameResult> {
const migratedIds = await findUserIdsByRole(currentName);
await updateUsersByRole(currentName, newName);
+ let role: IRole | null;
try {
const updates: Partial<IRole> = { name: newName, ...extraUpdates };
- const role = await updateRoleByName(currentName, updates);
- if (!role) {
- await rollbackMigratedUsers(migratedIds, currentName, newName);
- }
- return role;
+ role = await updateRoleByName(currentName, updates);
} catch (error) {
await rollbackMigratedUsers(migratedIds, currentName, newName);
throw error;
}
+ if (!role) {
+ await rollbackMigratedUsers(migratedIds, currentName, newName);
+ return { ok: false, code: 'ROLE_NOT_FOUND' };
+ }
+ const dependents = await moveRoleDependents(currentName, newName, tenantId);
+ if (!dependents.ok) {
+ await revertRoleUpdate(existing, currentName, newName, extraUpdates);
+ await rollbackMigratedUsers(migratedIds, currentName, newName);
+ }
+ await invalidateRenamedRole(tenantId);
+ return dependents.ok ? { ok: true, role, moved: dependents.moved } : dependents;
}
async function updateRoleHandler(req: ServerRequest, res: Response) {
@@ -380,7 +676,7 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
const body = req.body as { name?: string; description?: string };
const nameError = validateRoleName(body.name, false);
if (nameError) {
- return res.status(400).json({ error: nameError });
+ return res.status(400).json(nameError);
}
const descError = validateDescription(body.description);
if (descError) {
@@ -403,10 +699,21 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
}
if (isRename) {
- const duplicate = await getRoleByName(trimmedName);
+ const [duplicate, targetProfile] = await Promise.all([
+ getRoleByName(trimmedName),
+ renameConfigPrincipal && findConfigByPrincipal
+ ? findConfigByPrincipal(PrincipalType.ROLE, trimmedName, { includeInactive: true })
+ : null,
+ ]);
if (duplicate) {
return res.status(409).json({ error: `Role "${trimmedName}" already exists` });
}
+ if (targetProfile) {
+ return res.status(409).json({
+ error: `A config profile already exists for role "${trimmedName}"`,
+ code: 'ROLE_CONFIG_CONFLICT',
+ });
+ }
}
const updates: Partial<IRole> = {};
@@ -425,15 +732,30 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
if (isRename) {
const descUpdate =
updates.description !== undefined ? { description: updates.description } : undefined;
- const role = await renameRole(name, trimmedName, descUpdate);
- if (!role) {
- return res.status(404).json({ error: 'Role not found' });
+ const renamed = await renameRole(
+ existing,
+ name,
+ trimmedName,
+ req.user?.tenantId,
+ descUpdate,
+ );
+ if (!renamed.ok) {
+ return renameFailureResponse(res, renamed.code, trimmedName);
}
+ const { role, moved } = renamed;
await emitAudit(req, {
action: 'role.updated',
target: roleTarget(trimmedName),
- metadata: { previousName: name, descriptionChanged: descUpdate !== undefined },
+ metadata: {
+ previousName: name,
+ descriptionChanged: descUpdate !== undefined,
+ configMoved: moved.config != null,
+ grantsMoved: moved.grants.length,
+ grantCapabilities: moved.grants.map((grant) => grant.capability).join(',') || null,
+ aclEntriesMoved: moved.aclEntries,
+ },
});
+ await emitProfileMove(req, name, trimmedName, moved.config);
return res.status(200).json({ role });
}
@@ -565,27 +887,28 @@ export function createAdminRolesHandlers(deps: AdminRolesDeps): {
const grantSnapshot = findGrantsForPrincipal
? await findGrantsForPrincipal(PrincipalType.ROLE, name, { tenantId })
: null;
+ const configStep = cascadeStep(
+ 'config',
+ () => deleteConfig(PrincipalType.ROLE, name),
+ restoreConfig
+ ? async (config) => {
+ if (!config) {
+ return;
+ }
+ /** Insert-only: an override written after the snapshot is kept. */
+ const restored = await restoreConfig(config);
+ if (!restored) {
+ logger.warn('[adminRoles] config restore skipped, override exists:', name);
+ }
+ }
+ : undefined,
+ findConfigByPrincipal
+ ? () => findConfigByPrincipal(PrincipalType.ROLE, name, { includeInactive: true })
+ : undefined,
+ );
const cascade = await runCascade(
[
- cascadeStep(
- 'config',
- () => deleteConfig(PrincipalType.ROLE, name),
- restoreConfig
- ? async (config) => {
- if (!config) {
- return;
- }
- /** Insert-only: an override written after the snapshot is kept. */
- const restored = await restoreConfig(config);
- if (!restored) {
- logger.warn('[adminRoles] config restore skipped, override exists:', name);
- }
- }
- : undefined,
- findConfigByPrincipal
- ? () => findConfigByPrincipal(PrincipalType.ROLE, name, { includeInactive: true })
- : undefined,
- ),
+ ...(hasOwnConfigProfile(name) ? [configStep] : []),
cascadeStep('acl', async () => {
await deleteAclEntries({ principalType: PrincipalType.ROLE, principalId: name });
}),
diff --git a/packages/api/src/admin/secrets.integration.spec.ts b/packages/api/src/admin/secrets.integration.spec.ts
index e0fa3abc55..c4aacd62c5 100644
--- a/packages/api/src/admin/secrets.integration.spec.ts
+++ b/packages/api/src/admin/secrets.integration.spec.ts
@@ -272,7 +272,6 @@ beforeAll(async () => {
listAllConfigs: methods.listAllConfigs,
findConfigByPrincipal,
writeConfigDocument: methods.writeConfigDocument,
- tombstoneConfigField: methods.tombstoneConfigField,
unsetConfigField: methods.unsetConfigField,
deleteConfig: methods.deleteConfig,
toggleConfigActiveTracked: methods.toggleConfigActiveTracked,
@@ -1404,9 +1403,6 @@ describe('config secret registry — real handlers against a real Config collect
writeConfigDocument: async () => {
throw new Error('not written in this test');
},
- tombstoneConfigField: async () => {
- throw new Error('not written in this test');
- },
unsetConfigField: async () => null,
deleteConfig: async () => null,
toggleConfigActiveTracked: async () => null,
@@ -1483,9 +1479,6 @@ describe('config secret registry — real handlers against a real Config collect
writeConfigDocument: async () => {
throw new Error('not written in this test');
},
- tombstoneConfigField: async () => {
- throw new Error('not written in this test');
- },
unsetConfigField: async () => null,
deleteConfig: async () => null,
toggleConfigActiveTracked: async () => null,
diff --git a/packages/api/src/app/service.spec.ts b/packages/api/src/app/service.spec.ts
index e4e8bdc77c..303ffaf8c3 100644
--- a/packages/api/src/app/service.spec.ts
+++ b/packages/api/src/app/service.spec.ts
@@ -1025,6 +1025,48 @@ describe('createAppConfigService', () => {
expect(merged.endpoints).toEqual(['openAI']);
});
+ it('merges in precedence order, so cached and uncached reads agree on tied priorities', async () => {
+ const layer = (
+ principalType: string,
+ principalId: string,
+ priority: number,
+ _id: string,
+ customWelcome: string,
+ ) => ({
+ _id,
+ principalType,
+ principalId,
+ priority,
+ overrides: { interface: { customWelcome } },
+ isActive: true,
+ });
+ const layers = [
+ layer('role', '__base__', 90, '0a', 'base'),
+ layer('group', 'g1', 20, '0c', 'g1'),
+ layer('group', 'g2', 20, '0b', 'g2'),
+ layer('role', 'USER', 20, '0d', 'role'),
+ ];
+ let call = 0;
+ /** The store returns the same documents in a different order on every read. */
+ const getApplicableConfigs = jest.fn(async () => {
+ call += 1;
+ return call % 2 === 0 ? [...layers].reverse() : [...layers];
+ });
+ const deps = createDeps({ getApplicableConfigs });
+ const { getAppConfig } = createAppConfigService(deps);
+
+ const cached = await getAppConfig({ role: 'USER', userId: 'uid1' });
+ const uncached = await getAppConfig({ role: 'USER', userId: 'uid1', refresh: true });
+
+ expect(getApplicableConfigs).toHaveBeenCalledTimes(2);
+ expect(cached.interfaceConfig?.customWelcome).toBe('g1');
+ expect(uncached).toEqual(cached);
+
+ layers.push(layer('user', 'uid1', 20, '00', 'user'));
+ const userWins = await getAppConfig({ role: 'USER', userId: 'uid1', refresh: true });
+ expect(userWins.interfaceConfig?.customWelcome).toBe('user');
+ });
+
it('caches merged result with TTL', async () => {
const deps = createDeps({
getApplicableConfigs: jest
diff --git a/packages/api/src/app/service.ts b/packages/api/src/app/service.ts
index e343eae98e..7354a302d2 100644
--- a/packages/api/src/app/service.ts
+++ b/packages/api/src/app/service.ts
@@ -554,7 +554,9 @@ export function createAppConfigService(deps: AppConfigServiceDeps): {
*
* The base config (from YAML + AppService) is cached indefinitely. Per-principal merged
* configs are cached with a short TTL (`overrideCacheTtl`, default 60s). On cache miss,
- * `getApplicableConfigs` queries the DB for matching overrides and merges them by priority.
+ * `getApplicableConfigs` queries the DB for matching overrides, which merge in precedence
+ * order (`compareConfigPrecedence`): Base first, then ascending priority, then role < group <
+ * user, then document identity, the last layer winning.
*
* When `baseOnly` is true, returns the YAML-derived config without any DB queries.
* `role` and `userId` are ignored; tenantId still scopes YAML custom endpoints.
diff --git a/packages/api/src/mcp/registry/__tests__/tombstones.spec.ts b/packages/api/src/mcp/registry/__tests__/tombstones.spec.ts
index c89cfd8d0b..6d175427fe 100644
--- a/packages/api/src/mcp/registry/__tests__/tombstones.spec.ts
+++ b/packages/api/src/mcp/registry/__tests__/tombstones.spec.ts
@@ -208,7 +208,6 @@ beforeAll(async () => {
listAllConfigs: methods.listAllConfigs,
findConfigByPrincipal: methods.findConfigByPrincipal,
writeConfigDocument: methods.writeConfigDocument,
- tombstoneConfigField: methods.tombstoneConfigField,
unsetConfigField: methods.unsetConfigField,
deleteConfig: methods.deleteConfig,
toggleConfigActiveTracked: methods.toggleConfigActiveTracked,
diff --git a/packages/data-schemas/src/app/conformance.memory.spec.ts b/packages/data-schemas/src/app/conformance.memory.spec.ts
index 82c55d2f36..a5fec5f080 100644
--- a/packages/data-schemas/src/app/conformance.memory.spec.ts
+++ b/packages/data-schemas/src/app/conformance.memory.spec.ts
@@ -16,9 +16,13 @@ import { describeConfigStoreConformance } from './conformance';
* new engine implements. Each operation finishes its compare-and-swap without yielding, which
* is the atomicity a real engine gets from a conditional update.
*/
-function createMemoryConfigStore(): ConfigStore & { clear(): void } {
+function createMemoryConfigStore(): ConfigStore & {
+ clear(): void;
+ loseNextCreateAcknowledgement(): void;
+} {
const documents = new Map<string, string>();
let sequence = 0;
+ let acknowledgementLost = false;
const keyOf = ({ principalType, principalId }: ConfigPrincipal): string =>
`${principalType}\u0000${principalId}`;
@@ -32,10 +36,25 @@ function createMemoryConfigStore(): ConfigStore & { clear(): void } {
};
const all = (): ConfigRecord[] =>
[...documents.keys()].map((key) => load(key) as ConfigRecord).sort(compareConfigRecords);
+ /**
+ * A create whose acknowledgement was lost, settled by the identity it was given: still there
+ * at version 1, it committed. A real engine reaches this through its driver's error.
+ */
+ const settleCreate = (principal: ConfigPrincipal, identity: string): ConfigRecord => {
+ const stored = load(keyOf(principal));
+ if (stored?._id !== identity || stored.configVersion !== 1) {
+ throw new Error('The create was not acknowledged');
+ }
+ return stored;
+ };
return {
clear: () => documents.clear(),
+ loseNextCreateAcknowledgement: () => {
+ acknowledgementLost = true;
+ },
+
async read(principal) {
return load(keyOf(principal));
},
@@ -57,13 +76,18 @@ function createMemoryConfigStore(): ConfigStore & { clear(): void } {
throw new ConfigRevisionConflictError();
}
sequence += 1;
- return save({
+ const written = save({
...draft,
principalType: principal.principalType,
principalId: principal.principalId,
_id: current?._id ?? sequence.toString(16).padStart(24, '0'),
configVersion: (current?.configVersion ?? 0) + 1,
});
+ if (current || !acknowledgementLost) {
+ return written;
+ }
+ acknowledgementLost = false;
+ return settleCreate(principal, written._id);
},
async remove(principal, expected) {
@@ -95,6 +119,7 @@ const harness: ConfigStoreHarness = {
setup: async () => store,
teardown: async () => undefined,
reset: async () => store.clear(),
+ loseNextCreateAcknowledgement: () => store.loseNextCreateAcknowledgement(),
};
describeConfigStoreConformance(harness);
diff --git a/packages/data-schemas/src/app/conformance.mongoose.spec.ts b/packages/data-schemas/src/app/conformance.mongoose.spec.ts
index 3fd93f21f8..50e39006ac 100644
--- a/packages/data-schemas/src/app/conformance.mongoose.spec.ts
+++ b/packages/data-schemas/src/app/conformance.mongoose.spec.ts
@@ -31,6 +31,18 @@ const harness: ConfigStoreHarness = {
async reset() {
await mongoose.models.Config.deleteMany({});
},
+
+ /** The driver applies the insert, then reports the error a dropped connection gives. */
+ loseNextCreateAcknowledgement() {
+ const collection = mongoose.models.Config.collection;
+ const findOneAndUpdate = collection.findOneAndUpdate.bind(collection);
+ jest.spyOn(collection, 'findOneAndUpdate').mockImplementationOnce((async (
+ ...args: Parameters<typeof findOneAndUpdate>
+ ) => {
+ await findOneAndUpdate(...args);
+ throw new mongoose.mongo.MongoNetworkError('connection reset after the write was applied');
+ }) as unknown as typeof collection.findOneAndUpdate);
+ },
};
describeConfigStoreConformance(harness);
diff --git a/packages/data-schemas/src/app/conformance.ts b/packages/data-schemas/src/app/conformance.ts
index a191693b6c..785a58aa6f 100644
--- a/packages/data-schemas/src/app/conformance.ts
+++ b/packages/data-schemas/src/app/conformance.ts
@@ -20,14 +20,17 @@ import { PrincipalType, PrincipalModel } from 'librechat-data-provider';
import type { TCustomConfig } from 'librechat-data-provider';
import type { ConfigDraft, ConfigStore, ConfigRecord, ConfigPrincipal } from './store';
import {
+ isConfigMoveRefused,
+ getConfigRevision,
+ CONFIG_WRITE_ATTEMPTS,
ABSENT_CONFIG_REVISION,
createConfigOperations,
isConfigRevisionConflict,
- getConfigRevision,
} from './store';
import { BASE_CONFIG_PRINCIPAL_ID } from '~/admin/capabilities';
import { toConfigOverrideState } from './mutations';
import { applyConfigChanges } from './changes';
+import logger from '~/config/winston';
export interface ConfigStoreHarness {
readonly name: string;
@@ -36,6 +39,12 @@ export interface ConfigStoreHarness {
teardown(): Promise<void>;
/** Removes every document. */
reset(): Promise<void>;
+ /**
+ * Makes the engine's next create commit and then lose its acknowledgement, as a connection
+ * that drops after the database applied the write would. The engine must still return the
+ * document it created (`ConfigStore.write`).
+ */
+ loseNextCreateAcknowledgement(): void;
}
const role = (principalId: string): ConfigPrincipal => ({
@@ -48,6 +57,11 @@ const group = (principalId: string): ConfigPrincipal => ({
principalId,
});
+const user = (principalId: string): ConfigPrincipal => ({
+ principalType: PrincipalType.USER,
+ principalId,
+});
+
function draft(
overrides: Record<string, unknown> = {},
extra: Partial<ConfigDraft> = {},
@@ -117,6 +131,18 @@ export function describeConfigStoreConformance(harness: ConfigStoreHarness): voi
throw new Error('expected a revision conflict');
};
+ const ids = (records: ConfigRecord[]): string[] =>
+ records.map((record) => `${record.principalType}:${record.principalId}`);
+
+ /** The store with `hook` run before every removal, to land a concurrent write in between. */
+ const withRemoveHook = (hook: (principal: ConfigPrincipal) => Promise<void>): ConfigStore => ({
+ ...store,
+ remove: async (principal, expected) => {
+ await hook(principal);
+ return store.remove(principal, expected);
+ },
+ });
+
describe('documents', () => {
it('reads nothing for a principal without a document', async () => {
expect(await store.read(role('nobody'))).toBeNull();
@@ -320,6 +346,23 @@ export function describeConfigStoreConformance(harness: ConfigStoreHarness): voi
expect((await store.list()).length).toBe(1);
});
+ it('returns the document a create made even when its acknowledgement is lost', async () => {
+ harness.loseNextCreateAcknowledgement();
+
+ const created = await store.write(
+ role('unacknowledged'),
+ draft({ 'a.b': 1 }),
+ ABSENT_CONFIG_REVISION,
+ );
+
+ expect(created).toMatchObject({
+ principalId: 'unacknowledged',
+ configVersion: 1,
+ overrides: { 'a.b': 1 },
+ });
+ expect(await store.read(role('unacknowledged'))).toEqual(created);
+ });
+
it('rejects a malformed revision as a conflict without writing', async () => {
await store.write(role('odd'), draft({ a: 1 }), ABSENT_CONFIG_REVISION);
@@ -392,9 +435,6 @@ export function describeConfigStoreConformance(harness: ConfigStoreHarness): voi
return records;
}
- const ids = (records: ConfigRecord[]): string[] =>
- records.map((record) => `${record.principalType}:${record.principalId}`);
-
it('orders by priority, then identity, the same way every time', async () => {
const records = await seed();
const tied = records
@@ -572,6 +612,393 @@ export function describeConfigStoreConformance(harness: ConfigStoreHarness): voi
expect((await store.read(role('stale-op')))?.overrides).toEqual({ a: { b: 2 } });
});
+ it('lists and resolves documents in merge precedence order', async () => {
+ const operations = createConfigOperations(store);
+ for (const [principal, priority] of [
+ [user('u1'), 20],
+ [group('g2'), 20],
+ [role('editor'), 20],
+ [role(BASE_CONFIG_PRINCIPAL_ID), 50],
+ [group('g1'), 20],
+ [role('viewer'), 5],
+ ] as Array<[ConfigPrincipal, number]>) {
+ await store.write(principal, draft({}, { priority }), ABSENT_CONFIG_REVISION);
+ }
+ const tiedGroups = (await store.list())
+ .filter((record) => record.principalType === PrincipalType.GROUP)
+ .map((record) => `group:${record.principalId}`);
+
+ const expected = [
+ `role:${BASE_CONFIG_PRINCIPAL_ID}`,
+ 'role:viewer',
+ 'role:editor',
+ ...tiedGroups,
+ 'user:u1',
+ ];
+ expect(ids(await operations.listConfigs())).toEqual(expected);
+ expect(
+ ids(
+ await operations.getApplicableConfigs([
+ user('u1'),
+ group('g1'),
+ group('g2'),
+ role('editor'),
+ role('viewer'),
+ ]),
+ ),
+ ).toEqual(expected);
+ });
+
+ it('gives a document a write creates its principal type default priority', async () => {
+ const operations = createConfigOperations(store);
+ const fields = { 'interface.customWelcome': 'hi' };
+
+ const created = await Promise.all([
+ operations.setFields(role('defaults'), PrincipalModel.ROLE, fields),
+ operations.setFields(group('defaults'), PrincipalModel.GROUP, fields),
+ operations.setFields(user('defaults'), PrincipalModel.USER, fields),
+ operations.setFields(role(BASE_CONFIG_PRINCIPAL_ID), PrincipalModel.ROLE, fields),
+ ]);
+
+ expect(created.map((record) => record.priority)).toEqual([10, 20, 100, 0]);
+ });
+
+ it('keeps the stored priority when a replace or patch does not name one', async () => {
+ const operations = createConfigOperations(store);
+ await operations.setFields(group('kept'), PrincipalModel.GROUP, { a: 1 }, 35);
+
+ const replaced = await operations.replaceOverrides(group('kept'), PrincipalModel.GROUP, {
+ interface: { customWelcome: 'x' },
+ } as Partial<TCustomConfig>);
+ const patched = await operations.setFields(group('kept'), PrincipalModel.GROUP, { b: 2 });
+
+ expect(replaced?.priority).toBe(35);
+ expect(patched.priority).toBe(35);
+ });
+
+ it('changes only the priority, and writes nothing when it is unchanged', async () => {
+ const operations = createConfigOperations(store);
+ await operations.setFields(role('prio'), PrincipalModel.ROLE, { 'a.b': 1 });
+ await operations.tombstoneFields(role('prio'), PrincipalModel.ROLE, 'memory.agent');
+ const before = await operations.setActive(role('prio'), false);
+
+ const changed = await operations.setPriority(role('prio'), 42);
+ expect(changed?.changed).toBe(true);
+ expect(changed?.config).toMatchObject({
+ priority: 42,
+ overrides: { a: { b: 1 } },
+ tombstones: ['memory.agent'],
+ isActive: false,
+ configVersion: (before?.config.configVersion ?? 0) + 1,
+ });
+
+ const unchanged = await operations.setPriority(role('prio'), 42);
+ expect(unchanged).toEqual({ config: changed?.config, changed: false });
+ expect(await operations.setPriority(role('nobody'), 1)).toBeNull();
+ });
+
+ it('refuses a priority change at a stale revision', async () => {
+ const operations = createConfigOperations(store);
+ const first = await operations.setFields(role('prio-stale'), PrincipalModel.ROLE, { a: 1 });
+ await operations.setFields(role('prio-stale'), PrincipalModel.ROLE, { a: 2 });
+
+ const error = await conflictOf(
+ operations.setPriority(role('prio-stale'), 7, {
+ expectedRevision: getConfigRevision(first),
+ }),
+ );
+
+ expect(isConfigRevisionConflict(error)).toBe(true);
+ expect((await store.read(role('prio-stale')))?.priority).toBe(10);
+ });
+
+ it('moves a document to another principal, and never over an existing one', async () => {
+ const operations = createConfigOperations(store);
+ await operations.setFields(role('old'), PrincipalModel.ROLE, { 'a.b': 1 }, 15);
+ await operations.tombstoneFields(role('old'), PrincipalModel.ROLE, 'memory.agent');
+ await operations.setActive(role('old'), false);
+
+ const moved = await operations.movePrincipal(role('old'), role('new'));
+
+ expect(await store.read(role('old'))).toBeNull();
+ expect(moved).toMatchObject({
+ principalType: PrincipalType.ROLE,
+ principalId: 'new',
+ priority: 15,
+ overrides: { a: { b: 1 } },
+ tombstones: ['memory.agent'],
+ isActive: false,
+ });
+ expect(await store.read(role('new'))).toEqual(moved);
+ expect(await operations.movePrincipal(role('missing'), role('new'))).toBeNull();
+
+ await operations.setFields(role('other'), PrincipalModel.ROLE, { c: 1 });
+ const error = await conflictOf(operations.movePrincipal(role('other'), role('new')));
+ expect(isConfigMoveRefused(error, 'CONFIG_PRINCIPAL_EXISTS')).toBe(true);
+ expect(isConfigRevisionConflict(error)).toBe(false);
+ expect((await store.read(role('other')))?.overrides).toEqual({ c: 1 });
+ expect(await store.read(role('new'))).toEqual(moved);
+ });
+
+ it('never moves Base, nor moves a document onto it', async () => {
+ const operations = createConfigOperations(store);
+ const base = await operations.setFields(
+ role(BASE_CONFIG_PRINCIPAL_ID),
+ PrincipalModel.ROLE,
+ {
+ 'interface.customWelcome': 'everyone',
+ },
+ );
+
+ const demote = await conflictOf(
+ operations.movePrincipal(role(BASE_CONFIG_PRINCIPAL_ID), role('demoted')),
+ );
+
+ expect(isConfigMoveRefused(demote, 'CONFIG_PRINCIPAL_RESERVED')).toBe(true);
+ expect(await store.read(role(BASE_CONFIG_PRINCIPAL_ID))).toEqual(base);
+ expect(await store.read(role('demoted'))).toBeNull();
+
+ await operations.deleteConfig(role(BASE_CONFIG_PRINCIPAL_ID));
+ const profile = await operations.setFields(role('promoted'), PrincipalModel.ROLE, {
+ 'interface.customWelcome': 'one role',
+ });
+
+ const promote = await conflictOf(
+ operations.movePrincipal(role('promoted'), role(BASE_CONFIG_PRINCIPAL_ID)),
+ );
+
+ expect(isConfigMoveRefused(promote, 'CONFIG_PRINCIPAL_RESERVED')).toBe(true);
+ expect(await store.read(role(BASE_CONFIG_PRINCIPAL_ID))).toBeNull();
+ expect(await store.read(role('promoted'))).toEqual(profile);
+ });
+
+ it('withdraws the copy and moves again when the source changes before its removal', async () => {
+ let edits = 0;
+ const racing = withRemoveHook(async (principal) => {
+ if (principal.principalId === 'racing' && edits++ === 0) {
+ await createConfigOperations(store).setFields(role('racing'), PrincipalModel.ROLE, {
+ late: true,
+ });
+ }
+ });
+ const operations = createConfigOperations(racing);
+ await operations.setFields(role('racing'), PrincipalModel.ROLE, { early: true });
+
+ const moved = await operations.movePrincipal(role('racing'), role('settled'));
+
+ expect(edits).toBe(2);
+ expect(moved?.overrides).toEqual({ early: true, late: true });
+ expect(await store.read(role('settled'))).toEqual(moved);
+ expect(await store.read(role('racing'))).toBeNull();
+ });
+
+ it('keeps the copy when the removal committed before it failed', async () => {
+ let failed = false;
+ const flaky: ConfigStore = {
+ ...store,
+ remove: async (principal, expected) => {
+ const removed = await store.remove(principal, expected);
+ if (!failed && principal.principalId === 'flaky') {
+ failed = true;
+ throw new Error('connection reset after the delete');
+ }
+ return removed;
+ },
+ };
+ const operations = createConfigOperations(flaky);
+ await operations.setFields(role('flaky'), PrincipalModel.ROLE, { kept: true });
+
+ const moved = await operations.movePrincipal(role('flaky'), role('landed'));
+
+ expect(failed).toBe(true);
+ expect(moved?.overrides).toEqual({ kept: true });
+ expect(await store.read(role('landed'))).toEqual(moved);
+ expect(await store.read(role('flaky'))).toBeNull();
+ });
+
+ it('keeps the copy and reports the failure when a failed removal cannot be read back', async () => {
+ const removalFailure = new Error('connection reset after the delete');
+ let disconnected = false;
+ const blind: ConfigStore = {
+ ...store,
+ read: async (principal) => {
+ if (disconnected && principal.principalId === 'blind') {
+ throw new Error('connection still down');
+ }
+ return store.read(principal);
+ },
+ remove: async (principal, expected) => {
+ const removed = await store.remove(principal, expected);
+ if (!disconnected && principal.principalId === 'blind') {
+ disconnected = true;
+ throw removalFailure;
+ }
+ return removed;
+ },
+ };
+ const operations = createConfigOperations(blind);
+ await operations.setFields(role('blind'), PrincipalModel.ROLE, { kept: true });
+
+ const error = await conflictOf(operations.movePrincipal(role('blind'), role('shelter')));
+
+ expect(disconnected).toBe(true);
+ expect(error).toBe(removalFailure);
+ expect(await store.read(role('blind'))).toBeNull();
+ expect((await store.read(role('shelter')))?.overrides).toEqual({ kept: true });
+ });
+
+ it('finishes a move whose copy committed though its acknowledgement was lost', async () => {
+ const operations = createConfigOperations(store);
+ await operations.setFields(role('sender'), PrincipalModel.ROLE, { kept: true }, 12);
+ harness.loseNextCreateAcknowledgement();
+
+ const moved = await operations.movePrincipal(role('sender'), role('receiver'));
+
+ expect(moved).toMatchObject({ overrides: { kept: true }, priority: 12 });
+ expect(await store.read(role('receiver'))).toEqual(moved);
+ expect(await store.read(role('sender'))).toBeNull();
+ });
+
+ it('never removes a copy it cannot confirm it created, and reports the failure', async () => {
+ const unconfirmed = new Error('connection reset; the create could not be confirmed');
+ const unsure: ConfigStore = {
+ ...store,
+ write: async (principal, next, expected) => {
+ const written = await store.write(principal, next, expected);
+ if (principal.principalId === 'unsure-copy') {
+ throw unconfirmed;
+ }
+ return written;
+ },
+ };
+ const operations = createConfigOperations(unsure);
+ await operations.setFields(role('unsure'), PrincipalModel.ROLE, { kept: true });
+
+ const error = await conflictOf(
+ operations.movePrincipal(role('unsure'), role('unsure-copy')),
+ );
+
+ expect(error).toBe(unconfirmed);
+ expect((await store.read(role('unsure')))?.overrides).toEqual({ kept: true });
+ expect((await store.read(role('unsure-copy')))?.overrides).toEqual({ kept: true });
+ });
+
+ it('moves back only the document it moved, edits included, never one put there since', async () => {
+ const operations = createConfigOperations(store);
+ await operations.setFields(role('home'), PrincipalModel.ROLE, { mine: true });
+ const moved = await operations.movePrincipal(role('home'), role('away'));
+ await operations.setFields(role('away'), PrincipalModel.ROLE, { edited: true });
+
+ const back = await operations.movePrincipal(role('away'), role('home'), {
+ identity: moved?._id,
+ });
+
+ expect(back?.overrides).toEqual({ mine: true, edited: true });
+ expect(await store.read(role('away'))).toBeNull();
+
+ const again = await operations.movePrincipal(role('home'), role('away'));
+ await operations.deleteConfig(role('away'));
+ const replacement = await operations.setFields(role('away'), PrincipalModel.ROLE, {
+ theirs: true,
+ });
+
+ expect(
+ await operations.movePrincipal(role('away'), role('home'), { identity: again?._id }),
+ ).toBeNull();
+ expect(await store.read(role('away'))).toEqual(replacement);
+ expect(await store.read(role('home'))).toBeNull();
+ });
+
+ it('gives up with a revision conflict, leaving the source in place, when it keeps changing', async () => {
+ let edits = 0;
+ const busy = withRemoveHook(async (principal) => {
+ if (principal.principalId === 'busy') {
+ edits++;
+ await createConfigOperations(store).setFields(role('busy'), PrincipalModel.ROLE, {
+ edits,
+ });
+ }
+ });
+
+ await createConfigOperations(store).setFields(role('busy'), PrincipalModel.ROLE, {
+ seeded: true,
+ });
+
+ const exhausted = await conflictOf(
+ createConfigOperations(busy).movePrincipal(role('busy'), role('never')),
+ );
+
+ expect(edits).toBe(CONFIG_WRITE_ATTEMPTS);
+ expect(isConfigRevisionConflict(exhausted)).toBe(true);
+ expect(isConfigMoveRefused(exhausted)).toBe(false);
+ expect(await store.read(role('never'))).toBeNull();
+ expect((await store.read(role('busy')))?.overrides).toEqual({
+ seeded: true,
+ edits: CONFIG_WRITE_ATTEMPTS,
+ });
+ });
+
+ it('keeps a copy that was edited before it could be withdrawn, and reports the conflict', async () => {
+ const editBoth = withRemoveHook(async (principal) => {
+ if (principal.principalId !== 'source') {
+ return;
+ }
+ const operations = createConfigOperations(store);
+ await operations.setFields(role('source'), PrincipalModel.ROLE, { source: 2 });
+ await operations.setFields(role('copy'), PrincipalModel.ROLE, { copy: 'edited' });
+ });
+ const operations = createConfigOperations(editBoth);
+ await operations.setFields(role('source'), PrincipalModel.ROLE, { source: 1 });
+
+ const error = await conflictOf(operations.movePrincipal(role('source'), role('copy')));
+
+ expect(isConfigRevisionConflict(error)).toBe(true);
+ expect(isConfigMoveRefused(error)).toBe(false);
+ expect((await store.read(role('source')))?.overrides).toEqual({ source: 2 });
+ expect((await store.read(role('copy')))?.overrides).toEqual({
+ source: 1,
+ copy: 'edited',
+ });
+ });
+
+ it('names a copy it could not withdraw in the log, so it can be removed', async () => {
+ const unreachable = new Error('connection refused');
+ let down = false;
+ const failing: ConfigStore = {
+ ...store,
+ remove: async (principal, expected) => {
+ if (down) {
+ throw unreachable;
+ }
+ if (principal.principalId === 'cut') {
+ down = true;
+ throw unreachable;
+ }
+ return store.remove(principal, expected);
+ },
+ };
+ const operations = createConfigOperations(failing);
+ await operations.setFields(role('cut'), PrincipalModel.ROLE, { kept: true });
+ const errorLog = jest.spyOn(logger, 'error');
+
+ const error = await conflictOf(operations.movePrincipal(role('cut'), role('stranded')));
+
+ const copy = await store.read(role('stranded'));
+ expect(error).toBe(unreachable);
+ expect((await store.read(role('cut')))?.overrides).toEqual({ kept: true });
+ expect(copy?.overrides).toEqual({ kept: true });
+ expect(errorLog).toHaveBeenCalledWith(
+ '[configStore] A moved config document could not be withdrawn from its copy',
+ {
+ principalType: PrincipalType.ROLE,
+ principalId: 'stranded',
+ revision: copy && getConfigRevision(copy),
+ errName: 'Error',
+ errCode: null,
+ },
+ );
+ });
+
it('absorbs concurrent writes without a revision so none is lost', async () => {
const operations = createConfigOperations(store);
await operations.setFields(role('merge'), PrincipalModel.ROLE, { seed: true });
diff --git a/packages/data-schemas/src/app/index.ts b/packages/data-schemas/src/app/index.ts
index 0bc80cd458..6306eb188b 100644
--- a/packages/data-schemas/src/app/index.ts
+++ b/packages/data-schemas/src/app/index.ts
@@ -7,6 +7,7 @@ export * from './turnstile';
export * from './vertex';
export * from './web';
export * from './resolution';
+export * from './precedence';
export * from './paths';
export * from './mutations';
export * from './store';
diff --git a/packages/data-schemas/src/app/precedence.spec.ts b/packages/data-schemas/src/app/precedence.spec.ts
new file mode 100644
index 0000000000..a9968e483f
--- /dev/null
+++ b/packages/data-schemas/src/app/precedence.spec.ts
@@ -0,0 +1,126 @@
+import { PrincipalType } from 'librechat-data-provider';
+import type { ConfigPrecedenceKey } from './precedence';
+import {
+ BASE_CONFIG_PRIORITY,
+ isBaseConfigPrincipal,
+ sortByConfigPrecedence,
+ compareConfigPrecedence,
+ getDefaultConfigPriority,
+} from './precedence';
+import { BASE_CONFIG_PRINCIPAL_ID } from '~/admin/capabilities';
+
+function layer(
+ principalType: PrincipalType,
+ principalId: string,
+ priority: number,
+ _id?: string,
+): ConfigPrecedenceKey {
+ return { principalType, principalId, priority, _id };
+}
+
+const ids = (layers: ConfigPrecedenceKey[]): string[] =>
+ layers.map(({ principalType, principalId }) => `${principalType}:${principalId}`);
+
+/** Deterministic Fisher-Yates shuffle, so a failure reproduces. */
+function shuffled<T>(items: readonly T[], seed: number): T[] {
+ const result = [...items];
+ let state = seed;
+ for (let index = result.length - 1; index > 0; index--) {
+ state = (state * 1103515245 + 12345) % 2147483648;
+ const swap = state % (index + 1);
+ [result[index], result[swap]] = [result[swap], result[index]];
+ }
+ return result;
+}
+
+describe('compareConfigPrecedence', () => {
+ it('merges Base first whatever its priority', () => {
+ const base = layer(PrincipalType.ROLE, BASE_CONFIG_PRINCIPAL_ID, 50, 'a');
+ const role = layer(PrincipalType.ROLE, 'editor', 5, 'b');
+
+ expect(ids(sortByConfigPrecedence([role, base]))).toEqual([
+ `role:${BASE_CONFIG_PRINCIPAL_ID}`,
+ 'role:editor',
+ ]);
+ });
+
+ it('orders by priority, then role < group < user, then identity', () => {
+ const layers = [
+ layer(PrincipalType.USER, 'u1', 10, 'c'),
+ layer(PrincipalType.GROUP, 'g2', 10, 'b'),
+ layer(PrincipalType.GROUP, 'g1', 10, 'f'),
+ layer(PrincipalType.ROLE, 'editor', 10, 'e'),
+ layer(PrincipalType.ROLE, 'viewer', 5, 'z'),
+ layer(PrincipalType.USER, 'u2', 1, 'a'),
+ ];
+
+ expect(ids(sortByConfigPrecedence(layers))).toEqual([
+ 'user:u2',
+ 'role:viewer',
+ 'role:editor',
+ 'group:g2',
+ 'group:g1',
+ 'user:u1',
+ ]);
+ });
+
+ it('gives the same order for every input order', () => {
+ const layers = [
+ layer(PrincipalType.ROLE, BASE_CONFIG_PRINCIPAL_ID, 30, '07'),
+ layer(PrincipalType.GROUP, 'g1', 20, '03'),
+ layer(PrincipalType.GROUP, 'g2', 20, '01'),
+ layer(PrincipalType.GROUP, 'g3', 20, '05'),
+ layer(PrincipalType.ROLE, 'editor', 20, '09'),
+ layer(PrincipalType.USER, 'u1', 20, '02'),
+ ];
+ const expected = ids(sortByConfigPrecedence(layers));
+
+ for (let seed = 1; seed <= 20; seed++) {
+ expect(ids(sortByConfigPrecedence(shuffled(layers, seed)))).toEqual(expected);
+ }
+ expect(expected).toEqual([
+ `role:${BASE_CONFIG_PRINCIPAL_ID}`,
+ 'role:editor',
+ 'group:g2',
+ 'group:g1',
+ 'group:g3',
+ 'user:u1',
+ ]);
+ });
+
+ it('treats only the role principal named __base__ as Base', () => {
+ const group = layer(PrincipalType.GROUP, BASE_CONFIG_PRINCIPAL_ID, 50);
+ const role = layer(PrincipalType.ROLE, 'editor', 5);
+
+ expect(isBaseConfigPrincipal(group)).toBe(false);
+ expect(compareConfigPrecedence(group, role)).toBeGreaterThan(0);
+ });
+
+ it('keeps documents without an identity in their input order on a full tie', () => {
+ const first = layer(PrincipalType.ROLE, 'a', 10);
+ const second = layer(PrincipalType.ROLE, 'b', 10);
+
+ expect(compareConfigPrecedence(first, second)).toBe(0);
+ expect(ids(sortByConfigPrecedence([second, first]))).toEqual(['role:b', 'role:a']);
+ });
+});
+
+describe('getDefaultConfigPriority', () => {
+ it('ranks a narrower principal higher, and sits Base at the bottom', () => {
+ expect(getDefaultConfigPriority({ principalType: PrincipalType.ROLE, principalId: 'x' })).toBe(
+ 10,
+ );
+ expect(getDefaultConfigPriority({ principalType: PrincipalType.GROUP, principalId: 'x' })).toBe(
+ 20,
+ );
+ expect(getDefaultConfigPriority({ principalType: PrincipalType.USER, principalId: 'x' })).toBe(
+ 100,
+ );
+ expect(
+ getDefaultConfigPriority({
+ principalType: PrincipalType.ROLE,
+ principalId: BASE_CONFIG_PRINCIPAL_ID,
+ }),
+ ).toBe(BASE_CONFIG_PRIORITY);
+ });
+});
diff --git a/packages/data-schemas/src/app/precedence.ts b/packages/data-schemas/src/app/precedence.ts
new file mode 100644
index 0000000000..2bfae0c32a
--- /dev/null
+++ b/packages/data-schemas/src/app/precedence.ts
@@ -0,0 +1,101 @@
+import { PrincipalType } from 'librechat-data-provider';
+import { BASE_CONFIG_PRINCIPAL_ID } from '~/admin/capabilities';
+
+/**
+ * The order config overrides merge in, lowest precedence first, so the last layer wins:
+ *
+ * 1. Base (`role` / `__base__`) always merges first, whatever its stored priority.
+ * 2. Then ascending `priority`.
+ * 3. On equal priority, by principal type: role, then group, then user.
+ * 4. Then by document identity (`_id`), ascending.
+ *
+ * Every step is total, so a set of documents merges the same way however the store returned
+ * them. Identity order roughly follows creation order but is only promised to be stable.
+ */
+
+/** The fields of a config document that decide where it merges. */
+export interface ConfigPrecedenceKey {
+ principalType: string;
+ principalId: { toString(): string };
+ priority: number;
+ _id?: { toString(): string } | null;
+}
+
+/** Tie-break rank on equal priority: a narrower principal merges later and wins. */
+const PRINCIPAL_TYPE_RANK: Readonly<Record<string, number>> = {
+ [PrincipalType.ROLE]: 0,
+ [PrincipalType.GROUP]: 1,
+ [PrincipalType.USER]: 2,
+};
+
+const UNRANKED_PRINCIPAL_TYPE = 3;
+
+/** Priority a role's document gets when a write creates it without one. */
+export const DEFAULT_CONFIG_PRIORITY = 10;
+
+/**
+ * Priority a principal's document gets when a write creates it without one. A narrower
+ * principal defaults higher, so a group profile outranks a role profile and a user profile
+ * outranks both unless an admin says otherwise. Base sits at 0; it merges first regardless.
+ */
+export const DEFAULT_CONFIG_PRIORITIES: Readonly<Record<string, number>> = {
+ [PrincipalType.ROLE]: DEFAULT_CONFIG_PRIORITY,
+ [PrincipalType.GROUP]: 20,
+ [PrincipalType.USER]: 100,
+};
+
+export const BASE_CONFIG_PRIORITY = 0;
+
+/** Whether a document belongs to the tenant-wide Base principal (`role` / `__base__`). */
+export function isBaseConfigPrincipal(principal: {
+ principalType: string;
+ principalId?: { toString(): string } | null;
+}): boolean {
+ return (
+ principal.principalType === PrincipalType.ROLE &&
+ principal.principalId?.toString() === BASE_CONFIG_PRINCIPAL_ID
+ );
+}
+
+export function getDefaultConfigPriority(principal: {
+ principalType: string;
+ principalId?: { toString(): string } | null;
+}): number {
+ if (isBaseConfigPrincipal(principal)) {
+ return BASE_CONFIG_PRIORITY;
+ }
+ return DEFAULT_CONFIG_PRIORITIES[principal.principalType] ?? DEFAULT_CONFIG_PRIORITY;
+}
+
+function rankOf(principalType: string): number {
+ return PRINCIPAL_TYPE_RANK[principalType] ?? UNRANKED_PRINCIPAL_TYPE;
+}
+
+/** Orders documents by merge precedence (see the module comment); sort with it ascending. */
+export function compareConfigPrecedence(
+ left: ConfigPrecedenceKey,
+ right: ConfigPrecedenceKey,
+): number {
+ const leftBase = isBaseConfigPrincipal(left);
+ if (leftBase !== isBaseConfigPrincipal(right)) {
+ return leftBase ? -1 : 1;
+ }
+ if (left.priority !== right.priority) {
+ return left.priority - right.priority;
+ }
+ const rank = rankOf(left.principalType) - rankOf(right.principalType);
+ if (rank !== 0) {
+ return rank;
+ }
+ const leftId = left._id?.toString() ?? '';
+ const rightId = right._id?.toString() ?? '';
+ if (leftId === rightId) {
+ return 0;
+ }
+ return leftId < rightId ? -1 : 1;
+}
+
+/** A copy of `configs` in merge order. */
+export function sortByConfigPrecedence<T extends ConfigPrecedenceKey>(configs: readonly T[]): T[] {
+ return [...configs].sort(compareConfigPrecedence);
+}
diff --git a/packages/data-schemas/src/app/resolution.spec.ts b/packages/data-schemas/src/app/resolution.spec.ts
index f2dc5df306..5a8e991283 100644
--- a/packages/data-schemas/src/app/resolution.spec.ts
+++ b/packages/data-schemas/src/app/resolution.spec.ts
@@ -6,6 +6,7 @@ import {
import type { TCustomConfig, TWebSearchConfigInput } from 'librechat-data-provider';
import type { AppConfig, IConfig } from '~/types';
import {
+ resolveRawConfig,
foldConfigMergeKey,
isConfigRecordPath,
getConfigMergeRules,
@@ -2446,6 +2447,211 @@ describe('getConfigFieldIssues', () => {
});
});
+describe('merge precedence', () => {
+ function layer(
+ principalType: 'role' | 'group' | 'user',
+ principalId: string,
+ priority: number,
+ overrides: Record<string, unknown>,
+ _id: string,
+ tombstones?: string[],
+ ): IConfig {
+ return {
+ ...fakeConfig(overrides, priority, tombstones, principalId),
+ principalType,
+ _id,
+ } as unknown as IConfig;
+ }
+
+ const welcome = (configs: IConfig[]): unknown =>
+ (mergeConfigOverrides(baseConfig, configs).interfaceConfig as { customWelcome?: unknown })
+ ?.customWelcome;
+
+ it('lets a profile outrank Base even when Base has the higher priority', () => {
+ const base = layer(
+ 'role',
+ BASE_CONFIG_PRINCIPAL_ID,
+ 50,
+ { interface: { customWelcome: 'base' } },
+ '0a',
+ );
+ const role = layer('role', 'editor', 5, { interface: { customWelcome: 'role' } }, '0b');
+
+ expect(welcome([base, role])).toBe('role');
+ expect(welcome([role, base])).toBe('role');
+ });
+
+ it('merges tied group profiles the same way whatever order the store returned them in', () => {
+ const groups = ['0c', '0a', '0e', '0b', '0d'].map((id) =>
+ layer('group', `g-${id}`, 20, { interface: { customWelcome: id } }, id),
+ );
+ const results = new Set<unknown>();
+ for (let round = 0; round < 20; round++) {
+ const order = [...groups].sort(() => Math.random() - 0.5);
+ results.add(welcome(order));
+ }
+
+ expect([...results]).toEqual(['0e']);
+ });
+
+ it('lets a user profile beat a group profile, and a group beat a role, at equal priority', () => {
+ const role = layer('role', 'editor', 20, { interface: { customWelcome: 'role' } }, '0c');
+ const group = layer('group', 'g1', 20, { interface: { customWelcome: 'group' } }, '0b');
+ const user = layer('user', 'u1', 20, { interface: { customWelcome: 'user' } }, '0a');
+
+ expect(welcome([user, group, role])).toBe('user');
+ expect(welcome([group, role])).toBe('group');
+ });
+
+ it('lets a profile that writes fields of a librechat.yaml MCP server undo a Base hide of it, whatever Base priority', () => {
+ const github = { type: 'streamable-http', url: 'https://github.example.com/mcp' };
+ const appConfig = {
+ ...baseConfig,
+ mcpConfig: { github },
+ config: { mcpServers: { github } },
+ } as unknown as AppConfig;
+ const base = layer('role', BASE_CONFIG_PRINCIPAL_ID, 50, {}, '0a', ['mcpServers.github']);
+ const role = layer('role', 'editor', 5, { mcpServers: { github: { title: 'GitHub' } } }, '0b');
+
+ expect(mergeConfigOverrides(appConfig, [base]).mcpConfig).toEqual({});
+ expect(mergeConfigOverrides(appConfig, [base, role]).mcpConfig).toEqual({
+ github: { title: 'GitHub' },
+ });
+ });
+});
+
+describe('resolveRawConfig', () => {
+ const yaml = {
+ memory: { agent: { id: 'agent_1' } },
+ mcpServers: {
+ operator: { type: 'stdio', command: 'node', args: ['trusted-server.js'] },
+ },
+ } as unknown as Partial<TCustomConfig>;
+
+ /** Base's half of the memory switch: drop the YAML agent id, pick a provider and model. */
+ const memorySwitch = fakeConfig(
+ { memory: { agent: { provider: 'openAI', model: 'gpt-4o' } } },
+ 0,
+ ['memory.agent.id'],
+ BASE_CONFIG_PRINCIPAL_ID,
+ );
+
+ it('returns the YAML config untouched when there are no layers', () => {
+ expect(resolveRawConfig(yaml, [])).toBe(yaml);
+ });
+
+ it('resolves Base tombstones and overrides over the YAML config', () => {
+ expect(resolveRawConfig(yaml, [memorySwitch]).memory).toEqual({
+ agent: { provider: 'openAI', model: 'gpt-4o' },
+ });
+ });
+
+ it('is the floor a profile write validates on: valid there, invalid on the YAML alone', () => {
+ const write = { 'memory.agent.model': 'gpt-4.1' };
+
+ expect(getConfigFieldIssues(write, yaml).map((issue) => issue.code)).toContain(
+ 'union_dropped_key',
+ );
+ expect(getConfigFieldIssues(write, resolveRawConfig(yaml, [memorySwitch]))).toEqual([]);
+ });
+
+ it('agrees with the merge: what validates on the floor is kept, what fails there is dropped', () => {
+ const appConfig = {
+ ...baseConfig,
+ memory: yaml.memory,
+ config: yaml,
+ } as unknown as AppConfig;
+ const valid = fakeConfig({ memory: { agent: { model: 'gpt-4.1' } } }, 10, undefined, 'editor');
+ const floor = resolveRawConfig(yaml, [memorySwitch]);
+
+ expect(getConfigOverrideIssues(valid.overrides, floor)).toEqual([]);
+ expect(
+ (mergeConfigOverrides(appConfig, [memorySwitch, valid]) as unknown as { memory: unknown })
+ .memory,
+ ).toEqual({ agent: { provider: 'openAI', model: 'gpt-4.1' } });
+ });
+
+ it('reports a write that only fails on top of Base, which the merge would drop', () => {
+ /** The reverse switch: YAML picks a provider and model, Base switches to an agent id. */
+ const providerYaml = {
+ memory: { agent: { provider: 'openAI', model: 'gpt-4o' } },
+ } as unknown as Partial<TCustomConfig>;
+ const agentIdSwitch = fakeConfig(
+ { memory: { agent: { id: 'agent_9' } } },
+ 0,
+ ['memory.agent.provider', 'memory.agent.model'],
+ BASE_CONFIG_PRINCIPAL_ID,
+ );
+ const appConfig = {
+ ...baseConfig,
+ memory: providerYaml.memory,
+ config: providerYaml,
+ } as unknown as AppConfig;
+ const write = { 'memory.agent.model': 'gpt-4.1' };
+ const floor = resolveRawConfig(providerYaml, [agentIdSwitch]);
+
+ expect(getConfigFieldIssues(write, providerYaml)).toEqual([]);
+ expect(getConfigFieldIssues(write, floor)).toEqual([
+ {
+ path: 'memory.agent.model',
+ segments: ['memory', 'agent', 'model'],
+ code: 'union_dropped_key',
+ },
+ ]);
+ const profile = fakeConfig({ memory: { agent: { model: 'gpt-4.1' } } }, 10, undefined, 'x');
+ expect(
+ (mergeConfigOverrides(appConfig, [agentIdSwitch, profile]) as unknown as { memory: unknown })
+ .memory,
+ ).toEqual({ agent: { id: 'agent_9' } });
+ expect(resolveRawConfig(providerYaml, [agentIdSwitch, profile]).memory).toEqual(floor.memory);
+ });
+
+ it('strips a Base override that is invalid on the YAML config, as the merge does', () => {
+ const invalidBase = fakeConfig(
+ { memory: { agent: { id: 5 } }, interface: { customWelcome: 'hi' } },
+ 0,
+ undefined,
+ BASE_CONFIG_PRINCIPAL_ID,
+ );
+
+ const raw = resolveRawConfig(yaml, [invalidBase]);
+ expect(raw.memory).toEqual(yaml.memory);
+ expect(raw.interface).toEqual({ customWelcome: 'hi' });
+ });
+
+ it('never lets an override reach a process-backed MCP server', () => {
+ const base = fakeConfig(
+ {
+ mcpServers: {
+ operator: { command: '/bin/sh' },
+ remote: { type: 'streamable-http', url: 'https://mcp.example.com' },
+ },
+ },
+ 0,
+ undefined,
+ BASE_CONFIG_PRINCIPAL_ID,
+ );
+
+ const raw = resolveRawConfig(yaml, [base]);
+ expect(raw.mcpServers).toEqual({
+ operator: { type: 'stdio', command: 'node', args: ['trusted-server.js'] },
+ remote: { type: 'streamable-http', url: 'https://mcp.example.com' },
+ });
+ });
+
+ it('orders layers by merge precedence, so Base lands first', () => {
+ const role = fakeConfig({ interface: { customWelcome: 'role' } }, 1, undefined, 'editor');
+ const base = fakeConfig(
+ { interface: { customWelcome: 'base' } },
+ 99,
+ undefined,
+ BASE_CONFIG_PRINCIPAL_ID,
+ );
+
+ expect(resolveRawConfig({}, [role, base]).interface).toEqual({ customWelcome: 'role' });
+ });
+});
+
describe('top-level sections an override may hold', () => {
/** Runtime state AppService builds that `configSchema` does not define, so no override may set it. */
const RUNTIME_KEYS = [
diff --git a/packages/data-schemas/src/app/resolution.ts b/packages/data-schemas/src/app/resolution.ts
index 39d98b3907..4177543f04 100644
--- a/packages/data-schemas/src/app/resolution.ts
+++ b/packages/data-schemas/src/app/resolution.ts
@@ -12,9 +12,9 @@ import {
import type { TCustomConfig } from 'librechat-data-provider';
import type { AdminConfigMergeRules, AppConfig, Config, TWebSearchKeys } from '~/types';
import type { ConfigFieldWrite } from './mutations';
+import { isBaseConfigPrincipal, sortByConfigPrecedence } from './precedence';
import { setConfigFields, toConfigOverrideState } from './mutations';
import { webSearchPairedFields, unbindWebSearchKeys } from './web';
-import { BASE_CONFIG_PRINCIPAL_ID } from '~/admin/capabilities';
import { parseFieldPath, isDotFreePath } from './paths';
import logger from '~/config/winston';
@@ -24,6 +24,8 @@ type AnyObject = { [key: string]: unknown };
export type ConfigOverrideLayer = Pick<Config, 'principalType' | 'priority' | 'overrides'> & {
principalId: { toString(): string };
tombstones?: readonly unknown[];
+ /** The document's identity: the last tie-break of merge precedence. */
+ _id?: { toString(): string } | null;
};
const MAX_MERGE_DEPTH = 10;
@@ -1150,7 +1152,7 @@ function omitPath(target: unknown, segments: string[]): unknown {
* Drops the override nodes that make the merged config fail `configSchema`, so an invalid
* stored value (written before write-time validation, by an older server, or one that only
* fails once layered over other overrides) leaves the value beneath it in place. A layer
- * is not judged on what it leaves out, since a higher-priority layer may supply it.
+ * is not judged on what it leaves out, since a layer that merges after it may supply it.
*/
function stripInvalidOverrides(
config: ConfigOverrideLayer,
@@ -1352,30 +1354,25 @@ function withAcceptedSections(config: ConfigOverrideLayer): ConfigOverrideLayer
}
/**
- * Merge DB config overrides into a base AppConfig.
- *
- * Configs are sorted by priority ascending (lowest first, highest wins).
- * Each config's `overrides` is deep-merged into the base config in order.
- * A stored web search key is dropped when a layer other than its own decides
- * the URL it is sent to.
+ * Folds override layers, in merge precedence order (`compareConfigPrecedence`), into
+ * `merged`, the served config, and `raw`, the YAML-shaped config each layer is validated on
+ * before it lands (`stripInvalidOverrides`). `merged` starts as any object whose `mcpConfig`
+ * is the MCP servers config of `raw`, because the process-MCP filter reads it.
+ * `webSearchWriters` names the layer behind each paired web search field, by its position in
+ * that order.
*/
-export function mergeConfigOverrides(
- baseConfig: AppConfig,
+function foldConfigLayers<T extends AnyObject>(
+ initial: T,
+ initialRaw: Partial<TCustomConfig>,
configs: readonly ConfigOverrideLayer[],
-): AppConfig {
- if (!configs || configs.length === 0) {
- return baseConfig;
- }
-
- const sorted = [...configs].sort((a, b) => a.priority - b.priority);
-
- let merged = { ...baseConfig };
- /** The YAML-shaped config the next override lands on, for validating it in place. */
- let raw: Partial<TCustomConfig> = baseConfig.config ?? {};
+): { merged: T; raw: Partial<TCustomConfig>; webSearchWriters: WebSearchWriters } {
+ const sorted = sortByConfigPrecedence(configs);
+ let merged = initial;
+ let raw = initialRaw;
const webSearchWriters: WebSearchWriters = new Map();
for (let order = 0; order < sorted.length; order++) {
const config = withAcceptedSections(sorted[order]);
- const isBasePrincipal = config.principalId?.toString() === BASE_CONFIG_PRINCIPAL_ID;
+ const isBasePrincipal = isBaseConfigPrincipal(config);
if (Array.isArray(config.tombstones)) {
const removal: WebSearchWriter = { config, order, removed: true };
for (const path of config.tombstones) {
@@ -1404,10 +1401,7 @@ export function mergeConfigOverrides(
applied[key] = value;
const mappedKey = OVERRIDE_KEY_MAP[key as keyof typeof OVERRIDE_KEY_MAP] ?? key;
if (mappedKey === 'mcpConfig') {
- remapped[mappedKey] = filterMCPServerOverrides(
- value,
- (merged as unknown as AnyObject)[mappedKey],
- );
+ remapped[mappedKey] = filterMCPServerOverrides(value, merged[mappedKey]);
/** A server the filter removed must not complete a later layer's partial of it. */
applied[key] = remapped[mappedKey];
} else if (
@@ -1459,11 +1453,47 @@ export function mergeConfigOverrides(
});
}
}
+ return { merged, raw, webSearchWriters };
+}
- merged = bindWebSearchKeys(merged, webSearchWriters);
+/**
+ * Merge DB config overrides into a base AppConfig.
+ *
+ * Configs merge in precedence order (`compareConfigPrecedence`): Base first, then ascending
+ * priority, then role < group < user, then document identity; the last layer wins. Each
+ * config's `overrides` is deep-merged into the base config in that order. A stored web search
+ * key is dropped when a layer other than its own decides the URL it is sent to.
+ */
+export function mergeConfigOverrides(
+ baseConfig: AppConfig,
+ configs: readonly ConfigOverrideLayer[],
+): AppConfig {
+ if (!configs || configs.length === 0) {
+ return baseConfig;
+ }
+ const folded = foldConfigLayers({ ...baseConfig }, baseConfig.config ?? {}, configs);
+ const merged = bindWebSearchKeys(folded.merged, folded.webSearchWriters);
return preserveBaseOnlyPaths(baseConfig, preserveRuntimeStops(baseConfig, merged));
}
+/**
+ * The YAML-shaped config `configs` resolve to on top of `baseYaml`: exactly the value
+ * {@link mergeConfigOverrides} validates the next layer on, with the same precedence order,
+ * tombstones, base-only and dedicated-section filtering, invalid-override stripping and
+ * process-MCP filtering. It is a validation floor, not the served config (no AppService
+ * derivation runs on it).
+ */
+export function resolveRawConfig(
+ baseYaml: Partial<TCustomConfig>,
+ configs: readonly ConfigOverrideLayer[],
+): Partial<TCustomConfig> {
+ if (configs.length === 0) {
+ return baseYaml;
+ }
+ /** AppService serves `mcpServers` as `mcpConfig` unchanged (or `null`), and the fold reads it there. */
+ return foldConfigLayers({ mcpConfig: baseYaml.mcpServers ?? null }, baseYaml, configs).raw;
+}
+
function getPath(target: unknown, segments: string[]): unknown {
let current = target;
for (const segment of segments) {
@@ -1510,10 +1540,10 @@ export function isRuntimeDisabled(value: unknown): boolean {
* override that only flips the client's view produces a panel whose every action fails.
*
* Applied here rather than inside the merge deliberately. The merge folds overrides in
- * priority order into an ACCUMULATED value, so a guard there compares against whatever
- * the previous override left — which let a LOW-priority `false` block a HIGH-priority
- * `true` and broke highest-priority-wins. Overrides still order normally among
- * themselves; only the base stop is non-negotiable.
+ * precedence order into an ACCUMULATED value, so a guard there compares against whatever
+ * the previous override left — which let an EARLIER `false` block a LATER `true` and broke
+ * last-layer-wins. Overrides still order normally among themselves; only the base stop is
+ * non-negotiable.
*/
function preserveRuntimeStops<T extends AppConfig>(baseConfig: AppConfig, merged: T): T {
const baseInterface = (baseConfig as unknown as AnyObject).interfaceConfig as
diff --git a/packages/data-schemas/src/app/store.ts b/packages/data-schemas/src/app/store.ts
index 95262f07f4..c6711743f5 100644
--- a/packages/data-schemas/src/app/store.ts
+++ b/packages/data-schemas/src/app/store.ts
@@ -10,8 +10,15 @@ import {
replaceConfigOverrides,
isConfigOverrideStateEmpty,
} from './mutations';
+import {
+ isBaseConfigPrincipal,
+ sortByConfigPrecedence,
+ getDefaultConfigPriority,
+} from './precedence';
import { BASE_CONFIG_PRINCIPAL_ID } from '~/admin/capabilities';
+import { getSafeErrorFields } from '~/utils/errors';
import { parseFieldPath } from './paths';
+import logger from '~/config/winston';
/**
* The portable admin-config store contract.
@@ -27,7 +34,9 @@ import { parseFieldPath } from './paths';
* and keeps role documents (whose ids every tenant reuses) and every `listActive` read to one
* tenant partition (`tenantPartition`), so a merge never mixes tenants. Only a `list` that asks
* for `acrossTenants` reads every partition the caller's scope can see, for reports that name
- * each document's tenant.
+ * each document's tenant. The operations inherit the partition from these five: a role's
+ * priority change or move (`setPriority`, `movePrincipal`) reads and writes only the caller's
+ * partition, on both sides of a move.
*
* `./conformance` is the suite an engine must pass.
*/
@@ -35,9 +44,6 @@ import { parseFieldPath } from './paths';
/** Precondition meaning "the principal must not have a document yet" (create-only). */
export const ABSENT_CONFIG_REVISION = 'absent';
-/** Priority a principal's document gets when a write creates it without one. */
-export const DEFAULT_CONFIG_PRIORITY = 10;
-
/** How many times a write without a client precondition re-reads and retries on a conflict. */
export const CONFIG_WRITE_ATTEMPTS = 3;
@@ -107,6 +113,12 @@ export interface ConfigStore {
* Writes the whole document when the stored one is at `expected` (or, for
* {@link ABSENT_CONFIG_REVISION}, when none exists), incrementing `configVersion`. Any other
* state throws {@link ConfigRevisionConflictError} and changes nothing.
+ *
+ * A create that committed returns the document it created even when the engine's first
+ * acknowledgement of it was lost: the engine chooses the new identity before it writes and
+ * settles a lost acknowledgement by looking that identity up. Any other error means the
+ * create did not commit, or that the engine could not tell; a caller then never removes a
+ * document it finds, since it cannot confirm the document is its own.
*/
write(
principal: ConfigPrincipal,
@@ -148,6 +160,44 @@ export function isConfigRevisionConflict(error: unknown): error is ConfigRevisio
);
}
+/**
+ * Why a document move was refused before anything changed: the target principal already has
+ * a document, or either side is the tenant-wide Base principal, which never moves.
+ */
+export type ConfigMoveRefusal = 'CONFIG_PRINCIPAL_EXISTS' | 'CONFIG_PRINCIPAL_RESERVED';
+
+const CONFIG_MOVE_REFUSALS: ReadonlySet<unknown> = new Set<ConfigMoveRefusal>([
+ 'CONFIG_PRINCIPAL_EXISTS',
+ 'CONFIG_PRINCIPAL_RESERVED',
+]);
+
+/** `movePrincipal` refused the move and changed nothing; `code` says why. */
+export class ConfigMoveRefusedError extends Error {
+ readonly code: ConfigMoveRefusal;
+
+ constructor(code: ConfigMoveRefusal) {
+ super(
+ code === 'CONFIG_PRINCIPAL_EXISTS'
+ ? 'The target principal already has a config document'
+ : 'The base config document cannot be moved or replaced',
+ );
+ this.name = 'ConfigMoveRefusedError';
+ this.code = code;
+ }
+}
+
+/** Whether `error` is a refused move, optionally for one specific reason. */
+export function isConfigMoveRefused(
+ error: unknown,
+ code?: ConfigMoveRefusal,
+): error is ConfigMoveRefusedError {
+ if (!(error instanceof Error)) {
+ return false;
+ }
+ const actual = (error as { code?: unknown }).code;
+ return CONFIG_MOVE_REFUSALS.has(actual) && (code === undefined || actual === code);
+}
+
export function getConfigRevision(record: {
_id: { toString(): string };
configVersion?: number | null;
@@ -176,7 +226,11 @@ export function isConfigRevision(value: unknown): value is ConfigRevision {
);
}
-/** Store order: ascending priority, then the engine identity, so equal priorities never shuffle. */
+/**
+ * Store order: ascending priority, then the engine identity, so equal priorities never shuffle.
+ * It is what an engine can sort by natively; the operations re-sort into merge order
+ * (`compareConfigPrecedence`), which also puts Base first and ranks principal types.
+ */
export function compareConfigRecords(
left: Pick<ConfigRecord, '_id' | 'priority'>,
right: Pick<ConfigRecord, '_id' | 'priority'>,
@@ -286,20 +340,35 @@ function isEmptyRecord(record: ConfigRecord): boolean {
return isConfigOverrideStateEmpty(toConfigOverrideState(record));
}
+/**
+ * The next draft from `state`. An omitted priority keeps the stored one, and a document a
+ * write creates gets its principal type's default (`getDefaultConfigPriority`).
+ */
function toDraft(
+ principal: ConfigPrincipal,
current: ConfigRecord | null,
state: ConfigOverrideState,
defaults: Pick<ConfigDraft, 'principalModel'> & { priority?: number },
): ConfigDraft {
return {
principalModel: defaults.principalModel,
- priority: defaults.priority ?? current?.priority ?? DEFAULT_CONFIG_PRIORITY,
+ priority: defaults.priority ?? current?.priority ?? getDefaultConfigPriority(principal),
overrides: state.overrides,
tombstones: state.tombstones,
isActive: current?.isActive ?? true,
};
}
+/** Everything a stored document carries over to another principal or into a rewrite. */
+export function toConfigDraft(record: ConfigRecord): ConfigDraft {
+ return {
+ principalModel: record.principalModel,
+ priority: record.priority,
+ ...toConfigOverrideState(record),
+ isActive: record.isActive,
+ };
+}
+
/** The record a plan that always drafts has written. */
function writtenRecord(outcome: ConfigMutationOutcome<never>): ConfigRecord {
if (!outcome.written) {
@@ -327,13 +396,17 @@ function toTombstones(record: ConfigRecord): ConfigTombstones {
: { principalType, principalId, tenantId, tombstones };
}
-type ActiveToggle = { config: ConfigRecord; changed: boolean };
+/** A write that may find nothing to change: the document after it, and whether it wrote. */
+export type ConfigWriteOutcome = { config: ConfigRecord; changed: boolean };
export interface ConfigOperations {
findConfig(
principal: ConfigPrincipal,
options?: { includeInactive?: boolean },
): Promise<ConfigRecord | null>;
+ /** Every document (optionally only active or inactive ones), in merge precedence order. */
+ listConfigs(filter?: { isActive?: boolean }): Promise<ConfigRecord[]>;
+ /** Base and the given principals' active documents, in merge precedence order. */
getApplicableConfigs(
principals?: ReadonlyArray<{ principalType: string; principalId?: { toString(): string } }>,
): Promise<ConfigRecord[]>;
@@ -342,7 +415,7 @@ export interface ConfigOperations {
principal: ConfigPrincipal,
principalModel: PrincipalModel,
overrides: Partial<TCustomConfig>,
- priority: number,
+ priority?: number,
options?: ConfigLifecycleOptions & { preservePriority?: boolean },
): Promise<ConfigRecord | null>;
setFields(
@@ -372,7 +445,25 @@ export interface ConfigOperations {
principal: ConfigPrincipal,
isActive: boolean,
options?: ConfigLifecycleOptions,
- ): Promise<ActiveToggle | null>;
+ ): Promise<ConfigWriteOutcome | null>;
+ setPriority(
+ principal: ConfigPrincipal,
+ priority: number,
+ options?: ConfigWriteOptions,
+ ): Promise<ConfigWriteOutcome | null>;
+ movePrincipal(
+ from: ConfigPrincipal,
+ to: ConfigPrincipal,
+ options?: ConfigMoveOptions,
+ ): Promise<ConfigRecord | null>;
+}
+
+export interface ConfigMoveOptions {
+ /**
+ * Move `from`'s document only while it is this one (by `_id`, at any version): how a caller
+ * undoes its own move without taking a document someone else put there since.
+ */
+ identity?: string;
}
/**
@@ -408,8 +499,12 @@ export function createConfigOperations(store: ConfigStore): ConfigOperations {
return record;
}
+ async function listConfigs(filter?: { isActive?: boolean }): Promise<ConfigRecord[]> {
+ return sortByConfigPrecedence(await store.list(filter));
+ }
+
/** Base first in the query, then every principal that has an id; inactive documents excluded. */
- function getApplicableConfigs(
+ async function getApplicableConfigs(
principals?: ReadonlyArray<{ principalType: string; principalId?: { toString(): string } }>,
): Promise<ConfigRecord[]> {
const query: ConfigPrincipal[] = [
@@ -423,7 +518,7 @@ export function createConfigOperations(store: ConfigStore): ConfigOperations {
});
}
}
- return store.listActive(query);
+ return sortByConfigPrecedence(await store.listActive(query));
}
/**
@@ -440,12 +535,16 @@ export function createConfigOperations(store: ConfigStore): ConfigOperations {
return found;
}
- /** Replaces the overrides whole and activates the document; tombstones stay. */
+ /**
+ * Replaces the overrides whole and activates the document; tombstones stay. An omitted
+ * `priority` (or `preservePriority`) keeps the stored one, so a replace never reorders
+ * profiles it was not asked to.
+ */
async function replaceOverrides(
principal: ConfigPrincipal,
principalModel: PrincipalModel,
overrides: Partial<TCustomConfig>,
- priority: number,
+ priority?: number,
options?: ConfigLifecycleOptions & { preservePriority?: boolean },
): Promise<ConfigRecord | null> {
const outcome = await mutate<null>(
@@ -458,7 +557,7 @@ export function createConfigOperations(store: ConfigStore): ConfigOperations {
const keptPriority = options?.preservePriority ? (current?.priority ?? priority) : priority;
return {
draft: {
- ...toDraft(current, state, { principalModel, priority: keptPriority }),
+ ...toDraft(principal, current, state, { principalModel, priority: keptPriority }),
isActive: true,
},
};
@@ -483,10 +582,12 @@ export function createConfigOperations(store: ConfigStore): ConfigOperations {
const outcome = await mutate(
principal,
(current) => ({
- draft: toDraft(current, setConfigFields(toConfigOverrideState(current), writes), {
- principalModel,
- priority,
- }),
+ draft: toDraft(
+ principal,
+ current,
+ setConfigFields(toConfigOverrideState(current), writes),
+ { principalModel, priority },
+ ),
}),
options,
);
@@ -505,10 +606,12 @@ export function createConfigOperations(store: ConfigStore): ConfigOperations {
const outcome = await mutate(
principal,
(current) => ({
- draft: toDraft(current, tombstoneConfigPaths(toConfigOverrideState(current), paths), {
- principalModel,
- priority,
- }),
+ draft: toDraft(
+ principal,
+ current,
+ tombstoneConfigPaths(toConfigOverrideState(current), paths),
+ { principalModel, priority },
+ ),
}),
options,
);
@@ -529,7 +632,7 @@ export function createConfigOperations(store: ConfigStore): ConfigOperations {
return { draft: null, result: null };
}
const state = unsetConfigPaths(toConfigOverrideState(current), paths);
- return { draft: toDraft(current, state, current) };
+ return { draft: toDraft(principal, current, state, current) };
},
options,
);
@@ -576,8 +679,8 @@ export function createConfigOperations(store: ConfigStore): ConfigOperations {
principal: ConfigPrincipal,
isActive: boolean,
options?: ConfigLifecycleOptions,
- ): Promise<ActiveToggle | null> {
- const outcome = await mutate<ActiveToggle | null>(
+ ): Promise<ConfigWriteOutcome | null> {
+ const outcome = await mutate<ConfigWriteOutcome | null>(
principal,
(current) => {
if (!current || (options?.expectEmpty && !isEmptyRecord(current))) {
@@ -586,17 +689,121 @@ export function createConfigOperations(store: ConfigStore): ConfigOperations {
if (current.isActive === isActive) {
return { draft: null, result: { config: current, changed: false } };
}
- return {
- draft: { ...toDraft(current, toConfigOverrideState(current), current), isActive },
- };
+ return { draft: { ...toConfigDraft(current), isActive } };
},
options,
);
return outcome.written ? { config: outcome.record, changed: true } : outcome.result;
}
+ /**
+ * Sets the document's priority and nothing else: overrides, tombstones and `isActive` stay.
+ * `null` when there is no document; an unchanged priority is not written.
+ */
+ async function setPriority(
+ principal: ConfigPrincipal,
+ priority: number,
+ options?: ConfigWriteOptions,
+ ): Promise<ConfigWriteOutcome | null> {
+ const outcome = await mutate<ConfigWriteOutcome | null>(
+ principal,
+ (current) => {
+ if (!current) {
+ return { draft: null, result: null };
+ }
+ if (current.priority === priority) {
+ return { draft: null, result: { config: current, changed: false } };
+ }
+ return { draft: { ...toConfigDraft(current), priority } };
+ },
+ options,
+ );
+ return outcome.written ? { config: outcome.record, changed: true } : outcome.result;
+ }
+
+ /**
+ * The create-only copy a move starts with; a document already at `to` refuses the move. A
+ * copy that committed is returned even when its acknowledgement was lost (see
+ * {@link ConfigStore.write}), so any other failure leaves nothing this move can confirm it
+ * created, and nothing is removed.
+ */
+ async function copyTo(to: ConfigPrincipal, source: ConfigRecord): Promise<ConfigRecord> {
+ try {
+ return await store.write(to, toConfigDraft(source), ABSENT_CONFIG_REVISION);
+ } catch (error) {
+ throw isConfigRevisionConflict(error)
+ ? new ConfigMoveRefusedError('CONFIG_PRINCIPAL_EXISTS')
+ : error;
+ }
+ }
+
+ /**
+ * Moves `from`'s document, as stored, to `to` (a role rename), and returns it as `to` now
+ * holds it, or `null` when `from` has none. It is a create-only write at `to` followed by a
+ * removal of `from` at the revision just copied. The moved document has a new identity, so
+ * revisions of the old one no longer match.
+ *
+ * A refusal changes nothing and throws {@link ConfigMoveRefusedError}:
+ * `CONFIG_PRINCIPAL_EXISTS` when `to` already has a document, and `CONFIG_PRINCIPAL_RESERVED`
+ * when either side is Base, which is tenant-wide and never one principal's document. When
+ * `from` changes between the copy and the removal, the copy is withdrawn and the move
+ * retried. Once the retries run out, or when the copy was edited meanwhile and so is kept,
+ * the revision conflict is rethrown. When a failed removal cannot be confirmed by reading
+ * `from` back, the copy is kept, as it may be the only one left, and the removal's failure
+ * is rethrown. A copy that cannot be withdrawn is logged with its revision, so an operator can
+ * remove it. With `identity`, a `from` that holds another document (or none) moves nothing
+ * and resolves to `null`.
+ */
+ async function movePrincipal(
+ from: ConfigPrincipal,
+ to: ConfigPrincipal,
+ options?: ConfigMoveOptions,
+ ): Promise<ConfigRecord | null> {
+ if (isBaseConfigPrincipal(from) || isBaseConfigPrincipal(to)) {
+ throw new ConfigMoveRefusedError('CONFIG_PRINCIPAL_RESERVED');
+ }
+ for (let attempt = 1; ; attempt++) {
+ const current = await store.read(from);
+ if (!current || (options?.identity != null && current._id !== options.identity)) {
+ return null;
+ }
+ const moved = await copyTo(to, current);
+ let failure: unknown;
+ try {
+ await store.remove(from, getConfigRevision(current));
+ return moved;
+ } catch (error) {
+ failure = error;
+ }
+ /**
+ * A removal can fail after it committed; the copy is then the only one, so it stays. A
+ * source that cannot be read back may be gone as well, so the copy stays then too.
+ */
+ const remaining = await store.read(from).catch(() => {
+ throw failure;
+ });
+ if (remaining == null) {
+ return moved;
+ }
+ await store.remove(to, getConfigRevision(moved)).catch((withdrawal: unknown) => {
+ logger.error('[configStore] A moved config document could not be withdrawn from its copy', {
+ principalType: to.principalType,
+ principalId: to.principalId,
+ revision: getConfigRevision(moved),
+ ...getSafeErrorFields(withdrawal),
+ });
+ throw withdrawal;
+ });
+ if (!isConfigRevisionConflict(failure) || attempt >= CONFIG_WRITE_ATTEMPTS) {
+ throw failure;
+ }
+ await pauseBeforeRetry(attempt);
+ }
+ }
+
return {
findConfig,
+ listConfigs,
getApplicableConfigs,
listTombstones,
replaceOverrides,
@@ -605,5 +812,7 @@ export function createConfigOperations(store: ConfigStore): ConfigOperations {
unsetFields,
deleteConfig,
setActive,
+ setPriority,
+ movePrincipal,
};
}
diff --git a/packages/data-schemas/src/methods/aclEntry.spec.ts b/packages/data-schemas/src/methods/aclEntry.spec.ts
index 9b9a5c72aa..71ce1b9f78 100644
--- a/packages/data-schemas/src/methods/aclEntry.spec.ts
+++ b/packages/data-schemas/src/methods/aclEntry.spec.ts
@@ -12,7 +12,9 @@ import {
createAclEntryMethods,
permissionBitSupersets,
} from './aclEntry';
+import { tenantStorage } from '~/config/tenantContext';
import aclEntrySchema from '~/schema/aclEntry';
+import logger from '~/config/winston';
let mongoServer: MongoMemoryServer;
let AclEntry: mongoose.Model<t.IAclEntry>;
@@ -962,6 +964,123 @@ describe('AclEntry Model Tests', () => {
});
});
+ describe('moveAclEntriesToPrincipal', () => {
+ const grantToRole = (roleName: string, bits: number) =>
+ methods.grantPermission(
+ PrincipalType.ROLE,
+ roleName,
+ ResourceType.AGENT,
+ new mongoose.Types.ObjectId(),
+ bits,
+ grantedById,
+ );
+
+ const entriesOf = (roleName: string) =>
+ AclEntry.find({ principalType: PrincipalType.ROLE, principalId: roleName }).lean();
+
+ it('re-keys a role principal entries to the new name, keeping identity and bits', async () => {
+ const viewed = await grantToRole('editor', PermissionBits.VIEW);
+ await grantToRole('editor', PermissionBits.EDIT);
+ await grantToRole('other', PermissionBits.VIEW);
+
+ const moved = await methods.moveAclEntriesToPrincipal(PrincipalType.ROLE, 'editor', 'writer');
+
+ expect(moved).toHaveLength(2);
+ expect(await entriesOf('editor')).toHaveLength(0);
+ const writer = await entriesOf('writer');
+ expect(writer.map((entry) => entry._id.toString()).sort()).toEqual([...moved].sort());
+ expect(writer.find((entry) => entry._id.equals(viewed?._id))?.permBits).toBe(
+ PermissionBits.VIEW,
+ );
+ expect(await entriesOf('other')).toHaveLength(1);
+ });
+
+ it('moves back only the entries a move returned', async () => {
+ await grantToRole('editor', PermissionBits.VIEW);
+ const writerBefore = await grantToRole('writer', PermissionBits.EDIT);
+
+ const moved = await methods.moveAclEntriesToPrincipal(PrincipalType.ROLE, 'editor', 'writer');
+ await methods.moveAclEntriesToPrincipal(PrincipalType.ROLE, 'writer', 'editor', {
+ ids: moved,
+ });
+
+ expect((await entriesOf('editor')).map((entry) => entry._id.toString())).toEqual(moved);
+ expect((await entriesOf('writer')).map((entry) => entry._id.toString())).toEqual([
+ writerBefore?._id.toString(),
+ ]);
+ });
+
+ it('returns nothing for a principal without entries', async () => {
+ expect(
+ await methods.moveAclEntriesToPrincipal(PrincipalType.ROLE, 'nobody', 'writer'),
+ ).toEqual([]);
+ });
+
+ it('moves only platform-level entries without a tenant context', async () => {
+ const platform = await grantToRole('editor', PermissionBits.VIEW);
+ const tenant = await grantToRole('editor', PermissionBits.EDIT);
+ await AclEntry.collection.updateOne({ _id: tenant?._id }, { $set: { tenantId: 'tenant-a' } });
+
+ const moved = await methods.moveAclEntriesToPrincipal(PrincipalType.ROLE, 'editor', 'writer');
+
+ expect(moved).toEqual([platform?._id.toString()]);
+ expect((await entriesOf('editor')).map((entry) => entry._id.toString())).toEqual([
+ tenant?._id.toString(),
+ ]);
+ });
+
+ it('moves unclaimed entries as platform-level, and only the active tenant entries inside one', async () => {
+ const absent = await grantToRole('editor', PermissionBits.VIEW);
+ const unclaimed = await grantToRole('editor', PermissionBits.EDIT);
+ const tenant = await grantToRole('editor', PermissionBits.DELETE);
+ await AclEntry.collection.updateOne({ _id: unclaimed?._id }, { $set: { tenantId: null } });
+ await AclEntry.collection.updateOne({ _id: tenant?._id }, { $set: { tenantId: 'tenant-a' } });
+
+ const platformMoved = await methods.moveAclEntriesToPrincipal(
+ PrincipalType.ROLE,
+ 'editor',
+ 'writer',
+ );
+ const tenantMoved = await tenantStorage.run({ tenantId: 'tenant-a' }, () =>
+ methods.moveAclEntriesToPrincipal(PrincipalType.ROLE, 'editor', 'author'),
+ );
+
+ expect([...platformMoved].sort()).toEqual(
+ [absent?._id.toString(), unclaimed?._id.toString()].sort(),
+ );
+ expect(tenantMoved).toEqual([tenant?._id.toString()]);
+ expect(await entriesOf('editor')).toHaveLength(0);
+ });
+
+ it('logs the entry ids, never the error text, when the undo of a failed move fails too', async () => {
+ const entry = await grantToRole('editor', PermissionBits.VIEW);
+ const failure = new Error('write interrupted');
+ const updateMany = jest
+ .spyOn(AclEntry, 'updateMany')
+ .mockRejectedValueOnce(failure)
+ .mockRejectedValueOnce(new Error('undo failed near {"principalId":"editor"}'));
+ const logged = jest.spyOn(logger, 'error').mockReturnValue(logger);
+
+ await expect(
+ methods.moveAclEntriesToPrincipal(PrincipalType.ROLE, 'editor', 'writer'),
+ ).rejects.toBe(failure);
+ updateMany.mockRestore();
+
+ expect(logged).toHaveBeenCalledWith(
+ '[moveAclEntriesToPrincipal] undo after a failed move failed',
+ {
+ principalType: PrincipalType.ROLE,
+ fromPrincipalId: 'editor',
+ toPrincipalId: 'writer',
+ entryIds: entry?._id.toString(),
+ errName: 'Error',
+ errCode: null,
+ },
+ );
+ logged.mockRestore();
+ });
+ });
+
describe('bulkWriteAclEntries', () => {
test('should perform bulk inserts', async () => {
const res1 = new mongoose.Types.ObjectId();
diff --git a/packages/data-schemas/src/methods/aclEntry.ts b/packages/data-schemas/src/methods/aclEntry.ts
index 31b1c62dd0..b379d1b018 100644
--- a/packages/data-schemas/src/methods/aclEntry.ts
+++ b/packages/data-schemas/src/methods/aclEntry.ts
@@ -13,9 +13,12 @@ import type {
Model,
} from 'mongoose';
import type { IAclEntry } from '~/types';
+import { tenantPartitionFilter } from '~/models/plugins/tenantIsolation';
import { tenantSafeBulkWrite } from '~/utils/tenantBulkWrite';
import { MAX_PERM_BITS } from '~/common/permissions';
+import { getSafeErrorFields } from '~/utils/errors';
import { RoleBits } from '~/common/enum';
+import logger from '~/config/winston';
/**
* Empty frozen array shared by every rejection path. Returning a single
@@ -188,6 +191,12 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): {
filter: Record<string, unknown>,
options?: { session?: ClientSession },
) => Promise<DeleteResult>;
+ moveAclEntriesToPrincipal: (
+ principalType: PrincipalType,
+ fromPrincipalId: string,
+ toPrincipalId: string,
+ options?: { ids?: readonly string[] },
+ ) => Promise<string[]>;
replaceRoleBits: (
writes: RoleBitsWrite[],
options?: { session?: ClientSession; maxAttempts?: number },
@@ -543,6 +552,59 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): {
return AclEntry.deleteMany(filter, options || {});
}
+ /**
+ * 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
+ * identity and bits. A move that fails part-way is undone before it rethrows; an undo that
+ * fails too is logged with the entry ids, so an operator can finish it.
+ *
+ * Only the caller's tenant partition moves (`tenantPartitionFilter`): that tenant's entries,
+ * or without a tenant only platform-level ones. A rename re-keys one role, and must not re-key
+ * the entries of each tenant's own role that happens to share the name.
+ */
+ async function moveAclEntriesToPrincipal(
+ principalType: PrincipalType,
+ fromPrincipalId: string,
+ toPrincipalId: string,
+ options?: { ids?: readonly string[] },
+ ): Promise<string[]> {
+ const AclEntry = mongoose.models.AclEntry as Model<IAclEntry>;
+ const source = {
+ principalType,
+ principalId: fromPrincipalId,
+ ...tenantPartitionFilter('moveAclEntriesToPrincipal'),
+ };
+ const ids: Types.ObjectId[] = options?.ids
+ ? options.ids.map((id) => new Types.ObjectId(id))
+ : (await AclEntry.find(source).select('_id').lean<Array<{ _id: Types.ObjectId }>>()).map(
+ ({ _id }) => _id,
+ );
+ if (ids.length === 0) {
+ return [];
+ }
+ try {
+ await AclEntry.updateMany(
+ { ...source, _id: { $in: ids } },
+ { $set: { principalId: toPrincipalId } },
+ );
+ } catch (error) {
+ await AclEntry.updateMany(
+ { principalType, principalId: toPrincipalId, _id: { $in: ids } },
+ { $set: { principalId: fromPrincipalId } },
+ ).catch((undoError: unknown) =>
+ logger.error('[moveAclEntriesToPrincipal] undo after a failed move failed', {
+ principalType,
+ fromPrincipalId,
+ toPrincipalId,
+ entryIds: ids.map((id) => id.toString()).join(','),
+ ...getSafeErrorFields(undoError),
+ }),
+ );
+ throw error;
+ }
+ return ids.map((id) => id.toString());
+ }
+
/** Reject values JavaScript bit operations would truncate. Missing legacy fields mean zero. */
function permissionMask(value: unknown): number {
if (value === undefined) return 0;
@@ -836,6 +898,7 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): {
aggregateAclEntries,
getFirstOwnerIdsByResource,
getSoleOwnedResourceIds,
+ moveAclEntriesToPrincipal,
};
}
diff --git a/packages/data-schemas/src/methods/config.spec.ts b/packages/data-schemas/src/methods/config.spec.ts
index ac77550a99..924dceed6f 100644
--- a/packages/data-schemas/src/methods/config.spec.ts
+++ b/packages/data-schemas/src/methods/config.spec.ts
@@ -303,6 +303,38 @@ describe('getApplicableConfigs', () => {
expect(configs[1].principalId).toBe('admin');
});
+ it('returns Base first and a stable order for equal priorities, whatever the stored ones', async () => {
+ const groups = Array.from({ length: 5 }, () => new Types.ObjectId().toString());
+ for (const groupId of groups) {
+ await methods.upsertConfig(PrincipalType.GROUP, groupId, PrincipalModel.GROUP, {}, 20);
+ }
+ await methods.upsertConfig(PrincipalType.USER, 'u1', PrincipalModel.USER, {}, 20);
+ await methods.upsertConfig(PrincipalType.ROLE, 'admin', PrincipalModel.ROLE, {}, 20);
+ await methods.upsertConfig(PrincipalType.ROLE, '__base__', PrincipalModel.ROLE, {}, 90);
+ const principals = [
+ { principalType: PrincipalType.USER, principalId: 'u1' },
+ { principalType: PrincipalType.ROLE, principalId: 'admin' },
+ ...groups.map((principalId) => ({ principalType: PrincipalType.GROUP, principalId })),
+ ];
+ const order = async () =>
+ (await methods.getApplicableConfigs(principals)).map(
+ (config) => `${config.principalType}:${config.principalId}`,
+ );
+
+ const first = await order();
+ expect(first[0]).toBe('role:__base__');
+ expect(first[1]).toBe('role:admin');
+ expect(first[first.length - 1]).toBe('user:u1');
+ for (let round = 0; round < 5; round++) {
+ expect(await order()).toEqual(first);
+ }
+ expect(
+ (await methods.listAllConfigs()).map(
+ (config) => `${config.principalType}:${config.principalId}`,
+ ),
+ ).toEqual(first);
+ });
+
it('skips principals with undefined principalId', async () => {
await methods.upsertConfig(PrincipalType.ROLE, '__base__', PrincipalModel.ROLE, {}, 0);
@@ -573,6 +605,302 @@ describe('upsertConfig', () => {
});
});
+describe('upsertConfig priority', () => {
+ it('keeps the stored priority when none is given, and defaults by principal type on create', async () => {
+ const groupId = new Types.ObjectId().toString();
+ const created = await methods.upsertConfig(PrincipalType.GROUP, groupId, PrincipalModel.GROUP, {
+ interface: { modelSelect: false },
+ });
+ expect(created!.priority).toBe(20);
+
+ await methods.setConfigPriority(PrincipalType.GROUP, groupId, 35);
+ const replaced = await methods.upsertConfig(
+ PrincipalType.GROUP,
+ groupId,
+ PrincipalModel.GROUP,
+ { interface: { modelSelect: true } },
+ );
+ expect(replaced!.priority).toBe(35);
+ });
+});
+
+describe('setConfigPriority', () => {
+ it('changes only the priority of a stored document', async () => {
+ await methods.patchConfigFields(PrincipalType.ROLE, 'prio', PrincipalModel.ROLE, {
+ 'interface.customWelcome': 'hi',
+ });
+ await methods.tombstoneConfigField(PrincipalType.ROLE, 'prio', PrincipalModel.ROLE, 'memory');
+ await methods.toggleConfigActive(PrincipalType.ROLE, 'prio', false);
+
+ const result = await methods.setConfigPriority(PrincipalType.ROLE, 'prio', 3);
+
+ expect(result!.changed).toBe(true);
+ const stored = await methods.findConfigByPrincipal(PrincipalType.ROLE, 'prio', {
+ includeInactive: true,
+ });
+ expect(stored).toMatchObject({
+ priority: 3,
+ overrides: { interface: { customWelcome: 'hi' } },
+ tombstones: ['memory'],
+ isActive: false,
+ configVersion: 4,
+ });
+ expect(await methods.setConfigPriority(PrincipalType.ROLE, 'missing', 3)).toBeNull();
+ });
+});
+
+describe('renameConfigPrincipal', () => {
+ it('moves a profile with dotted keys, storing them as the engine accepts them', async () => {
+ const profiles = { 'us.anthropic.claude-sonnet-4-5': 'arn:aws:x' };
+ await methods.patchConfigFields(PrincipalType.ROLE, 'editor', PrincipalModel.ROLE, {
+ 'endpoints.bedrock.inferenceProfiles': profiles,
+ });
+
+ const moved = await methods.renameConfigPrincipal(PrincipalType.ROLE, 'editor', 'writer');
+
+ expect(moved!.principalId).toBe('writer');
+ expect(moved!.overrides).toEqual({ endpoints: { bedrock: { inferenceProfiles: profiles } } });
+ expect(await raw().findOne({ principalId: 'editor' })).toBeNull();
+ const stored = await raw().findOne({ principalId: 'writer' });
+ expect(stored!.overrides.endpoints.bedrock.inferenceProfiles).toEqual(profiles);
+ expect(stored!.keyEncoding).toBeUndefined();
+ });
+
+ it('refuses to move onto a principal that has a profile, changing nothing', async () => {
+ await methods.patchConfigFields(PrincipalType.ROLE, 'a', PrincipalModel.ROLE, { x: 1 });
+ await methods.patchConfigFields(PrincipalType.ROLE, 'b', PrincipalModel.ROLE, { y: 1 });
+
+ await expect(methods.renameConfigPrincipal(PrincipalType.ROLE, 'a', 'b')).rejects.toMatchObject(
+ { code: 'CONFIG_PRINCIPAL_EXISTS' },
+ );
+ expect((await methods.findConfigByPrincipal(PrincipalType.ROLE, 'a'))!.overrides).toEqual({
+ x: 1,
+ });
+ expect((await methods.findConfigByPrincipal(PrincipalType.ROLE, 'b'))!.overrides).toEqual({
+ y: 1,
+ });
+ });
+});
+
+const inTenant = <T>(tenantId: string, run: () => Promise<T>): Promise<T> =>
+ tenantStorage.run({ tenantId }, run);
+const seedTenant = (tenantId: string, principalId: string, overrides: Record<string, unknown>) =>
+ inTenant(tenantId, () =>
+ methods.patchConfigFields(PrincipalType.ROLE, principalId, PrincipalModel.ROLE, overrides),
+ );
+/**
+ * A platform-level document, inserted directly so it keeps exactly the tenantless form it is
+ * given: no `tenantId`, or an unclaimed `null` or `''`.
+ */
+const seedPlatform = (
+ principalId: string,
+ overrides: Record<string, unknown>,
+ tenant: { tenantId?: string | null } = {},
+) =>
+ raw().insertOne({
+ principalType: PrincipalType.ROLE,
+ principalId,
+ principalModel: PrincipalModel.ROLE,
+ priority: 10,
+ overrides,
+ tombstones: [],
+ isActive: true,
+ configVersion: 1,
+ ...tenant,
+ });
+/** Every stored role document as `tenant/principalId`, platform-level ones as `-/…`. */
+const layout = async () =>
+ (
+ await raw()
+ .find({ principalType: PrincipalType.ROLE })
+ .project<{ principalId: string; tenantId?: string | null }>({ principalId: 1, tenantId: 1 })
+ .toArray()
+ )
+ .map((document) => `${document.tenantId || '-'}/${document.principalId}`)
+ .sort();
+/** Every stored role document as `tenant/principalId:priority`, platform-level ones as `-/…`. */
+const priorities = async () =>
+ (
+ await raw()
+ .find({ principalType: PrincipalType.ROLE })
+ .project<{ principalId: string; priority: number; tenantId?: string | null }>({
+ principalId: 1,
+ priority: 1,
+ tenantId: 1,
+ })
+ .toArray()
+ )
+ .map((document) => `${document.tenantId || '-'}/${document.principalId}:${document.priority}`)
+ .sort();
+
+describe('renameConfigPrincipal in the caller tenant partition', () => {
+ it('moves only the platform-level profile for a caller without a tenant', async () => {
+ await seedTenant('tenant-a', 'editor', { x: 'tenant-a' });
+ await seedPlatform('editor', { x: 'platform' });
+
+ const moved = await methods.renameConfigPrincipal(PrincipalType.ROLE, 'editor', 'writer');
+
+ expect(moved!.overrides).toEqual({ x: 'platform' });
+ expect(moved!.tenantId).toBeUndefined();
+ expect(await layout()).toEqual(['-/writer', 'tenant-a/editor']);
+ });
+
+ it("never moves a tenant's profile to the platform when the platform role has none", async () => {
+ await seedTenant('tenant-a', 'editor', { x: 'tenant-a' });
+
+ expect(await methods.renameConfigPrincipal(PrincipalType.ROLE, 'editor', 'writer')).toBeNull();
+ expect(await layout()).toEqual(['tenant-a/editor']);
+ });
+
+ it('is refused only by a profile at the new name in the same partition', async () => {
+ await seedTenant('tenant-a', 'writer', { x: 'tenant-a' });
+ await seedPlatform('editor', { x: 'platform' });
+
+ const moved = await methods.renameConfigPrincipal(PrincipalType.ROLE, 'editor', 'writer');
+
+ expect(moved!.overrides).toEqual({ x: 'platform' });
+ expect(await layout()).toEqual(['-/writer', 'tenant-a/writer']);
+ await seedPlatform('editor', { x: 'again' });
+ await expect(
+ methods.renameConfigPrincipal(PrincipalType.ROLE, 'editor', 'writer'),
+ ).rejects.toMatchObject({ code: 'CONFIG_PRINCIPAL_EXISTS' });
+ expect(await layout()).toEqual(['-/editor', '-/writer', 'tenant-a/writer']);
+ });
+
+ it("moves only the active tenant's profile inside a tenant", async () => {
+ await seedPlatform('editor', { x: 'platform' });
+ await seedTenant('tenant-b', 'editor', { x: 'tenant-b' });
+ await seedTenant('tenant-a', 'editor', { x: 'tenant-a' });
+
+ const moved = await inTenant('tenant-a', () =>
+ methods.renameConfigPrincipal(PrincipalType.ROLE, 'editor', 'writer'),
+ );
+
+ expect(moved!.overrides).toEqual({ x: 'tenant-a' });
+ expect(moved!.tenantId).toBe('tenant-a');
+ expect(await layout()).toEqual(['-/editor', 'tenant-a/writer', 'tenant-b/editor']);
+ });
+
+ it('treats an unclaimed profile (null or empty tenant) as platform-level', async () => {
+ await seedTenant('tenant-a', 'editor', { x: 'tenant-a' });
+ await seedPlatform('editor', { x: 'unclaimed' }, { tenantId: '' });
+ await seedPlatform('author', { x: 'unclaimed' }, { tenantId: null });
+
+ const moved = await Promise.all([
+ methods.renameConfigPrincipal(PrincipalType.ROLE, 'editor', 'writer'),
+ methods.renameConfigPrincipal(PrincipalType.ROLE, 'author', 'reader'),
+ ]);
+
+ expect(moved.map((record) => record!.overrides)).toEqual([
+ { x: 'unclaimed' },
+ { x: 'unclaimed' },
+ ]);
+ expect(await layout()).toEqual(['-/reader', '-/writer', 'tenant-a/editor']);
+ });
+
+ it("reads a role's profile only in the caller partition, as a rename's target check does", async () => {
+ await seedTenant('tenant-a', 'editor', { x: 'tenant-a' });
+
+ const platformRead = await methods.findConfigByPrincipal(PrincipalType.ROLE, 'editor', {
+ includeInactive: true,
+ });
+ const tenantRead = await inTenant('tenant-a', () =>
+ methods.findConfigByPrincipal(PrincipalType.ROLE, 'editor'),
+ );
+
+ expect(platformRead).toBeNull();
+ expect(tenantRead!.overrides).toEqual({ x: 'tenant-a' });
+ });
+
+ /**
+ * The driver applies the next insert and reports a dropped connection instead of its reply;
+ * with `unsettled`, the lookup that would settle it fails as well.
+ */
+ function loseNextCreateAcknowledgement(options: { unsettled?: boolean } = {}): Error {
+ const collection = mongoose.models.Config.collection;
+ const findOneAndUpdate = collection.findOneAndUpdate.bind(collection);
+ const lost = new mongoose.mongo.MongoNetworkError('connection reset after the write applied');
+ jest.spyOn(collection, 'findOneAndUpdate').mockImplementationOnce((async (
+ ...args: Parameters<typeof findOneAndUpdate>
+ ) => {
+ await findOneAndUpdate(...args);
+ if (options.unsettled) {
+ jest
+ .spyOn(collection, 'findOne')
+ .mockRejectedValueOnce(new mongoose.mongo.MongoNetworkError('still disconnected'));
+ }
+ throw lost;
+ }) as unknown as typeof collection.findOneAndUpdate);
+ return lost;
+ }
+
+ it("settles a copy whose acknowledgement was lost and finishes the move in the caller's tenant", async () => {
+ await seedTenant('tenant-b', 'writer', { x: 'tenant-b' });
+ await seedTenant('tenant-a', 'editor', { x: 'tenant-a' });
+ loseNextCreateAcknowledgement();
+
+ const moved = await inTenant('tenant-a', () =>
+ methods.renameConfigPrincipal(PrincipalType.ROLE, 'editor', 'writer'),
+ );
+
+ expect(moved!.overrides).toEqual({ x: 'tenant-a' });
+ expect(moved!.tenantId).toBe('tenant-a');
+ expect(await layout()).toEqual(['tenant-a/writer', 'tenant-b/writer']);
+ });
+
+ it('keeps both documents and rethrows when a lost acknowledgement cannot be settled', async () => {
+ await seedPlatform('editor', { x: 'platform' });
+ const lost = loseNextCreateAcknowledgement({ unsettled: true });
+
+ await expect(
+ methods.renameConfigPrincipal(PrincipalType.ROLE, 'editor', 'writer'),
+ ).rejects.toBe(lost);
+ expect(await layout()).toEqual(['-/editor', '-/writer']);
+ });
+});
+
+describe('setConfigPriority in the caller tenant partition', () => {
+ it('changes only the platform-level profile for a caller without a tenant', async () => {
+ await seedTenant('tenant-a', 'editor', { x: 'tenant-a' });
+ await seedPlatform('editor', { x: 'platform' });
+ await seedPlatform('author', { x: 'unclaimed' }, { tenantId: '' });
+
+ const result = await methods.setConfigPriority(PrincipalType.ROLE, 'editor', 40);
+ const unclaimed = await methods.setConfigPriority(PrincipalType.ROLE, 'author', 30);
+
+ expect(result).toMatchObject({ changed: true, config: { priority: 40 } });
+ expect(result!.config.overrides).toEqual({ x: 'platform' });
+ expect(result!.config.tenantId).toBeUndefined();
+ expect(unclaimed).toMatchObject({ changed: true, config: { overrides: { x: 'unclaimed' } } });
+ expect(await priorities()).toEqual(['-/author:30', '-/editor:40', 'tenant-a/editor:10']);
+ });
+
+ it("never changes or returns a tenant's profile when the platform role has none", async () => {
+ const tenantProfile = await seedTenant('tenant-a', 'editor', { x: 'tenant-a' });
+
+ expect(await methods.setConfigPriority(PrincipalType.ROLE, 'editor', 40)).toBeNull();
+ await expect(
+ methods.setConfigPriority(PrincipalType.ROLE, 'editor', 40, {
+ expectedRevision: `${tenantProfile!._id}:${tenantProfile!.configVersion}`,
+ }),
+ ).rejects.toMatchObject({ code: 'CONFIG_VERSION_CONFLICT', currentRevision: null });
+ expect(await priorities()).toEqual(['tenant-a/editor:10']);
+ });
+
+ it("changes only the active tenant's profile inside a tenant", async () => {
+ await seedPlatform('editor', { x: 'platform' });
+ await seedTenant('tenant-b', 'editor', { x: 'tenant-b' });
+ await seedTenant('tenant-a', 'editor', { x: 'tenant-a' });
+
+ const result = await inTenant('tenant-a', () =>
+ methods.setConfigPriority(PrincipalType.ROLE, 'editor', 40),
+ );
+
+ expect(result!.config).toMatchObject({ tenantId: 'tenant-a', overrides: { x: 'tenant-a' } });
+ expect(await priorities()).toEqual(['-/editor:10', 'tenant-a/editor:40', 'tenant-b/editor:10']);
+ });
+});
+
describe('unsetConfigField', () => {
it('removes a field from overrides via $unset', async () => {
await methods.upsertConfig(
@@ -1386,6 +1714,21 @@ describe('key encoding at rest', () => {
});
});
+ it('moves a profile on an engine that refuses raw key names, keeping its keys encoded', async () => {
+ const refusing = createConfigMethods(mongoose);
+ const findOneAndUpdate = refuseRawKeyNames();
+ await refusing.upsertConfig(PrincipalType.ROLE, 'from', PrincipalModel.ROLE, dotted as never);
+
+ const moved = await refusing.renameConfigPrincipal(PrincipalType.ROLE, 'from', 'to');
+
+ expect(moved!.overrides).toEqual(dotted);
+ expect(await raw().findOne({ principalId: 'from' })).toBeNull();
+ const stored = await raw().findOne({ principalId: 'to' });
+ expect(stored!.keyEncoding).toBe(1);
+ expect(stored!.overrides['%24top']).toEqual({ 'a%2Eb': '$value.stays' });
+ expect(findOneAndUpdate).toHaveBeenCalled();
+ });
+
it('restores a deleted document with dotted keys in the form the engine accepts', async () => {
await methods.upsertConfig(
PrincipalType.ROLE,
diff --git a/packages/data-schemas/src/methods/config.ts b/packages/data-schemas/src/methods/config.ts
index 98ec5a430c..432b34a511 100644
--- a/packages/data-schemas/src/methods/config.ts
+++ b/packages/data-schemas/src/methods/config.ts
@@ -5,6 +5,8 @@ import type { Model } from 'mongoose';
import type {
ConfigDraft,
ConfigStore,
+ ConfigMoveOptions,
+ ConfigWriteOutcome,
ConfigRecord,
ConfigRevision,
ConfigPrincipal,
@@ -23,6 +25,7 @@ import {
createConfigOperations,
getConfigRevision,
parseConfigRevision,
+ isConfigRevisionConflict,
} from '~/app/store';
import {
toStoredKeys,
@@ -240,6 +243,12 @@ export function createConfigStore(mongoose: typeof import('mongoose')): ConfigSt
* engines, such as DocumentDB elastic clusters, do not enforce); the index still turns two
* racing inserts into a duplicate-key conflict. Timestamps are set here because Mongoose would
* otherwise `$set` `updatedAt` on the document it found.
+ *
+ * The `_id` is chosen here, so an insert whose acknowledgement is lost (the connection drops
+ * after the server applied it, where the driver cannot retry the write) is settled by looking
+ * that `_id` up: found at version 1, the insert committed and its document is returned, as
+ * the contract requires. Otherwise, or when the lookup fails too, the write's own error is
+ * rethrown.
*/
async function create(
principal: ConfigPrincipal,
@@ -269,6 +278,16 @@ export function createConfigStore(mongoose: typeof import('mongoose')): ConfigSt
if (isDuplicateKeyError(error)) {
throw new ConfigRevisionConflictError();
}
+ if (isConfigRevisionConflict(error) || isFieldNameRejection(error)) {
+ throw error;
+ }
+ const created = await model()
+ .findOne({ ...principalFilter(principal, 'configStore.write'), _id, configVersion: 1 })
+ .lean<StoredConfig>()
+ .catch(() => null);
+ if (created) {
+ return toRecord(created);
+ }
throw error;
}
}
@@ -393,10 +412,11 @@ export function createConfigMethods(mongoose: typeof import('mongoose')) {
const operations = createConfigOperations(store);
return {
+ /** The documents the store lists, in merge precedence order (`compareConfigPrecedence`). */
listAllConfigs: (
filter?: { isActive?: boolean },
_session?: NoSession,
- ): Promise<ConfigRecord[]> => store.list(filter),
+ ): Promise<ConfigRecord[]> => operations.listConfigs(filter),
findConfigByPrincipal: (
principalType: PrincipalType,
@@ -406,6 +426,7 @@ export function createConfigMethods(mongoose: typeof import('mongoose')) {
): Promise<ConfigRecord | null> =>
operations.findConfig(toPrincipal(principalType, principalId), options),
+ /** Base and the principals' active documents, in merge precedence order. */
getApplicableConfigs: (
principals?: Array<{ principalType: string; principalId?: ConfigPrincipalId }>,
_session?: NoSession,
@@ -418,13 +439,16 @@ export function createConfigMethods(mongoose: typeof import('mongoose')) {
listConfigTombstones: (fieldPath: string, _session?: NoSession): Promise<ConfigTombstones[]> =>
operations.listTombstones(fieldPath),
- /** Replaces the overrides whole and activates the document; tombstones stay. */
+ /**
+ * Replaces the overrides whole and activates the document; tombstones stay. An omitted
+ * `priority` keeps the stored one, or gives a new document its principal type's default.
+ */
upsertConfig: (
principalType: PrincipalType,
principalId: ConfigPrincipalId,
principalModel: PrincipalModel,
overrides: Partial<TCustomConfig>,
- priority: number,
+ priority?: number,
_session?: NoSession,
options?: ConfigLifecycleOptions & { preservePriority?: boolean },
): Promise<ConfigRecord | null> =>
@@ -524,6 +548,43 @@ export function createConfigMethods(mongoose: typeof import('mongoose')) {
): Promise<{ config: ConfigRecord; changed: boolean } | null> =>
operations.setActive(toPrincipal(principalType, principalId), isActive, options),
+ /**
+ * Sets only the priority; overrides, tombstones and `isActive` stay. Resolves to the
+ * document and whether this write changed it, or `null` when the principal has none.
+ * A role's document is the one in the caller's tenant partition, as for every write.
+ */
+ setConfigPriority: (
+ principalType: PrincipalType,
+ principalId: ConfigPrincipalId,
+ priority: number,
+ options?: ConfigWriteOptions,
+ ): Promise<ConfigWriteOutcome | null> =>
+ operations.setPriority(toPrincipal(principalType, principalId), priority, options),
+
+ /**
+ * Moves a principal's document to another id of the same type (a role rename) and
+ * returns it as moved, or `null` when there is none to move. Throws a
+ * `ConfigMoveRefusedError`, changing nothing, when the target already has one
+ * (`CONFIG_PRINCIPAL_EXISTS`) or either side is Base (`CONFIG_PRINCIPAL_RESERVED`).
+ *
+ * A role's documents on both sides are the ones in the caller's tenant partition: outside a
+ * tenant only a platform-level document moves, and only a platform-level one at the target
+ * refuses the move, so a tenant's role of the same name keeps its profile. With `identity`
+ * (how a rename undoes its move), only that document moves, and `null` means the source
+ * holds another or none.
+ */
+ renameConfigPrincipal: (
+ principalType: PrincipalType,
+ fromPrincipalId: ConfigPrincipalId,
+ toPrincipalId: ConfigPrincipalId,
+ options?: ConfigMoveOptions,
+ ): Promise<ConfigRecord | null> =>
+ operations.movePrincipal(
+ toPrincipal(principalType, fromPrincipalId),
+ toPrincipal(principalType, toPrincipalId),
+ options,
+ ),
+
/**
* Writes a principal's whole document when it is still at `expected` (`absent`: only when
* none exists). The admin API plans the next document from the one it read, so validation
diff --git a/packages/data-schemas/src/methods/index.ts b/packages/data-schemas/src/methods/index.ts
index f624427bcf..64be35bad8 100644
--- a/packages/data-schemas/src/methods/index.ts
+++ b/packages/data-schemas/src/methods/index.ts
@@ -204,6 +204,7 @@ import {
} from './agent';
/* Config */
import { createConfigMethods, type ConfigMethods } from './config';
+import { createPrincipalMethods, type PrincipalMethods } from './principal';
import {
createMCPAuthorityMethods,
MCPAuthorityProofError,
@@ -317,6 +318,7 @@ export type AllMethods = SubagentContentMethods &
ScheduleMethods &
AgentMethods &
ConfigMethods &
+ PrincipalMethods &
MCPAuthorityMethods &
InsightsMethods;
@@ -566,6 +568,7 @@ export function createMethods(
...agentMethods,
/* Config */
...createConfigMethods(mongoose),
+ ...createPrincipalMethods(mongoose),
/* MCP authority proofs */
...createMCPAuthorityMethods(mongoose),
/* Insights */
@@ -662,6 +665,7 @@ export type {
AgentGraphAccess,
AgentGraphAccessContext,
ConfigMethods,
+ PrincipalMethods,
MCPAuthorityMethods,
MCPAuthorityMethodHooks,
MCPAuthorityConfigSourceDocument,
diff --git a/packages/data-schemas/src/methods/principal.spec.ts b/packages/data-schemas/src/methods/principal.spec.ts
new file mode 100644
index 0000000000..096c75d105
--- /dev/null
+++ b/packages/data-schemas/src/methods/principal.spec.ts
@@ -0,0 +1,141 @@
+import mongoose from 'mongoose';
+import { MongoMemoryServer } from 'mongodb-memory-server';
+import { PrincipalType, SystemRoles } from 'librechat-data-provider';
+import { tenantStorage, runAsSystem } from '~/config/tenantContext';
+import { createPrincipalMethods } from './principal';
+import { createModels } from '~/models';
+
+let mongoServer: MongoMemoryServer;
+let methods: ReturnType<typeof createPrincipalMethods>;
+
+beforeAll(async () => {
+ mongoServer = await MongoMemoryServer.create();
+ await mongoose.connect(mongoServer.getUri());
+ createModels(mongoose);
+ methods = createPrincipalMethods(mongoose);
+});
+
+afterAll(async () => {
+ await mongoose.disconnect();
+ await mongoServer.stop();
+});
+
+beforeEach(async () => {
+ await Promise.all(['Role', 'Group', 'User'].map((name) => mongoose.models[name].deleteMany({})));
+});
+
+const inTenant = <T>(tenantId: string, run: () => Promise<T>): Promise<T> =>
+ tenantStorage.run({ tenantId }, run);
+
+/** A role, group and user, created in the active tenant context (or at platform level). */
+async function seedPrincipals(label: string): Promise<{ groupId: string; userId: string }> {
+ await new mongoose.models.Role({ name: `${label}-role` }).save();
+ const group = await new mongoose.models.Group({ name: `${label} group`, source: 'local' }).save();
+ const user = await new mongoose.models.User({
+ email: `${label}@example.com`,
+ provider: 'local',
+ }).save();
+ return { groupId: group._id.toString(), userId: user._id.toString() };
+}
+
+const existence = ({ groupId, userId }: { groupId: string; userId: string }, label: string) =>
+ Promise.all([
+ methods.principalExists(PrincipalType.ROLE, `${label}-role`),
+ methods.principalExists(PrincipalType.GROUP, groupId),
+ methods.principalExists(PrincipalType.USER, userId),
+ ]);
+
+describe('principalExists', () => {
+ it('finds platform-level principals, and never a tenant one, for a caller without a tenant', async () => {
+ const platform = await seedPrincipals('platform');
+ const tenant = await inTenant('tenant-a', () => seedPrincipals('tenant'));
+
+ expect(await existence(platform, 'platform')).toEqual([true, true, true]);
+ expect(await existence(tenant, 'tenant')).toEqual([false, false, false]);
+ });
+
+ it('finds only the active tenant principals inside a tenant', async () => {
+ const platform = await seedPrincipals('platform');
+ const tenantA = await inTenant('tenant-a', () => seedPrincipals('a'));
+ const tenantB = await inTenant('tenant-b', () => seedPrincipals('b'));
+
+ const [ownA, otherB, platformFromA] = await inTenant('tenant-a', () =>
+ Promise.all([
+ existence(tenantA, 'a'),
+ existence(tenantB, 'b'),
+ existence(platform, 'platform'),
+ ]),
+ );
+
+ expect(ownA).toEqual([true, true, true]);
+ expect(otherB).toEqual([false, false, false]);
+ expect(platformFromA).toEqual([false, false, false]);
+ });
+
+ it('treats an unclaimed principal (null or empty tenant) as platform-level', async () => {
+ const unclaimed = await seedPrincipals('unclaimed');
+ await Promise.all([
+ mongoose.models.Role.collection.updateOne(
+ { name: 'unclaimed-role' },
+ { $set: { tenantId: null } },
+ ),
+ mongoose.models.Group.collection.updateOne(
+ { _id: new mongoose.Types.ObjectId(unclaimed.groupId) },
+ { $set: { tenantId: '' } },
+ ),
+ ]);
+
+ expect(await existence(unclaimed, 'unclaimed')).toEqual([true, true, true]);
+ });
+
+ it('matches a role by its exact name only', async () => {
+ await new mongoose.models.Role({ name: 'Editor' }).save();
+
+ expect(await methods.principalExists(PrincipalType.ROLE, 'Editor')).toBe(true);
+ expect(await methods.principalExists(PrincipalType.ROLE, 'editor')).toBe(false);
+ expect(await methods.principalExists(PrincipalType.ROLE, 'Edit.*')).toBe(false);
+ });
+
+ it('counts the system roles as existing without creating their documents', async () => {
+ const found = await inTenant('tenant-a', () =>
+ Promise.all(
+ Object.values(SystemRoles).map((name) => methods.principalExists(PrincipalType.ROLE, name)),
+ ),
+ );
+
+ expect(found.every(Boolean)).toBe(true);
+ expect(await runAsSystem(() => mongoose.models.Role.countDocuments({}))).toBe(0);
+ });
+
+ it('refuses an uppercase spelling of a real group or user id, which config lookups never match', async () => {
+ const groupId = 'a1b2c3d4e5f6a1b2c3d4e5f6';
+ const userId = 'f6e5d4c3b2a1f6e5d4c3b2a1';
+ await new mongoose.models.Group({ _id: groupId, name: 'upper group', source: 'local' }).save();
+ await new mongoose.models.User({
+ _id: userId,
+ email: '[email protected]',
+ provider: 'local',
+ }).save();
+ const groupFind = jest.spyOn(mongoose.models.Group, 'findOne');
+ const userFind = jest.spyOn(mongoose.models.User, 'findOne');
+
+ expect(await methods.principalExists(PrincipalType.GROUP, groupId.toUpperCase())).toBe(false);
+ expect(await methods.principalExists(PrincipalType.USER, userId.toUpperCase())).toBe(false);
+ expect(groupFind).not.toHaveBeenCalled();
+ expect(userFind).not.toHaveBeenCalled();
+ expect(await methods.principalExists(PrincipalType.GROUP, groupId)).toBe(true);
+ expect(await methods.principalExists(PrincipalType.USER, userId)).toBe(true);
+ groupFind.mockRestore();
+ userFind.mockRestore();
+ });
+
+ it('answers false without a query for an id that cannot name a group or user', async () => {
+ const findOne = jest.spyOn(mongoose.models.Group, 'findOne');
+
+ expect(await methods.principalExists(PrincipalType.GROUP, 'grp_engineering')).toBe(false);
+ expect(await methods.principalExists(PrincipalType.USER, 'not-an-id')).toBe(false);
+ expect(await methods.principalExists(PrincipalType.PUBLIC, 'anyone')).toBe(false);
+ expect(findOne).not.toHaveBeenCalled();
+ findOne.mockRestore();
+ });
+});
diff --git a/packages/data-schemas/src/methods/principal.ts b/packages/data-schemas/src/methods/principal.ts
new file mode 100644
index 0000000000..690bd1e43e
--- /dev/null
+++ b/packages/data-schemas/src/methods/principal.ts
@@ -0,0 +1,57 @@
+import { PrincipalType, SystemRoles } from 'librechat-data-provider';
+import type { Model } from 'mongoose';
+import { tenantPartitionFilter } from '~/models/plugins/tenantIsolation';
+import { isCanonicalObjectIdString } from '~/utils/objectId';
+
+const systemRoleNames: ReadonlySet<string> = new Set(Object.values(SystemRoles));
+
+export interface PrincipalMethods {
+ principalExists: (principalType: PrincipalType, principalId: string) => Promise<boolean>;
+}
+
+/** Principal lookups that stay in the caller's tenant partition. */
+export function createPrincipalMethods(mongoose: typeof import('mongoose')): PrincipalMethods {
+ async function existsInPartition(
+ modelName: 'Role' | 'Group' | 'User',
+ filter: { name: string } | { _id: string },
+ ): Promise<boolean> {
+ const model = mongoose.models[modelName] as Model<{ name?: string; tenantId?: string }>;
+ const found = await model
+ .findOne({ ...filter, ...tenantPartitionFilter('principalExists') })
+ .select('_id')
+ .lean();
+ return found != null;
+ }
+
+ /**
+ * Whether a role (by its exact name), group or user (by ObjectId) exists in the caller's
+ * tenant partition (`tenantPartitionFilter`): the active tenant's principals, or outside a
+ * tenant only platform-level ones, never one that only some tenant holds. The system roles
+ * always exist, since `getRoleByName` creates them on first use; this lookup creates nothing
+ * and reads no cache. Any other type, or an id that cannot name a group or user, is `false`:
+ * a group or user id must be canonical (lowercase hex, as `ObjectId#toString()` writes it),
+ * because config documents and merges match the id as a string, and an uppercase spelling
+ * that the database would still cast to the same ObjectId names a profile that never applies.
+ */
+ async function principalExists(
+ principalType: PrincipalType,
+ principalId: string,
+ ): Promise<boolean> {
+ switch (principalType) {
+ case PrincipalType.ROLE:
+ return systemRoleNames.has(principalId) || existsInPartition('Role', { name: principalId });
+ case PrincipalType.GROUP:
+ return (
+ isCanonicalObjectIdString(principalId) && existsInPartition('Group', { _id: principalId })
+ );
+ case PrincipalType.USER:
+ return (
+ isCanonicalObjectIdString(principalId) && existsInPartition('User', { _id: principalId })
+ );
+ default:
+ return false;
+ }
+ }
+
+ return { principalExists };
+}
diff --git a/packages/data-schemas/src/methods/role.methods.spec.ts b/packages/data-schemas/src/methods/role.methods.spec.ts
index 6efa0bdcce..1e9c40bfc9 100644
--- a/packages/data-schemas/src/methods/role.methods.spec.ts
+++ b/packages/data-schemas/src/methods/role.methods.spec.ts
@@ -1150,6 +1150,22 @@ describe('updateUsersRoleByIds', () => {
`${AUTH_USER_DOC_BY_ID_PREFIX}:${bob._id.toString()}`,
);
});
+
+ it('with fromRole, changes only the users still on that role', async () => {
+ const [alice, bob] = await User.create([
+ { name: 'Alice', email: '[email protected]', role: 'writer', username: 'alice' },
+ { name: 'Bob', email: '[email protected]', role: 'viewer', username: 'bob' },
+ ]);
+
+ await updateUsersRoleByIds([alice._id.toString(), bob._id.toString()], 'editor', {
+ fromRole: 'writer',
+ });
+
+ const roles = await User.find({ _id: { $in: [alice._id, bob._id] } })
+ .sort({ username: 1 })
+ .lean();
+ expect(roles.map((user) => user.role)).toEqual(['editor', 'viewer']);
+ });
});
describe('countUsersByRole', () => {
diff --git a/packages/data-schemas/src/methods/role.ts b/packages/data-schemas/src/methods/role.ts
index 3b9a24da9f..250bae2777 100644
--- a/packages/data-schemas/src/methods/role.ts
+++ b/packages/data-schemas/src/methods/role.ts
@@ -60,7 +60,11 @@ export function createRoleMethods(
deleteRoleByName: (roleName: string, options?: { id?: string }) => Promise<IRole | null>;
updateUsersByRole: (oldRole: string, newRole: string) => Promise<void>;
findUserIdsByRole: (roleName: string) => Promise<string[]>;
- updateUsersRoleByIds: (userIds: string[], newRole: string) => Promise<void>;
+ updateUsersRoleByIds: (
+ userIds: string[],
+ newRole: string,
+ options?: { fromRole?: string },
+ ) => Promise<void>;
listUsersByRole: (
roleName: string,
options?: { limit?: number; offset?: number },
@@ -547,12 +551,26 @@ export function createRoleMethods(
return users.map((u) => u._id.toString());
}
- async function updateUsersRoleByIds(userIds: string[], newRole: string): Promise<void> {
+ /**
+ * Sets the role of the given users. With `fromRole`, only users whose role is still that one
+ * change, so undoing a migration never overwrites a reassignment made since.
+ */
+ async function updateUsersRoleByIds(
+ userIds: string[],
+ newRole: string,
+ options?: { fromRole?: string },
+ ): Promise<void> {
if (userIds.length === 0) {
return;
}
const User = mongoose.models.User as Model<IUser>;
- await User.updateMany({ _id: { $in: userIds } }, { $set: { role: newRole } });
+ await User.updateMany(
+ {
+ _id: { $in: userIds },
+ ...(options?.fromRole !== undefined ? { role: options.fromRole } : {}),
+ },
+ { $set: { role: newRole } },
+ );
await invalidateAuthUserDocCache(userIds);
}
diff --git a/packages/data-schemas/src/methods/systemGrant.spec.ts b/packages/data-schemas/src/methods/systemGrant.spec.ts
index 867805097b..82497c4d3f 100644
--- a/packages/data-schemas/src/methods/systemGrant.spec.ts
+++ b/packages/data-schemas/src/methods/systemGrant.spec.ts
@@ -790,6 +790,233 @@ describe('systemGrant methods', () => {
});
});
+ describe('moveGrantsToPrincipal', () => {
+ const grant = (principalId: string, capability: SystemCapability, tenantId?: string) =>
+ methods.grantCapability({
+ principalType: PrincipalType.ROLE,
+ principalId,
+ capability,
+ tenantId,
+ });
+
+ const held = async (principalId: string) =>
+ (
+ await SystemGrant.find({ principalType: PrincipalType.ROLE, principalId })
+ .sort({ capability: 1, tenantId: 1 })
+ .lean()
+ ).map((g) => `${g.tenantId ?? '-'}:${g.capability}`);
+
+ it('re-keys every grant to the new name, keeping identity and history', async () => {
+ const { grant: readUsers } = await grant('editor', SystemCapabilities.READ_USERS);
+ await grant('editor', SystemCapabilities.READ_CONFIGS);
+
+ const move = await methods.moveGrantsToPrincipal(PrincipalType.ROLE, 'editor', 'writer');
+
+ expect(move.moved.map((g) => g.capability).sort()).toEqual(
+ [SystemCapabilities.READ_CONFIGS, SystemCapabilities.READ_USERS].sort(),
+ );
+ expect(move.superseded).toEqual([]);
+ expect(await held('editor')).toEqual([]);
+ expect(await held('writer')).toEqual(
+ [`-:${SystemCapabilities.READ_CONFIGS}`, `-:${SystemCapabilities.READ_USERS}`].sort(),
+ );
+ const after = await SystemGrant.findById(readUsers?._id).lean();
+ expect(after?.principalId).toBe('writer');
+ expect(after?.grantedAt).toEqual(readUsers?.grantedAt);
+ });
+
+ it('moves only the caller tenant grants when a tenant is given, like the delete cascade', async () => {
+ await grant('editor', SystemCapabilities.READ_USERS, 'tenant-a');
+ await grant('editor', SystemCapabilities.READ_USERS, 'tenant-b');
+ await grant('editor', SystemCapabilities.READ_CONFIGS);
+
+ await methods.moveGrantsToPrincipal(PrincipalType.ROLE, 'editor', 'writer', {
+ tenantId: 'tenant-a',
+ });
+
+ expect(await held('writer')).toEqual([`tenant-a:${SystemCapabilities.READ_USERS}`]);
+ expect(await held('editor')).toEqual(
+ [
+ `-:${SystemCapabilities.READ_CONFIGS}`,
+ `tenant-b:${SystemCapabilities.READ_USERS}`,
+ ].sort(),
+ );
+ });
+
+ it('moves only platform-level grants when no tenant is given, unlike the delete cascade', async () => {
+ await grant('editor', SystemCapabilities.READ_USERS, 'tenant-a');
+ await grant('editor', SystemCapabilities.READ_CONFIGS);
+ await grant('writer', SystemCapabilities.READ_USERS, 'tenant-a');
+
+ const move = await methods.moveGrantsToPrincipal(PrincipalType.ROLE, 'editor', 'writer');
+
+ expect(move.moved.map((g) => g.capability)).toEqual([SystemCapabilities.READ_CONFIGS]);
+ expect(await held('editor')).toEqual([`tenant-a:${SystemCapabilities.READ_USERS}`]);
+ expect(await held('writer')).toEqual(
+ [
+ `-:${SystemCapabilities.READ_CONFIGS}`,
+ `tenant-a:${SystemCapabilities.READ_USERS}`,
+ ].sort(),
+ );
+ });
+
+ it('drops a grant the new name already holds instead of colliding on the unique index', async () => {
+ await grant('editor', SystemCapabilities.READ_USERS);
+ await grant('editor', SystemCapabilities.READ_CONFIGS);
+ await grant('writer', SystemCapabilities.READ_USERS);
+
+ const move = await methods.moveGrantsToPrincipal(PrincipalType.ROLE, 'editor', 'writer');
+
+ expect(move.moved.map((g) => g.capability)).toEqual([SystemCapabilities.READ_CONFIGS]);
+ expect(move.superseded.map((g) => g.capability)).toEqual([SystemCapabilities.READ_USERS]);
+ expect(await held('editor')).toEqual([]);
+ expect(await held('writer')).toEqual(
+ [`-:${SystemCapabilities.READ_CONFIGS}`, `-:${SystemCapabilities.READ_USERS}`].sort(),
+ );
+ });
+
+ it('returns nothing and writes nothing for a principal without grants', async () => {
+ await grant('writer', SystemCapabilities.READ_USERS);
+
+ expect(await methods.moveGrantsToPrincipal(PrincipalType.ROLE, 'none', 'writer')).toEqual({
+ moved: [],
+ superseded: [],
+ });
+ expect(await held('writer')).toEqual([`-:${SystemCapabilities.READ_USERS}`]);
+ });
+
+ it('restores the source exactly, leaving grants the target held before untouched', async () => {
+ const { grant: readUsers } = await grant('editor', SystemCapabilities.READ_USERS);
+ const { grant: readConfigs } = await grant('editor', SystemCapabilities.READ_CONFIGS);
+ await grant('writer', SystemCapabilities.READ_USERS);
+
+ const move = await methods.moveGrantsToPrincipal(PrincipalType.ROLE, 'editor', 'writer');
+ await methods.restoreMovedGrants(PrincipalType.ROLE, 'editor', 'writer', move);
+
+ expect(await held('editor')).toEqual(
+ [`-:${SystemCapabilities.READ_CONFIGS}`, `-:${SystemCapabilities.READ_USERS}`].sort(),
+ );
+ expect(await held('writer')).toEqual([`-:${SystemCapabilities.READ_USERS}`]);
+ const restored = await SystemGrant.find({ principalId: 'editor' }).lean();
+ expect(restored.map((g) => g._id.toString()).sort()).toEqual(
+ [readUsers?._id.toString(), readConfigs?._id.toString()].sort(),
+ );
+ });
+
+ it('never re-creates a moved grant that was revoked before the undo', async () => {
+ await grant('editor', SystemCapabilities.READ_USERS);
+ await grant('editor', SystemCapabilities.READ_CONFIGS);
+
+ const move = await methods.moveGrantsToPrincipal(PrincipalType.ROLE, 'editor', 'writer');
+ await methods.revokeCapability({
+ principalType: PrincipalType.ROLE,
+ principalId: 'writer',
+ capability: SystemCapabilities.READ_USERS,
+ });
+ await methods.restoreMovedGrants(PrincipalType.ROLE, 'editor', 'writer', move);
+
+ expect(await held('editor')).toEqual([`-:${SystemCapabilities.READ_CONFIGS}`]);
+ expect(await held('writer')).toEqual([]);
+ });
+
+ it('never reports or re-creates a grant revoked between its snapshot and the move', async () => {
+ await grant('editor', SystemCapabilities.READ_USERS);
+ await grant('editor', SystemCapabilities.READ_CONFIGS);
+ await grant('writer', SystemCapabilities.READ_USERS);
+ const findOneAndDelete = SystemGrant.findOneAndDelete.bind(SystemGrant);
+ /** Another admin revokes the superseded grant after the move read it, before it is removed. */
+ jest.spyOn(SystemGrant, 'findOneAndDelete').mockImplementationOnce(((
+ ...args: Parameters<typeof SystemGrant.findOneAndDelete>
+ ) => ({
+ lean: () => ({
+ exec: () =>
+ methods
+ .revokeCapability({
+ principalType: PrincipalType.ROLE,
+ principalId: 'editor',
+ capability: SystemCapabilities.READ_USERS,
+ })
+ .then(() =>
+ findOneAndDelete(...args)
+ .lean()
+ .exec(),
+ ),
+ }),
+ })) as never);
+
+ const move = await methods.moveGrantsToPrincipal(PrincipalType.ROLE, 'editor', 'writer');
+ await methods.restoreMovedGrants(PrincipalType.ROLE, 'editor', 'writer', move);
+
+ expect(move.superseded).toEqual([]);
+ expect(await held('editor')).toEqual([`-:${SystemCapabilities.READ_CONFIGS}`]);
+ expect(await held('writer')).toEqual([`-:${SystemCapabilities.READ_USERS}`]);
+ });
+
+ it('re-creates a superseded grant only while the new name still holds the one that superseded it', async () => {
+ await grant('editor', SystemCapabilities.READ_USERS);
+ await grant('editor', SystemCapabilities.READ_CONFIGS);
+ await grant('writer', SystemCapabilities.READ_USERS);
+ await grant('writer', SystemCapabilities.READ_CONFIGS);
+
+ const move = await methods.moveGrantsToPrincipal(PrincipalType.ROLE, 'editor', 'writer');
+ await methods.revokeCapability({
+ principalType: PrincipalType.ROLE,
+ principalId: 'writer',
+ capability: SystemCapabilities.READ_USERS,
+ });
+ await methods.restoreMovedGrants(PrincipalType.ROLE, 'editor', 'writer', move);
+
+ expect(move.superseded).toHaveLength(2);
+ expect(await held('editor')).toEqual([`-:${SystemCapabilities.READ_CONFIGS}`]);
+ expect(await held('writer')).toEqual([`-:${SystemCapabilities.READ_CONFIGS}`]);
+ });
+
+ it('undoes a move that fails part-way before rethrowing', async () => {
+ await grant('editor', SystemCapabilities.READ_USERS);
+ await grant('editor', SystemCapabilities.READ_CONFIGS);
+ await grant('writer', SystemCapabilities.READ_USERS);
+ const failure = new Error('write interrupted');
+ const updateMany = jest.spyOn(SystemGrant, 'updateMany').mockRejectedValueOnce(failure);
+
+ await expect(
+ methods.moveGrantsToPrincipal(PrincipalType.ROLE, 'editor', 'writer'),
+ ).rejects.toBe(failure);
+ updateMany.mockRestore();
+
+ expect(await held('editor')).toEqual(
+ [`-:${SystemCapabilities.READ_CONFIGS}`, `-:${SystemCapabilities.READ_USERS}`].sort(),
+ );
+ expect(await held('writer')).toEqual([`-:${SystemCapabilities.READ_USERS}`]);
+ });
+
+ it('logs the grant ids, never the error text, when the undo of a failed move fails too', async () => {
+ const { grant: readUsers } = await grant('editor', SystemCapabilities.READ_USERS);
+ const failure = new Error('write interrupted');
+ const updateMany = jest
+ .spyOn(SystemGrant, 'updateMany')
+ .mockRejectedValueOnce(failure)
+ .mockRejectedValueOnce(new Error('undo failed near {"principalId":"editor"}'));
+ (logger.error as jest.Mock).mockClear();
+
+ await expect(
+ methods.moveGrantsToPrincipal(PrincipalType.ROLE, 'editor', 'writer'),
+ ).rejects.toBe(failure);
+ updateMany.mockRestore();
+
+ expect(logger.error).toHaveBeenCalledWith(
+ '[moveGrantsToPrincipal] undo after a failed move failed',
+ {
+ principalType: PrincipalType.ROLE,
+ fromPrincipalId: 'editor',
+ toPrincipalId: 'writer',
+ grantIds: readUsers?._id.toString(),
+ errName: 'Error',
+ errCode: null,
+ },
+ );
+ });
+ });
+
describe('deleteGrantsForPrincipal', () => {
it('deletes all grants for a principal', async () => {
const groupId = new Types.ObjectId();
diff --git a/packages/data-schemas/src/methods/systemGrant.ts b/packages/data-schemas/src/methods/systemGrant.ts
index e49d166d61..d20a34d9ca 100644
--- a/packages/data-schemas/src/methods/systemGrant.ts
+++ b/packages/data-schemas/src/methods/systemGrant.ts
@@ -1,10 +1,11 @@
import { PrincipalType, SystemRoles } from 'librechat-data-provider';
import type { Types, Model, ClientSession, FilterQuery } from 'mongoose';
+import type { ISystemGrant, SystemGrantMove } from '~/types';
import type { SystemCapability } from '~/types/admin';
-import type { ISystemGrant } from '~/types';
import { SystemCapabilities, CapabilityImplications } from '~/admin/capabilities';
import { tenantSafeBulkWrite } from '~/utils/tenantBulkWrite';
import { normalizePrincipalId } from '~/utils/principal';
+import { getSafeErrorFields } from '~/utils/errors';
import logger from '~/config/winston';
/**
@@ -144,6 +145,18 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
principalId: string | Types.ObjectId,
options?: { tenantId?: string },
) => Promise<ISystemGrant[]>;
+ moveGrantsToPrincipal: (
+ principalType: PrincipalType,
+ fromPrincipalId: string | Types.ObjectId,
+ toPrincipalId: string | Types.ObjectId,
+ options?: { tenantId?: string },
+ ) => Promise<SystemGrantMove>;
+ restoreMovedGrants: (
+ principalType: PrincipalType,
+ fromPrincipalId: string | Types.ObjectId,
+ toPrincipalId: string | Types.ObjectId,
+ move: SystemGrantMove,
+ ) => Promise<void>;
} {
function tenantCondition(tenantId?: string): FilterQuery<ISystemGrant> {
return tenantId != null
@@ -609,6 +622,164 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
}).lean<ISystemGrant[]>();
}
+ /** One grant per principal, capability and tenant scope (the unique index); platform-level is ''. */
+ function grantScopeKey(grant: Pick<ISystemGrant, 'capability' | 'tenantId'>): string {
+ return `${grant.tenantId ?? ''}\u0000${grant.capability}`;
+ }
+
+ /** The capability scopes (`grantScopeKey`) among `grants` that `principalId` holds now. */
+ async function findHeldScopes(
+ principalType: PrincipalType,
+ principalId: string | Types.ObjectId,
+ grants: readonly Pick<ISystemGrant, 'capability' | 'tenantId'>[],
+ ): Promise<Set<string>> {
+ const SystemGrant = mongoose.models.SystemGrant as Model<ISystemGrant>;
+ const held = await SystemGrant.find({
+ principalType,
+ principalId,
+ capability: { $in: [...new Set(grants.map((grant) => grant.capability))] },
+ })
+ .select('capability tenantId')
+ .lean<Array<Pick<ISystemGrant, 'capability' | 'tenantId'>>>();
+ return new Set(held.map(grantScopeKey));
+ }
+
+ /**
+ * 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
+ * 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.
+ *
+ * Returns what it changed, to audit the move or undo it with {@link restoreMovedGrants}: the
+ * grants it re-keyed, and only the superseded grants whose removal it confirmed (a grant
+ * revoked by someone else meanwhile is not among them). A move that fails part-way is undone
+ * the same way before it rethrows; an undo that fails too, or a removal that cannot be
+ * confirmed, is logged with the grant ids.
+ */
+ async function moveGrantsToPrincipal(
+ principalType: PrincipalType,
+ fromPrincipalId: string | Types.ObjectId,
+ toPrincipalId: string | Types.ObjectId,
+ 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,
+ }).lean<ISystemGrant[]>();
+ if (grants.length === 0) {
+ return { moved: [], superseded: [] };
+ }
+ const target = normalizePrincipalId(toPrincipalId, principalType);
+ const heldKeys = await findHeldScopes(principalType, target, grants);
+ const moved: ISystemGrant[] = [];
+ const supersedable: ISystemGrant[] = [];
+ for (const grant of grants) {
+ (heldKeys.has(grantScopeKey(grant)) ? supersedable : moved).push(grant);
+ }
+ const superseded: ISystemGrant[] = [];
+ try {
+ const removals = await Promise.allSettled(
+ supersedable.map((grant) =>
+ SystemGrant.findOneAndDelete({ _id: grant._id, principalType, principalId: source })
+ .lean<ISystemGrant>()
+ .exec(),
+ ),
+ );
+ const unconfirmed: string[] = [];
+ let failure: unknown;
+ removals.forEach((removal, index) => {
+ if (removal.status === 'fulfilled') {
+ if (removal.value) {
+ superseded.push(removal.value);
+ }
+ return;
+ }
+ failure ??= removal.reason;
+ unconfirmed.push(supersedable[index]._id.toString());
+ });
+ if (unconfirmed.length > 0) {
+ logger.error('[moveGrantsToPrincipal] removal of superseded grants not confirmed', {
+ principalType,
+ fromPrincipalId: fromPrincipalId.toString(),
+ toPrincipalId: toPrincipalId.toString(),
+ grantIds: unconfirmed.join(','),
+ });
+ throw failure;
+ }
+ if (moved.length > 0) {
+ await SystemGrant.updateMany(
+ { _id: { $in: moved.map((grant) => grant._id) }, principalType, principalId: source },
+ { $set: { principalId: target } },
+ );
+ }
+ } catch (error) {
+ const undo = { moved, superseded };
+ await restoreMovedGrants(principalType, fromPrincipalId, toPrincipalId, undo).catch(
+ (restoreError: unknown) =>
+ logger.error('[moveGrantsToPrincipal] undo after a failed move failed', {
+ principalType,
+ fromPrincipalId: fromPrincipalId.toString(),
+ toPrincipalId: toPrincipalId.toString(),
+ grantIds: [...moved, ...superseded].map((grant) => grant._id.toString()).join(','),
+ ...getSafeErrorFields(restoreError),
+ }),
+ );
+ throw error;
+ }
+ return { moved, superseded };
+ }
+
+ /**
+ * Undoes {@link moveGrantsToPrincipal}, and only what it changed: each grant it re-keyed goes
+ * back to `fromPrincipalId` by identity while it is still at `toPrincipalId`, and each grant
+ * it removed as superseded is re-created as it was while the target still holds the grant
+ * that superseded it. A grant revoked meanwhile, from either name, stays revoked, and a grant
+ * on the target that the move did not bring is left alone.
+ */
+ async function restoreMovedGrants(
+ principalType: PrincipalType,
+ fromPrincipalId: string | Types.ObjectId,
+ toPrincipalId: string | Types.ObjectId,
+ move: SystemGrantMove,
+ ): Promise<void> {
+ const SystemGrant = mongoose.models.SystemGrant as Model<ISystemGrant>;
+ const source = normalizePrincipalId(fromPrincipalId, principalType);
+ const target = normalizePrincipalId(toPrincipalId, principalType);
+ if (move.moved.length > 0) {
+ await SystemGrant.updateMany(
+ { _id: { $in: move.moved.map((grant) => grant._id) }, principalType, principalId: target },
+ { $set: { principalId: source } },
+ );
+ }
+ if (move.superseded.length === 0) {
+ return;
+ }
+ const heldKeys = await findHeldScopes(principalType, target, move.superseded);
+ await Promise.all(
+ move.superseded
+ .filter((grant) => heldKeys.has(grantScopeKey(grant)))
+ .map((grant) =>
+ SystemGrant.updateOne(
+ {
+ principalType,
+ principalId: source,
+ capability: grant.capability,
+ tenantId: grant.tenantId != null ? grant.tenantId : { $exists: false },
+ },
+ { $setOnInsert: { ...grant, principalId: source } },
+ { upsert: true, timestamps: false },
+ ),
+ ),
+ );
+ }
+
return {
grantCapability,
seedSystemGrants,
@@ -622,6 +793,8 @@ export function createSystemGrantMethods(mongoose: typeof import('mongoose')): {
getCapabilitiesForPrincipals,
deleteGrantsForPrincipal,
findGrantsForPrincipal,
+ moveGrantsToPrincipal,
+ restoreMovedGrants,
};
}
diff --git a/packages/data-schemas/src/types/admin.ts b/packages/data-schemas/src/types/admin.ts
index 64c9397876..5d46ab74dc 100644
--- a/packages/data-schemas/src/types/admin.ts
+++ b/packages/data-schemas/src/types/admin.ts
@@ -142,8 +142,10 @@ export type AdminConfigChangesRequest = AdminConfigWritePrecondition & {
ops: AdminConfigChangeOp[];
/**
* Broad `manage:configs` only; anyone else's is ignored and the stored priority kept. A new
- * priority is written even when no change alters the document, and on a principal without
- * one it creates a document that holds only the priority, as PUT does.
+ * priority is written even when no change alters the document, and on an existing principal
+ * without one it creates a document that holds only the priority, as PUT does. A batch for a
+ * principal with no document that does not exist answers 404 `PRINCIPAL_NOT_FOUND`, a dry
+ * run included.
*/
priority?: number;
/** Validate and report without writing. */
@@ -281,6 +283,31 @@ export type AdminConfigChangeErrorResponse = {
* principal's config cannot be read, every hideable server is withheld. Process-backed
* (`stdio`) and Agent Plugins servers cannot be hidden, and deleting the tombstone shows the
* server again.
+ * - `deterministicPrecedence`: config documents merge in one fixed order, the last winning:
+ * Base (`role` / `__base__`) first whatever its priority, then ascending `priority`, then
+ * role < group < user on equal priority, then document `_id`; `GET /` lists them in that
+ * order. A write (PUT, PATCH `/fields`, POST `/fields/tombstone` or `/changes`) that creates
+ * a document without `priority` gives it its principal type's default (role 10, group 20,
+ * user 100; Base 0), and a write that omits `priority` keeps the stored one, so a PUT no
+ * longer resets it. A profile write validates on `librechat.yaml` with the active Base
+ * document resolved over it, as the merge applies it; when Base changes before the write
+ * commits, the write is judged on that Base, and taken back (400) when it fails there.
+ * - `priorityRoute`: PATCH `/:principalType/:principalId/priority` `{ priority,
+ * expectedRevision? }` sets only the priority (overrides, tombstones and `isActive` stay),
+ * for broad `manage:configs` only. No document answers 404 `CONFIG_NOT_FOUND`, an invalid
+ * priority 400 `INVALID_PRIORITY`; an unchanged priority is neither written nor audited.
+ * - `principalCheck`: a write that would create a principal's first document (PUT, PATCH
+ * `/fields`, POST `/fields/tombstone` or `/changes`, including a dry run or a batch that only
+ * sets a priority) answers 404 `PRINCIPAL_NOT_FOUND` unless the role (by exact name), group
+ * or user (by lowercase ObjectId) exists in the caller's tenant (outside a tenant, at
+ * platform level). A PUT with `expectedRevision: 'absent'` creates the profile even with no
+ * overrides: 201, or 409 `CONFIG_VERSION_CONFLICT` when one exists.
+ * - `roleRenameMovesProfile`: renaming a role (PATCH `/api/admin/roles/:name`) moves its
+ * config profile, system grants and ACL entries to the new name in the caller's tenant, or
+ * undoes every step and answers 500 `ROLE_RENAME_FAILED`; the undo takes back only what the
+ * rename changed, so a grant revoked or a member reassigned meanwhile stays that way. A profile already held by the new
+ * name answers 409 `ROLE_CONFIG_CONFLICT`, and the Base principal id is a reserved role name
+ * (400 `ROLE_NAME_RESERVED`).
*/
export type AdminConfigFeatureFlag =
| 'dottedKeys'
@@ -292,7 +319,11 @@ export type AdminConfigFeatureFlag =
| 'prunesEmptyParents'
| 'awaitedInvalidation'
| 'changesBatch'
- | 'yamlMcpHide';
+ | 'yamlMcpHide'
+ | 'deterministicPrecedence'
+ | 'priorityRoute'
+ | 'principalCheck'
+ | 'roleRenameMovesProfile';
export type AdminConfigFeatures = Record<AdminConfigFeatureFlag, boolean>;
diff --git a/packages/data-schemas/src/types/systemGrant.ts b/packages/data-schemas/src/types/systemGrant.ts
index 09cff1aec6..7948185d56 100644
--- a/packages/data-schemas/src/types/systemGrant.ts
+++ b/packages/data-schemas/src/types/systemGrant.ts
@@ -1,5 +1,5 @@
-import type { Document, Types } from 'mongoose';
import type { PrincipalType } from 'librechat-data-provider';
+import type { Document, Types } from 'mongoose';
import type { SystemCapability } from '~/types/admin';
export type SystemGrant = {
@@ -23,3 +23,13 @@ export type ISystemGrant = SystemGrant &
Document & {
_id: Types.ObjectId;
};
+
+/**
+ * What `moveGrantsToPrincipal` changed, as the grants were before it: the grants it re-keyed to
+ * the new principal, and the ones it removed because the new principal already held the same
+ * capability in the same tenant scope. `restoreMovedGrants` undoes exactly these.
+ */
+export type SystemGrantMove = {
+ moved: ISystemGrant[];
+ superseded: ISystemGrant[];
+};
diff --git a/packages/data-schemas/src/utils/errors.ts b/packages/data-schemas/src/utils/errors.ts
new file mode 100644
index 0000000000..d7900d54ec
--- /dev/null
+++ b/packages/data-schemas/src/utils/errors.ts
@@ -0,0 +1,15 @@
+/** What a log may keep of a failure: an error's message can echo query text, filters or connection details. */
+export interface SafeErrorFields {
+ errName: string;
+ errCode: string | number | null;
+}
+
+/** The failure's name and driver code, never its message or stack. */
+export function getSafeErrorFields(error: unknown): SafeErrorFields {
+ const code =
+ error != null && typeof error === 'object' ? (error as { code?: unknown }).code : null;
+ return {
+ errName: error instanceof Error ? error.name : typeof error,
+ errCode: typeof code === 'string' || typeof code === 'number' ? code : null,
+ };
+}
diff --git a/packages/data-schemas/src/utils/objectId.ts b/packages/data-schemas/src/utils/objectId.ts
index c368c47371..48b9e16562 100644
--- a/packages/data-schemas/src/utils/objectId.ts
+++ b/packages/data-schemas/src/utils/objectId.ts
@@ -1,2 +1,9 @@
/** Returns true when `id` is a 24-character hex string (MongoDB ObjectId format). */
export const isValidObjectIdString = (id: string): boolean => /^[a-f\d]{24}$/i.test(id);
+
+/**
+ * Returns true when `id` is an ObjectId exactly as `ObjectId#toString()` writes it: 24 lowercase
+ * hex characters. Ids stored as strings (config `principalId`s) are matched by string equality,
+ * so an uppercase spelling of a real id names a document no lookup will ever find.
+ */
+export const isCanonicalObjectIdString = (id: string): boolean => /^[a-f\d]{24}$/.test(id);