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: Reject Unknown Admin Config Sections and Scope Write Responses to Read Access (#17315)

Danny Avilaa3e842658897
diff --git a/api/server/experimental.js b/api/server/experimental.js
index cad00b256c..5290cfac98 100644
--- a/api/server/experimental.js
+++ b/api/server/experimental.js
@@ -497,24 +497,24 @@ if (cluster.isMaster) {
logger.error('[sweepOrphanedPreviews] Background sweep failed:', err);
});
- /** Initialize app configuration */
- const appConfig = await getAppConfig();
+ /**
+ * Boot reads librechat.yaml only, as `server/index.js` does. File storage, skill sync and
+ * deletion, the expired-file sweep, tool-approval hooks and the other worker-wide settings
+ * below are fixed for the process lifetime, so DB `__base__` overrides must not decide them.
+ */
+ const appConfig = await getAppConfig({ baseOnly: true });
initializeFileStorage(appConfig);
initializeGitHubSkillSync(appConfig);
startSkillDeletionSweep(appConfig.skillDeletion);
// Register configured tool-approval policy hooks (mirrors the standard startup path).
- // Honors the `enabled` kill switch; hooks are base-config-only, registered process-wide.
- // Read from the BASE config specifically — `appConfig` above (getAppConfig() with no
- // principal) still merges DB `__base__` overrides, which must not drive which hook
- // modules load in every worker (matches api/server/index.js's baseOnly usage).
- const baseAppConfig = await getAppConfig({ baseOnly: true });
- await configureSubagentTaskRouting(baseAppConfig?.endpoints?.agents?.subagentActivity);
+ // Honors the `enabled` kill switch; hooks are registered process-wide.
+ await configureSubagentTaskRouting(appConfig?.endpoints?.agents?.subagentActivity);
registerBackgroundTaskShutdown({
- interruptGraceMs: baseAppConfig?.endpoints?.agents?.backgroundTasks?.shutdownInterruptGraceMs,
+ interruptGraceMs: appConfig?.endpoints?.agents?.backgroundTasks?.shutdownInterruptGraceMs,
getBudgetMs: clusterShutdownBudgetMs,
});
- configureAgentEventRuntime(baseAppConfig?.endpoints?.agents?.eventDriven);
- const toolApproval = baseAppConfig?.endpoints?.agents?.toolApproval;
+ configureAgentEventRuntime(appConfig?.endpoints?.agents?.eventDriven);
+ const toolApproval = appConfig?.endpoints?.agents?.toolApproval;
await loadToolApprovalHooks(toolApproval?.enabled ? toolApproval.hooks : undefined, {
basePath: path.resolve(__dirname, '../..'),
});
@@ -555,13 +555,13 @@ if (cluster.isMaster) {
so the answer is the deployment's base configuration, like index.js. */
indexHTML = injectConfiguredFooterBootstrap(indexHTML, {
customFooter: process.env.CUSTOM_FOOTER,
- landingFooter: baseAppConfig?.interfaceConfig?.landingFooter,
+ landingFooter: appConfig?.interfaceConfig?.landingFooter,
});
- indexHTML = injectColorModeHandoff(indexHTML, baseAppConfig?.interfaceConfig?.colorModeFromUrl);
+ indexHTML = injectColorModeHandoff(indexHTML, appConfig?.interfaceConfig?.colorModeFromUrl);
const indexShell = createDeploymentThemeShell(
indexHTML,
- baseAppConfig?.interfaceConfig?.theme,
+ appConfig?.interfaceConfig?.theme,
readBundledThemeBoot(appConfig.paths.dist),
);
@@ -733,12 +733,12 @@ if (cluster.isMaster) {
await initializeAgentTriggerService({
address: server.address(),
completionResultBatchSize:
- baseAppConfig?.endpoints?.agents?.backgroundTasks?.completionResultBatchSize,
+ appConfig?.endpoints?.agents?.backgroundTasks?.completionResultBatchSize,
completionReceiptBatching:
- baseAppConfig?.endpoints?.agents?.backgroundTasks?.completionReceiptBatching,
+ appConfig?.endpoints?.agents?.backgroundTasks?.completionReceiptBatching,
deadLetterRetentionDays:
- baseAppConfig?.endpoints?.agents?.eventDriven?.deadLetterRetentionDays,
- idlePolling: baseAppConfig?.endpoints?.agents?.eventDriven?.idlePolling,
+ appConfig?.endpoints?.agents?.eventDriven?.deadLetterRetentionDays,
+ idlePolling: appConfig?.endpoints?.agents?.eventDriven?.idlePolling,
});
} catch (initErr) {
logger.error(`Worker ${process.pid} post-listen initialization failed:`, initErr);
diff --git a/api/server/experimental.spec.js b/api/server/experimental.spec.js
index a5d7d489c9..c15eaee8b5 100644
--- a/api/server/experimental.spec.js
+++ b/api/server/experimental.spec.js
@@ -86,7 +86,7 @@ describe('Experimental server configuration', () => {
it('configures routed subagent controls before a worker accepts requests', () => {
const redisReadyIndex = source.indexOf('await waitForKeyvRedisClient();');
const routingIndex = source.indexOf(
- 'await configureSubagentTaskRouting(baseAppConfig?.endpoints?.agents?.subagentActivity);',
+ 'await configureSubagentTaskRouting(appConfig?.endpoints?.agents?.subagentActivity);',
);
const listenIndex = source.indexOf('const server = app.listen');
@@ -97,10 +97,10 @@ describe('Experimental server configuration', () => {
it('projects base-only event rollout barriers before accepting requests', () => {
const baseConfigIndex = source.indexOf(
- 'const baseAppConfig = await getAppConfig({ baseOnly: true });',
+ 'const appConfig = await getAppConfig({ baseOnly: true });',
);
const eventRuntimeIndex = source.indexOf(
- 'configureAgentEventRuntime(baseAppConfig?.endpoints?.agents?.eventDriven);',
+ 'configureAgentEventRuntime(appConfig?.endpoints?.agents?.eventDriven);',
);
const listenIndex = source.indexOf('const server = app.listen');
@@ -111,20 +111,42 @@ describe('Experimental server configuration', () => {
it('passes the same idle recovery policy to both server startup paths', () => {
const standard = fs.readFileSync(path.join(__dirname, 'index.js'), 'utf8');
- for (const [entrypoint, config] of [
- [source, 'baseAppConfig'],
- [standard, 'appConfig'],
- ]) {
+ for (const entrypoint of [source, standard]) {
const start = entrypoint.indexOf('await initializeAgentTriggerService({');
expect(start).toBeGreaterThan(-1);
const call = entrypoint.slice(start, entrypoint.indexOf('});', start));
- expect(call).toContain(`idlePolling: ${config}?.endpoints?.agents?.eventDriven?.idlePolling`);
+ expect(call).toContain('idlePolling: appConfig?.endpoints?.agents?.eventDriven?.idlePolling');
expect(call.replace(/\s+/g, ' ')).toContain(
- `deadLetterRetentionDays: ${config}?.endpoints?.agents?.eventDriven?.deadLetterRetentionDays`,
+ 'deadLetterRetentionDays: appConfig?.endpoints?.agents?.eventDriven?.deadLetterRetentionDays',
);
}
});
+ it('boots from librechat.yaml only, like the standard entry, so `__base__` overrides never reach worker-wide state', () => {
+ const standard = fs.readFileSync(path.join(__dirname, 'index.js'), 'utf8');
+ for (const entrypoint of [source, standard]) {
+ const reads = entrypoint.match(/await getAppConfig\([^)]*\)/g);
+ expect(reads).toEqual(['await getAppConfig({ baseOnly: true })']);
+ const readIndex = entrypoint.indexOf(
+ 'const appConfig = await getAppConfig({ baseOnly: true });',
+ );
+ expect(readIndex).toBeGreaterThan(-1);
+ for (const consumer of [
+ 'initializeFileStorage(appConfig);',
+ 'initializeGitHubSkillSync(appConfig);',
+ 'startSkillDeletionSweep(appConfig.skillDeletion);',
+ 'await performStartupChecks(appConfig);',
+ 'await configureSocialLogins(app, appConfig);',
+ ]) {
+ expect(entrypoint.indexOf(consumer)).toBeGreaterThan(readIndex);
+ }
+ }
+ expect(source).toContain(
+ 'expiredFileSweep.configure({ appConfig, loadAppConfig: getAppConfig });',
+ );
+ expect(source).not.toContain('baseAppConfig');
+ });
+
it('matches the standard server pre-authentication tenant routes', () => {
expect(source).toContain("app.use('/oauth', preAuthTenantMiddleware, routes.oauth);");
expect(source).toContain("app.use('/api/auth', preAuthTenantMiddleware, routes.auth);");
diff --git a/packages/api/src/admin/config.handler.spec.ts b/packages/api/src/admin/config.handler.spec.ts
index f42710d475..33388cdf25 100644
--- a/packages/api/src/admin/config.handler.spec.ts
+++ b/packages/api/src/admin/config.handler.spec.ts
@@ -18,6 +18,7 @@ jest.mock('@librechat/data-schemas', () => {
};
});
+import { configSchema } from 'librechat-data-provider';
import {
getConfigFieldIssues,
getConfigOverrideIssues,
@@ -539,6 +540,11 @@ describe('createAdminConfigHandlers', () => {
await handlers.upsertConfigOverrides(req, res);
expect(res.statusCode).toBe(400);
+ expect(res.body).toEqual({
+ error: 'Invalid config override',
+ code: 'CONFIG_OVERRIDE_INVALID',
+ issues: [{ path: 'mcpConfig', segments: ['mcpConfig'], code: 'unknown_section' }],
+ });
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
@@ -1304,6 +1310,7 @@ describe('createAdminConfigHandlers', () => {
await handlers.patchConfigField(req, res);
expect(res.statusCode).toBe(400);
+ expect(res.body).toEqual({ error: 'Unknown config section', code: 'UNKNOWN_SECTION' });
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
@@ -2949,6 +2956,554 @@ describe('createAdminConfigHandlers', () => {
});
});
+ describe('override sections outside configSchema', () => {
+ /** Runtime state AppService builds that `configSchema` does not define, so no override may set it. */
+ const RUNTIME_KEYS = [
+ 'paths',
+ 'config',
+ 'availableTools',
+ 'interfaceConfig',
+ 'turnstileConfig',
+ 'mcpConfig',
+ ];
+ const MARKER = '/tmp/attacker-controlled';
+ const params = { principalType: 'role', principalId: 'admin' };
+ const UNKNOWN_SECTION = { error: 'Unknown config section', code: 'UNKNOWN_SECTION' };
+
+ it.each(RUNTIME_KEYS)('rejects a whole-document write holding `%s`', async (key) => {
+ const { handlers, deps } = createHandlers();
+ const res = mockRes();
+
+ await handlers.upsertConfigOverrides(
+ mockReq({
+ params,
+ body: { overrides: { [key]: { uploads: MARKER }, registration: { enabled: false } } },
+ }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toEqual({
+ error: 'Invalid config override',
+ code: 'CONFIG_OVERRIDE_INVALID',
+ issues: [{ path: key, segments: [key], code: 'unknown_section' }],
+ });
+ expect(JSON.stringify(res.body)).not.toContain(MARKER);
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ 'paths.uploads',
+ 'config.permissions',
+ 'config',
+ 'interfaceConfig.prompts',
+ 'turnstileConfig.siteKey',
+ 'mcpConfig.remote.url',
+ 'availableTools.calculator',
+ ])('rejects a field write to `%s` without echoing the path', async (fieldPath) => {
+ const { handlers, deps } = createHandlers();
+ const res = mockRes();
+
+ await handlers.patchConfigField(
+ mockReq({ params, body: { entries: [{ fieldPath, value: MARKER }] } }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toEqual(UNKNOWN_SECTION);
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
+ expect(deps.findConfigByPrincipal).not.toHaveBeenCalled();
+ });
+
+ it('rejects the whole batch when any entry addresses an unknown section', async () => {
+ const { handlers, deps } = createHandlers();
+ const res = mockRes();
+
+ await handlers.patchConfigField(
+ mockReq({
+ params,
+ body: {
+ entries: [
+ { fieldPath: 'registration.enabled', value: false },
+ { fieldPath: 'paths.uploads', value: MARKER },
+ ],
+ },
+ }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toEqual(UNKNOWN_SECTION);
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
+ });
+
+ it('still accepts keys the schema does not define inside a known section', async () => {
+ const { handlers, deps } = createHandlers();
+ const res = mockRes();
+
+ await handlers.patchConfigField(
+ mockReq({
+ params,
+ body: { entries: [{ fieldPath: 'registration.futureOption', value: 1 }] },
+ }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(deps.writeConfigDocument).toHaveBeenCalledTimes(1);
+ expect(writtenDraft(deps).overrides).toEqual({ registration: { futureOption: 1 } });
+ });
+
+ it.each(['paths', 'paths.uploads', 'config.permissions', 'interfaceConfig.prompts'])(
+ 'rejects a tombstone on `%s`',
+ async (fieldPath) => {
+ const { handlers, deps } = createHandlers();
+ const res = mockRes();
+
+ await handlers.tombstoneConfigField(mockReq({ params, body: { fieldPath } }), res);
+
+ 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();
+ },
+ );
+
+ it('lets a broad manager remove a value stored under an unknown section', async () => {
+ const { handlers, deps } = createHandlers({
+ unsetConfigField: jest.fn().mockResolvedValue({ _id: 'c1', overrides: {}, tombstones: [] }),
+ });
+ const res = mockRes();
+
+ await handlers.deleteConfigField(mockReq({ params, query: { fieldPath: 'paths' } }), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(deps.unsetConfigField).toHaveBeenCalledWith('role', 'admin', ['paths'], undefined, {
+ expectedRevision: undefined,
+ });
+ });
+
+ it('does not let a section-scoped manager remove a value under an unknown section', async () => {
+ const { handlers, deps } = createHandlers({
+ hasConfigCapability: jest.fn(async (_user, section) => section === 'memory'),
+ });
+ const res = mockRes();
+
+ await handlers.deleteConfigField(
+ mockReq({ params, query: { fieldPath: 'paths.uploads' } }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(403);
+ expect(deps.unsetConfigField).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('write responses: filtered by read access', () => {
+ const params = { principalType: 'role', principalId: 'editors' };
+
+ function writtenDoc() {
+ return {
+ _id: 'c1',
+ principalType: 'role',
+ principalId: 'editors',
+ priority: 10,
+ configVersion: 2,
+ isActive: true,
+ overrides: {
+ endpoints: {
+ agents: { disableBuilder: true },
+ custom: [{ name: 'groq', apiKey: 'v3:endpoint-cipher', apiKeyPreview: '...abcd' }],
+ },
+ memory: { charLimit: 500 },
+ webSearch: {
+ searchProvider: 'serper',
+ serperApiKey: 'v3:serper-cipher',
+ serperApiKeyPreview: '...wxyz',
+ },
+ },
+ tombstones: ['endpoints.bedrock', 'memory.tokenLimit', 'webSearch.jinaApiUrl'],
+ };
+ }
+
+ /** A caller holding only the listed `<verb>:configs:<section>` grants, never the broad ones. */
+ function scopedCapability(grants: string[]) {
+ return jest.fn(
+ async (_user: unknown, section: string | null, verb = 'manage') =>
+ section != null && grants.includes(`${verb}:${section}`),
+ );
+ }
+
+ type WrittenBody = { overrides: Record<string, unknown>; tombstones: string[] };
+
+ it('PATCH: a section manager sees only the sections it wrote', async () => {
+ const { handlers } = createHandlers({
+ hasConfigCapability: scopedCapability(['manage:endpoints']),
+ writeConfigDocument: jest.fn().mockResolvedValue(writtenDoc()),
+ });
+ const res = mockRes();
+
+ await handlers.patchConfigField(
+ mockReq({
+ params,
+ body: { entries: [{ fieldPath: 'endpoints.agents.disableBuilder', value: true }] },
+ }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(200);
+ const body = res.body!.config as WrittenBody;
+ expect(Object.keys(body.overrides)).toEqual(['endpoints']);
+ expect(body.tombstones).toEqual(['endpoints.bedrock']);
+ expect(body).toMatchObject({ principalId: 'editors', priority: 10, configVersion: 2 });
+ expect(JSON.stringify(res.body)).not.toMatch(/charLimit|serper|cipher/);
+ });
+
+ it('PATCH: adds the other sections the caller can read', async () => {
+ const { handlers } = createHandlers({
+ hasConfigCapability: scopedCapability(['manage:endpoints', 'read:memory']),
+ writeConfigDocument: jest.fn().mockResolvedValue(writtenDoc()),
+ });
+ const res = mockRes();
+
+ await handlers.patchConfigField(
+ mockReq({
+ params,
+ body: { entries: [{ fieldPath: 'endpoints.agents.disableBuilder', value: true }] },
+ }),
+ res,
+ );
+
+ const body = res.body!.config as WrittenBody;
+ expect(Object.keys(body.overrides).sort()).toEqual(['endpoints', 'memory']);
+ expect(body.tombstones).toEqual(['endpoints.bedrock', 'memory.tokenLimit']);
+ });
+
+ it('PATCH: uses the batched read lookup, once and before the write', async () => {
+ const getReadableConfigSections = jest
+ .fn()
+ .mockResolvedValue({ broad: false, sections: new Set(['webSearch']) });
+ const writeConfigDocument = jest.fn().mockResolvedValue(writtenDoc());
+ const { handlers } = createHandlers({
+ hasConfigCapability: scopedCapability(['manage:endpoints']),
+ getReadableConfigSections,
+ writeConfigDocument,
+ });
+ const res = mockRes();
+
+ await handlers.patchConfigField(
+ mockReq({
+ params,
+ body: { entries: [{ fieldPath: 'endpoints.agents.disableBuilder', value: true }] },
+ }),
+ res,
+ );
+
+ expect(getReadableConfigSections).toHaveBeenCalledTimes(1);
+ expect([...getReadableConfigSections.mock.calls[0][1]].sort()).toEqual(
+ Object.keys(configSchema.shape).sort(),
+ );
+ expect(getReadableConfigSections.mock.invocationCallOrder[0]).toBeLessThan(
+ writeConfigDocument.mock.invocationCallOrder[0],
+ );
+ const body = res.body!.config as WrittenBody;
+ expect(Object.keys(body.overrides).sort()).toEqual(['endpoints', 'webSearch']);
+ expect(body.overrides.webSearch).toEqual({
+ searchProvider: 'serper',
+ serperApiKeyPreview: '...wxyz',
+ });
+ });
+
+ it('PATCH: resolves read access alongside the base config read, not after it', async () => {
+ let releaseBase: (appConfig: { config: object }) => void = () => undefined;
+ const getAppConfig = jest.fn(
+ () => new Promise<{ config: object }>((resolve) => (releaseBase = resolve)),
+ );
+ const getReadableConfigSections = jest
+ .fn()
+ .mockResolvedValue({ broad: false, sections: new Set<string>() });
+ const writeConfigDocument = jest.fn().mockResolvedValue(writtenDoc());
+ const { handlers } = createHandlers({
+ hasConfigCapability: scopedCapability(['manage:endpoints']),
+ getAppConfig,
+ getReadableConfigSections,
+ writeConfigDocument,
+ });
+ const res = mockRes();
+
+ const pending = handlers.patchConfigField(
+ mockReq({
+ params,
+ body: { entries: [{ fieldPath: 'endpoints.agents.disableBuilder', value: true }] },
+ }),
+ res,
+ );
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(getAppConfig).toHaveBeenCalledTimes(1);
+ expect(getReadableConfigSections).toHaveBeenCalledTimes(1);
+ expect(writeConfigDocument).not.toHaveBeenCalled();
+ releaseBase({ config: {} });
+ await pending;
+ expect(res.statusCode).toBe(200);
+ expect(writeConfigDocument).toHaveBeenCalledTimes(1);
+ });
+
+ it('/changes: resolves read access with the base config read, then filters the reply', async () => {
+ let releaseBase: (appConfig: { config: object }) => void = () => undefined;
+ const getAppConfig = jest.fn(
+ () => new Promise<{ config: object }>((resolve) => (releaseBase = resolve)),
+ );
+ const getReadableConfigSections = jest
+ .fn()
+ .mockResolvedValue({ broad: false, sections: new Set(['webSearch']) });
+ const writeConfigDocument = jest.fn().mockResolvedValue(writtenDoc());
+ const { handlers } = createHandlers({
+ hasConfigCapability: scopedCapability(['manage:endpoints']),
+ getAppConfig,
+ getReadableConfigSections,
+ writeConfigDocument,
+ });
+ const res = mockRes();
+
+ const pending = handlers.applyConfigChanges(
+ mockReq({
+ params,
+ body: { ops: [{ op: 'set', fieldPath: 'endpoints.agents.disableBuilder', value: true }] },
+ }),
+ res,
+ );
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(getAppConfig).toHaveBeenCalledTimes(1);
+ expect(getReadableConfigSections).toHaveBeenCalledTimes(1);
+ expect([...getReadableConfigSections.mock.calls[0][1]].sort()).toEqual(
+ Object.keys(configSchema.shape).sort(),
+ );
+ expect(writeConfigDocument).not.toHaveBeenCalled();
+ releaseBase({ config: {} });
+ await pending;
+
+ expect(res.statusCode).toBe(200);
+ expect(writeConfigDocument).toHaveBeenCalledTimes(1);
+ expect(getReadableConfigSections).toHaveBeenCalledTimes(1);
+ expect(res.body).toMatchObject({ written: true, revision: 'c1:2' });
+ const body = res.body!.config as WrittenBody & { revision: string };
+ expect(Object.keys(body.overrides).sort()).toEqual(['endpoints', 'webSearch']);
+ expect(body.overrides.webSearch).toEqual({
+ searchProvider: 'serper',
+ serperApiKeyPreview: '...wxyz',
+ });
+ expect(body.tombstones).toEqual(['endpoints.bedrock', 'webSearch.jinaApiUrl']);
+ expect(body.revision).toBe('c1:2');
+ expect(JSON.stringify(res.body)).not.toMatch(/charLimit|cipher/);
+ });
+
+ it('/changes: a dry run returns no document and resolves no read access', async () => {
+ const getReadableConfigSections = jest.fn();
+ const { handlers, deps } = createHandlers({
+ hasConfigCapability: scopedCapability(['manage:endpoints']),
+ getReadableConfigSections,
+ });
+ const res = mockRes();
+
+ await handlers.applyConfigChanges(
+ mockReq({
+ params,
+ body: {
+ ops: [{ op: 'set', fieldPath: 'endpoints.agents.disableBuilder', value: true }],
+ dryRun: true,
+ },
+ }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toMatchObject({ written: false, dryRun: true });
+ expect(res.body).not.toHaveProperty('config');
+ expect(getReadableConfigSections).not.toHaveBeenCalled();
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [
+ 'PATCH',
+ 'writeConfigDocument',
+ (h: ReturnType<typeof createHandlers>['handlers'], res: Response) =>
+ h.patchConfigField(
+ mockReq({
+ params,
+ body: { entries: [{ fieldPath: 'endpoints.agents.disableBuilder', value: true }] },
+ }),
+ res,
+ ),
+ ],
+ [
+ 'tombstone',
+ 'tombstoneConfigField',
+ (h: ReturnType<typeof createHandlers>['handlers'], res: Response) =>
+ h.tombstoneConfigField(
+ mockReq({ params, body: { fieldPath: 'endpoints.bedrock' } }),
+ res,
+ ),
+ ],
+ [
+ 'field delete',
+ 'unsetConfigField',
+ (h: ReturnType<typeof createHandlers>['handlers'], res: Response) =>
+ h.deleteConfigField(mockReq({ params, query: { fieldPath: 'endpoints.bedrock' } }), res),
+ ],
+ [
+ '/changes',
+ 'writeConfigDocument',
+ (h: ReturnType<typeof createHandlers>['handlers'], res: Response) =>
+ h.applyConfigChanges(
+ mockReq({
+ params,
+ body: {
+ ops: [{ op: 'set', fieldPath: 'endpoints.agents.disableBuilder', value: true }],
+ },
+ }),
+ res,
+ ),
+ ],
+ ] as const)(
+ '%s: a failed read lookup fails the request before anything is written',
+ async (_label, write, run) => {
+ const recordAuditEntry = jest.fn().mockResolvedValue(undefined);
+ const invalidateConfigCaches = jest.fn().mockResolvedValue(undefined);
+ const { handlers, deps } = createHandlers({
+ 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,
+ });
+ const res = mockRes();
+
+ await run(handlers, res);
+
+ expect(res.statusCode).toBe(500);
+ expect((deps as Record<string, jest.Mock>)[write]).not.toHaveBeenCalled();
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
+ expect(recordAuditEntry).not.toHaveBeenCalled();
+ expect(invalidateConfigCaches).not.toHaveBeenCalled();
+ },
+ );
+
+ it('a broad manager gets the whole redacted document without a read lookup', async () => {
+ const hasConfigCapability = jest.fn().mockResolvedValue(true);
+ const getReadableConfigSections = jest.fn();
+ const { handlers } = createHandlers({
+ hasConfigCapability,
+ getReadableConfigSections,
+ writeConfigDocument: jest.fn().mockResolvedValue(writtenDoc()),
+ });
+ const res = mockRes();
+
+ await handlers.patchConfigField(
+ mockReq({
+ params,
+ body: { entries: [{ fieldPath: 'endpoints.agents.disableBuilder', value: true }] },
+ }),
+ res,
+ );
+
+ const body = res.body!.config as WrittenBody;
+ expect(Object.keys(body.overrides).sort()).toEqual(['endpoints', 'memory', 'webSearch']);
+ expect(body.tombstones).toHaveLength(3);
+ expect(JSON.stringify(res.body)).not.toContain('cipher');
+ expect(getReadableConfigSections).not.toHaveBeenCalled();
+ expect(hasConfigCapability.mock.calls.every(([, , verb]) => verb !== 'read')).toBe(true);
+ });
+
+ it('tombstone: a section manager sees only the tombstoned section', async () => {
+ const { handlers } = createHandlers({
+ hasConfigCapability: scopedCapability(['manage:memory']),
+ tombstoneConfigField: jest.fn().mockResolvedValue(writtenDoc()),
+ });
+ const res = mockRes();
+
+ await handlers.tombstoneConfigField(
+ mockReq({ params, body: { fieldPath: 'memory.tokenLimit' } }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(200);
+ const body = res.body!.config as WrittenBody;
+ expect(body.overrides).toEqual({ memory: { charLimit: 500 } });
+ expect(body.tombstones).toEqual(['memory.tokenLimit']);
+ });
+
+ it('field delete: a section manager sees only that section, secrets redacted', async () => {
+ const before = writtenDoc();
+ const { handlers, deps } = createHandlers({
+ hasConfigCapability: scopedCapability(['manage:webSearch']),
+ findConfigByPrincipal: jest.fn().mockResolvedValue({
+ ...before,
+ configVersion: 1,
+ overrides: {
+ ...before.overrides,
+ webSearch: { ...before.overrides.webSearch, jinaApiUrl: 'https://jina.example.com' },
+ },
+ }),
+ writeConfigDocument: jest.fn().mockResolvedValue(writtenDoc()),
+ });
+ const res = mockRes();
+
+ await handlers.deleteConfigField(
+ mockReq({ params, query: { fieldPath: 'webSearch.jinaApiUrl' } }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(deps.unsetConfigField).not.toHaveBeenCalled();
+ expect(deps.writeConfigDocument).toHaveBeenCalledTimes(1);
+ expect(deps.writeConfigDocument.mock.calls[0][3]).toBe('c1:1');
+ expect(writtenDraft(deps).overrides.webSearch).not.toHaveProperty('jinaApiUrl');
+ const body = res.body!.config as WrittenBody;
+ expect(body.overrides).toEqual({
+ webSearch: { searchProvider: 'serper', serperApiKeyPreview: '...wxyz' },
+ });
+ expect(body.tombstones).toEqual(['webSearch.jinaApiUrl']);
+ });
+
+ it('toggle and scope creation: an assign-only caller sees no section it cannot read', async () => {
+ const getReadableConfigSections = jest.fn();
+ const deps = {
+ hasConfigCapability: scopedCapability([]),
+ getReadableConfigSections,
+ hasCapability: jest.fn().mockResolvedValue(true),
+ writeConfigDocument: jest.fn().mockResolvedValue({ ...writtenDoc(), configVersion: 1 }),
+ toggleConfigActiveTracked: jest
+ .fn()
+ .mockResolvedValue({ config: writtenDoc(), changed: true }),
+ };
+ const { handlers } = createHandlers(deps);
+
+ const toggled = mockRes();
+ await handlers.toggleConfig(mockReq({ params, body: { isActive: false } }), toggled);
+ const created = mockRes();
+ await handlers.upsertConfigOverrides(
+ mockReq({ params, body: { overrides: {}, priority: 5 } }),
+ created,
+ );
+
+ expect(toggled.statusCode).toBe(200);
+ expect(created.statusCode).toBe(201);
+ for (const res of [toggled, created]) {
+ const body = res.body!.config as WrittenBody;
+ expect(body.overrides).toEqual({});
+ expect(body.tombstones).toEqual([]);
+ expect(body).toMatchObject({ principalId: 'editors', isActive: true });
+ }
+ expect(getReadableConfigSections).not.toHaveBeenCalled();
+ });
+ });
+
describe('revision preconditions', () => {
const params = { principalType: 'role', principalId: 'editor' };
const stored = {
diff --git a/packages/api/src/admin/config.integration.spec.ts b/packages/api/src/admin/config.integration.spec.ts
new file mode 100644
index 0000000000..490282dff5
--- /dev/null
+++ b/packages/api/src/admin/config.integration.spec.ts
@@ -0,0 +1,394 @@
+import mongoose from 'mongoose';
+import { MongoMemoryServer } from 'mongodb-memory-server';
+import { PrincipalModel, PrincipalType } from 'librechat-data-provider';
+import type { SystemCapability } from '@librechat/data-schemas';
+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 ConfigMethods = ReturnType<DataSchemas['createMethods']>;
+type AdminConfigHandlers = ReturnType<typeof import('./config').createAdminConfigHandlers>;
+type AdminConfigDeps = Parameters<typeof import('./config').createAdminConfigHandlers>[0];
+type CapabilityCheck = AdminConfigDeps['hasConfigCapability'];
+
+interface MockRes {
+ statusCode: number;
+ body: undefined | { config?: StoredConfig; error?: string; [key: string]: unknown };
+ status: jest.Mock;
+ json: jest.Mock;
+}
+
+interface StoredConfig {
+ overrides: Record<string, unknown>;
+ tombstones?: string[];
+}
+
+const ROLE = PrincipalType.ROLE;
+const MARKER = '/tmp/attacker-controlled';
+
+let mongoServer: MongoMemoryServer;
+let methods: ConfigMethods;
+let createAdminConfigHandlers: typeof import('./config').createAdminConfigHandlers;
+let generateCapabilityCheck: typeof import('~/middleware/capabilities').generateCapabilityCheck;
+let mergeConfigOverrides: DataSchemas['mergeConfigOverrides'];
+
+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;
+}
+
+/** Real handlers over the real Config collection, with the caller's capabilities decided by `hasConfigCapability`. */
+function handlersFor(
+ hasConfigCapability: CapabilityCheck,
+ extra: Partial<AdminConfigDeps> = {},
+): AdminConfigHandlers {
+ return createAdminConfigHandlers({
+ listAllConfigs: methods.listAllConfigs,
+ findConfigByPrincipal: methods.findConfigByPrincipal,
+ writeConfigDocument: methods.writeConfigDocument,
+ tombstoneConfigField: methods.tombstoneConfigField,
+ unsetConfigField: methods.unsetConfigField,
+ deleteConfig: methods.deleteConfig,
+ toggleConfigActiveTracked: methods.toggleConfigActiveTracked,
+ hasConfigCapability,
+ hasAnyConfigReadAccess: async () => true,
+ hasCapability: async () => true,
+ ...extra,
+ });
+}
+
+/** A caller holding only the listed `<verb>:configs:<section>` grants, never the broad ones. */
+function scoped(grants: string[]): CapabilityCheck {
+ return async (_user, section, verb = 'manage') =>
+ section != null && grants.includes(`${verb}:${section}`);
+}
+
+async function readStored(principalId: string): Promise<StoredConfig | null> {
+ const doc = await mongoose.models.Config.findOne({ principalType: ROLE, principalId }).lean();
+ return doc as StoredConfig | null;
+}
+
+beforeAll(async () => {
+ jest.resetModules();
+ const dataSchemas = await import('@librechat/data-schemas');
+ jest.spyOn(dataSchemas.logger, 'error').mockReturnValue(dataSchemas.logger);
+ jest.spyOn(dataSchemas.logger, 'warn').mockReturnValue(dataSchemas.logger);
+ jest.spyOn(dataSchemas.logger, 'info').mockReturnValue(dataSchemas.logger);
+ ({ mergeConfigOverrides } = dataSchemas);
+ ({ createAdminConfigHandlers } = await import('./config'));
+ ({ generateCapabilityCheck } = await import('~/middleware/capabilities'));
+
+ mongoServer = await MongoMemoryServer.create();
+ await mongoose.connect(mongoServer.getUri());
+ dataSchemas.createModels(mongoose);
+ methods = dataSchemas.createMethods(mongoose);
+});
+
+afterEach(async () => {
+ await Promise.all([
+ mongoose.models.Config.deleteMany({}),
+ mongoose.models.SystemGrant.deleteMany({}),
+ ]);
+});
+
+afterAll(async () => {
+ await mongoose.disconnect();
+ await mongoServer.stop();
+});
+
+describe('admin config writes against a real Config collection', () => {
+ describe('top-level sections outside configSchema', () => {
+ it('stores nothing from a whole-document write that holds runtime state', async () => {
+ const handlers = handlersFor(async () => true);
+ const res = mockRes();
+
+ await handlers.upsertConfigOverrides(
+ mockReq({
+ params: { principalType: ROLE, principalId: 'editors' },
+ body: { overrides: { paths: { uploads: MARKER }, registration: { enabled: false } } },
+ }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body?.issues).toEqual([
+ { path: 'paths', segments: ['paths'], code: 'unknown_section' },
+ ]);
+ expect(await readStored('editors')).toBeNull();
+ });
+
+ it('stores nothing from a field write or tombstone under runtime state', async () => {
+ const handlers = handlersFor(async () => true);
+ const params = { principalType: ROLE, principalId: 'editors' };
+ const patched = mockRes();
+ const tombstoned = mockRes();
+
+ await handlers.patchConfigField(
+ mockReq({ params, body: { entries: [{ fieldPath: 'config.permissions', value: {} }] } }),
+ patched,
+ );
+ await handlers.tombstoneConfigField(
+ mockReq({ params, body: { fieldPath: 'paths' } }),
+ tombstoned,
+ );
+
+ expect(patched.statusCode).toBe(400);
+ expect(tombstoned.statusCode).toBe(400);
+ expect(await readStored('editors')).toBeNull();
+ });
+
+ it('lets a document that already holds runtime state take unrelated writes, then removes it', async () => {
+ /** Written straight through the data layer, as a server without the section check could. */
+ await methods.patchConfigFields(
+ ROLE,
+ 'legacy',
+ PrincipalModel.ROLE,
+ { 'paths.uploads': MARKER, 'registration.enabled': true },
+ 10,
+ );
+ await methods.tombstoneConfigField(ROLE, 'legacy', PrincipalModel.ROLE, 'config', 10);
+ const stored = await readStored('legacy');
+ expect(stored?.overrides.paths).toEqual({ uploads: MARKER });
+
+ const merged = mergeConfigOverrides(
+ { paths: { uploads: '/srv/uploads' }, config: { version: '1.3.0' } } as never,
+ [stored as never],
+ ) as unknown as Record<string, unknown>;
+ expect(merged.paths).toEqual({ uploads: '/srv/uploads' });
+ expect(merged.config).toEqual({ version: '1.3.0' });
+ expect(merged.registration).toEqual({ enabled: true });
+
+ const handlers = handlersFor(async () => true);
+ const params = { principalType: ROLE, principalId: 'legacy' };
+ const patched = mockRes();
+ await handlers.patchConfigField(
+ mockReq({
+ params,
+ body: { entries: [{ fieldPath: 'registration.enabled', value: false }] },
+ }),
+ patched,
+ );
+ expect(patched.statusCode).toBe(200);
+
+ for (const fieldPath of ['paths', 'config']) {
+ const removed = mockRes();
+ await handlers.deleteConfigField(mockReq({ params, query: { fieldPath } }), removed);
+ expect(removed.statusCode).toBe(200);
+ }
+ expect(await readStored('legacy')).toMatchObject({
+ overrides: { registration: { enabled: false } },
+ tombstones: [],
+ });
+ expect((await readStored('legacy'))?.overrides).not.toHaveProperty('paths');
+ });
+ });
+
+ describe('write responses', () => {
+ const params = { principalType: ROLE, principalId: 'editors' };
+
+ /** A broad manager writes three sections (one with a secret) and a tombstone. */
+ async function seed(): Promise<void> {
+ const seeded = mockRes();
+ await handlersFor(async () => true).upsertConfigOverrides(
+ mockReq({
+ params,
+ body: {
+ overrides: {
+ endpoints: { agents: { disableBuilder: false } },
+ memory: { charLimit: 500 },
+ webSearch: { searchProvider: 'serper', serperApiKey: 'sk-serper-secret-value' },
+ },
+ },
+ }),
+ seeded,
+ );
+ expect(seeded.statusCode).toBe(201);
+ const tombstoned = mockRes();
+ await handlersFor(async () => true).tombstoneConfigField(
+ mockReq({ params, body: { fieldPath: 'memory.tokenLimit' } }),
+ tombstoned,
+ );
+ expect(tombstoned.statusCode).toBe(200);
+ }
+
+ it('show a section manager only the sections it wrote or can read', async () => {
+ await seed();
+ const writer = mockRes();
+ await handlersFor(scoped(['manage:endpoints'])).patchConfigField(
+ mockReq({
+ params,
+ body: { entries: [{ fieldPath: 'endpoints.agents.disableBuilder', value: true }] },
+ }),
+ writer,
+ );
+ expect(writer.statusCode).toBe(200);
+ expect(writer.body?.config?.overrides).toEqual({
+ endpoints: { agents: { disableBuilder: true } },
+ });
+ expect(writer.body?.config?.tombstones).toEqual([]);
+
+ const reader = mockRes();
+ await handlersFor(scoped(['manage:endpoints', 'read:memory'])).tombstoneConfigField(
+ mockReq({ params, body: { fieldPath: 'endpoints.bedrock' } }),
+ reader,
+ );
+ expect(reader.statusCode).toBe(200);
+ expect(Object.keys(reader.body?.config?.overrides ?? {}).sort()).toEqual([
+ 'endpoints',
+ 'memory',
+ ]);
+ expect(reader.body?.config?.tombstones).toEqual(['memory.tokenLimit', 'endpoints.bedrock']);
+ expect(JSON.stringify([writer.body, reader.body])).not.toContain('serper');
+
+ const remover = mockRes();
+ await handlersFor(scoped(['manage:webSearch'])).deleteConfigField(
+ mockReq({ params, query: { fieldPath: 'webSearch.searchProvider' } }),
+ remover,
+ );
+ expect(remover.statusCode).toBe(200);
+ expect(remover.body?.config?.overrides).toEqual({
+ webSearch: { serperApiKeyPreview: '...alue' },
+ });
+ expect(remover.body?.config?.tombstones).toEqual([]);
+ expect(JSON.stringify(remover.body)).not.toContain('v3:');
+ });
+
+ it('show a section manager holding real grants no more than a read shows it', async () => {
+ await seed();
+ const admin = handlersFor(async () => true);
+ const otherField = mockRes();
+ await admin.patchConfigField(
+ mockReq({
+ params,
+ body: { entries: [{ fieldPath: 'endpoints.agents.recursionLimit', value: 30 }] },
+ }),
+ otherField,
+ );
+ const otherTombstone = mockRes();
+ await admin.tombstoneConfigField(
+ mockReq({ params, body: { fieldPath: 'endpoints.bedrock' } }),
+ otherTombstone,
+ );
+ expect([otherField.statusCode, otherTombstone.statusCode]).toEqual([200, 200]);
+
+ const userId = new mongoose.Types.ObjectId().toString();
+ await methods.grantCapability({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ capability: 'manage:configs:endpoints' as SystemCapability,
+ });
+ const grants = generateCapabilityCheck({
+ getUserPrincipals: methods.getUserPrincipals,
+ hasCapabilityForPrincipals: methods.hasCapabilityForPrincipals,
+ hasAnyConfigReadAccess: methods.hasAnyConfigReadAccess,
+ getHeldCapabilities: methods.getHeldCapabilities,
+ });
+ const manager = handlersFor(grants.hasConfigCapability, {
+ hasCapability: grants.hasCapability,
+ hasAnyConfigReadAccess: grants.hasAnyConfigReadAccess,
+ getReadableConfigSections: grants.getReadableConfigSections,
+ });
+ const user = { id: userId, role: 'USER', _id: { toString: () => userId } };
+
+ const written = mockRes();
+ await manager.patchConfigField(
+ mockReq({
+ user,
+ params,
+ body: { entries: [{ fieldPath: 'endpoints.agents.disableBuilder', value: true }] },
+ }),
+ written,
+ );
+ const read = mockRes();
+ await manager.getConfig(mockReq({ user, params }), read);
+
+ expect([written.statusCode, read.statusCode]).toEqual([200, 200]);
+ expect(read.body?.config?.overrides).toEqual({
+ endpoints: { agents: { disableBuilder: true, recursionLimit: 30 } },
+ });
+ expect(read.body?.config?.tombstones).toEqual(['endpoints.bedrock']);
+ expect(written.body?.config?.overrides).toEqual(read.body?.config?.overrides);
+ expect(written.body?.config?.tombstones).toEqual(read.body?.config?.tombstones);
+ });
+
+ it('store nothing when the read lookup fails, so a retry is never a second write', async () => {
+ await seed();
+ const before = await readStored('editors');
+ const failing = handlersFor(scoped(['manage:endpoints', 'manage:memory']), {
+ getReadableConfigSections: async () => {
+ throw new Error('grant lookup down');
+ },
+ });
+
+ const patched = mockRes();
+ await failing.patchConfigField(
+ mockReq({
+ params,
+ body: { entries: [{ fieldPath: 'endpoints.agents.disableBuilder', value: true }] },
+ }),
+ patched,
+ );
+ const tombstoned = mockRes();
+ await failing.tombstoneConfigField(
+ mockReq({ params, body: { fieldPath: 'endpoints.bedrock' } }),
+ tombstoned,
+ );
+ const removed = mockRes();
+ await failing.deleteConfigField(
+ mockReq({ params, query: { fieldPath: 'memory.charLimit' } }),
+ removed,
+ );
+
+ expect([patched.statusCode, tombstoned.statusCode, removed.statusCode]).toEqual([
+ 500, 500, 500,
+ ]);
+ expect(await readStored('editors')).toEqual(before);
+ });
+
+ it('show a broad manager the whole document with secrets redacted', async () => {
+ await seed();
+ const res = mockRes();
+ await handlersFor(async () => true).patchConfigField(
+ mockReq({ params, body: { entries: [{ fieldPath: 'memory.charLimit', value: 600 }] } }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(Object.keys(res.body?.config?.overrides ?? {}).sort()).toEqual([
+ 'endpoints',
+ 'memory',
+ 'webSearch',
+ ]);
+ expect(res.body?.config?.overrides.webSearch).toEqual({
+ searchProvider: 'serper',
+ serperApiKeyPreview: '...alue',
+ });
+ expect(JSON.stringify(res.body)).not.toContain('sk-serper-secret-value');
+ });
+ });
+});
diff --git a/packages/api/src/admin/config.ts b/packages/api/src/admin/config.ts
index 2095ee099c..84b9e7f7e0 100644
--- a/packages/api/src/admin/config.ts
+++ b/packages/api/src/admin/config.ts
@@ -2,6 +2,7 @@ import {
BASE_PRINCIPAL_CONFIG_SECTIONS,
BASE_ONLY_CONFIG_SECTIONS,
BASE_ONLY_CONFIG_PATHS,
+ configSchema,
PrincipalType,
PrincipalModel,
INTERFACE_PERMISSION_FIELDS,
@@ -96,6 +97,7 @@ import {
isConfigSecretRelatedSegments,
preserveConfigSecrets,
redactConfigSecrets,
+ redactResolvedConfigSecrets,
} from './secrets';
import {
getBatchReentryIssues,
@@ -169,7 +171,7 @@ export function getTopLevelSection(fieldPath: string): string {
function isProcessMCPServerFieldPath(fieldPath: string, value: unknown): boolean {
const [section, _serverName, field] = fieldPath.split('.');
- if (section !== 'mcpServers' && section !== 'mcpConfig') {
+ if (section !== 'mcpServers') {
return false;
}
if (field == null) {
@@ -698,6 +700,12 @@ const APP_CONFIG_FIELD_TO_SECTION: Readonly<Record<string, string>> = {
type ReadableSections = { broad: boolean; sections: ReadonlySet<string> };
+/** Every section `configSchema` defines: a write resolves read access to all of them before it commits. */
+const CONFIG_SCHEMA_SECTIONS = Object.keys(configSchema.shape) as ConfigSection[];
+const FULL_READ_ACCESS: ReadableSections = { broad: true, sections: new Set() };
+/** Shows no section: an assign-only write stores an empty document, and a dry run returns none. */
+const NO_READ_ACCESS: ReadableSections = { broad: false, sections: new Set() };
+
function canReadSection(readable: ReadableSections, section: string): boolean {
return readable.broad || readable.sections.has(section);
}
@@ -796,12 +804,42 @@ function redactConfigForResponse(config: ConfigRecord): ConfigResponse {
function redactAppConfigForResponse(appConfig: AppConfig, yamlConfig?: AppConfig): AppConfig {
const safeConfig = JSON.parse(JSON.stringify(appConfig)) as AppConfig & { config?: unknown };
redactConfigSecrets(safeConfig, { previewPlaintext: yamlConfig != null, yamlConfig });
+ redactResolvedConfigSecrets(safeConfig);
if (safeConfig.config != null && typeof safeConfig.config === 'object') {
redactConfigSecrets(safeConfig.config);
+ redactResolvedConfigSecrets(safeConfig.config);
}
return safeConfig;
}
+/**
+ * A written document the way a read would return it: filtered to the read access resolved
+ * before the write, then redacted, with the revision of the whole stored document so the next
+ * write can be conditioned on it.
+ */
+function toWrittenConfig(config: ConfigRecord, access: ReadableSections): ConfigResponse {
+ const readable = access.broad ? config : filterConfigDocForReadAccess(config, access);
+ return redactConfigForResponse(readable);
+}
+
+function sendWrittenConfig(
+ res: Response,
+ status: number,
+ config: ConfigRecord,
+ access: ReadableSections,
+): Response {
+ return res.status(status).json({ config: toWrittenConfig(config, access) });
+}
+
+/**
+ * Field writes must address a section `configSchema` defines: anything else (`paths`, the raw
+ * `config`, an AppService alias such as `interfaceConfig`) would reach runtime state. The path
+ * is not echoed back.
+ */
+function unknownSectionResponse(res: Response): Response {
+ return res.status(400).json({ error: 'Unknown config section', code: 'UNKNOWN_SECTION' });
+}
+
/**
* Reports only locations and stable codes: schema messages can echo the submitted values.
* `segments` names the location key by key, since `path` is ambiguous once a record key
@@ -1570,6 +1608,31 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
return appConfig?.config ?? {};
}
+ /**
+ * 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
+ * `read:configs:<section>` from the same section's `manage:configs:<section>`, so a GET shows a
+ * section manager that whole section. The written sections are added anyway, so the reply
+ * always carries what was stored. It covers every schema section in one batched lookup, so it
+ * runs alongside the write's other pre-reads, and a failed lookup fails the request before
+ * anything is stored instead of turning a committed write into a 500. Broad managers can read
+ * every section and skip it.
+ */
+ async function resolveWriteReadAccess(
+ user: CapabilityUser,
+ hasBroadManage: boolean,
+ managedSections: readonly string[],
+ ): Promise<ReadableSections> {
+ if (hasBroadManage) {
+ return FULL_READ_ACCESS;
+ }
+ const readable = await getReadableConfigSections(user, CONFIG_SCHEMA_SECTIONS);
+ return {
+ broad: readable.broad,
+ sections: new Set([...readable.sections, ...managedSections]),
+ };
+ }
+
/**
* GET / — List all active config overrides.
*/
@@ -1729,10 +1792,7 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
const rawOverrides = overrides as Record<string, unknown>;
- if (
- hasProcessMCPServerConfig(rawOverrides.mcpServers) ||
- hasProcessMCPServerConfig(rawOverrides.mcpConfig)
- ) {
+ if (hasProcessMCPServerConfig(rawOverrides.mcpServers)) {
return res.status(400).json({ error: PROCESS_MCP_CONFIG_ERROR });
}
@@ -1934,7 +1994,12 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
priority: config.priority,
},
});
- return res.status(created ? 201 : 200).json({ config: redactConfigForResponse(config) });
+ return sendWrittenConfig(
+ res,
+ created ? 201 : 200,
+ config,
+ hasBroadManage ? FULL_READ_ACCESS : NO_READ_ACCESS,
+ );
} catch (error) {
if (isFieldNameRejection(error)) {
return unstorableKeyResponse(res, 'upsertConfigOverrides');
@@ -1994,6 +2059,9 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
if (!read.ok) {
return fieldTargetErrorResponse(res, read);
}
+ if (!isAcceptedOverrideSection(getTopLevelSection(read.target.fieldPath))) {
+ return unknownSectionResponse(res);
+ }
const value = entry?.value;
const guardError = getFieldWriteError(read.target.fieldPath, value);
if (guardError) {
@@ -2039,14 +2107,14 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
);
}
+ const writtenSections = [
+ ...new Set(validEntries.map(({ target }) => getTopLevelSection(target.fieldPath))),
+ ];
if (!hasBroadManage) {
- const sections = [
- ...new Set(validEntries.map(({ target }) => getTopLevelSection(target.fieldPath))),
- ];
const allowed = await Promise.all(
- sections.map((s) => hasConfigCapability(user, s as ConfigSection, 'manage')),
+ writtenSections.map((s) => hasConfigCapability(user, s as ConfigSection, 'manage')),
);
- const denied = sections.find((_, i) => !allowed[i]);
+ const denied = writtenSections.find((_, i) => !allowed[i]);
if (denied) {
return res.status(403).json({
error: `Insufficient permissions for config section: ${denied}`,
@@ -2080,7 +2148,10 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
const requestedPriority = hasBroadManage ? priority : undefined;
- const baseYaml = await getBaseYamlConfig(user.tenantId);
+ const [baseYaml, access] = await Promise.all([
+ getBaseYamlConfig(user.tenantId),
+ resolveWriteReadAccess(user, hasBroadManage, writtenSections),
+ ]);
const encryptedFields = encryptConfigSecretFields(fields);
const requested = validEntries.map(({ target, value }) => ({
segments: target.segments,
@@ -2145,7 +2216,7 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
fieldPaths: validEntries.map(({ target }) => describeFieldTarget(target)).join(','),
},
});
- return res.status(200).json({ config: redactConfigForResponse(config) });
+ return sendWrittenConfig(res, 200, config, access);
} catch (error) {
if (isFieldNameRejection(error)) {
return unstorableKeyResponse(res, 'patchConfigField');
@@ -2206,6 +2277,10 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
});
}
const { fieldPath } = read.target;
+ const section = getTopLevelSection(fieldPath);
+ if (!isAcceptedOverrideSection(section)) {
+ return unknownSectionResponse(res);
+ }
const removalError = getFieldRemovalError(fieldPath);
if (removalError) {
return res.status(400).json({ error: removalError.error });
@@ -2216,18 +2291,17 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
return res.status(401).json({ error: 'Authentication required' });
}
- const section = getTopLevelSection(fieldPath);
-
const hasBroadManage = await hasConfigCapability(user, null, 'manage');
if (principalId === BASE_CONFIG_PRINCIPAL_ID && !hasBroadManage) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
- if (
- !hasBroadManage &&
- !(await hasConfigCapability(user, section as ConfigSection, 'manage'))
- ) {
+ const [canManageSection, access] = await Promise.all([
+ hasBroadManage || hasConfigCapability(user, section as ConfigSection, 'manage'),
+ resolveWriteReadAccess(user, hasBroadManage, [section]),
+ ]);
+ if (!canManageSection) {
return res.status(403).json({
error: `Insufficient permissions for config section: ${section}`,
});
@@ -2288,7 +2362,7 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
target: configTarget(principalType, principalId),
metadata: { operation: 'tombstone', fieldPath },
});
- return res.status(200).json({ config: redactConfigForResponse(config) });
+ return sendWrittenConfig(res, 200, config, access);
} catch (error) {
logger.error('[adminConfig] tombstoneConfigField error:', getSafeErrorMetadata(error));
return res.status(500).json({ error: 'Failed to tombstone config field' });
@@ -2298,6 +2372,10 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
/**
* DELETE /:principalType/:principalId/fields?fieldPath=dotted.path
* (or `?segments=<JSON array>` for a path whose keys contain dots)
+ *
+ * Unlike the writes, a path under an unknown section is accepted: removing it only clears
+ * what an earlier write stored there (the merge ignores it either way), and it is the only
+ * way to drop such a tombstone without deleting the whole document.
*/
async function deleteConfigField(req: ServerRequest, res: Response): Promise<Response> {
try {
@@ -2347,10 +2425,11 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
return res.status(403).json({ error: 'Insufficient permissions' });
}
- if (
- !hasBroadManage &&
- !(await hasConfigCapability(user, section as ConfigSection, 'manage'))
- ) {
+ const [canManageSection, access] = await Promise.all([
+ hasBroadManage || hasConfigCapability(user, section as ConfigSection, 'manage'),
+ resolveWriteReadAccess(user, hasBroadManage, [section]),
+ ]);
+ if (!canManageSection) {
return res.status(403).json({
error: `Insufficient permissions for config section: ${section}`,
});
@@ -2410,34 +2489,13 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
target: configTarget(principalType, principalId),
metadata: { operation: 'unset', fieldPath: describeFieldTarget(target) },
});
- return res.status(200).json({ config: redactConfigForResponse(config) });
+ return sendWrittenConfig(res, 200, config, access);
} catch (error) {
logger.error('[adminConfig] deleteConfigField error:', getSafeErrorMetadata(error));
return res.status(500).json({ error: 'Failed to delete config field' });
}
}
- /**
- * The document a write returns, as a read would show it to the caller: redacted, and limited
- * to the sections they can read plus the ones they just managed (`manage:configs:<section>`
- * does not imply reading other sections).
- */
- async function toReadableConfig(
- user: CapabilityUser,
- config: ConfigRecord,
- access: { hasBroadManage: boolean; managedSections: readonly string[] },
- ): Promise<ConfigResponse> {
- const safeConfig = redactConfigForResponse(config);
- if (access.hasBroadManage) {
- return safeConfig;
- }
- const readable = await getReadableConfigSections(user, [
- ...new Set(collectConfigSections(safeConfig)),
- ] as ConfigSection[]);
- const sections = new Set([...readable.sections, ...access.managedSections]);
- return filterConfigDocForReadAccess(safeConfig, { broad: readable.broad, sections });
- }
-
/**
* POST /:principalType/:principalId/changes — Apply a batch of changes atomically.
*
@@ -2560,7 +2618,11 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
const requestedPriority = hasBroadManage ? (priority as number | undefined) : undefined;
- const baseYaml = await getBaseYamlConfig(user.tenantId);
+ /** A dry run returns no document, so it has no read access to resolve. */
+ const [baseYaml, access] = await Promise.all([
+ getBaseYamlConfig(user.tenantId),
+ dryRun ? NO_READ_ACCESS : resolveWriteReadAccess(user, hasBroadManage, managedSections),
+ ]);
for (const change of changes) {
if (
change.op === 'rename' &&
@@ -2749,9 +2811,7 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
...(dryRun
? {}
: {
- config: config
- ? await toReadableConfig(user, config, { hasBroadManage, managedSections })
- : null,
+ config: config ? toWrittenConfig(config, access) : null,
}),
revision: config ? getConfigRevision(config) : null,
written: outcome.written,
@@ -2914,7 +2974,12 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
metadata: { isActive },
});
}
- return res.status(200).json({ config: redactConfigForResponse(config) });
+ return sendWrittenConfig(
+ res,
+ 200,
+ config,
+ hasBroadManage ? FULL_READ_ACCESS : NO_READ_ACCESS,
+ );
} catch (error) {
logger.error('[adminConfig] toggleConfig error:', getSafeErrorMetadata(error));
return res.status(500).json({ error: 'Failed to toggle config' });
diff --git a/packages/api/src/admin/meta.spec.ts b/packages/api/src/admin/meta.spec.ts
index beb293a77f..534270642d 100644
--- a/packages/api/src/admin/meta.spec.ts
+++ b/packages/api/src/admin/meta.spec.ts
@@ -57,6 +57,12 @@ type ResponseBody = { config?: { overrides: Doc; revision?: string }; [key: stri
type MockRes = Response & { statusCode: number; body: ResponseBody | undefined };
type MockReqInit = Omit<Partial<ServerRequest>, 'body'> & { body?: object };
type PatchEntry = { fieldPath: string; value: unknown };
+type WriteHandler =
+ | 'upsertConfigOverrides'
+ | 'patchConfigField'
+ | 'tombstoneConfigField'
+ | 'deleteConfigField'
+ | 'applyConfigChanges';
function mockRes(): MockRes {
const res = { statusCode: 200, body: undefined } as MockRes;
@@ -107,26 +113,31 @@ async function getMeta(): Promise<{ status: number; meta: AdminConfigMeta }> {
return { status: res.statusCode, meta: res.body as AdminConfigMeta };
}
-async function patch(
- entries: PatchEntry[],
+async function write(
+ handler: WriteHandler,
+ init: MockReqInit,
overrides: Partial<AdminConfigDeps> = {},
): Promise<MockRes> {
const res = mockRes();
- await createHandlers(overrides).patchConfigField(
- mockReq({ params: { principalType: 'role', principalId: 'r1' }, body: { entries } }),
+ await createHandlers(overrides)[handler](
+ mockReq({ params: { principalType: 'role', principalId: 'r1' }, ...init }),
res,
);
return res;
}
-function storedConfig(overrides: Doc): ConfigRecord {
+function patch(entries: PatchEntry[], overrides: Partial<AdminConfigDeps> = {}): Promise<MockRes> {
+ return write('patchConfigField', { body: { entries } }, overrides);
+}
+
+function storedConfig(overrides: Doc, tombstones: string[] = []): ConfigRecord {
return {
_id: 'c1',
principalType: 'role',
principalId: 'r1',
priority: 10,
overrides,
- tombstones: [],
+ tombstones,
isActive: true,
configVersion: 1,
} as Partial<ConfigRecord> as ConfigRecord;
@@ -229,6 +240,21 @@ describe('GET /api/admin/config/meta', () => {
]);
});
+ it('reports every admin config behaviour this server ships as on', async () => {
+ const { meta } = await getMeta();
+ expect(meta.features).toEqual({
+ dottedKeys: true,
+ sectionAllowlist: true,
+ readFilteredWriteResponses: true,
+ webSearchStoredKeys: true,
+ expectedRevision: true,
+ prunesEmptyParents: true,
+ awaitedInvalidation: true,
+ changesBatch: true,
+ yamlMcpHide: true,
+ });
+ });
+
it('reports the override cache TTL the app config service runs with', async () => {
const res = mockRes();
await createHandlers({ overrideCacheTtlMs: 15_000 }).getConfigMeta(mockReq(), res);
@@ -376,23 +402,78 @@ const FEATURE_PROBES: Record<AdminConfigFeatureFlag, () => Promise<boolean>> = {
return keepsDots && unsafe.statusCode === 400 && flagsFixedShape;
},
async sectionAllowlist() {
- return getConfigOverrideIssues({ paths: { uploads: '/tmp' } }).length > 0;
+ const put = await write('upsertConfigOverrides', {
+ body: { overrides: { paths: { uploads: '/tmp' } } },
+ });
+ const fieldWrites = await Promise.all([
+ patch([{ fieldPath: 'paths.uploads', value: '/tmp' }]),
+ write('tombstoneConfigField', { body: { fieldPath: 'paths' } }),
+ write('applyConfigChanges', {
+ body: { ops: [{ op: 'set', fieldPath: 'paths.uploads', value: '/tmp' }] },
+ }),
+ ]);
+ const merged = mergeConfigOverrides(
+ { config: {}, paths: { uploads: '/srv/uploads' } } as Partial<AppConfig> as AppConfig,
+ [storedConfig({ paths: { uploads: '/tmp' } }), storedConfig({}, ['paths'])],
+ );
+ return (
+ put.statusCode === 400 &&
+ JSON.stringify(put.body?.issues) ===
+ JSON.stringify([{ path: 'paths', segments: ['paths'], code: 'unknown_section' }]) &&
+ fieldWrites.every((res) => res.statusCode === 400 && res.body?.code === 'UNKNOWN_SECTION') &&
+ merged.paths?.uploads === '/srv/uploads'
+ );
},
async readFilteredWriteResponses() {
- const res = await patch([{ fieldPath: 'endpoints.openAI.titleModel', value: 'gpt-4o-mini' }], {
- hasConfigCapability: jest.fn(
- async (_user, section, verb = 'manage') => verb === 'manage' && section === 'endpoints',
- ),
- getReadableConfigSections: jest.fn().mockResolvedValue({ broad: false, sections: new Set() }),
- writeConfigDocument: jest.fn().mockResolvedValue(
- storedConfig({
- endpoints: { openAI: { titleModel: 'gpt-4o-mini' } },
- memory: { disabled: true },
+ const written = storedConfig({
+ endpoints: { openAI: { titleModel: 'gpt-4o-mini' } },
+ memory: { disabled: true },
+ });
+ /** Each request gets its own store; a grant lookup made after its write fails the request. */
+ const scopedDeps = (): Partial<AdminConfigDeps> => {
+ let committed = false;
+ const commit = jest.fn(async () => {
+ committed = true;
+ return written;
+ });
+ return {
+ hasConfigCapability: jest.fn(
+ async (_user, section, verb = 'manage') => verb === 'manage' && section === 'endpoints',
+ ),
+ getReadableConfigSections: jest.fn(async () => {
+ if (committed) {
+ throw new Error('read access resolved after the write');
+ }
+ return { broad: false, sections: new Set<string>() };
}),
+ writeConfigDocument: commit,
+ tombstoneConfigField: commit,
+ unsetConfigField: commit,
+ };
+ };
+ const responses = await Promise.all([
+ patch([{ fieldPath: 'endpoints.openAI.titleModel', value: 'gpt-4o-mini' }], scopedDeps()),
+ write('tombstoneConfigField', { body: { fieldPath: 'endpoints.bedrock' } }, scopedDeps()),
+ write('deleteConfigField', { query: { fieldPath: 'endpoints.bedrock' } }, scopedDeps()),
+ write(
+ 'applyConfigChanges',
+ {
+ body: {
+ ops: [{ op: 'set', fieldPath: 'endpoints.openAI.titleModel', value: 'gpt-4o-mini' }],
+ },
+ },
+ scopedDeps(),
),
+ ]);
+ return responses.every((res) => {
+ const overrides = res.body?.config?.overrides;
+ return (
+ res.statusCode === 200 &&
+ overrides != null &&
+ 'endpoints' in overrides &&
+ !('memory' in overrides)
+ );
});
- const overrides = res.body?.config?.overrides;
- return res.statusCode === 200 && overrides != null && !('memory' in overrides);
},
async webSearchStoredKeys() {
const keys = {
diff --git a/packages/api/src/admin/meta.ts b/packages/api/src/admin/meta.ts
index df439d4ece..5962af0109 100644
--- a/packages/api/src/admin/meta.ts
+++ b/packages/api/src/admin/meta.ts
@@ -21,8 +21,8 @@ import { getConfigSecretRules } from './secrets';
*/
export const ADMIN_CONFIG_FEATURES: Readonly<AdminConfigFeatures> = {
dottedKeys: true,
- sectionAllowlist: false,
- readFilteredWriteResponses: false,
+ sectionAllowlist: true,
+ readFilteredWriteResponses: true,
webSearchStoredKeys: true,
expectedRevision: true,
prunesEmptyParents: true,
diff --git a/packages/api/src/admin/secrets.integration.spec.ts b/packages/api/src/admin/secrets.integration.spec.ts
index efd48f0a4d..e0fa3abc55 100644
--- a/packages/api/src/admin/secrets.integration.spec.ts
+++ b/packages/api/src/admin/secrets.integration.spec.ts
@@ -1378,6 +1378,10 @@ describe('config secret registry — real handlers against a real Config collect
});
describe('getBaseConfig', () => {
+ afterEach(() => {
+ delete process.env.WEST_AZURE_API_KEY;
+ });
+
it('redacts literal secrets sourced from the resolved AppConfig (e.g. YAML literals)', async () => {
const appConfig = {
speech: {
@@ -1427,5 +1431,108 @@ describe('config secret registry — real handlers against a real Config collect
expect(getAtPath(config, 'langfuse.secretKeyPreview')).toBe('*********');
expect(getAtPath(config, 'config.speech.tts.openai.apiKey')).toBeUndefined();
});
+
+ it('redacts literal Azure group keys and the Vertex service key from what AppService builds', async () => {
+ const AZURE_KEY = 'azure-literal-group-key-0123456789';
+ const PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----vertex-test-key';
+ const { AppService } = await import('@librechat/data-schemas');
+ /** `azureConfigSetup` resolves each group's key reference at load, as a deployment would. */
+ process.env.WEST_AZURE_API_KEY = 'west-env-value';
+ const appConfig = await AppService({
+ config: {
+ endpoints: {
+ azureOpenAI: {
+ groups: [
+ {
+ group: 'east',
+ apiKey: AZURE_KEY,
+ instanceName: 'east-instance',
+ version: '2024-02-01',
+ models: { 'gpt-4o': { deploymentName: 'gpt-4o' } },
+ },
+ {
+ group: 'west',
+ apiKey: '${WEST_AZURE_API_KEY}',
+ instanceName: 'west-instance',
+ version: '2024-02-01',
+ models: { 'gpt-4o-mini': { deploymentName: 'gpt-4o-mini' } },
+ },
+ ],
+ },
+ anthropic: {
+ vertex: {
+ region: 'us-east5',
+ serviceKeyFile: JSON.stringify({
+ type: 'service_account',
+ private_key: PRIVATE_KEY,
+ }),
+ models: ['claude-sonnet-4'],
+ },
+ },
+ },
+ },
+ });
+ expect(JSON.stringify(appConfig)).toContain(AZURE_KEY);
+ expect(JSON.stringify(appConfig)).toContain(PRIVATE_KEY);
+
+ const { createAdminConfigHandlers } = await import('./config');
+ const getAppConfig = jest.fn(async (_options?: { baseOnly?: boolean }) => appConfig);
+ const baseHandlers = createAdminConfigHandlers({
+ listAllConfigs: async () => [],
+ findConfigByPrincipal: async () => null,
+ 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,
+ hasConfigCapability: async () => true,
+ hasAnyConfigReadAccess: async () => true,
+ hasCapability: async () => true,
+ getAppConfig,
+ });
+
+ for (const query of [{}, { baseOnly: 'true' }]) {
+ const res = mockRes();
+ await baseHandlers.getBaseConfig(mockReq({ query }), res);
+ expect(res.statusCode).toBe(200);
+ const payload = JSON.stringify(res.body);
+ expect(payload).not.toContain(AZURE_KEY);
+ expect(payload).not.toContain(PRIVATE_KEY);
+
+ const config = res.body!.config as Record<string, unknown>;
+ expect(getAtPath(config, 'endpoints.azureOpenAI.groupMap.east.instanceName')).toBe(
+ 'east-instance',
+ );
+ expect(getAtPath(config, 'endpoints.azureOpenAI.groupMap.east.apiKey')).toBeUndefined();
+ expect(getAtPath(config, 'endpoints.azureOpenAI.groupMap.west.apiKey')).toBe(
+ '${WEST_AZURE_API_KEY}',
+ );
+ const yamlGroups = getAtPath(config, 'config.endpoints.azureOpenAI.groups') as Array<
+ Record<string, unknown>
+ >;
+ expect(yamlGroups.map((group) => group.apiKey)).toEqual([
+ undefined,
+ '${WEST_AZURE_API_KEY}',
+ ]);
+ expect(getAtPath(config, 'endpoints.anthropic.vertexConfig.region')).toBe('us-east5');
+ expect(
+ getAtPath(config, 'endpoints.anthropic.vertexConfig.serviceKeyFile'),
+ ).toBeUndefined();
+ expect(getAtPath(config, 'endpoints.anthropic.vertex.serviceKeyFile')).toBeUndefined();
+ expect(
+ getAtPath(config, 'config.endpoints.anthropic.vertex.serviceKeyFile'),
+ ).toBeUndefined();
+ }
+ expect(getAppConfig.mock.calls.map(([options]) => options?.baseOnly)).toEqual([
+ false,
+ true,
+ true,
+ ]);
+ expect(JSON.stringify(appConfig)).toContain(AZURE_KEY);
+ });
});
});
diff --git a/packages/api/src/admin/secrets.spec.ts b/packages/api/src/admin/secrets.spec.ts
index fda6a18207..cd1b7a916d 100644
--- a/packages/api/src/admin/secrets.spec.ts
+++ b/packages/api/src/admin/secrets.spec.ts
@@ -18,6 +18,7 @@ let isConfigSecretDescendantPath: typeof import('./secrets').isConfigSecretDesce
let isConfigSecretKeyRename: typeof import('./secrets').isConfigSecretKeyRename;
let preserveConfigSecrets: typeof import('./secrets').preserveConfigSecrets;
let redactConfigSecrets: typeof import('./secrets').redactConfigSecrets;
+let redactResolvedConfigSecrets: typeof import('./secrets').redactResolvedConfigSecrets;
let resolveConfigSecret: typeof import('./secrets').resolveConfigSecret;
let resolveStoredConfigSecret: typeof import('./secrets').resolveStoredConfigSecret;
let getConfigSecretRules: typeof import('./secrets').getConfigSecretRules;
@@ -41,6 +42,7 @@ beforeAll(async () => {
isConfigSecretKeyRename,
preserveConfigSecrets,
redactConfigSecrets,
+ redactResolvedConfigSecrets,
resolveConfigSecret,
resolveStoredConfigSecret,
getConfigSecretRules,
@@ -1102,6 +1104,109 @@ describe('Custom endpoint config secrets', () => {
});
});
+describe('Resolved config secrets (Azure groups and the Vertex service key)', () => {
+ const SERVICE_KEY_JSON =
+ '{"type":"service_account","private_key":"-----BEGIN PRIVATE KEY-----x"}';
+
+ it('removes literal Azure group keys from groupMap, merged groups and the raw YAML copy', () => {
+ const azure = () => ({
+ groups: [
+ { group: 'east', apiKey: 'azure-literal-east-key', instanceName: 'east' },
+ { group: 'west', apiKey: '${WEST_API_KEY}', instanceName: 'west' },
+ { group: 'user', apiKey: 'user_provided', instanceName: 'user' },
+ { group: 'blank', apiKey: '', instanceName: 'blank' },
+ ],
+ groupMap: {
+ east: {
+ apiKey: 'azure-literal-east-key',
+ instanceName: 'east',
+ models: { 'gpt-4o': true },
+ },
+ west: { apiKey: ' ${WEST_API_KEY} ', instanceName: 'west' },
+ user: { apiKey: 'user_provided', instanceName: 'user' },
+ },
+ });
+ const resolved = redactResolvedConfigSecrets({
+ endpoints: { azureOpenAI: azure() },
+ config: { endpoints: { azureOpenAI: azure() } },
+ });
+ redactResolvedConfigSecrets(resolved.config);
+
+ expect(JSON.stringify(resolved)).not.toContain('azure-literal-east-key');
+ for (const target of [resolved.endpoints.azureOpenAI, resolved.config.endpoints.azureOpenAI]) {
+ expect(target.groups.map((group) => group.apiKey)).toEqual([
+ undefined,
+ '${WEST_API_KEY}',
+ 'user_provided',
+ '',
+ ]);
+ expect(target.groups[0]).toEqual({ group: 'east', instanceName: 'east' });
+ }
+ expect(resolved.endpoints.azureOpenAI.groupMap).toEqual({
+ east: { instanceName: 'east', models: { 'gpt-4o': true } },
+ west: { apiKey: ' ${WEST_API_KEY} ', instanceName: 'west' },
+ user: { apiKey: 'user_provided', instanceName: 'user' },
+ });
+ });
+
+ it('removes the Vertex service key unless it is an unresolved environment reference', () => {
+ const resolved = redactResolvedConfigSecrets({
+ endpoints: {
+ anthropic: {
+ vertex: { serviceKeyFile: SERVICE_KEY_JSON, region: 'us-east5' },
+ vertexConfig: { serviceKeyFile: '/secrets/vertex.json', region: 'us-east5' },
+ },
+ },
+ });
+ expect(resolved.endpoints.anthropic).toEqual({
+ vertex: { region: 'us-east5' },
+ vertexConfig: { region: 'us-east5' },
+ });
+
+ const referenced = redactResolvedConfigSecrets({
+ endpoints: {
+ anthropic: {
+ vertex: { serviceKeyFile: '${GOOGLE_SERVICE_KEY_FILE}' },
+ vertexConfig: { serviceKeyFile: '${GOOGLE_SERVICE_KEY_FILE}' },
+ },
+ },
+ });
+ expect(referenced.endpoints.anthropic.vertex.serviceKeyFile).toBe('${GOOGLE_SERVICE_KEY_FILE}');
+ expect(referenced.endpoints.anthropic.vertexConfig.serviceKeyFile).toBe(
+ '${GOOGLE_SERVICE_KEY_FILE}',
+ );
+
+ const userProvided = redactResolvedConfigSecrets({
+ endpoints: { anthropic: { vertex: { serviceKeyFile: 'user_provided' } } },
+ });
+ expect(userProvided.endpoints.anthropic.vertex).toEqual({});
+ });
+
+ it('fails closed on malformed shapes: non-string values and swapped containers', () => {
+ const resolved = redactResolvedConfigSecrets({
+ endpoints: {
+ azureOpenAI: {
+ groups: { east: { apiKey: 'azure-literal-in-record' } },
+ groupMap: [{ apiKey: 'azure-literal-in-array' }, { apiKey: { nested: 'object-key' } }],
+ },
+ anthropic: { vertex: { serviceKeyFile: { private_key: 'object-key' } } },
+ },
+ });
+
+ expect(JSON.stringify(resolved)).not.toMatch(/azure-literal|object-key/);
+ });
+
+ it('leaves configs without these endpoints, and unrelated fields, untouched', () => {
+ const config = {
+ endpoints: { custom: [{ name: 'A', apiKey: 'custom-literal' }], azureOpenAI: null },
+ speech: { tts: { openai: { apiKey: 'speech-literal' } } },
+ };
+ expect(redactResolvedConfigSecrets(structuredClone(config))).toEqual(config);
+ expect(redactResolvedConfigSecrets(null)).toBeNull();
+ expect(redactResolvedConfigSecrets('text')).toBe('text');
+ });
+});
+
describe('isConfigSecretKeyRename', () => {
it('refuses a rename that would move a value onto or off a literal secret location', () => {
expect(isConfigSecretKeyRename(['webSearch'], 'serperApiKey', 'other')).toBe(true);
diff --git a/packages/api/src/admin/secrets.ts b/packages/api/src/admin/secrets.ts
index b0768181ff..bdc7ce4e26 100644
--- a/packages/api/src/admin/secrets.ts
+++ b/packages/api/src/admin/secrets.ts
@@ -74,6 +74,11 @@ interface ArraySecretField {
isPassthroughValue: (value: string) => boolean;
}
+/** `user_provided` and `${ENV_VAR}`: values that name where a credential comes from, not the credential. */
+function isCredentialReference(value: string): boolean {
+ return isUserProvided(value) || envVarRegex.test(value);
+}
+
/**
* Registry of array-item secret locations, the sibling of
* `CONFIG_SECRET_FIELDS` for secrets that live on entries of an array
@@ -85,10 +90,33 @@ const ARRAY_SECRET_FIELDS: readonly ArraySecretField[] = [
secretKey: 'apiKey',
previewKey: 'apiKeyPreview',
identityKey: 'name',
- isPassthroughValue: (value) => isUserProvided(value) || envVarRegex.test(value),
+ isPassthroughValue: isCredentialReference,
},
];
+/** A credential location in a resolved config; `*` matches every item of an array or value of a record. */
+interface ResolvedSecretField {
+ segments: readonly string[];
+ isPassthroughValue: (value: string) => boolean;
+}
+
+/**
+ * Credentials that reach the resolved config (AppService output, and the raw `librechat.yaml`
+ * copy it carries as `config`) from places the write registry above does not cover yet: Azure
+ * group keys, which `azureConfigSetup` also copies into `groupMap`, and the Vertex service key,
+ * which `vertexConfigSetup` resolves from `${ENV_VAR}` into `vertexConfig`. Reads remove them;
+ * writes to these paths are unchanged.
+ */
+const RESOLVED_SECRET_FIELDS: readonly ResolvedSecretField[] = [
+ { path: 'endpoints.azureOpenAI.groups.*.apiKey', isPassthroughValue: isCredentialReference },
+ { path: 'endpoints.azureOpenAI.groupMap.*.apiKey', isPassthroughValue: isCredentialReference },
+ { path: 'endpoints.anthropic.vertex.serviceKeyFile', isPassthroughValue: isEnvPlaceholder },
+ {
+ path: 'endpoints.anthropic.vertexConfig.serviceKeyFile',
+ isPassthroughValue: isEnvPlaceholder,
+ },
+].map(({ path, isPassthroughValue }) => ({ segments: path.split('.'), isPassthroughValue }));
+
const SECRET_FIELDS_BY_PATH = new Map<string, ConfigSecretField>(
CONFIG_SECRET_FIELDS.map((field) => [field.path, field]),
);
@@ -1100,3 +1128,50 @@ export function redactConfigSecrets<T>(
}
return root;
}
+
+/** Deletes the value at `segments` under `node` unless it is empty or a pass-through reference. */
+function redactResolvedSecret(
+ node: unknown,
+ segments: readonly string[],
+ field: ResolvedSecretField,
+): void {
+ const [segment, ...rest] = segments;
+ if (segment === '*') {
+ const children = Array.isArray(node) ? node : Object.values(getPlainRecord(node) ?? {});
+ for (const child of children) {
+ redactResolvedSecret(child, rest, field);
+ }
+ return;
+ }
+ const record = getPlainRecord(node);
+ if (!record || !Object.prototype.hasOwnProperty.call(record, segment)) {
+ return;
+ }
+ if (rest.length > 0) {
+ redactResolvedSecret(record[segment], rest, field);
+ return;
+ }
+ const value = record[segment];
+ if (typeof value === 'string') {
+ const normalized = normalizeSecretString(value);
+ if (normalized == null || field.isPassthroughValue(normalized)) {
+ return;
+ }
+ }
+ delete record[segment];
+}
+
+/**
+ * Deletes, in place, the credentials a resolved config carries outside the write registry
+ * (`RESOLVED_SECRET_FIELDS`), for admin reads of the AppConfig or its raw `config`. Empty
+ * values and pass-through references stay readable; anything else that is not a string is
+ * removed too. Stored override documents are left alone: their writes do not preserve an
+ * omitted value at these paths yet, so redacting them would break a read-then-write round
+ * trip. The caller passes a cloned object.
+ */
+export function redactResolvedConfigSecrets<T>(root: T): T {
+ for (const field of RESOLVED_SECRET_FIELDS) {
+ redactResolvedSecret(root, field.segments, field);
+ }
+ return root;
+}
diff --git a/packages/api/src/app/service.spec.ts b/packages/api/src/app/service.spec.ts
index 12d7cbba14..472147c0ab 100644
--- a/packages/api/src/app/service.spec.ts
+++ b/packages/api/src/app/service.spec.ts
@@ -11,9 +11,9 @@ import {
import { getProviderConfig } from '~/endpoints/config/providers';
/** Extends AppConfig with mock fields used by merge behavior tests. */
+/** `version` is a plain string section, so a test can mark which override layer it read. */
interface TestConfig extends AppConfig {
- restricted?: boolean;
- x?: string;
+ version?: string;
}
/**
@@ -345,7 +345,7 @@ describe('createAppConfigService', () => {
getApplicableConfigs: jest
.fn()
.mockImplementation(async () => [
- { priority: 10, overrides: { x: getTenantId() }, isActive: true },
+ { priority: 10, overrides: { version: getTenantId() }, isActive: true },
]),
});
const { getAppConfig, clearOverrideCache } = createAppConfigService(deps);
@@ -353,10 +353,10 @@ describe('createAppConfigService', () => {
tenantStorage.run({ tenantId: tenant }, () =>
getAppConfig({ role: 'USER', tenantId: stale }),
);
- expect(((await read('tenant-a', 'tenant-b')) as TestConfig).x).toBe('tenant-a');
- expect(((await read('tenant-b', 'tenant-a')) as TestConfig).x).toBe('tenant-b');
- expect(((await read('tenant-a', 'tenant-b')) as TestConfig).x).toBe('tenant-a');
- expect(((await read('tenant-b', 'tenant-a')) as TestConfig).x).toBe('tenant-b');
+ expect(((await read('tenant-a', 'tenant-b')) as TestConfig).version).toBe('tenant-a');
+ expect(((await read('tenant-b', 'tenant-a')) as TestConfig).version).toBe('tenant-b');
+ expect(((await read('tenant-a', 'tenant-b')) as TestConfig).version).toBe('tenant-a');
+ expect(((await read('tenant-b', 'tenant-a')) as TestConfig).version).toBe('tenant-b');
expect(deps.getApplicableConfigs).toHaveBeenCalledTimes(2);
await clearOverrideCache('tenant-a');
await read('tenant-b', 'tenant-a');
@@ -369,31 +369,31 @@ describe('createAppConfigService', () => {
getApplicableConfigs: jest
.fn()
.mockImplementation(async () => [
- { priority: 10, overrides: { x: getTenantId() ?? 'global' }, isActive: true },
+ { priority: 10, overrides: { version: getTenantId() ?? 'global' }, isActive: true },
]),
});
const { getAppConfig, clearOverrideCache } = createAppConfigService(deps);
const global = () => getAppConfig({ role: 'USER' });
const tenant = () => getAppConfig({ role: 'USER', tenantId: '__default__' });
- expect(((await global()) as TestConfig).x).toBe('global');
- expect(((await tenant()) as TestConfig).x).toBe('__default__');
- expect(((await global()) as TestConfig).x).toBe('global');
+ expect(((await global()) as TestConfig).version).toBe('global');
+ expect(((await tenant()) as TestConfig).version).toBe('__default__');
+ expect(((await global()) as TestConfig).version).toBe('global');
expect(deps.getApplicableConfigs).toHaveBeenCalledTimes(2);
await clearOverrideCache('__default__');
await global();
expect(deps.getApplicableConfigs).toHaveBeenCalledTimes(2);
- expect(((await tenant()) as TestConfig).x).toBe('__default__');
+ expect(((await tenant()) as TestConfig).version).toBe('__default__');
expect(deps.getApplicableConfigs).toHaveBeenCalledTimes(3);
});
it('ignores override cache entries written by heads with stale tenant-key selection', async () => {
const deps = createDeps();
- await deps._cache.set('_OVERRIDE_:tenant-a:USER', { x: 'tenant-b' });
+ await deps._cache.set('_OVERRIDE_:tenant-a:USER', { version: 'tenant-b' });
const { getAppConfig } = createAppConfigService(deps);
const config = await tenantStorage.run({ tenantId: 'tenant-a' }, () =>
getAppConfig({ role: 'USER' }),
);
- expect((config as TestConfig).x).toBeUndefined();
+ expect((config as TestConfig).version).toBeUndefined();
expect(deps.getApplicableConfigs).toHaveBeenCalledTimes(1);
});
@@ -753,6 +753,44 @@ describe('createAppConfigService', () => {
expect(config.modelSpecs?.list?.[0]?.preset?.agent_id).toBe('agent_abc');
});
+ /**
+ * `paths` drives where uploads are written and deleted, and `config` is the raw
+ * librechat.yaml that operator-only readers trust; neither is a `configSchema` section,
+ * so an override stored under one (or a tombstone on one) must not reach them.
+ */
+ it('ignores stored overrides and tombstones on runtime state outside configSchema', async () => {
+ const baseConfig = {
+ paths: { uploads: '/srv/uploads', imageOutput: '/srv/images' },
+ config: { permissions: { leaseTtlMs: 60_000 } },
+ interfaceConfig: { modelSelect: true, prompts: true },
+ };
+ const deps = createDeps({
+ loadBaseConfig: jest.fn().mockResolvedValue(baseConfig),
+ getApplicableConfigs: jest.fn().mockResolvedValue([
+ {
+ principalType: 'role',
+ principalId: 'USER',
+ priority: 10,
+ isActive: true,
+ overrides: {
+ paths: { uploads: '/tmp/attacker' },
+ config: { permissions: { leaseTtlMs: 1 } },
+ interfaceConfig: { prompts: false },
+ interface: { modelSelect: false },
+ },
+ tombstones: ['paths.imageOutput', 'config'],
+ },
+ ]),
+ });
+ const { getAppConfig } = createAppConfigService(deps);
+
+ const config = await getAppConfig({ role: 'USER' });
+
+ expect(config.paths).toEqual(baseConfig.paths);
+ expect(config.config).toEqual(baseConfig.config);
+ expect(config.interfaceConfig).toEqual({ modelSelect: false, prompts: true });
+ });
+
it('leaves unknown colors out of a theme a DB override supplies', async () => {
const deps = createDeps({
getApplicableConfigs: jest.fn().mockResolvedValue([
@@ -905,7 +943,7 @@ describe('createAppConfigService', () => {
const deps = createDeps({
getApplicableConfigs: jest
.fn()
- .mockResolvedValue([{ priority: 10, overrides: { x: 1 }, isActive: true }]),
+ .mockResolvedValue([{ priority: 10, overrides: { version: '1' }, isActive: true }]),
});
const { getAppConfig } = createAppConfigService(deps);
@@ -920,7 +958,7 @@ describe('createAppConfigService', () => {
getApplicableConfigs: jest
.fn()
.mockResolvedValue([
- { priority: 100, overrides: { x: 'user-specific' }, isActive: true },
+ { priority: 100, overrides: { version: 'user-specific' }, isActive: true },
]),
});
const { getAppConfig } = createAppConfigService(deps);
@@ -935,7 +973,7 @@ describe('createAppConfigService', () => {
const deps = createDeps({
getApplicableConfigs: jest
.fn()
- .mockResolvedValue([{ priority: 100, overrides: { y: 1 }, isActive: true }]),
+ .mockResolvedValue([{ priority: 100, overrides: { version: '1' }, isActive: true }]),
});
const { getAppConfig } = createAppConfigService(deps);
@@ -952,7 +990,7 @@ describe('createAppConfigService', () => {
const deps = createDeps({
getApplicableConfigs: jest
.fn()
- .mockResolvedValue([{ priority: 10, overrides: { x: 1 }, isActive: true }]),
+ .mockResolvedValue([{ priority: 10, overrides: { version: '1' }, isActive: true }]),
});
const { getAppConfig } = createAppConfigService(deps);
@@ -970,12 +1008,12 @@ describe('createAppConfigService', () => {
await getAppConfig();
mockGetConfigs.mockResolvedValueOnce([
- { priority: 10, overrides: { restricted: true }, isActive: true },
+ { priority: 10, overrides: { secureImageLinks: true }, isActive: true },
]);
const config = await getAppConfig({ role: 'ADMIN' });
expect(mockGetConfigs).toHaveBeenCalledTimes(2);
- expect((config as TestConfig).restricted).toBe(true);
+ expect((config as TestConfig).secureImageLinks).toBe(true);
});
it('does not short-circuit other users when one user has no overrides', async () => {
@@ -987,12 +1025,12 @@ describe('createAppConfigService', () => {
expect(mockGetConfigs).toHaveBeenCalledTimes(1);
mockGetConfigs.mockResolvedValueOnce([
- { priority: 10, overrides: { x: 'admin-only' }, isActive: true },
+ { priority: 10, overrides: { version: 'admin-only' }, isActive: true },
]);
const config = await getAppConfig({ role: 'ADMIN' });
expect(mockGetConfigs).toHaveBeenCalledTimes(2);
- expect((config as TestConfig).x).toBe('admin-only');
+ expect((config as TestConfig).version).toBe('admin-only');
});
it('passes empty principals to getApplicableConfigs when buildPrincipals returns empty', async () => {
@@ -1063,7 +1101,9 @@ describe('createAppConfigService', () => {
const deps = createDeps({
getApplicableConfigs: jest
.fn()
- .mockResolvedValue([{ priority: 5, overrides: { restricted: true }, isActive: true }]),
+ .mockResolvedValue([
+ { priority: 5, overrides: { secureImageLinks: true }, isActive: true },
+ ]),
});
const { getAppConfig } = createAppConfigService(deps);
@@ -1072,7 +1112,7 @@ describe('createAppConfigService', () => {
);
expect(deps.getApplicableConfigs).toHaveBeenCalledWith([]);
- expect((config as TestConfig).restricted).toBe(true);
+ expect((config as TestConfig).secureImageLinks).toBe(true);
});
});
@@ -1099,7 +1139,7 @@ describe('createAppConfigService', () => {
const deps = createDeps({
getApplicableConfigs: jest
.fn()
- .mockResolvedValue([{ priority: 10, overrides: { x: 1 }, isActive: true }]),
+ .mockResolvedValue([{ priority: 10, overrides: { version: '1' }, isActive: true }]),
});
const { getAppConfig } = createAppConfigService(deps);
@@ -1123,20 +1163,20 @@ describe('createAppConfigService', () => {
getApplicableConfigs: jest
.fn()
.mockImplementation(async () => [
- { priority: 10, overrides: { whoami: getTenantId() }, isActive: true },
+ { priority: 10, overrides: { version: getTenantId() }, isActive: true },
]),
});
const { getAppConfig } = createAppConfigService(deps);
const configA = (await tenantStorage.run({ tenantId: 'tenant-a' }, async () =>
getAppConfig({ role: 'USER' }),
- )) as TestConfig & { whoami?: string };
+ )) as TestConfig;
const configB = (await tenantStorage.run({ tenantId: 'tenant-b' }, async () =>
getAppConfig({ role: 'USER' }),
- )) as TestConfig & { whoami?: string };
+ )) as TestConfig;
- expect(configA.whoami).toBe('tenant-a');
- expect(configB.whoami).toBe('tenant-b');
+ expect(configA.version).toBe('tenant-a');
+ expect(configB.version).toBe('tenant-b');
// A cache collision would short-circuit the second tenant's DB read.
expect(deps.getApplicableConfigs).toHaveBeenCalledTimes(2);
});
@@ -1348,8 +1388,14 @@ describe('createAppConfigService', () => {
/** A reload that read librechat.yaml before a clear must not be what the clear leaves cached. */
describe('while a reload is in flight', () => {
const tick = () => new Promise((resolve) => setImmediate(resolve));
- const stale = { x: 'stale', availableTools: { staleTool: {} } } as unknown as TestConfig;
- const fresh = { x: 'fresh', availableTools: { freshTool: {} } } as unknown as TestConfig;
+ const stale = {
+ version: 'stale',
+ availableTools: { staleTool: {} },
+ } as unknown as TestConfig;
+ const fresh = {
+ version: 'fresh',
+ availableTools: { freshTool: {} },
+ } as unknown as TestConfig;
async function startStaleReload() {
const deps = createDeps();
@@ -1380,10 +1426,12 @@ describe('createAppConfigService', () => {
expect(deps.loadBaseConfig).toHaveBeenCalledTimes(2);
settleStale(stale);
- expect(((await staleRead) as TestConfig).x).toBe('stale');
- expect(((await freshRead) as TestConfig).x).toBe('fresh');
+ expect(((await staleRead) as TestConfig).version).toBe('stale');
+ expect(((await freshRead) as TestConfig).version).toBe('fresh');
expect(deps.loadBaseConfig).toHaveBeenCalledTimes(3);
- expect(((await service.getAppConfig({ baseOnly: true })) as TestConfig).x).toBe('fresh');
+ expect(((await service.getAppConfig({ baseOnly: true })) as TestConfig).version).toBe(
+ 'fresh',
+ );
expect(deps.loadBaseConfig).toHaveBeenCalledTimes(3);
expect(deps.setCachedTools).not.toHaveBeenCalledWith(stale.availableTools);
expect(deps.setCachedTools).toHaveBeenLastCalledWith(fresh.availableTools);
@@ -1396,7 +1444,9 @@ describe('createAppConfigService', () => {
await staleRead;
expect(deps._cache._store.has('app_config:_BASE_')).toBe(false);
- expect(((await service.getAppConfig({ baseOnly: true })) as TestConfig).x).toBe('fresh');
+ expect(((await service.getAppConfig({ baseOnly: true })) as TestConfig).version).toBe(
+ 'fresh',
+ );
});
it('does not restore the last good config over the clear when the stale reload fails', async () => {
@@ -1406,7 +1456,9 @@ describe('createAppConfigService', () => {
expect(await staleRead).toEqual(deps._baseConfig);
expect(deps._cache._store.has('app_config:_BASE_')).toBe(false);
- expect(((await service.getAppConfig({ baseOnly: true })) as TestConfig).x).toBe('fresh');
+ expect(((await service.getAppConfig({ baseOnly: true })) as TestConfig).version).toBe(
+ 'fresh',
+ );
});
});
@@ -1437,9 +1489,9 @@ describe('createAppConfigService', () => {
const deps = createDeps({
loadBaseConfig: jest
.fn()
- .mockResolvedValueOnce({ x: 'first' })
- .mockResolvedValueOnce({ x: 'stale' })
- .mockResolvedValue({ x: 'fresh' }),
+ .mockResolvedValueOnce({ version: 'first' })
+ .mockResolvedValueOnce({ version: 'stale' })
+ .mockResolvedValue({ version: 'fresh' }),
});
const service = createAppConfigService(deps);
await service.getAppConfig({ baseOnly: true });
@@ -1451,17 +1503,21 @@ describe('createAppConfigService', () => {
await service.clearAppConfigCache();
release();
- expect(((await staleRead) as TestConfig).x).toBe('stale');
+ expect(((await staleRead) as TestConfig).version).toBe('stale');
expect(deps._cache._store.has('app_config:_BASE_')).toBe(false);
- expect(((await service.getAppConfig({ baseOnly: true })) as TestConfig).x).toBe('fresh');
+ expect(((await service.getAppConfig({ baseOnly: true })) as TestConfig).version).toBe(
+ 'fresh',
+ );
});
it('removes the overtaken merge so the next read merges again', async () => {
const deps = createDeps({
getApplicableConfigs: jest
.fn()
- .mockResolvedValueOnce([{ priority: 10, overrides: { x: 'stale' }, isActive: true }])
- .mockResolvedValue([{ priority: 10, overrides: { x: 'fresh' }, isActive: true }]),
+ .mockResolvedValueOnce([
+ { priority: 10, overrides: { version: 'stale' }, isActive: true },
+ ])
+ .mockResolvedValue([{ priority: 10, overrides: { version: 'fresh' }, isActive: true }]),
});
const service = createAppConfigService(deps);
await service.getAppConfig({ baseOnly: true });
@@ -1472,8 +1528,10 @@ describe('createAppConfigService', () => {
await service.clearOverrideCache();
release();
- expect(((await staleRead) as TestConfig).x).toBe('stale');
- expect(((await service.getAppConfig({ role: 'ADMIN' })) as TestConfig).x).toBe('fresh');
+ expect(((await staleRead) as TestConfig).version).toBe('stale');
+ expect(((await service.getAppConfig({ role: 'ADMIN' })) as TestConfig).version).toBe(
+ 'fresh',
+ );
expect(deps.getApplicableConfigs).toHaveBeenCalledTimes(2);
});
});
@@ -1484,8 +1542,8 @@ describe('createAppConfigService', () => {
const deps = createDeps({
loadBaseConfig: jest
.fn()
- .mockResolvedValueOnce({ x: 'before' })
- .mockResolvedValue({ x: 'after' }),
+ .mockResolvedValueOnce({ version: 'before' })
+ .mockResolvedValue({ version: 'after' }),
getUserPrincipals: jest
.fn()
.mockImplementationOnce(() => new Promise((resolve) => (releasePrincipals = resolve)))
@@ -1498,11 +1556,11 @@ describe('createAppConfigService', () => {
await new Promise((resolve) => setImmediate(resolve));
await clearAppConfigCache();
releasePrincipals(principals);
- expect(((await inFlight) as TestConfig).x).toBe('before');
+ expect(((await inFlight) as TestConfig).version).toBe('before');
const next = (await getAppConfig({ role: 'USER', userId: 'uid1' })) as TestConfig;
- expect(next.x).toBe('after');
+ expect(next.version).toBe('after');
});
});
@@ -1511,7 +1569,7 @@ describe('createAppConfigService', () => {
const deps = createDeps({
getApplicableConfigs: jest
.fn()
- .mockResolvedValue([{ priority: 10, overrides: { x: 1 }, isActive: true }]),
+ .mockResolvedValue([{ priority: 10, overrides: { version: '1' }, isActive: true }]),
});
const { getAppConfig, clearOverrideCache } = createAppConfigService(deps);
@@ -1531,7 +1589,7 @@ describe('createAppConfigService', () => {
const deps = createDeps({
getApplicableConfigs: jest
.fn()
- .mockResolvedValue([{ priority: 10, overrides: { x: 1 }, isActive: true }]),
+ .mockResolvedValue([{ priority: 10, overrides: { version: '1' }, isActive: true }]),
});
const { getAppConfig, clearOverrideCache } = createAppConfigService(deps);
@@ -1577,8 +1635,8 @@ describe('createAppConfigService', () => {
['the same tenant', 'tenant-a', 'tenant-a'],
])('drops a merge read before a clear of %s', async (_label, cleared, tenantId) => {
let releaseRead: (configs: unknown[]) => void = () => undefined;
- const stale = [{ priority: 10, overrides: { x: 'stale' }, isActive: true }];
- const fresh = [{ priority: 10, overrides: { x: 'fresh' }, isActive: true }];
+ const stale = [{ priority: 10, overrides: { version: 'stale' }, isActive: true }];
+ const fresh = [{ priority: 10, overrides: { version: 'fresh' }, isActive: true }];
const deps = createDeps({
getApplicableConfigs: jest
.fn()
@@ -1591,11 +1649,11 @@ describe('createAppConfigService', () => {
await new Promise((resolve) => setImmediate(resolve));
await clearOverrideCache(cleared);
releaseRead(stale);
- expect(((await inFlight) as TestConfig).x).toBe('stale');
+ expect(((await inFlight) as TestConfig).version).toBe('stale');
const next = (await getAppConfig({ role: 'ADMIN', tenantId })) as TestConfig;
- expect(next.x).toBe('fresh');
+ expect(next.version).toBe('fresh');
expect(deps.getApplicableConfigs).toHaveBeenCalledTimes(2);
});
@@ -1612,7 +1670,7 @@ describe('createAppConfigService', () => {
const inFlight = getAppConfig({ role: 'ADMIN', tenantId: 'tenant-a' });
await new Promise((resolve) => setImmediate(resolve));
await clearOverrideCache('tenant-b');
- releaseRead([{ priority: 10, overrides: { x: 1 }, isActive: true }]);
+ releaseRead([{ priority: 10, overrides: { version: '1' }, isActive: true }]);
await inFlight;
await getAppConfig({ role: 'ADMIN', tenantId: 'tenant-a' });
@@ -1625,9 +1683,13 @@ describe('createAppConfigService', () => {
const deps = createDeps({
getApplicableConfigs: jest
.fn()
- .mockResolvedValueOnce([{ priority: 10, overrides: { x: 'first' }, isActive: true }])
- .mockResolvedValueOnce([{ priority: 10, overrides: { x: 'second' }, isActive: true }])
- .mockResolvedValue([{ priority: 10, overrides: { x: 'third' }, isActive: true }]),
+ .mockResolvedValueOnce([
+ { priority: 10, overrides: { version: 'first' }, isActive: true },
+ ])
+ .mockResolvedValueOnce([
+ { priority: 10, overrides: { version: 'second' }, isActive: true },
+ ])
+ .mockResolvedValue([{ priority: 10, overrides: { version: 'third' }, isActive: true }]),
});
const { getAppConfig } = createAppConfigService(deps);
@@ -1639,9 +1701,9 @@ describe('createAppConfigService', () => {
})) as TestConfig;
const again = (await getAppConfig({ role: 'ADMIN' })) as TestConfig;
- expect(cached.x).toBe('first');
- expect(bypassed.x).toBe('second');
- expect(again.x).toBe('first');
+ expect(cached.version).toBe('first');
+ expect(bypassed.version).toBe('second');
+ expect(again.version).toBe('first');
expect(deps._cache.set).not.toHaveBeenCalled();
expect(deps.loadBaseConfig).toHaveBeenCalledTimes(1);
});
@@ -1652,7 +1714,7 @@ describe('createAppConfigService', () => {
const deps = createDeps({
getApplicableConfigs: jest
.fn()
- .mockResolvedValue([{ priority: 10, overrides: { x: 1 }, isActive: true }]),
+ .mockResolvedValue([{ priority: 10, overrides: { version: '1' }, isActive: true }]),
});
const { getAppConfig } = createAppConfigService(deps);
const resolvedPrincipals = [{ principalType: 'group', principalId: 'g1' }];
@@ -1683,7 +1745,7 @@ describe('createAppConfigService', () => {
createDeps({
getApplicableConfigs: jest
.fn()
- .mockResolvedValue([{ priority: 10, overrides: { x: 1 }, isActive: true }]),
+ .mockResolvedValue([{ priority: 10, overrides: { version: '1' }, isActive: true }]),
...overrides,
});
diff --git a/packages/data-schemas/src/app/resolution.spec.ts b/packages/data-schemas/src/app/resolution.spec.ts
index 4c265fd400..071bcb660f 100644
--- a/packages/data-schemas/src/app/resolution.spec.ts
+++ b/packages/data-schemas/src/app/resolution.spec.ts
@@ -593,13 +593,13 @@ describe('mergeConfigOverrides', () => {
__proto__: { polluted: true },
constructor: { bad: true },
prototype: { evil: true },
- safe: 'ok',
+ registration: { enabled: false },
},
10,
),
];
const result = mergeConfigOverrides(baseConfig, configs) as unknown as Record<string, unknown>;
- expect(result.safe).toBe('ok');
+ expect(result.registration).toEqual({ enabled: false });
expect(({} as Record<string, unknown>).polluted).toBeUndefined();
expect(Object.prototype.hasOwnProperty.call(result, 'constructor')).toBe(false);
expect(Object.prototype.hasOwnProperty.call(result, 'prototype')).toBe(false);
@@ -912,21 +912,27 @@ describe('mergeConfigOverrides', () => {
});
});
- it('drops process-backed MCP servers supplied through the runtime config alias', () => {
+ it('ignores servers supplied through the runtime config alias, process-backed or not', () => {
+ const base = {
+ mcpConfig: { github: { type: 'streamable-http', url: 'https://github.example.com' } },
+ } as unknown as AppConfig;
const configs = [
fakeConfig(
{
mcpConfig: {
injected: { command: '/bin/sh', args: ['-c', 'id'] },
+ remote: { type: 'streamable-http', url: 'https://attacker.example.com' },
},
},
10,
),
];
- const result = mergeConfigOverrides(baseConfig, configs) as unknown as Record<string, unknown>;
+ const result = mergeConfigOverrides(base, configs) as unknown as Record<string, unknown>;
- expect(result.mcpConfig).toEqual({});
+ expect(result.mcpConfig).toEqual({
+ github: { type: 'streamable-http', url: 'https://github.example.com' },
+ });
});
it('applies tombstones after remapping YAML paths to AppConfig paths', () => {
@@ -1773,10 +1779,10 @@ describe('getConfigOverrideIssues', () => {
).toEqual([]);
});
- it('accepts keys the schema does not define and stored secret shapes', () => {
- expect(
- getConfigOverrideIssues({ unknownSection: 5, registration: { enabled: false } }),
- ).toEqual([]);
+ it('accepts keys the schema does not define inside a known section, and stored secret shapes', () => {
+ expect(getConfigOverrideIssues({ registration: { enabled: false, futureOption: 5 } })).toEqual(
+ [],
+ );
expect(
getConfigOverrideIssues({
endpoints: {
@@ -2069,6 +2075,138 @@ describe('getConfigFieldIssues', () => {
});
});
+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 = [
+ 'paths',
+ 'config',
+ 'availableTools',
+ 'interfaceConfig',
+ 'turnstileConfig',
+ 'mcpConfig',
+ ];
+
+ const base = {
+ paths: { uploads: '/srv/uploads', imageOutput: '/srv/images' },
+ config: { permissions: { leaseTtlMs: 60_000 }, rateLimits: { fileUploads: { ipMax: 100 } } },
+ availableTools: { calculator: { type: 'function' } },
+ interfaceConfig: { modelSelect: true, prompts: true },
+ turnstileConfig: { siteKey: 'site' },
+ mcpConfig: { github: { type: 'streamable-http', url: 'https://github.example.com' } },
+ registration: { enabled: true },
+ } as unknown as AppConfig;
+
+ let warn: jest.SpyInstance;
+ beforeEach(() => {
+ warn = jest.spyOn(logger, 'warn').mockReturnValue(logger);
+ });
+ afterEach(() => {
+ warn.mockRestore();
+ });
+
+ it('accepts exactly the sections configSchema defines', () => {
+ for (const section of ['interface', 'mcpServers', 'turnstile', 'endpoints', 'filters']) {
+ expect(isAcceptedOverrideSection(section)).toBe(true);
+ }
+ for (const key of [...RUNTIME_KEYS, '', 'toString', 'constructor', '__proto__']) {
+ expect(isAcceptedOverrideSection(key)).toBe(false);
+ }
+ });
+
+ it('reports every top-level key outside configSchema as unknown_section', () => {
+ const overrides = Object.fromEntries([
+ ...RUNTIME_KEYS.map((key) => [key, { uploads: '/tmp' }]),
+ ['registration', { enabled: false }],
+ ]);
+
+ expect(getConfigOverrideIssues(overrides)).toEqual(
+ RUNTIME_KEYS.map((key) => ({ path: key, segments: [key], code: 'unknown_section' })),
+ );
+ });
+
+ it('reports a dotted top-level key once, as dotted_key rather than unknown_section', () => {
+ expect(getConfigOverrideIssues({ 'paths.uploads': '/tmp', config: {} })).toEqual([
+ { path: 'paths.uploads', segments: ['paths.uploads'], code: 'dotted_key' },
+ { path: 'config', segments: ['config'], code: 'unknown_section' },
+ ]);
+ });
+
+ it('still validates the known sections written next to an unknown one', () => {
+ expect(
+ getConfigOverrideIssues({
+ paths: { uploads: '/tmp' },
+ registration: { oauthStateTtlMs: 5 },
+ }).map(({ path, code }) => ({ path, code })),
+ ).toEqual([
+ { path: 'paths', code: 'unknown_section' },
+ { path: 'registration.oauthStateTtlMs', code: 'too_small' },
+ ]);
+ });
+
+ it('reports a field write under an unknown section', () => {
+ expect(
+ getConfigFieldIssues({ 'interfaceConfig.prompts': false }).map(({ path, code }) => ({
+ path,
+ code,
+ })),
+ ).toEqual([{ path: 'interfaceConfig', code: 'unknown_section' }]);
+ });
+
+ it('does not let an unknown section stored earlier block an unrelated field write', () => {
+ const stored = { overrides: { paths: { uploads: '/tmp' } }, tombstones: ['config'] };
+
+ expect(getConfigFieldIssues({ 'registration.enabled': false }, {}, stored)).toEqual([]);
+ });
+
+ it('ignores stored overrides and tombstones outside configSchema at merge', () => {
+ const merged = mergeConfigOverrides(base, [
+ fakeConfig(
+ {
+ paths: { uploads: '/tmp/attacker' },
+ config: { permissions: { leaseTtlMs: 1 }, rateLimits: {} },
+ availableTools: { injected: { type: 'function' } },
+ interfaceConfig: { prompts: false, modelSelect: false },
+ turnstileConfig: { siteKey: 'attacker' },
+ mcpConfig: { injected: { type: 'streamable-http', url: 'https://attacker.example.com' } },
+ registration: { enabled: false },
+ },
+ 10,
+ ['paths', 'config.permissions', 'interfaceConfig.modelSelect', 'mcpConfig.github'],
+ ),
+ ]);
+
+ expect(merged).toEqual({ ...base, registration: { enabled: false } });
+ });
+
+ it('keeps tombstones and overrides of known sections in the same document', () => {
+ const merged = mergeConfigOverrides(base, [
+ fakeConfig({ paths: { uploads: '/tmp' }, interface: { modelSelect: false } }, 10, [
+ 'paths.uploads',
+ 'mcpServers.github',
+ ]),
+ ]) as unknown as Record<string, unknown>;
+
+ expect(merged.paths).toEqual(base.paths);
+ expect(merged.interfaceConfig).toEqual({ modelSelect: false, prompts: true });
+ expect(merged.mcpConfig).toEqual({});
+ });
+
+ it('warns once per document, naming the ignored sections but none of their values', () => {
+ mergeConfigOverrides(base, [
+ fakeConfig({ paths: { uploads: '/tmp/attacker' }, config: { secret: 'leak' } }, 10, [
+ 'paths.uploads',
+ 'interfaceConfig.prompts',
+ ]),
+ fakeConfig({ registration: { enabled: false } }, 20, undefined, 'clean'),
+ ]);
+
+ const messages = warn.mock.calls.map(([message]) => String(message));
+ expect(messages).toEqual([
+ '[mergeConfigOverrides] Ignoring unknown config sections paths, config, interfaceConfig for role/test',
+ ]);
+ });
+});
+
describe('getConfigFieldIssues: tombstones a write clears', () => {
const unionBase = {
memory: { agent: { id: 'agent_yaml' } },
diff --git a/packages/data-schemas/src/app/resolution.ts b/packages/data-schemas/src/app/resolution.ts
index 490ee9bff0..bc9d809201 100644
--- a/packages/data-schemas/src/app/resolution.ts
+++ b/packages/data-schemas/src/app/resolution.ts
@@ -307,9 +307,9 @@ export type ConfigOverrideIssue = {
segments: string[];
/**
* A stable, machine-readable reason: a zod issue code (`invalid_type`, `custom`, ...),
- * `missing_merge_key`, `duplicate_merge_key`, `indexed_merge_key_write`, `union_dropped_key`,
- * `dotted_key`, or `invalid_document`. Schema messages are not carried because they can echo
- * the submitted values.
+ * `unknown_section`, `missing_merge_key`, `duplicate_merge_key`, `indexed_merge_key_write`,
+ * `union_dropped_key`, `dotted_key`, or `invalid_document`. Schema messages are not carried
+ * because they can echo the submitted values.
*/
code: string;
};
@@ -761,9 +761,11 @@ export function getDottedSectionIssues(overrides: unknown): ConfigOverrideIssue[
* to the override node that caused it. Unions, refinements, required fields and defaults
* are therefore judged on the merged result, not on the patch alone. An issue caused only
* by leaving something out (a required or related field another layer may supply) is not
- * reported, except inside an array the merge replaces, where nothing can supply it. Keys the
- * schema does not define are accepted unchanged; a key holding a dot is a `dotted_key` issue
- * unless it sits where the schema has a record.
+ * reported, except inside an array the merge replaces, where nothing can supply it. A top-level
+ * key that is not a `configSchema` section is reported as `unknown_section` (or as `dotted_key`
+ * alone when it holds a dot); keys the schema does not define inside a known section are
+ * accepted unchanged, and a key holding a dot is a `dotted_key` issue unless it sits where the
+ * schema has a record.
*/
export function getConfigOverrideIssues(
overrides: unknown,
@@ -778,6 +780,9 @@ export function getConfigOverrideIssues(
const shape = configSchema.shape;
for (const section of Object.keys(overrides)) {
if (!hasOwn(shape, section)) {
+ if (!seen.has(section)) {
+ issues.push(toIssue([section], 'unknown_section'));
+ }
continue;
}
const schema = shape[section as keyof typeof shape] as unknown as SchemaNode;
@@ -1168,6 +1173,49 @@ function bindWebSearchKeys(merged: AppConfig, writers: WebSearchWriters): AppCon
return { ...merged, webSearch };
}
+/**
+ * The document with only what the merge may apply: override keys and tombstones under a
+ * top-level section `configSchema` defines. Anything else was stored before writes were
+ * checked (or by another writer) and would reach runtime state no override may set, so it is
+ * dropped here, which neutralizes it without a migration. One warning per document.
+ */
+function withAcceptedSections(config: ConfigOverrideLayer): ConfigOverrideLayer {
+ const ignored = new Set<string>();
+ let overrides = config.overrides;
+ if (isPlainObject(overrides)) {
+ const accepted: AnyObject = {};
+ for (const [key, value] of Object.entries(overrides)) {
+ if (isAcceptedOverrideSection(key)) {
+ accepted[key] = value;
+ } else {
+ ignored.add(key);
+ }
+ }
+ overrides = accepted as Partial<TCustomConfig>;
+ }
+ let tombstones = config.tombstones;
+ if (Array.isArray(tombstones)) {
+ tombstones = tombstones.filter((path) => {
+ if (typeof path !== 'string') {
+ return false;
+ }
+ const section = path.split('.')[0];
+ if (isAcceptedOverrideSection(section)) {
+ return true;
+ }
+ ignored.add(section);
+ return false;
+ });
+ }
+ if (ignored.size === 0) {
+ return config;
+ }
+ logger.warn(
+ `[mergeConfigOverrides] Ignoring unknown config sections ${[...ignored].join(', ')} for ${config.principalType}/${config.principalId}`,
+ );
+ return { ...config, overrides, tombstones };
+}
+
/**
* Merge DB config overrides into a base AppConfig.
*
@@ -1191,7 +1239,7 @@ export function mergeConfigOverrides(
let raw: Partial<TCustomConfig> = baseConfig.config ?? {};
const webSearchWriters: WebSearchWriters = new Map();
for (let order = 0; order < sorted.length; order++) {
- const config = sorted[order];
+ const config = withAcceptedSections(sorted[order]);
const isBasePrincipal = config.principalId?.toString() === BASE_CONFIG_PRINCIPAL_ID;
if (Array.isArray(config.tombstones)) {
const removal: WebSearchWriter = { config, order, removed: true };