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

🔐 feat: Admin Config Secrets v2 (MCP and Azure Credentials, Re-entry, Env Allowlist, Rebinding) (#17353)

Danny Aviladb225c09190a
diff --git a/.env.example b/.env.example
index dc2eafe767..9fe1f8d087 100644
--- a/.env.example
+++ b/.env.example
@@ -247,6 +247,15 @@ NODE_MAX_OLD_SPACE_SIZE=6144
# CONFIG_PATH="/alternative/path/to/librechat.yaml"
+# Config overrides written through the admin API (profiles and the Base profile) may reference
+# only the ${ENV_VAR} names librechat.yaml references, the built-in endpoint credentials
+# (OPENAI_API_KEY, ANTHROPIC_API_KEY, ...), and the names listed here (comma or space separated).
+# Any other reference is rejected on write and resolves to nothing at runtime. Only the interface
+# and modelSpecs sections and these prompt fields are left unchecked, because they are used as
+# written: each endpoint's title, activity and reasoning-label prompts, summarization.prompt and
+# updatePrompt, memory.agent.instructions, and webSearch firecrawl changeTrackingOptions.prompt.
+# CONFIG_OVERRIDE_ENV_ALLOWLIST=MY_GATEWAY_KEY,MY_GATEWAY_URL
+
# Deployment skills are loaded read-only at startup and exposed to all users
# with the Skills capability enabled. Defaults to project root ./skill.
# DEPLOYMENT_SKILLS_DIR=./skill
diff --git a/api/server/controllers/__tests__/mcp.servers.spec.js b/api/server/controllers/__tests__/mcp.servers.spec.js
index 76b9ef15a9..d8f59e8a08 100644
--- a/api/server/controllers/__tests__/mcp.servers.spec.js
+++ b/api/server/controllers/__tests__/mcp.servers.spec.js
@@ -251,6 +251,51 @@ describe('getMCPServersList', () => {
expect(payload.yamlServer.url).toBeUndefined();
});
+ it('never returns an admin-stored credential, its ciphertext or its preview', async () => {
+ await seedManageMcpGrant();
+ const reqUser = await createUser(SystemRoles.ADMIN);
+ const ciphertext = 'v3:0123456789abcdef0123456789abcdef:feedface';
+ mockResolveAllMcpConfigs.mockResolvedValue({
+ dbServer: createDbConfig(new mongoose.Types.ObjectId()),
+ configServer: {
+ type: 'streamable-http',
+ url: 'https://config.example.com/mcp',
+ title: 'Config Server',
+ source: 'config',
+ apiKey: {
+ source: 'admin',
+ authorization_type: 'bearer',
+ key: 'sk-decrypted-admin-key',
+ keyPreview: '...-key',
+ },
+ oauth: {
+ client_id: 'client-id',
+ client_secret: ciphertext,
+ client_secretPreview: '...face',
+ authorization_url: 'https://config.example.com/auth',
+ token_url: 'https://config.example.com/token',
+ },
+ },
+ });
+
+ const res = createRes();
+ await getMCPServersList({ user: reqUser }, res);
+
+ const payload = res.json.mock.calls[0][0];
+ /** The manager sees the destination, never the credential. */
+ expect(payload.configServer.url).toBe('https://config.example.com/mcp');
+ expect(payload.configServer.apiKey).toEqual({ source: 'admin', authorization_type: 'bearer' });
+ expect(payload.configServer.oauth).toEqual({
+ client_id: 'client-id',
+ authorization_url: 'https://config.example.com/auth',
+ token_url: 'https://config.example.com/token',
+ });
+ const body = JSON.stringify(payload);
+ for (const secret of ['sk-decrypted-admin-key', '...-key', ciphertext, '...face']) {
+ expect(body).not.toContain(secret);
+ }
+ });
+
it('leaves DB-backed servers redacted for viewer-only ACL', async () => {
const reqUser = await createUser();
const dbId = new mongoose.Types.ObjectId();
diff --git a/api/server/routes/admin/config.js b/api/server/routes/admin/config.js
index 1e5caead2f..2962476556 100644
--- a/api/server/routes/admin/config.js
+++ b/api/server/routes/admin/config.js
@@ -38,6 +38,7 @@ const handlers = createAdminConfigHandlers({
recordAuditEntry: db.recordAuditEntry,
auditFailClosed: process.env.AUDIT_LOG_FAIL_CLOSED === 'true',
overrideCacheTtlMs: overrideCacheTtl,
+ overrideEnvAllowlist: process.env.CONFIG_OVERRIDE_ENV_ALLOWLIST,
});
router.use(requireJwtAuth, requireAdminAccess, rejectUnsafeConfigKeys);
diff --git a/api/server/services/Config/app.js b/api/server/services/Config/app.js
index 3492c0dffe..839373266d 100644
--- a/api/server/services/Config/app.js
+++ b/api/server/services/Config/app.js
@@ -55,6 +55,7 @@ const appConfigService = createAppConfigService({
cacheKeys: CacheKeys,
getApplicableConfigs: db.getApplicableConfigs,
getUserPrincipals: db.getUserPrincipals,
+ overrideEnvAllowlist: process.env.CONFIG_OVERRIDE_ENV_ALLOWLIST,
augmentConfig: ({ appConfig, baseConfig, principals, options }) => {
if (!options.userId) return appConfig;
return mergeAccessibleCodeEnvironments({
diff --git a/packages/api/src/admin/binding.spec.ts b/packages/api/src/admin/binding.spec.ts
new file mode 100644
index 0000000000..20d2191b37
--- /dev/null
+++ b/packages/api/src/admin/binding.spec.ts
@@ -0,0 +1,124 @@
+import type { ConfigOverrideState } from '@librechat/data-schemas';
+import { bindSecretDestinations, entersBoundSecret } from './binding';
+import { getRebindingIdentity } from '~/app/rebinding';
+
+const STORED = 'v3:00000000000000000000000000000000:abcdef';
+const ENTERED = 'v3:11111111111111111111111111111111:abcdef';
+const FINGERPRINT = 'a'.repeat(64);
+const OTHER = 'b'.repeat(64);
+
+function state(overrides: Record<string, unknown>): ConfigOverrideState {
+ return { overrides, tombstones: [] } as ConfigOverrideState;
+}
+
+const endpointIdentity = (name: string) =>
+ getRebindingIdentity(['endpoints', 'custom', name, 'apiKey']);
+
+describe('bindSecretDestinations', () => {
+ it('binds a key the request entered to the destination the guard reported, by identity', () => {
+ const candidate = state({
+ endpoints: { custom: [{ name: 'ollama', apiKey: ENTERED, apiKeyBinding: OTHER }] },
+ mcpServers: { tools: { apiKey: { source: 'admin', key: ENTERED } } },
+ ocr: { apiKey: ENTERED },
+ });
+ const destinations = new Map([
+ [endpointIdentity('Ollama'), FINGERPRINT],
+ [getRebindingIdentity(['mcpServers', 'tools', 'apiKey', 'key']), FINGERPRINT],
+ ]);
+
+ const bound = bindSecretDestinations({
+ stored: null,
+ candidate,
+ entered: new Set([ENTERED]),
+ destinations,
+ });
+
+ expect(bound.overrides).toEqual({
+ endpoints: { custom: [{ name: 'ollama', apiKey: ENTERED, apiKeyBinding: FINGERPRINT }] },
+ mcpServers: { tools: { apiKey: { source: 'admin', key: ENTERED, keyBinding: FINGERPRINT } } },
+ ocr: { apiKey: ENTERED },
+ });
+ expect(candidate.overrides.endpoints?.custom?.[0]).toHaveProperty('apiKeyBinding', OTHER);
+ });
+
+ it('carries the stored fingerprint with a kept key, across a rename too', () => {
+ const stored = state({
+ endpoints: { custom: [{ name: 'Old', apiKey: STORED, apiKeyBinding: FINGERPRINT }] },
+ mcpConfig: {
+ tools: { oauth: { client_secret: STORED, client_secretBinding: FINGERPRINT } },
+ },
+ });
+ const candidate = state({
+ endpoints: { custom: [{ name: 'New', apiKey: STORED, apiKeyBinding: OTHER }] },
+ mcpConfig: { tools: { oauth: { client_secret: STORED } } },
+ });
+
+ const bound = bindSecretDestinations({ stored, candidate, entered: new Set() });
+
+ expect(bound.overrides).toEqual({
+ endpoints: { custom: [{ name: 'New', apiKey: STORED, apiKeyBinding: FINGERPRINT }] },
+ mcpConfig: {
+ tools: { oauth: { client_secret: STORED, client_secretBinding: FINGERPRINT } },
+ },
+ });
+ });
+
+ it('removes every fingerprint no key the server bound stands beside', () => {
+ const stored = state({
+ ocr: { apiKey: STORED },
+ endpoints: { custom: [{ name: 'Mine', apiKey: '${MY_KEY}', apiKeyBinding: FINGERPRINT }] },
+ });
+ const candidate = state({
+ ocr: { apiKey: STORED, apiKeyBinding: FINGERPRINT },
+ speech: { tts: { openai: { apiKeyBinding: FINGERPRINT } } },
+ endpoints: {
+ custom: [
+ { name: 'Users', apiKey: 'user_provided', apiKeyBinding: FINGERPRINT },
+ { name: 'Mine', apiKey: '${OTHER_KEY}', apiKeyBinding: FINGERPRINT },
+ ],
+ azureOpenAI: {
+ groups: [{ group: 'east', apiKey: STORED, apiKeyBinding: FINGERPRINT }],
+ groupMap: { east: { apiKeyBinding: FINGERPRINT } },
+ },
+ },
+ });
+
+ const bound = bindSecretDestinations({ stored, candidate, entered: new Set() });
+
+ expect(JSON.stringify(bound.overrides)).not.toContain('Binding');
+ });
+
+ it('keeps a reference bound where the same reference was bound before', () => {
+ const stored = state({
+ endpoints: { custom: [{ name: 'Mine', apiKey: '${MY_KEY}', apiKeyBinding: FINGERPRINT }] },
+ });
+ const candidate = state({
+ endpoints: { custom: [{ name: 'Mine', apiKey: '${MY_KEY}', models: { default: ['m'] } }] },
+ });
+
+ const bound = bindSecretDestinations({ stored, candidate, entered: new Set() });
+
+ expect(bound.overrides.endpoints?.custom?.[0]).toHaveProperty('apiKeyBinding', FINGERPRINT);
+ });
+
+ it('returns the candidate itself when nothing changes', () => {
+ const candidate = state({ ocr: { apiKey: STORED }, interface: { customWelcome: 'hi' } });
+ expect(bindSecretDestinations({ stored: candidate, candidate, entered: new Set() })).toBe(
+ candidate,
+ );
+ });
+});
+
+describe('entersBoundSecret', () => {
+ it('finds a key the request entered at a bound location, and nothing else', () => {
+ const candidate = state({
+ endpoints: { custom: [{ name: 'Mine', apiKey: ENTERED }] },
+ webSearch: { serperApiKey: ENTERED },
+ });
+ expect(entersBoundSecret(candidate, new Set([ENTERED]))).toBe(true);
+ expect(entersBoundSecret(candidate, new Set([STORED]))).toBe(false);
+ expect(
+ entersBoundSecret(state({ webSearch: { serperApiKey: ENTERED } }), new Set([ENTERED])),
+ ).toBe(false);
+ });
+});
diff --git a/packages/api/src/admin/binding.ts b/packages/api/src/admin/binding.ts
index f8ba0c5849..5b57444db0 100644
--- a/packages/api/src/admin/binding.ts
+++ b/packages/api/src/admin/binding.ts
@@ -1,6 +1,15 @@
import isPlainObject from 'lodash/isPlainObject';
-import { webSearchPairedFields, getRebindingWebSearchKeys } from '@librechat/data-schemas';
-import type { Config, ConfigFieldWrite, ConfigOverrideIssue } from '@librechat/data-schemas';
+import {
+ getAtPath,
+ setAtPath,
+ isPlainRecord,
+ webSearchPairedFields,
+ getRebindingWebSearchKeys,
+} from '@librechat/data-schemas';
+import type { Config, ConfigOverrideIssue, ConfigOverrideState } from '@librechat/data-schemas';
+import { getSecretBindingKey, getBoundSecretLocations } from '~/app/rebinding';
+import { isEncryptedConfigSecret, isUserVariableTemplate } from './secrets';
+import { isUserProvided } from '~/utils/common';
/** Issue code for a URL a write changed while the secret stored beside it stays. */
export const SECRET_REENTRY_REQUIRED = 'secret_reentry_required';
@@ -82,105 +91,150 @@ export function isWebSearchBindingPath(fieldPath: string): boolean {
}
/**
- * Re-entry issues for a write that replaces a document's overrides. Its
- * tombstones stay as stored.
+ * Re-entry issues for a write (a replace, a field patch, a batch of changes
+ * or a field removal), judged on the document it would store: each stored
+ * key the planned document keeps beside a paired URL the write set, changed,
+ * blanked or removed.
+ *
+ * A key counts as entered again only when the planned document holds a value
+ * the request itself entered (`getEnteredConfigSecrets`). Writes apply in
+ * order, so a later write can put the stored key back over one an earlier
+ * write supplied (a whole `webSearch` after one of its keys); judging by the
+ * value the document ends up with, not by the paths the request wrote, keeps
+ * that order from hiding a kept key.
* @param stored - The document before the write.
- * @param input - The overrides the request supplied.
- * @param next - The overrides the write would store, omitted secrets preserved.
+ * @param next - The overrides and tombstones the write would store, omitted secrets preserved.
+ * @param entered - The secret values the request itself entered, encrypted; none for a removal.
*/
-export function getReplaceReentryIssues(
+export function getWebSearchReentryIssues(
stored: StoredConfigState,
- input: unknown,
- next: unknown,
+ next: StoredConfigState,
+ entered: ReadonlySet<string>,
): SecretReentryIssue[] {
- const tombstones = stored?.tombstones;
- const written = new Set(Object.keys(getWebSearch(input) ?? {}));
+ const nextWebSearch = getWebSearch(next?.overrides);
+ const written = new Set<string>();
+ for (const [field, value] of Object.entries(nextWebSearch ?? {})) {
+ if (typeof value === 'string' && entered.has(value)) {
+ written.add(field);
+ }
+ }
return toReentryIssues(
- getWebSearchView(getWebSearch(stored?.overrides), tombstones),
- getWebSearchView(getWebSearch(next), tombstones),
+ getWebSearchView(getWebSearch(stored?.overrides), stored?.tombstones),
+ getWebSearchView(nextWebSearch, next?.tombstones),
written,
);
}
+/** A key the rebinding guard binds to a destination: set, and not a value each user enters. */
+function isBindableKey(value: unknown): value is string {
+ if (typeof value !== 'string') {
+ return false;
+ }
+ const trimmed = value.trim();
+ return trimmed !== '' && !isUserProvided(trimmed) && !isUserVariableTemplate(trimmed);
+}
+
+/** A destination fingerprint a stored document holds beside one of its keys. */
+interface StoredBinding {
+ identity: string;
+ value: string;
+ fingerprint: string;
+}
+
+function getStoredBindings(overrides: unknown): StoredBinding[] {
+ return getBoundSecretLocations(overrides).flatMap(({ owner, key, identity }) => {
+ const record = getAtPath(overrides, owner);
+ if (!isPlainRecord(record)) {
+ return [];
+ }
+ const value = record[key];
+ const fingerprint = record[getSecretBindingKey(key)];
+ return typeof value === 'string' && typeof fingerprint === 'string'
+ ? [{ identity, value, fingerprint }]
+ : [];
+ });
+}
+
/**
- * Re-entry issues for a field patch, judged on the document the patch would
- * store. Writes apply in request order, so a later write can replace what an
- * earlier one set (a whole `webSearch` after one of its fields); only the
- * planned document says which URL a stored key ends up beside.
- * @param stored - The document before the write.
- * @param writes - The field writes the request supplied, in order.
- * @param next - The overrides and tombstones the write would store, omitted secrets preserved.
+ * The fingerprint a kept key brings from the stored document: the one beside the same value at
+ * the same secret, or, for a ciphertext (which only the stored key it was carried from holds),
+ * beside the same value anywhere, so a rename or copy keeps the destination it was entered for.
*/
-export function getPatchReentryIssues(
- stored: StoredConfigState,
- writes: readonly ConfigFieldWrite[],
- next: StoredConfigState,
-): SecretReentryIssue[] {
- if (!writes.some(({ segments }) => segments[0] === WEB_SEARCH)) {
- return [];
+function getKeptFingerprint(
+ stored: readonly StoredBinding[],
+ identity: string,
+ value: string,
+): string | undefined {
+ const same = stored.find((binding) => binding.identity === identity && binding.value === value);
+ if (same != null || !isEncryptedConfigSecret(value)) {
+ return same?.fingerprint;
}
- return getBatchReentryIssues(stored, writes, next);
+ return stored.find((binding) => binding.value === value)?.fingerprint;
}
/**
- * Re-entry issues for a batch of changes, judged on the document the batch
- * would store. Its sets, unsets and tombstones apply in order, so only the
- * planned document says which URL a stored key ends up beside; a key the batch
- * sets counts as entered again.
- * @param stored - The document before the batch.
- * @param writes - The values the batch sets, in order.
- * @param next - The overrides and tombstones the batch would store.
+ * Sets the destination fingerprint (`<key>Binding`) beside each bound key a planned document
+ * holds, so the merge's rebinding guard keeps a key only where it was entered:
+ * - a key the request entered gets the fingerprint of where the merge sends it over the floor
+ * (`destinations`, from the guard's report), when that is not where librechat.yaml and the
+ * document alone send it; otherwise none, since the guard then needs none;
+ * - a key the request kept brings the fingerprint stored beside it;
+ * - anything else, a fingerprint a client sent included, is removed.
+ *
+ * Only this server writes the fingerprints: whatever the request held there is replaced.
+ * @param destinations - Fingerprints by secret identity (`getRebindingIdentity`); none for a
+ * write that enters nothing, or that binds nothing new.
*/
-export function getBatchReentryIssues(
- stored: StoredConfigState,
- writes: readonly ConfigFieldWrite[],
- next: StoredConfigState,
-): SecretReentryIssue[] {
- const written = new Set<string>();
- for (const { segments, value } of writes) {
- if (segments[0] !== WEB_SEARCH) {
+export function bindSecretDestinations(params: {
+ stored: StoredConfigState;
+ candidate: ConfigOverrideState;
+ entered: ReadonlySet<string>;
+ destinations?: ReadonlyMap<string, string>;
+}): ConfigOverrideState {
+ const { stored, candidate, entered, destinations } = params;
+ const storedBindings = getStoredBindings(stored?.overrides);
+ let overrides = candidate.overrides as ConfigFields;
+ for (const { owner, key, identity } of getBoundSecretLocations(candidate.overrides)) {
+ const record = getAtPath(overrides, owner);
+ if (!isPlainRecord(record)) {
continue;
}
- if (segments.length === 1) {
- Object.keys(getRecord(value) ?? {}).forEach((field) => written.add(field));
- } else if (segments.length === 2) {
- written.add(segments[1]);
+ const value = record[key];
+ const companion = getSecretBindingKey(key);
+ let fingerprint: string | undefined;
+ if (isBindableKey(value)) {
+ fingerprint = entered.has(value)
+ ? destinations?.get(identity)
+ : getKeptFingerprint(storedBindings, identity, value);
+ }
+ if (record[companion] === fingerprint) {
+ continue;
}
+ const { [companion]: _previous, ...rest } = record;
+ overrides = setAtPath(
+ overrides,
+ owner,
+ fingerprint === undefined ? rest : { ...rest, [companion]: fingerprint },
+ );
}
- return toReentryIssues(
- getWebSearchView(getWebSearch(stored?.overrides), stored?.tombstones),
- getWebSearchView(getWebSearch(next?.overrides), next?.tombstones),
- written,
- );
+ return overrides === candidate.overrides
+ ? candidate
+ : { ...candidate, overrides: overrides as ConfigOverrideState['overrides'] };
}
/**
- * Re-entry issues for removing one field path from a document: a field delete
- * unsets the value and clears tombstones at and below the path, and a
- * tombstone unsets the value and suppresses the inherited one.
- * @param stored - The document before the write.
- * @param fieldPath - The dot-path the write removes.
- * @param tombstone - Whether the write tombstones the path rather than deleting it.
+ * Whether a planned document holds a key the request entered at a place the merge binds to a
+ * destination, so its fingerprint must be worked out over the floor.
*/
-export function getRemovalReentryIssues(
- stored: StoredConfigState,
- fieldPath: string,
- tombstone: boolean,
-): SecretReentryIssue[] {
- const field = getPairedField(fieldPath);
- if (field == null) {
- return [];
+export function entersBoundSecret(
+ candidate: ConfigOverrideState,
+ entered: ReadonlySet<string>,
+): boolean {
+ if (entered.size === 0) {
+ return false;
}
- const storedWebSearch = getWebSearch(stored?.overrides);
- const nextWebSearch = { ...storedWebSearch };
- delete nextWebSearch[field];
- const tombstones = stored?.tombstones ?? [];
- const nextTombstones = tombstone
- ? [...tombstones, fieldPath]
- : tombstones.filter((path) => path !== fieldPath && !path.startsWith(`${fieldPath}.`));
- return toReentryIssues(
- getWebSearchView(storedWebSearch, tombstones),
- getWebSearchView(nextWebSearch, nextTombstones),
- new Set(),
- );
+ return getBoundSecretLocations(candidate.overrides).some(({ owner, key }) => {
+ const value = getAtPath(getAtPath(candidate.overrides, owner), [key]);
+ return isBindableKey(value) && entered.has(value);
+ });
}
diff --git a/packages/api/src/admin/config.changes.integration.spec.ts b/packages/api/src/admin/config.changes.integration.spec.ts
index c9c216b0d8..5cce76f60d 100644
--- a/packages/api/src/admin/config.changes.integration.spec.ts
+++ b/packages/api/src/admin/config.changes.integration.spec.ts
@@ -1,4 +1,5 @@
import mongoose from 'mongoose';
+import { isDeepStrictEqual } from 'node:util';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { PrincipalType, PrincipalModel } from 'librechat-data-provider';
import type { AppConfig, ConfigDraft } from '@librechat/data-schemas';
@@ -130,6 +131,17 @@ async function storedDocument(principalId: string) {
return raw().findOne({ principalId });
}
+/** The value at `segments`, `undefined` when anything on the way is missing. */
+function valueAt(root: unknown, segments: readonly string[]): unknown {
+ return segments.reduce<unknown>(
+ (value, key) =>
+ value != null && typeof value === 'object'
+ ? (value as Record<string, unknown>)[key]
+ : undefined,
+ root,
+ );
+}
+
/** Stores a role document as is, past every API guard, as an older server or another writer might. */
async function seedDocument(
principalId: string,
@@ -402,7 +414,7 @@ describe('POST …/changes: secrets', () => {
expect(JSON.stringify(body)).not.toContain(ciphertext);
});
- it('encrypts an entry key, keeps it through a rename and an edit, and never needs it again', async () => {
+ it('encrypts an entry key and keeps it through a rename and an edit that leave its destination', async () => {
const params = nextParams();
const created = await send(
{
@@ -422,15 +434,15 @@ describe('POST …/changes: secrets', () => {
expect(storedEntry.apiKey.startsWith('v3:')).toBe(true);
expect(storedEntry.apiKeyPreview).toBe('...0001');
+ const edited = endpoint('new', {
+ baseURL: 'https://old.example.com/v1',
+ models: { default: ['m', 'n'] },
+ });
const { status, body } = await send(
{
ops: [
{ op: 'rename', fieldPath: 'endpoints.custom', from: 'old', to: 'new' },
- {
- op: 'upsertEntry',
- fieldPath: 'endpoints.custom',
- entry: endpoint('new', { baseURL: 'https://new.example.com/v2' }),
- },
+ { op: 'upsertEntry', fieldPath: 'endpoints.custom', entry: edited },
],
},
params,
@@ -439,7 +451,7 @@ describe('POST …/changes: secrets', () => {
expect(status).toBe(200);
const [entry] = (await storedDocument(params.principalId))!.overrides.endpoints.custom;
expect(entry).toEqual({
- ...endpoint('new', { baseURL: 'https://new.example.com/v2' }),
+ ...edited,
apiKey: storedEntry.apiKey,
apiKeyPreview: '...0001',
});
@@ -449,6 +461,89 @@ describe('POST …/changes: secrets', () => {
expect(returned).toHaveProperty('apiKeyPreview', '...0001');
});
+ it('needs an entry key again when a batch moves its destination, renamed or not', async () => {
+ const params = nextParams();
+ const created = await send(
+ {
+ ops: [
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('old', { apiKey: 'sk-endpoint-secret-0002' }),
+ },
+ ],
+ },
+ params,
+ );
+ expect(created.status).toBe(200);
+ const before = await storedDocument(params.principalId);
+
+ const moves: Array<[string, Array<Record<string, unknown>>]> = [
+ [
+ 'an upsert of the entry with another base URL',
+ [
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('old', { baseURL: 'https://attacker.example.com/v1' }),
+ },
+ ],
+ ],
+ [
+ 'a rename, then an upsert under the new name with another base URL',
+ [
+ { op: 'rename', fieldPath: 'endpoints.custom', from: 'old', to: 'new' },
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('new', { baseURL: 'https://new.example.com/v2' }),
+ },
+ ],
+ ],
+ [
+ 'an upsert that sets a native client destination',
+ [
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('old', { addParams: { anthropicApiUrl: 'https://attacker.example' } }),
+ },
+ ],
+ ],
+ ];
+ for (const [, ops] of moves) {
+ for (const dryRun of [true, false]) {
+ const { status, body } = await send({ ops, dryRun }, params);
+ expect(status).toBe(400);
+ expect(body).toMatchObject({ code: 'CONFIG_SECRET_REENTRY_REQUIRED' });
+ expect(body.issues).toEqual([
+ expect.objectContaining({
+ code: 'secret_reentry_required',
+ secretPath: 'endpoints.custom.0.apiKey',
+ }),
+ ]);
+ }
+ }
+ expect(await storedDocument(params.principalId)).toEqual(before);
+
+ const reentered = await send(
+ {
+ ops: [
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('old', {
+ baseURL: 'https://attacker.example.com/v1',
+ apiKey: 'sk-endpoint-secret-0003',
+ }),
+ },
+ ],
+ },
+ params,
+ );
+ expect(reentered.status).toBe(200);
+ });
+
it('refuses submitted ciphertext and writes under a secret, naming the change', async () => {
const params = nextParams();
@@ -575,6 +670,497 @@ describe('POST …/changes: a stored web search key and the URL it is sent to',
});
});
+describe('POST …/changes: a stored MCP credential and where it is sent', () => {
+ const GOOD = 'https://good.example.com/mcp';
+ const EVIL = 'https://evil.example.com/mcp';
+ const server = (url: string, key?: string) => ({
+ type: 'streamable-http',
+ url,
+ apiKey: { source: 'admin', authorization_type: 'bearer', ...(key != null && { key }) },
+ });
+ const REENTRY = (name: string) => ({
+ error: expect.stringContaining('Re-enter apiKey.key'),
+ code: 'MCP_API_KEY_REENTRY_REQUIRED',
+ server: name,
+ fields: ['url'],
+ });
+
+ /** Stores each named server with its own key, as an admin who can enter them would. */
+ async function storeServers(servers: Record<string, ReturnType<typeof server>>) {
+ const params = nextParams();
+ const { status } = await send(
+ {
+ ops: Object.entries(servers).map(([name, value]) => ({
+ op: 'set',
+ fieldPath: `mcpServers.${name}`,
+ value,
+ })),
+ },
+ params,
+ );
+ expect(status).toBe(200);
+ return { params, before: await storedDocument(params.principalId) };
+ }
+
+ /** Sends the batch as a dry run and for real; what each answered, and whether it wrote. */
+ async function attempt(
+ params: { principalType: string; principalId: string },
+ ops: Array<Record<string, unknown>>,
+ ) {
+ const before = await storedDocument(params.principalId);
+ const answers = [];
+ for (const dryRun of [true, false]) {
+ const { status, body } = await send({ ops, dryRun }, params);
+ answers.push({ status, body });
+ }
+ const unchanged = isDeepStrictEqual(await storedDocument(params.principalId), before);
+ return { answers, unchanged };
+ }
+
+ /** Both the dry run and the write refused, naming the server, and nothing stored. */
+ const refused = (name: string) => ({
+ answers: [
+ { status: 400, body: REENTRY(name) },
+ { status: 400, body: REENTRY(name) },
+ ],
+ unchanged: true,
+ });
+
+ it('encrypts a key set on a server, returns only its preview, and keeps it when a set omits it', async () => {
+ const { params, before } = await storeServers({ probe: server(GOOD, 'sk-probe-secret-1111') });
+ const key = before!.overrides.mcpServers.probe.apiKey.key as string;
+ expect(key.startsWith('v3:')).toBe(true);
+ expect(decryptV3(key)).toBe('sk-probe-secret-1111');
+ expect(before!.overrides.mcpServers.probe.apiKey.keyPreview).toBe('...1111');
+
+ const { status, body } = await send(
+ {
+ ops: [{ op: 'set', fieldPath: 'mcpServers.probe', value: { ...server(GOOD), title: 'P' } }],
+ },
+ params,
+ );
+
+ expect(status).toBe(200);
+ const after = await storedDocument(params.principalId);
+ expect(after!.overrides.mcpServers.probe.apiKey.key).toBe(key);
+ expect(after!.overrides.mcpServers.probe.title).toBe('P');
+ const payload = JSON.stringify(body);
+ expect(payload).not.toContain('sk-probe-secret-1111');
+ expect(payload).not.toContain(key);
+ expect(payload).toContain('...1111');
+ });
+
+ it('refuses a URL change that keeps the stored key', async () => {
+ const { params } = await storeServers({ probe: server(GOOD, 'sk-probe-secret-1111') });
+
+ expect(
+ await attempt(params, [{ op: 'set', fieldPath: 'mcpServers.probe.url', value: EVIL }]),
+ ).toEqual(refused('probe'));
+ });
+
+ it('refuses a batch that renames the server away and back around a decoy key', async () => {
+ const { params } = await storeServers({ probe: server(GOOD, 'sk-probe-secret-1111') });
+
+ expect(
+ await attempt(params, [
+ { op: 'rename', fieldPath: 'mcpServers', from: 'probe', to: 'tmp' },
+ { op: 'set', fieldPath: 'mcpServers.probe.apiKey.key', value: 'sk-decoy-key-0000' },
+ { op: 'unset', fieldPath: 'mcpServers.probe' },
+ { op: 'rename', fieldPath: 'mcpServers', from: 'tmp', to: 'probe' },
+ { op: 'set', fieldPath: 'mcpServers.probe.url', value: EVIL },
+ ]),
+ ).toEqual(refused('probe'));
+ });
+
+ it('follows a key through a rename, or a chain of them, to the server it came from', async () => {
+ const { params } = await storeServers({ a: server(GOOD, 'sk-a-secret-key-1111') });
+
+ expect(
+ await attempt(params, [
+ { op: 'rename', fieldPath: 'mcpServers', from: 'a', to: 'b' },
+ { op: 'set', fieldPath: 'mcpServers.b.url', value: EVIL },
+ ]),
+ ).toEqual(refused('b'));
+ expect(
+ await attempt(params, [
+ { op: 'rename', fieldPath: 'mcpServers', from: 'a', to: 'b' },
+ { op: 'rename', fieldPath: 'mcpServers', from: 'b', to: 'c' },
+ { op: 'set', fieldPath: 'mcpServers.c.url', value: EVIL },
+ ]),
+ ).toEqual(refused('c'));
+ });
+
+ it('accepts a rename that keeps where the key goes, or a move that enters the key again', async () => {
+ const { params, before } = await storeServers({ a: server(GOOD, 'sk-a-secret-key-1111') });
+ const key = before!.overrides.mcpServers.a.apiKey.key as string;
+
+ const renamed = await send(
+ { ops: [{ op: 'rename', fieldPath: 'mcpServers', from: 'a', to: 'b' }] },
+ params,
+ );
+ expect(renamed.status).toBe(200);
+ expect((await storedDocument(params.principalId))!.overrides.mcpServers.b.apiKey.key).toBe(key);
+
+ const moved = await send(
+ {
+ ops: [
+ { op: 'rename', fieldPath: 'mcpServers', from: 'b', to: 'c' },
+ { op: 'set', fieldPath: 'mcpServers.c.url', value: EVIL },
+ { op: 'set', fieldPath: 'mcpServers.c.apiKey.key', value: 'sk-entered-again-2222' },
+ ],
+ },
+ params,
+ );
+ expect(moved.status).toBe(200);
+ const stored = (await storedDocument(params.principalId))!.overrides.mcpServers.c;
+ expect(stored.url).toBe(EVIL);
+ expect(decryptV3(stored.apiKey.key)).toBe('sk-entered-again-2222');
+ });
+
+ it('accepts a name swap that moves each key with its own server', async () => {
+ const { params, before } = await storeServers({
+ a: server(GOOD, 'sk-a-secret-key-1111'),
+ b: server(EVIL, 'sk-b-secret-key-2222'),
+ });
+ const { a, b } = before!.overrides.mcpServers;
+
+ const { status } = await send(
+ {
+ ops: [
+ { op: 'rename', fieldPath: 'mcpServers', from: 'a', to: 'tmp' },
+ { op: 'rename', fieldPath: 'mcpServers', from: 'b', to: 'a' },
+ { op: 'rename', fieldPath: 'mcpServers', from: 'tmp', to: 'b' },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(200);
+ expect((await storedDocument(params.principalId))!.overrides.mcpServers).toEqual({
+ a: b,
+ b: a,
+ });
+ });
+});
+
+describe('POST …/changes: env references and the credentials a write leaves elsewhere', () => {
+ const UNLISTED_URL = 'https://h.example/${LC8_UNLISTED_NAME}';
+
+ it('names an upserted entry by its position once the batch has moved it', async () => {
+ const params = nextParams();
+ await seedDocument(
+ params.principalId,
+ { endpoints: { custom: [endpoint('first'), endpoint('second')] } },
+ [],
+ );
+
+ const { status, body } = await send(
+ {
+ ops: [
+ { op: 'removeEntry', fieldPath: 'endpoints.custom', key: 'first' },
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('second', { baseURL: 'https://h.example/${LC8_UNLISTED_NAME}' }),
+ },
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('third', { headers: { 'X-Key': '${LC8_UNLISTED_NAME}' } }),
+ },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(400);
+ expect(body).toMatchObject({
+ code: 'CONFIG_OVERRIDE_INVALID',
+ issues: [
+ {
+ path: 'endpoints.custom.0.baseURL',
+ segments: ['endpoints', 'custom', '0', 'baseURL'],
+ code: 'env_reference_not_allowed',
+ },
+ {
+ path: 'endpoints.custom.1.headers.X-Key',
+ segments: ['endpoints', 'custom', '1', 'headers', 'X-Key'],
+ code: 'env_reference_not_allowed',
+ },
+ ],
+ });
+ expect((await storedDocument(params.principalId))!.overrides.endpoints.custom).toEqual([
+ endpoint('first'),
+ endpoint('second'),
+ ]);
+ });
+
+ it('names an upserted entry where the batch leaves it, after a later removal', async () => {
+ const params = nextParams();
+ await seedDocument(
+ params.principalId,
+ { endpoints: { custom: [endpoint('first'), endpoint('second')] } },
+ [],
+ );
+
+ const { status, body } = await send(
+ {
+ dryRun: true,
+ ops: [
+ { op: 'upsertEntry', entry: endpoint('bad', { baseURL: UNLISTED_URL }) },
+ { op: 'removeEntry', key: 'first' },
+ ].map((op) => ({ ...op, fieldPath: 'endpoints.custom' })),
+ },
+ params,
+ );
+
+ expect(status).toBe(400);
+ expect(body).toMatchObject({
+ code: 'CONFIG_OVERRIDE_INVALID',
+ issues: [
+ {
+ path: 'endpoints.custom.1.baseURL',
+ segments: ['endpoints', 'custom', '1', 'baseURL'],
+ code: 'env_reference_not_allowed',
+ },
+ ],
+ });
+ expect(body.issues).toHaveLength(1);
+ });
+
+ it('judges references on the document the batch leaves, not on values a later change removed', async () => {
+ const cases = [
+ {
+ stored: { endpoints: { custom: [endpoint('first')] } },
+ ops: [
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('bad', { baseURL: UNLISTED_URL }),
+ },
+ { op: 'set', fieldPath: 'endpoints.custom', value: [endpoint('c')] },
+ ],
+ path: ['endpoints', 'custom'],
+ left: [endpoint('c')],
+ },
+ {
+ stored: { ocr: { mistralModel: 'mistral-ocr-latest' } },
+ ops: [
+ { op: 'set', fieldPath: 'ocr.baseURL', value: UNLISTED_URL },
+ { op: 'unset', fieldPath: 'ocr' },
+ ],
+ path: ['ocr'],
+ left: undefined,
+ },
+ {
+ stored: { ocr: { mistralModel: 'mistral-ocr-latest' } },
+ ops: [
+ { op: 'set', fieldPath: 'ocr.baseURL', value: UNLISTED_URL },
+ {
+ op: 'set',
+ fieldPath: 'ocr',
+ value: { baseURL: 'https://ocr.example.com/v1', mistralModel: 'mistral-ocr-latest' },
+ },
+ ],
+ path: ['ocr', 'baseURL'],
+ left: 'https://ocr.example.com/v1',
+ },
+ ];
+
+ for (const { stored, ops, path, left } of cases) {
+ for (const dryRun of [true, false]) {
+ const params = nextParams();
+ await seedDocument(params.principalId, stored, []);
+
+ const { status, body } = await send({ dryRun, ops }, params);
+
+ expect({ status, issues: body.issues }).toEqual({ status: 200, issues: undefined });
+ const document = (await storedDocument(params.principalId))?.overrides;
+ expect(valueAt(document, path)).toEqual(dryRun ? valueAt(stored, path) : left);
+ }
+ }
+ });
+
+ it('still refuses a reference the batch leaves, held encrypted or written with spaces', async () => {
+ const params = nextParams();
+
+ const { status, body } = await send(
+ {
+ ops: [
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('gateway', { apiKey: 'pa${LC8_UNLISTED_NAME}ss' }),
+ },
+ { op: 'set', fieldPath: 'ocr.apiKey', value: ' ${LC8_UNLISTED_NAME} ' },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(400);
+ expect(body.issues).toEqual([
+ {
+ path: 'endpoints.custom.0.apiKey',
+ segments: ['endpoints', 'custom', '0', 'apiKey'],
+ code: 'env_reference_not_allowed',
+ },
+ { path: 'ocr.apiKey', segments: ['ocr', 'apiKey'], code: 'env_reference_not_allowed' },
+ ]);
+ expect(await storedDocument(params.principalId)).toBeNull();
+ });
+
+ it('leaves a stored reference a batch puts back where it was to merge time', async () => {
+ const params = nextParams();
+ const ocr = { baseURL: UNLISTED_URL, mistralModel: 'mistral-ocr-latest' };
+ await seedDocument(params.principalId, { ocr }, []);
+
+ const { status } = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'ocr.baseURL', value: 'https://ocr.example.com/v1' },
+ { op: 'set', fieldPath: 'ocr', value: { ...ocr } },
+ { op: 'set', fieldPath: 'interface.customWelcome', value: 'Welcome' },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(200);
+ const { overrides } = (await storedDocument(params.principalId))!;
+ expect(overrides.ocr).toEqual(ocr);
+ expect(overrides.interface).toEqual({ customWelcome: 'Welcome' });
+ });
+
+ it('follows each entry of a collection a change sets by its key, through later changes', async () => {
+ const bad = (name: string) => endpoint(name, { headers: { 'X-Key': '${LC8_UNLISTED_NAME}' } });
+ const cases = [
+ {
+ ops: [
+ {
+ op: 'set',
+ fieldPath: 'endpoints.custom',
+ value: [endpoint('good'), bad('bad')],
+ },
+ { op: 'removeEntry', fieldPath: 'endpoints.custom', key: 'good' },
+ ],
+ path: ['endpoints', 'custom', '0', 'headers', 'X-Key'],
+ },
+ {
+ ops: [
+ {
+ op: 'set',
+ fieldPath: 'endpoints',
+ value: { custom: [endpoint('good'), bad('bad')] },
+ },
+ { op: 'removeEntry', fieldPath: 'endpoints.custom', key: 'good' },
+ { op: 'rename', fieldPath: 'endpoints.custom', from: 'bad', to: 'renamed' },
+ { op: 'upsertEntry', fieldPath: 'endpoints.custom', entry: endpoint('first') },
+ ],
+ path: ['endpoints', 'custom', '0', 'headers', 'X-Key'],
+ },
+ {
+ ops: [
+ {
+ op: 'set',
+ fieldPath: 'mcpServers',
+ value: {
+ draft: { type: 'streamable-http', url: 'https://h.example/${LC8_UNLISTED_NAME}' },
+ },
+ },
+ { op: 'rename', fieldPath: 'mcpServers', from: 'draft', to: 'tools' },
+ ],
+ path: ['mcpServers', 'tools', 'url'],
+ },
+ ];
+
+ for (const { ops, path } of cases) {
+ for (const dryRun of [true, false]) {
+ const params = nextParams();
+
+ const { status, body } = await send({ dryRun, ops }, params);
+
+ expect({ status, issues: body.issues }).toEqual({
+ status: 400,
+ issues: [{ path: path.join('.'), segments: path, code: 'env_reference_not_allowed' }],
+ });
+ expect(await storedDocument(params.principalId)).toBeNull();
+ }
+ }
+ });
+
+ it('names a value under a key a later rename moved by the new key', async () => {
+ const params = nextParams();
+
+ const { status, body } = await send(
+ {
+ ops: [
+ {
+ op: 'set',
+ fieldPath: 'mcpServers.draft',
+ value: { type: 'streamable-http', url: 'https://h.example/${LC8_UNLISTED_NAME}' },
+ },
+ { op: 'rename', fieldPath: 'mcpServers', from: 'draft', to: 'tools' },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(400);
+ expect(body).toMatchObject({
+ code: 'CONFIG_OVERRIDE_INVALID',
+ issues: [
+ {
+ path: 'mcpServers.tools.url',
+ segments: ['mcpServers', 'tools', 'url'],
+ code: 'env_reference_not_allowed',
+ },
+ ],
+ });
+ expect(await storedDocument(params.principalId)).toBeNull();
+ });
+
+ it('reports the librechat.yaml key a batch leaves on a new URL, written or planned', async () => {
+ const yaml = {
+ ...YAML,
+ mcpServers: {
+ ...YAML.mcpServers,
+ tools: {
+ type: 'streamable-http',
+ url: 'https://tools.example.com/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: '${TOOLS_KEY}' },
+ },
+ },
+ };
+ const deps = createDeps({
+ getAppConfig: async () =>
+ ({ config: yaml, mcpConfig: structuredClone(yaml.mcpServers) }) as unknown as AppConfig,
+ });
+ const ops = [
+ { op: 'set', fieldPath: 'mcpServers.tools.url', value: 'https://evil.example.com/mcp' },
+ ];
+ const rebinding = {
+ path: 'mcpServers.tools.apiKey.key',
+ segments: ['mcpServers', 'tools', 'apiKey', 'key'],
+ reason: 'secret_rebinding',
+ };
+
+ const planned = await send({ ops, dryRun: true }, nextParams(), deps);
+ expect(planned.status).toBe(200);
+ expect(planned.body).toMatchObject({ dryRun: true, written: false });
+ expect(planned.body.ignored).toEqual([rebinding]);
+
+ const params = nextParams();
+ const written = await send({ ops }, params, deps);
+ expect(written.status).toBe(200);
+ expect(written.body.written).toBe(true);
+ expect(written.body.ignored).toEqual([rebinding]);
+ expect((await storedDocument(params.principalId))!.overrides.mcpServers.tools.url).toBe(
+ 'https://evil.example.com/mcp',
+ );
+ });
+});
+
describe('POST …/changes: entries librechat.yaml owns', () => {
it('refuses to rename a YAML entry or to take its name', async () => {
const params = nextParams();
diff --git a/packages/api/src/admin/config.handler.spec.ts b/packages/api/src/admin/config.handler.spec.ts
index 70c24a2cae..8a10a9c465 100644
--- a/packages/api/src/admin/config.handler.spec.ts
+++ b/packages/api/src/admin/config.handler.spec.ts
@@ -716,7 +716,7 @@ describe('createAdminConfigHandlers', () => {
});
it('encrypts custom endpoint API keys on full override writes and redacts responses', async () => {
- const { handlers, deps } = createHandlers();
+ const { handlers, deps } = createHandlers({ overrideEnvAllowlist: 'OPENROUTER_KEY' });
const req = mockReq({
params: { principalType: 'role', principalId: 'admin' },
body: {
@@ -1535,6 +1535,134 @@ describe('createAdminConfigHandlers', () => {
});
});
+ /**
+ * A stored credential and its URL, and a patch that enters a decoy key at the credential's path
+ * and then writes an ancestor without it: secret preservation fills the ancestor in from the
+ * stored document, so the stored key, not the decoy, is what the document keeps.
+ */
+ describe('patchConfigField: a decoy key before an ancestor that keeps the stored one', () => {
+ const GOOD = 'https://good.example.com/mcp';
+ const EVIL = 'https://evil.example.com/mcp';
+ /** `encryptV3` is mocked as `v3:test:<plaintext>` in this file. */
+ const STORED_MCP_KEY = 'v3:test:sk-original-mcp-1111';
+ const STORED_FIRECRAWL_KEY = 'v3:test:fc-original-key-2222';
+ const DECOY = 'sk-decoy-key-0000';
+
+ const stored: ConfigRecord = {
+ _id: 'c1',
+ principalType: 'role' as ConfigRecord['principalType'],
+ principalId: 'admin',
+ principalModel: 'Role' as ConfigRecord['principalModel'],
+ priority: 10,
+ isActive: true,
+ configVersion: 1,
+ tombstones: [],
+ overrides: {
+ mcpServers: {
+ probe: {
+ type: 'streamable-http',
+ url: GOOD,
+ apiKey: {
+ source: 'admin',
+ authorization_type: 'bearer',
+ key: STORED_MCP_KEY,
+ keyPreview: '...1111',
+ },
+ },
+ },
+ webSearch: {
+ firecrawlApiUrl: 'https://fc-good.example.com',
+ firecrawlApiKey: STORED_FIRECRAWL_KEY,
+ firecrawlApiKeyPreview: '...2222',
+ },
+ } as ConfigRecord['overrides'],
+ };
+ const keyless = (url: string) => ({
+ type: 'streamable-http',
+ url,
+ apiKey: { source: 'admin', authorization_type: 'bearer' },
+ });
+
+ async function patchStored(entries: Array<{ fieldPath: string; value: unknown }>) {
+ const { handlers, deps } = createHandlers({
+ findConfigByPrincipal: jest.fn(async (_type: string, principalId: string) =>
+ principalId === 'admin' ? structuredClone(stored) : null,
+ ),
+ });
+ const res = mockRes();
+ await handlers.patchConfigField(
+ mockReq({ params: { principalType: 'role', principalId: 'admin' }, body: { entries } }),
+ res,
+ );
+ return { res, deps };
+ }
+
+ it('refuses moving a stored MCP key that a decoy entry did not replace', async () => {
+ const { res, deps } = await patchStored([
+ { fieldPath: 'mcpServers.probe.apiKey.key', value: DECOY },
+ { fieldPath: 'mcpServers.probe', value: keyless(EVIL) },
+ ]);
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toMatchObject({
+ code: 'MCP_API_KEY_REENTRY_REQUIRED',
+ server: 'probe',
+ fields: ['url'],
+ });
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
+ });
+
+ it('refuses moving a stored web search key that a decoy entry did not replace', async () => {
+ const { res, deps } = await patchStored([
+ { fieldPath: 'webSearch.firecrawlApiKey', value: DECOY },
+ { fieldPath: 'webSearch', value: { firecrawlApiUrl: 'https://fc-evil.example.com' } },
+ ]);
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toMatchObject({
+ code: 'CONFIG_SECRET_REENTRY_REQUIRED',
+ issues: [
+ expect.objectContaining({
+ path: 'webSearch.firecrawlApiUrl',
+ secretPath: 'webSearch.firecrawlApiKey',
+ }),
+ ],
+ });
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
+ });
+
+ it("keeps the stored key's own preview when the decoy is overwritten in place", async () => {
+ const { res, deps } = await patchStored([
+ { fieldPath: 'mcpServers.probe.apiKey.key', value: DECOY },
+ { fieldPath: 'mcpServers.probe', value: keyless(GOOD) },
+ { fieldPath: 'webSearch.firecrawlApiKey', value: DECOY },
+ { fieldPath: 'webSearch', value: { firecrawlApiUrl: 'https://fc-good.example.com' } },
+ ]);
+
+ expect(res.statusCode).toBe(200);
+ expect(writtenField(deps, 'mcpServers.probe.apiKey')).toEqual({
+ source: 'admin',
+ authorization_type: 'bearer',
+ key: STORED_MCP_KEY,
+ keyPreview: '...1111',
+ });
+ expect(writtenField(deps, 'webSearch.firecrawlApiKey')).toBe(STORED_FIRECRAWL_KEY);
+ expect(writtenField(deps, 'webSearch.firecrawlApiKeyPreview')).toBe('...2222');
+ });
+
+ it('stores the decoy, with its preview, when it is written after the ancestor', async () => {
+ const { res, deps } = await patchStored([
+ { fieldPath: 'mcpServers.probe', value: keyless(EVIL) },
+ { fieldPath: 'mcpServers.probe.apiKey.key', value: DECOY },
+ ]);
+
+ expect(res.statusCode).toBe(200);
+ expect(writtenField(deps, 'mcpServers.probe.apiKey.key')).toBe(`v3:test:${DECOY}`);
+ expect(writtenField(deps, 'mcpServers.probe.apiKey.keyPreview')).toBe('...0000');
+ expect(writtenField(deps, 'mcpServers.probe.url')).toBe(EVIL);
+ });
+ });
+
describe('patchConfigField: section-scoped priority preservation', () => {
it('ignores request-supplied priority when caller lacks broad manage:configs', async () => {
const { handlers, deps } = createHandlers({
@@ -2565,7 +2693,7 @@ describe('createAdminConfigHandlers', () => {
expect(getAppConfig).toHaveBeenCalledWith(expect.objectContaining({ baseOnly: true }));
});
- it('previews a plaintext secret an override stored, never one librechat.yaml supplies', async () => {
+ it('previews a plaintext secret an override stored by its value, and a librechat.yaml one only with the fixed mask', async () => {
const yaml = {
webSearch: {
serperApiKey: 'serper-yaml-literal-0001',
@@ -2590,11 +2718,14 @@ describe('createAdminConfigHandlers', () => {
expect(res.statusCode).toBe(200);
expect(JSON.stringify(res.body)).not.toContain('kn-legacy-plain-0002');
+ expect(JSON.stringify(res.body)).not.toContain('0001');
expect((res.body!.config as typeof merged).webSearch).toEqual({
keenableApiKeyPreview: '...0002',
+ serperApiKeyPreview: '********',
});
expect((baseOnlyRes.body!.config as typeof yaml).webSearch).toEqual({
keenableApiKey: '${KEENABLE_API_KEY}',
+ serperApiKeyPreview: '********',
});
});
@@ -4232,8 +4363,8 @@ describe('createAdminConfigHandlers', () => {
custom: [
{
name: 'Private',
- baseURL: 'https://private.example.com/v2',
- models: { default: ['m'] },
+ baseURL: 'https://private.example.com/v1',
+ models: { default: ['m', 'n'] },
},
],
},
@@ -4245,10 +4376,12 @@ describe('createAdminConfigHandlers', () => {
expect(res.statusCode).toBe(200);
const [entry] = (
- writtenDraft(deps).overrides.endpoints as { custom: Array<Record<string, string>> }
+ writtenDraft(deps).overrides.endpoints as {
+ custom: Array<Record<string, string> & { models: { default: string[] } }>;
+ }
).custom;
expect(entry.apiKey).toBe('v3:test:sk-stored');
- expect(entry.baseURL).toBe('https://private.example.com/v2');
+ expect(entry.models.default).toEqual(['m', 'n']);
/** Validation saw the document the write stores, with the kept secret in place. */
const overrideCalls = jest.mocked(getConfigOverrideIssues).mock.calls;
const validated = overrideCalls[overrideCalls.length - 1][0] as {
diff --git a/packages/api/src/admin/config.ts b/packages/api/src/admin/config.ts
index 95960b279c..a8857689ff 100644
--- a/packages/api/src/admin/config.ts
+++ b/packages/api/src/admin/config.ts
@@ -11,6 +11,7 @@ import {
hasProcessMCPServerConfig,
isProcessMCPServerConfig,
isProcessMCPServerField,
+ EModelEndpoint,
} from 'librechat-data-provider';
import {
logger,
@@ -60,6 +61,9 @@ import {
isConfigRevisionConflict,
isConfigOverrideStateEmpty,
toConfigDraft,
+ toConfigIdentityPath,
+ renameConfigIdentityPath,
+ resolveConfigIdentityPath,
} from '@librechat/data-schemas';
import type {
AppConfig,
@@ -76,25 +80,33 @@ import type {
ConfigOverrideIssue,
ConfigPathErrorReason,
ConfigOverrideState,
+ ConfigOverrideLayer,
ConfigEntryError,
AdminConfigChangeOp,
AdminConfigChangeRef,
AdminConfigSkipReason,
AdminConfigIgnoreReason,
+ AdminConfigIgnoredSecret,
AdminConfigChangesResponse,
AdminConfigChangeErrorResponse,
ConfigMutationOutcome,
ConfigMutationPlan,
+ ConfigIdentityStep,
} from '@librechat/data-schemas';
import type { TCustomConfig } from 'librechat-data-provider';
import type { Response } from 'express';
import type { CapabilityUser } from '~/middleware/capabilities';
+import type { EnvReferencePolicy } from '~/app/allowlist';
+import type { ConfigSecretRename } from './secrets';
import type { SecretReentryIssue } from './binding';
import type { ServerRequest } from '~/types/http';
import type { RecordAuditEntry } from './audit';
+import type { SecretReentry } from './reentry';
import {
encryptConfigSecretFields,
encryptConfigSecrets,
+ carryRenamedConfigSecrets,
+ getEnteredConfigSecrets,
getConfigSecretMutationPaths,
getConfigSecretInputError,
getConfigSecretSections,
@@ -108,15 +120,35 @@ import {
redactResolvedConfigSecrets,
} from './secrets';
import {
- getBatchReentryIssues,
- getPatchReentryIssues,
+ parseEnvAllowlist,
+ getEnvReferenceIssues,
+ createEnvReferencePolicy,
+ ENV_REFERENCE_NOT_ALLOWED,
+ hasDisallowedStoredReference,
+} from '~/app/allowlist';
+import {
+ SECRET_BINDINGS,
+ REBINDING_SECTIONS,
+ getRebindingIdentity,
+ toIgnoredSecretOverride,
+ withoutStoredSecretBindings,
+} from '~/app/rebinding';
+import {
+ MCP_SERVER_SECTIONS,
+ findSecretReentry,
+ getBoundKeyReentryIssues,
+ getAzureGroupReentryIssues,
+} from './reentry';
+import {
+ entersBoundSecret,
+ bindSecretDestinations,
isWebSearchBindingPath,
- getRemovalReentryIssues,
- getReplaceReentryIssues,
+ getWebSearchReentryIssues,
} from './binding';
import { createAdminAuditEmitter, configTarget } from './audit';
import { DEFAULT_OVERRIDE_CACHE_TTL } from '~/app/service';
import { getSafeErrorMetadata } from '~/utils/errors';
+import { mergeOverrideLayers } from '~/app/overrides';
import { buildAdminConfigMeta } from './meta';
const UNSAFE_SEGMENTS = /(?:^|\.)(__[\w]*|constructor|prototype)(?:\.|$)/;
@@ -279,8 +311,10 @@ function readSegmentsQuery(value: unknown): unknown {
/**
* The field writes in request order: each dot-free entry as encryption and secret
- * preservation left it (one they dropped is skipped), each dotted entry as sent, then any
- * field the secret pipeline added, such as a preview companion.
+ * preservation left it (one they dropped is skipped), right after it the preview companion
+ * the secret pipeline wrote for it, each dotted entry as sent, then any other field the
+ * pipeline added. A preview travels with its secret, so a later write of an ancestor that
+ * puts the stored secret back replaces both, and no preview ever describes another key.
*/
function toOrderedWrites(
entries: ReadonlyArray<{ target: FieldTarget; value: unknown }>,
@@ -291,9 +325,16 @@ function toOrderedWrites(
for (const { target, value } of entries) {
if (!target.dotFree) {
writes.push({ segments: target.segments, value });
- } else if (pending.has(target.fieldPath)) {
- writes.push({ segments: target.segments, value: pending.get(target.fieldPath) });
- pending.delete(target.fieldPath);
+ continue;
+ }
+ if (!pending.has(target.fieldPath)) {
+ continue;
+ }
+ for (const fieldPath of getConfigSecretMutationPaths(target.fieldPath)) {
+ if (pending.has(fieldPath)) {
+ writes.push({ segments: parseFieldPath(fieldPath), value: pending.get(fieldPath) });
+ pending.delete(fieldPath);
+ }
}
}
for (const [fieldPath, value] of pending) {
@@ -631,6 +672,12 @@ export interface AdminConfigDeps {
* Defaults to the service's own default.
*/
overrideCacheTtlMs?: number;
+ /**
+ * Extra env names override values may reference (`CONFIG_OVERRIDE_ENV_ALLOWLIST`), beyond
+ * those librechat.yaml references and the built-in endpoint credentials. Must match what the
+ * app config service is given, so a write is judged by the policy its values resolve under.
+ */
+ overrideEnvAllowlist?: string;
}
// ── Validation helpers ───────────────────────────────────────────────
@@ -728,7 +775,7 @@ 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. */
+/** Shows no section: an assign-only write stores an empty document. */
const NO_READ_ACCESS: ReadableSections = { broad: false, sections: new Set() };
function canReadSection(readable: ReadableSections, section: string): boolean {
@@ -815,6 +862,7 @@ type ConfigResponse = ConfigRecord & { revision: ConfigRevision };
function redactConfigForResponse(config: ConfigRecord): ConfigResponse {
const safeConfig = JSON.parse(JSON.stringify(config)) as ConfigRecord;
if (safeConfig.overrides) {
+ safeConfig.overrides = withoutStoredSecretBindings(safeConfig.overrides);
redactConfigSecrets(safeConfig.overrides, { previewPlaintext: true });
}
return { ...safeConfig, revision: getConfigRevision(config) };
@@ -847,13 +895,38 @@ function toWrittenConfig(config: ConfigRecord, access: ReadableSections): Config
return redactConfigForResponse(readable);
}
+/**
+ * The credentials a written document's layer drops at merge (`secretRebinding`), limited to the
+ * sections the response may show: each path names a server, endpoint or group of its section.
+ */
+function filterIgnoredForReadAccess(
+ ignored: readonly AdminConfigIgnoredSecret[],
+ access: ReadableSections,
+): AdminConfigIgnoredSecret[] {
+ return ignored.filter(({ segments }) => canReadSection(access, segments[0]));
+}
+
+/** Read access to only the sections a write manages, for a response that resolves no other. */
+function toWrittenSectionsAccess(
+ hasBroadManage: boolean,
+ managedSections: readonly string[],
+): ReadableSections {
+ return hasBroadManage ? FULL_READ_ACCESS : { broad: false, sections: new Set(managedSections) };
+}
+
+/** A write's response: the written document as a read shows it, and what its layer drops. */
function sendWrittenConfig(
res: Response,
status: number,
config: ConfigRecord,
access: ReadableSections,
+ ignoredSecrets: readonly AdminConfigIgnoredSecret[] = [],
): Response {
- return res.status(status).json({ config: toWrittenConfig(config, access) });
+ const ignored = filterIgnoredForReadAccess(ignoredSecrets, access);
+ return res.status(status).json({
+ config: toWrittenConfig(config, access),
+ ...(ignored.length > 0 && { ignored }),
+ });
}
/**
@@ -915,15 +988,28 @@ function secretReentryResponse(res: Response, issues: SecretReentryIssue[]): Res
});
}
-/** Why a planned unset or tombstone wrote nothing. */
+/**
+ * A write run on the validation floor, with the active Base document it was last judged on
+ * (`undefined` when the write read none: Base itself, or a write with nothing to validate).
+ */
+type FloorOutcome<T> = ConfigMutationOutcome<T> & { base?: ConfigRecord | null };
+
+/**
+ * Why a planned unset or tombstone wrote nothing: no document to unset, no principal to create
+ * one for, or a stored credential it would send elsewhere without entering it again.
+ */
type RemovalStop =
| { status: 404; missing: 'config' | 'principal' }
- | { status: 400; reentry: SecretReentryIssue[] };
+ | { status: 400; reentry: SecretReentryIssue[] }
+ | { status: 400; mcpReentry: SecretReentry };
function removalStopResponse(res: Response, stop: RemovalStop): Response {
- if (stop.status === 400) {
+ if ('reentry' in stop) {
return secretReentryResponse(res, stop.reentry);
}
+ if ('mcpReentry' in stop) {
+ return mcpReentryResponse(res, stop.mcpReentry);
+ }
return stop.missing === 'principal'
? principalNotFoundResponse(res)
: res.status(404).json({ error: 'Config not found' });
@@ -970,6 +1056,204 @@ function preservePatchedConfigSecretFields(
return result;
}
+/** Most rename hints one write accepts. */
+const MAX_RENAMES = 50;
+const UNSAFE_NAME = /^(?:\$|__)|^(?:constructor|prototype)$/;
+
+type RenamesRead = { ok: true; renames: ConfigSecretRename[] } | { ok: false; reason: string };
+
+/**
+ * Reads the body's `renames` hint: `[{ path: 'mcpServers', previousName, name }]`, telling the
+ * write that the server it writes as `name` was renamed (or duplicated) from the stored
+ * `previousName`, so secrets it omits are carried from there. Never stored.
+ */
+function readRenames(value: unknown): RenamesRead {
+ if (value === undefined || value === null) {
+ return { ok: true, renames: [] };
+ }
+ if (!Array.isArray(value) || value.length > MAX_RENAMES) {
+ return { ok: false, reason: 'invalid_renames' };
+ }
+ const renames: ConfigSecretRename[] = [];
+ const targets = new Set<string>();
+ for (const item of value) {
+ const { path, previousName, name } = (item ?? {}) as Record<string, unknown>;
+ if (path !== 'mcpServers') {
+ return { ok: false, reason: 'unsupported_path' };
+ }
+ if (
+ typeof previousName !== 'string' ||
+ typeof name !== 'string' ||
+ previousName === '' ||
+ name === '' ||
+ previousName === name ||
+ UNSAFE_NAME.test(previousName) ||
+ UNSAFE_NAME.test(name)
+ ) {
+ return { ok: false, reason: 'invalid_name' };
+ }
+ if (targets.has(name)) {
+ return { ok: false, reason: 'duplicate_target' };
+ }
+ targets.add(name);
+ renames.push({ path, previousName, name });
+ }
+ return { ok: true, renames };
+}
+
+function invalidRenameResponse(res: Response, reason: string): Response {
+ return res
+ .status(400)
+ .json({ error: 'Invalid rename hint', code: 'CONFIG_RENAME_INVALID', reason });
+}
+
+/** Whether a write sets the value at `target`: at it, below it, or at an ancestor whose value reaches it. */
+function writesTarget(writes: readonly ConfigFieldWrite[], target: readonly string[]): boolean {
+ return writes.some(
+ ({ segments, value }) =>
+ isSegmentPrefix(target, segments) ||
+ (isSegmentPrefix(segments, target) &&
+ getAtPath(value, target.slice(segments.length)) !== undefined),
+ );
+}
+
+/**
+ * Why a rename hint cannot apply to this write: its source is not a stored server, or the write
+ * does not write its target.
+ */
+function getRenameIssue(
+ renames: readonly ConfigSecretRename[],
+ stored: { overrides?: unknown } | null,
+ writes: readonly ConfigFieldWrite[],
+): string | null {
+ for (const { path, previousName, name } of renames) {
+ const storedRecord = (stored?.overrides as Record<string, unknown> | undefined)?.[path];
+ if (
+ storedRecord == null ||
+ typeof storedRecord !== 'object' ||
+ !Object.prototype.hasOwnProperty.call(storedRecord, previousName)
+ ) {
+ return 'source_not_found';
+ }
+ if (!writesTarget(writes, [path, name])) {
+ return 'target_not_written';
+ }
+ }
+ return null;
+}
+
+function mcpReentryResponse(res: Response, reentry: SecretReentry): Response {
+ const { message, code, server, fields } = reentry;
+ return res.status(400).json({ error: message, code, server, fields });
+}
+
+/** Describes rename hints for the audit record: paths and names, never values. */
+function describeRenames(renames: readonly ConfigSecretRename[]): string {
+ return renames.map(({ path, previousName, name }) => `${path}:${previousName}>${name}`).join(',');
+}
+
+/**
+ * Whether removing a field in `section` can change where a bound secret is sent: only then does a
+ * field removal or tombstone report what it drops.
+ */
+function isBoundSecretSection(section: string | undefined): boolean {
+ return section != null && REBINDING_SECTIONS.includes(section);
+}
+
+/** Whether a document overrides or tombstones anything in a section with bound secrets. */
+function touchesBoundSecretSections(
+ record: Pick<ConfigOverrideLayer, 'overrides' | 'tombstones'>,
+): boolean {
+ const overrides = (record.overrides ?? {}) as Record<string, unknown>;
+ return REBINDING_SECTIONS.some(
+ (section) =>
+ section in overrides ||
+ (record.tombstones ?? []).some(
+ (path) => typeof path === 'string' && path.split('.')[0] === section,
+ ),
+ );
+}
+
+const MCP_SECTIONS = new Set<string>(MCP_SERVER_SECTIONS);
+
+/** A removal enters no secret: whatever credential it leaves in place was kept. */
+const NO_ENTERED_SECRETS: ReadonlySet<string> = new Set();
+
+/** Whether a path holds Azure groups or anything in them: `endpoints`, and all of its Azure section. */
+function isAzureGroupPath(segments: readonly string[]): boolean {
+ return (
+ segments[0] === 'endpoints' &&
+ (segments.length === 1 || segments[1] === EModelEndpoint.azureOpenAI)
+ );
+}
+
+/** Sections whose keys sit beside their own destination: OCR's and each speech service's. */
+const SCALAR_BOUND_SECTIONS = new Set<string>(['ocr', 'speech']);
+
+/** Whether a path names an OCR or speech key itself, or its preview: removing it moves nothing. */
+function isScalarSecretPath(segments: readonly string[]): boolean {
+ return SECRET_BINDINGS.some(
+ ({ path, secretKey }) =>
+ segments.length === path.length + 1 &&
+ path.every((segment, index) => segments[index] === segment) &&
+ (segments[path.length] === secretKey || segments[path.length] === `${secretKey}Preview`),
+ );
+}
+
+/**
+ * Whether a path holds a key bound to the destination beside it, or that destination: OCR,
+ * speech, or a custom endpoint (and `endpoints` whole). The key itself is not such a path.
+ */
+function isBoundKeyPath(segments: readonly string[]): boolean {
+ if (isScalarSecretPath(segments)) {
+ return false;
+ }
+ return (
+ SCALAR_BOUND_SECTIONS.has(segments[0]) ||
+ (segments[0] === 'endpoints' && (segments.length === 1 || segments[1] === 'custom'))
+ );
+}
+
+/**
+ * Whether removing or tombstoning `target` can change where a stored credential is sent: a web
+ * search URL (or the whole section) beside a stored key, any field of an MCP server, anything an
+ * Azure group's key and destination sit in, or anything an OCR, speech or custom endpoint key
+ * and its destination sit in.
+ */
+function isBoundRemoval(target: FieldTarget): boolean {
+ return (
+ (target.dotFree && isWebSearchBindingPath(target.fieldPath)) ||
+ MCP_SECTIONS.has(target.segments[0]) ||
+ isAzureGroupPath(target.segments) ||
+ isBoundKeyPath(target.segments)
+ );
+}
+
+/**
+ * The stored keys a planned document keeps beside a destination it changes, which the request
+ * must enter again: web search keys, Azure group keys (compared over librechat.yaml's resolved
+ * groups, from `baseConfig`), and custom endpoint, OCR and speech keys (compared as the document
+ * alone sends them over librechat.yaml). MCP credentials answer with their own error
+ * (`findSecretReentry`).
+ */
+function getKeptKeyReentryIssues(
+ stored: ConfigRecord | null | undefined,
+ candidate: ConfigOverrideState,
+ entered: ReadonlySet<string>,
+ baseConfig: AppConfig | undefined,
+): SecretReentryIssue[] {
+ return [
+ ...getWebSearchReentryIssues(stored, candidate, entered),
+ ...getAzureGroupReentryIssues({
+ stored,
+ candidate,
+ entered,
+ baseGroupMap: baseConfig?.endpoints?.[EModelEndpoint.azureOpenAI]?.groupMap,
+ }),
+ ...getBoundKeyReentryIssues({ stored, candidate, entered, baseConfig }),
+ ];
+}
+
// ── Change batches ───────────────────────────────────────────────────
type ChangeOpKind = AdminConfigChangeOp['op'];
@@ -1021,7 +1305,10 @@ interface PreparedChange {
key?: string;
/** The new key of `rename`. */
to?: string;
- /** `set`: the value to store, after normalization and stripping. */
+ /**
+ * `set`: the value to store, after normalization and stripping. `upsertEntry`: the entry as
+ * submitted, before its secrets are encrypted.
+ */
value?: unknown;
/** `set` on a dot-free path: `value` with secrets encrypted, plus any preview companion. */
fields?: Record<string, unknown>;
@@ -1210,7 +1497,7 @@ function prepareEntryChange(
return changeFailure(index, guardError.error, guardError.code);
}
const [entry] = encryptConfigSecrets([raw.entry as Record<string, unknown>], target.fieldPath);
- change = { ...base, key, entry };
+ change = { ...base, key, entry, value: raw.entry };
}
if (skipReason) {
return { ok: true, change: null, skipped: [{ ...toChangeRef(change), reason: skipReason }] };
@@ -1466,6 +1753,103 @@ function describeChange(change: PreparedChange): string {
return change.key !== undefined ? `${path}[${JSON.stringify(change.key)}]` : path;
}
+/**
+ * Where the value an applied change sends sits in the document it leaves (`next`): a set's path,
+ * or an upserted entry at its position in its collection. `null` for a change that sends none.
+ */
+function getSentLocation(change: PreparedChange, next: ConfigOverrideState): string[] | null {
+ const { segments } = change.target;
+ if (change.op === 'set' && !change.paths) {
+ return [...segments];
+ }
+ if (change.op !== 'upsertEntry') {
+ return null;
+ }
+ const keyField = getConfigArrayMergeKey(segments);
+ const entries = getAtPath(next.overrides, segments);
+ const index =
+ keyField && Array.isArray(entries)
+ ? entries.findIndex(getConfigEntryMatcher(segments, keyField, change.key ?? ''))
+ : -1;
+ return index >= 0 ? [...segments, String(index)] : null;
+}
+
+/**
+ * Env reference issues in the value an applied change sent, by identity
+ * (`toConfigIdentityPath`): each location is named in the document the change left, with every
+ * entry of a merged-by-key array by its key, so the issue still names that entry however later
+ * changes of the batch move, add or remove other entries.
+ */
+function getSentEnvIssuePaths(
+ change: PreparedChange,
+ next: ConfigOverrideState,
+ policy: EnvReferencePolicy,
+): ConfigIdentityStep[][] {
+ const location = getSentLocation(change, next);
+ if (!location) {
+ return [];
+ }
+ return getEnvReferenceIssues(change.value, policy, location).map(({ segments }) =>
+ toConfigIdentityPath(next.overrides, segments),
+ );
+}
+
+/**
+ * Env reference issues for the values a batch's changes sent, judged on the document the batch
+ * leaves as its other issues are. Each is held by identity (`getSentEnvIssuePaths`), carried
+ * through the batch's later renames, and named where the batch leaves the value; it counts only
+ * when the end state still holds a disallowed reference there (as stored, ciphertext by its
+ * plaintext) at a location the batch changed (`written`). A reference a later change removed or
+ * replaced, or one that leaves the stored value as it was, does not.
+ */
+function getBatchEnvIssues(
+ sent: ReadonlyArray<readonly ConfigIdentityStep[]>,
+ state: ConfigOverrideState,
+ written: ReadonlyArray<readonly string[]>,
+ policy: EnvReferencePolicy,
+): ConfigOverrideIssue[] {
+ const reported = new Set<string>();
+ return sent.flatMap((path): ConfigOverrideIssue[] => {
+ const segments = resolveConfigIdentityPath(state.overrides, path);
+ if (!segments) {
+ return [];
+ }
+ const kept = getAtPath(state.overrides, segments);
+ const key = segments.join('\u0000');
+ if (
+ reported.has(key) ||
+ typeof kept !== 'string' ||
+ !hasDisallowedStoredReference(kept, policy, segments) ||
+ !written.some((writtenPath) => isSegmentPrefix(writtenPath, segments))
+ ) {
+ return [];
+ }
+ reported.add(key);
+ return [{ path: segments.join('.'), segments, code: ENV_REFERENCE_NOT_ALLOWED }];
+ });
+}
+
+/**
+ * The secret values a batch's changes entered, encrypted, before secret preservation fills in
+ * what they omit (see `getEnteredConfigSecrets`).
+ */
+function getEnteredChangeSecrets(changes: readonly PreparedChange[]): Set<string> {
+ return getEnteredConfigSecrets(
+ changes.flatMap((change): ConfigFieldWrite[] => {
+ if (change.op === 'upsertEntry' && change.entry) {
+ return [{ segments: change.target.segments, value: [change.entry] }];
+ }
+ if (change.op !== 'set' || !change.fields) {
+ return [];
+ }
+ return Object.entries(change.fields).map(([fieldPath, value]) => ({
+ segments: parseFieldPath(fieldPath),
+ value,
+ }));
+ }),
+ );
+}
+
// ── Handler factory ──────────────────────────────────────────────────
export function createAdminConfigHandlers(deps: AdminConfigDeps): {
@@ -1508,8 +1892,11 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
recordAuditEntry,
auditFailClosed,
overrideCacheTtlMs = DEFAULT_OVERRIDE_CACHE_TTL,
+ overrideEnvAllowlist,
} = deps;
+ const envAllowlist = parseEnvAllowlist(overrideEnvAllowlist);
+
const emitAudit = createAdminAuditEmitter({
recordAuditEntry,
failClosed: auditFailClosed,
@@ -1602,21 +1989,32 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
/**
- * Unsets or tombstones a dot-free path (a secret together with its preview) in a write
+ * Unsets or tombstones a path (a dot-free secret together with its preview) in a write
* planned from the document it replaces, so each check judges exactly the revision the write
* lands on: a tombstone that creates the principal's first document needs the principal
- * (`canCreateFor`), and removing a web search URL needs its stored key entered again. A
+ * (`canCreateFor`), and a removal that changes where a stored credential is sent needs it
+ * entered again, as a write would: a web search URL beside a stored key, an Azure group's
+ * destination beside its stored key, or a field of an MCP server that keeps a stored credential
+ * (judged over librechat.yaml, as on every write). A
* write that lands in between is re-read and re-checked, or answers 409 under
* `expectedRevision`. An unset stops when there is no document.
*/
- function removeConfigPath(
+ async function removeConfigPath(
principalType: PrincipalType,
principalId: string,
- fieldPath: string,
+ target: FieldTarget,
removal: { tombstone: true; priority?: number } | { tombstone: false },
expectedRevision: ConfigRevision | undefined,
+ tenantId: string | undefined,
): Promise<ConfigMutationOutcome<RemovalStop>> {
- const paths = getConfigSecretMutationPaths(fieldPath).map(parseFieldPath);
+ const paths = getRemovalPaths(target);
+ const baseConfig =
+ MCP_SECTIONS.has(target.segments[0]) ||
+ isAzureGroupPath(target.segments) ||
+ isBoundKeyPath(target.segments)
+ ? await getBaseAppConfig(tenantId)
+ : undefined;
+ const base: Partial<TCustomConfig> = baseConfig?.config ?? {};
return runConfigMutation<RemovalStop>(
{
read: () => readStoredConfig(principalType, principalId),
@@ -1630,14 +2028,28 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
if (!stored && !(await canCreateFor(principalType, principalId))) {
return { draft: null, result: { status: 404, missing: 'principal' } };
}
- const reentry = getRemovalReentryIssues(stored, fieldPath, removal.tombstone);
- if (reentry.length > 0) {
- return { draft: null, result: { status: 400, reentry } };
- }
const current = toConfigOverrideState(stored);
const state = removal.tombstone
? tombstoneConfigPaths(current, paths)
: unsetConfigPaths(current, paths);
+ const reentry = getKeptKeyReentryIssues(stored, state, NO_ENTERED_SECRETS, baseConfig);
+ if (reentry.length > 0) {
+ return { draft: null, result: { status: 400, reentry } };
+ }
+ const mcpReentry = findSecretReentry({
+ stored,
+ candidate: state,
+ base,
+ entered: NO_ENTERED_SECRETS,
+ });
+ if (mcpReentry) {
+ return { draft: null, result: { status: 400, mcpReentry } };
+ }
+ const bound = bindSecretDestinations({
+ stored,
+ candidate: state,
+ entered: NO_ENTERED_SECRETS,
+ });
return {
draft: {
principalModel: stored?.principalModel ?? principalModel(principalType),
@@ -1645,8 +2057,8 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
(removal.tombstone ? removal.priority : undefined) ??
stored?.priority ??
getDefaultConfigPriority({ principalType, principalId }),
- overrides: state.overrides,
- tombstones: state.tombstones,
+ overrides: bound.overrides,
+ tombstones: bound.tombstones,
isActive: stored?.isActive ?? true,
},
};
@@ -1655,13 +2067,131 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
);
}
- /** The deployment's `librechat.yaml` config, which overrides are validated on top of. */
- async function getBaseYamlConfig(tenantId?: string): Promise<Partial<TCustomConfig>> {
+ /**
+ * The deployment's resolved `librechat.yaml` config. Its raw `config` is what overrides are
+ * validated on top of, and what decides which env names they may reference.
+ */
+ async function getBaseAppConfig(tenantId?: string): Promise<AppConfig | undefined> {
if (!getAppConfig) {
- return {};
+ return undefined;
+ }
+ return getAppConfig({ tenantId, baseOnly: true });
+ }
+
+ function getEnvPolicy(baseYaml: Partial<TCustomConfig>): EnvReferencePolicy {
+ return createEnvReferencePolicy({ config: baseYaml, allowlist: envAllowlist });
+ }
+
+ /**
+ * The secrets the written document's layer drops at merge (`app/rebinding.ts`): inherited ones
+ * it sends somewhere new, and its own whose destination a layer below changed. Judged on the
+ * Base floor: librechat.yaml, then the active Base profile (for any other principal; Base
+ * always merges first), then this document. A user or group can have other profiles in
+ * between, so this is what the document does over the floor. PUT, PATCH and change batches
+ * report it (a dry run for the document it plans) on the Base their write was last judged on
+ * (`base`), and field removals and tombstones in a section with bound secrets read it; the
+ * base config is loaded only when the document overrides or tombstones such a section. A
+ * failure is logged and reports nothing: the write itself has committed.
+ */
+ async function reportIgnored(
+ written: ConfigOverrideLayer,
+ tenantId: string | undefined,
+ loaded?: {
+ baseConfig: AppConfig | undefined;
+ envPolicy: EnvReferencePolicy;
+ base?: ConfigRecord | null;
+ },
+ ): Promise<AdminConfigIgnoredSecret[]> {
+ if (!touchesBoundSecretSections(written)) {
+ return [];
+ }
+ try {
+ const baseConfig = loaded ? loaded.baseConfig : await getBaseAppConfig(tenantId);
+ if (!baseConfig) {
+ return [];
+ }
+ const envPolicy = loaded?.envPolicy ?? getEnvPolicy(baseConfig.config ?? {});
+ const writtenId = written.principalId?.toString();
+ const isBase = isBaseConfigPrincipal(written);
+ let floor: ConfigRecord | null = null;
+ if (!isBase) {
+ floor = loaded?.base !== undefined ? loaded.base : await readActiveBase();
+ }
+ const ignored: AdminConfigIgnoredSecret[] = [];
+ mergeOverrideLayers(baseConfig, floor ? [floor, written] : [written], {
+ envPolicy,
+ onRebinding: (rebinding) => {
+ if (
+ rebinding.layer.principalType === written.principalType &&
+ rebinding.layer.principalId?.toString() === writtenId
+ ) {
+ ignored.push(toIgnoredSecretOverride(rebinding));
+ }
+ },
+ });
+ return ignored;
+ } catch (error) {
+ logger.error(
+ '[adminConfig] Failed to report ignored overrides:',
+ getSafeErrorMetadata(error),
+ );
+ return [];
}
- const appConfig = await getAppConfig({ tenantId, baseOnly: true });
- return appConfig?.config ?? {};
+ }
+
+ /**
+ * Binds the keys a planned document holds to the destinations they were entered for
+ * (`bindSecretDestinations`): a key the request entered, to where the merge sends it over the
+ * active Base when that is not where librechat.yaml and the document alone send it, as the
+ * rebinding guard reports it (`SecretRebinding.binding`); a key it kept, to what is stored
+ * beside it. A profile can then enter its own key for an endpoint, server or service Base
+ * defines without restating the destination, and the key is dropped again once Base, or any
+ * layer below the profile, moves that destination. Base merges first, so nothing moves its
+ * keys from below.
+ */
+ function bindPlannedSecrets(params: {
+ principalType: PrincipalType;
+ principalId: string;
+ stored: ConfigRecord | null;
+ candidate: ConfigOverrideState;
+ entered: ReadonlySet<string>;
+ base: ConfigRecord | null;
+ baseConfig: AppConfig | undefined;
+ envPolicy: EnvReferencePolicy;
+ }): ConfigOverrideState {
+ const { principalType, principalId, stored, candidate, entered, base } = params;
+ const kept = bindSecretDestinations({ stored, candidate, entered });
+ if (
+ base == null ||
+ isBaseConfigPrincipal({ principalType, principalId }) ||
+ !entersBoundSecret(kept, entered)
+ ) {
+ return kept;
+ }
+ const destinations = new Map<string, string>();
+ const layer: ConfigOverrideLayer = {
+ principalType,
+ principalId,
+ priority: getDefaultConfigPriority({ principalType, principalId }),
+ overrides: kept.overrides,
+ tombstones: kept.tombstones,
+ };
+ mergeOverrideLayers(params.baseConfig ?? ({} as AppConfig), [base, layer], {
+ envPolicy: params.envPolicy,
+ onRebinding: (rebinding) => {
+ if (
+ rebinding.binding != null &&
+ rebinding.layer.principalType === principalType &&
+ rebinding.layer.principalId?.toString() === principalId
+ ) {
+ destinations.set(getRebindingIdentity(rebinding.segments), rebinding.binding);
+ }
+ },
+ });
+ if (destinations.size === 0) {
+ return kept;
+ }
+ return bindSecretDestinations({ stored, candidate: kept, entered, destinations });
}
/**
@@ -1723,7 +2253,9 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
* `librechat.yaml` alone for Base itself. The principal's other profiles vary per user and
* are left to the merge. Base is read from the caller's tenant partition, so a caller without
* a tenant validates on the platform-level Base and never on a tenant's. With `yaml` `null`
- * the write does not validate on the floor, and `plan` gets an empty one.
+ * the write does not validate on the floor, and `plan` gets an empty one. `plan` also gets the
+ * Base document itself (`null` for Base, or when none is active), which binds the keys the
+ * write enters to the destinations they are sent to over it (`bindPlannedSecrets`).
*
* Base is its own document, which the profile's compare-and-swap does not cover. So each
* attempt reads Base beside the profile (a retry never reuses a Base a concurrent write has
@@ -1731,6 +2263,10 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
* request is judged once more, `plan` on the document the write replaced, on the Base the
* write landed over (`judgeOnLandedBase`): a write still valid there stands, and one that is
* not is withdrawn (`withdrawWrite`) and answered with that judgement.
+ *
+ * The outcome carries the Base it was last judged on (`base`, `undefined` when none was
+ * read), so what the written or planned document drops at merge (`reportIgnored`) is judged
+ * on the same Base without reading it again.
*/
async function runOnValidationFloor<T>(
principalType: PrincipalType,
@@ -1740,9 +2276,10 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
plan: (
stored: ConfigRecord | null,
floor: Partial<TCustomConfig>,
+ base: ConfigRecord | null,
) => Promise<ConfigMutationPlan<T>>,
expectedRevision: ConfigRevision | undefined,
- ): Promise<ConfigMutationOutcome<T>> {
+ ): Promise<FloorOutcome<T>> {
const readsBase = yaml != null && !isBaseConfigPrincipal({ principalType, principalId });
const attempt: { base: ConfigRecord | null } = { base: null };
const floorOver = (base: ConfigRecord | null): Partial<TCustomConfig> => {
@@ -1764,17 +2301,21 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
write: (draft, revision) =>
writeConfigDocument(principalType, principalId, draft, revision),
},
- (stored) => plan(stored, floorOver(attempt.base)),
+ (stored) => plan(stored, floorOver(attempt.base), attempt.base),
{ expectedRevision },
);
- if (!outcome.written || !readsBase) {
+ if (!readsBase) {
return outcome;
}
- const judged = await judgeOnLandedBase(attempt.base, (landed) =>
- plan(outcome.previous, floorOver(landed)),
- );
+ if (!outcome.written) {
+ return { ...outcome, base: attempt.base };
+ }
+ const judged = await judgeOnLandedBase(attempt.base, (landed) => {
+ attempt.base = landed;
+ return plan(outcome.previous, floorOver(landed), landed);
+ });
if (judged == null || judged.draft != null) {
- return outcome;
+ return { ...outcome, base: attempt.base };
}
const current = await withdrawWrite(
principalType,
@@ -1783,7 +2324,7 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
outcome.previous,
);
await invalidateCaches(tenantId, 'withdrawn write');
- return { written: false, current, result: judged.result };
+ return { written: false, current, result: judged.result, base: attempt.base };
}
/**
@@ -1980,6 +2521,11 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
return invalidExpectedRevisionResponse(res);
}
+ const renames = readRenames((req.body as { renames?: unknown }).renames);
+ if (!renames.ok) {
+ return invalidRenameResponse(res, renames.reason);
+ }
+
const rawOverrides = overrides as Record<string, unknown>;
if (hasProcessMCPServerConfig(rawOverrides.mcpServers)) {
return res.status(400).json({ error: PROCESS_MCP_CONFIG_ERROR });
@@ -2090,14 +2636,29 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
}
+ const baseConfig =
+ overrideSections.length > 0 ? await getBaseAppConfig(user.tenantId) : undefined;
+ const baseYaml: Partial<TCustomConfig> = baseConfig?.config ?? {};
+ const envPolicy = getEnvPolicy(baseYaml);
+ const envIssues = getEnvReferenceIssues(filteredOverrides, envPolicy);
+ if (envIssues.length > 0) {
+ return invalidOverrideResponse(res, envIssues);
+ }
+
const encryptedOverrides = encryptConfigSecrets(filteredOverrides);
- const yaml = overrideSections.length > 0 ? await getBaseYamlConfig(user.tenantId) : null;
+ /** What the request itself supplies, before secret preservation fills in what it omits. */
+ const requestWrites: ConfigFieldWrite[] = [{ segments: [], value: encryptedOverrides }];
+ const entered = getEnteredConfigSecrets(requestWrites);
+ /** A write without override sections (create-only or priority-only) validates nothing. */
+ const yaml = overrideSections.length > 0 ? baseYaml : null;
type PutStop =
| { status: 403 }
| { status: 404 }
| { status: 400; issues: ConfigOverrideIssue[] }
- | { status: 400; reentry: SecretReentryIssue[] };
+ | { status: 400; renameIssue: string }
+ | { status: 400; reentry: SecretReentryIssue[] }
+ | { status: 400; mcpReentry: SecretReentry };
let outcome;
try {
outcome = await runOnValidationFloor<PutStop>(
@@ -2105,7 +2666,7 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
principalId,
user.tenantId,
yaml,
- async (stored, floor) => {
+ async (stored, floor, base) => {
if (!stored && !(await canCreateFor(principalType, principalId))) {
return { draft: null, result: { status: 404 } };
}
@@ -2117,8 +2678,13 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
) {
return { draft: null, result: { status: 403 } };
}
+ const renameIssue = getRenameIssue(renames.renames, stored, requestWrites);
+ if (renameIssue) {
+ return { draft: null, result: { status: 400, renameIssue } };
+ }
/** Secrets an object omits are kept before validation sees the document. */
const preserved = preserveConfigSecrets(encryptedOverrides, stored?.overrides);
+ carryRenamedConfigSecrets(preserved, stored?.overrides, renames.renames);
/** A full replace keeps the principal's tombstones, so they shape its base. */
const issues = getConfigOverrideIssues(
preserved,
@@ -2128,10 +2694,15 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
return { draft: null, result: { status: 400, issues } };
}
/** A changed URL beside a stored key that stays needs that key entered again. */
- const reentry = getReplaceReentryIssues(stored, filteredOverrides, preserved);
+ const candidate = replaceConfigOverrides(toConfigOverrideState(stored), preserved);
+ const reentry = getKeptKeyReentryIssues(stored, candidate, entered, baseConfig);
if (reentry.length > 0) {
return { draft: null, result: { status: 400, reentry } };
}
+ const mcpReentry = findSecretReentry({ stored, candidate, base: baseYaml, entered });
+ if (mcpReentry) {
+ return { draft: null, result: { status: 400, mcpReentry } };
+ }
const next = { ...preserved } as Record<string, unknown>;
if (principalId === BASE_CONFIG_PRINCIPAL_ID) {
for (const section of BASE_PRINCIPAL_OVERRIDE_SECTIONS) {
@@ -2143,10 +2714,19 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
}
}
- const state = replaceConfigOverrides(
- toConfigOverrideState(stored),
- next as Partial<TCustomConfig>,
- );
+ const state = bindPlannedSecrets({
+ principalType,
+ principalId,
+ stored,
+ candidate: replaceConfigOverrides(
+ toConfigOverrideState(stored),
+ next as Partial<TCustomConfig>,
+ ),
+ entered,
+ base,
+ baseConfig,
+ envPolicy,
+ });
/** An omitted priority keeps the stored one, so a replace never reorders profiles. */
const requestedPriority = hasBroadManage ? priority : undefined;
return {
@@ -2176,9 +2756,15 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
if (stop.status === 404) {
return principalNotFoundResponse(res);
}
+ if ('renameIssue' in stop) {
+ return invalidRenameResponse(res, stop.renameIssue);
+ }
if ('reentry' in stop) {
return secretReentryResponse(res, stop.reentry);
}
+ if ('mcpReentry' in stop) {
+ return mcpReentryResponse(res, stop.mcpReentry);
+ }
return invalidOverrideResponse(res, stop.issues);
}
@@ -2192,6 +2778,7 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
operation: 'replace',
sections: overrideSections.join(','),
priority: config.priority,
+ ...(renames.renames.length > 0 && { renames: describeRenames(renames.renames) }),
},
});
return sendWrittenConfig(
@@ -2199,6 +2786,7 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
created ? 201 : 200,
config,
hasBroadManage ? FULL_READ_ACCESS : NO_READ_ACCESS,
+ await reportIgnored(config, user.tenantId, { baseConfig, envPolicy, base: outcome.base }),
);
} catch (error) {
if (isFieldNameRejection(error)) {
@@ -2243,6 +2831,11 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
return invalidExpectedRevisionResponse(res);
}
+ const renames = readRenames((req.body as { renames?: unknown }).renames);
+ if (!renames.ok) {
+ return invalidRenameResponse(res, renames.reason);
+ }
+
if (!Array.isArray(entries) || entries.length === 0) {
return res.status(400).json({ error: 'entries array is required and must not be empty' });
}
@@ -2348,46 +2941,85 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
const requestedPriority = hasBroadManage ? priority : undefined;
- const [yaml, access] = await Promise.all([
- getBaseYamlConfig(user.tenantId),
+ const [baseConfig, access] = await Promise.all([
+ getBaseAppConfig(user.tenantId),
resolveWriteReadAccess(user, hasBroadManage, writtenSections),
]);
+ const baseYaml: Partial<TCustomConfig> = baseConfig?.config ?? {};
+ const envPolicy = getEnvPolicy(baseYaml);
+ const envIssues = validEntries.flatMap(({ target, value }) =>
+ getEnvReferenceIssues(value, envPolicy, target.segments),
+ );
+ if (envIssues.length > 0) {
+ return invalidOverrideResponse(res, envIssues);
+ }
+
const encryptedFields = encryptConfigSecretFields(fields);
- const requested = validEntries.map(({ target, value }) => ({
- segments: target.segments,
- value,
- }));
+ /** What the request itself supplies, before secret preservation fills in what it omits. */
+ const requestWrites = toOrderedWrites(validEntries, encryptedFields);
+ const entered = getEnteredConfigSecrets(requestWrites);
type PatchStop =
| { status: 404 }
| { status: 400; issues: ConfigOverrideIssue[] }
- | { status: 400; reentry: SecretReentryIssue[] };
+ | { status: 400; renameIssue: string }
+ | { status: 400; reentry: SecretReentryIssue[] }
+ | { status: 400; mcpReentry: SecretReentry };
let outcome;
try {
outcome = await runOnValidationFloor<PatchStop>(
principalType,
principalId,
user.tenantId,
- yaml,
- async (stored, floor) => {
+ baseYaml,
+ async (stored, floor, base) => {
if (!stored && !(await canCreateFor(principalType, principalId))) {
return { draft: null, result: { status: 404 } };
}
+ const renameIssue = getRenameIssue(renames.renames, stored, requestWrites);
+ if (renameIssue) {
+ return { draft: null, result: { status: 400, renameIssue } };
+ }
/** Secrets an object omits are kept before validation sees the document. */
- const writes = toOrderedWrites(
- validEntries,
- preservePatchedConfigSecretFields(encryptedFields, stored?.overrides),
+ const preservedFields = preservePatchedConfigSecretFields(
+ encryptedFields,
+ stored?.overrides,
);
+ for (const [fieldPath, value] of Object.entries(preservedFields)) {
+ if (isConfigSecretPreservablePatch(fieldPath, value)) {
+ carryRenamedConfigSecrets(value, stored?.overrides, renames.renames, fieldPath);
+ }
+ }
+ const writes = toOrderedWrites(validEntries, preservedFields);
const fieldIssues = getConfigFieldIssues(writes, floor, stored);
if (fieldIssues.length > 0) {
return { draft: null, result: { status: 400, issues: fieldIssues } };
}
const state = setConfigFields(toConfigOverrideState(stored), writes);
/** A changed URL beside a stored key that stays needs that key entered again. */
- const reentry = getPatchReentryIssues(stored, requested, state);
+ const reentry = getKeptKeyReentryIssues(stored, state, entered, baseConfig);
if (reentry.length > 0) {
return { draft: null, result: { status: 400, reentry } };
}
+ const mcpReentry = findSecretReentry({
+ stored,
+ candidate: state,
+ base: baseYaml,
+ entered,
+ });
+ if (mcpReentry) {
+ return { draft: null, result: { status: 400, mcpReentry } };
+ }
+ const bound = bindPlannedSecrets({
+ principalType,
+ principalId,
+ stored,
+ candidate: state,
+ entered,
+ base,
+ baseConfig,
+ envPolicy,
+ });
return {
draft: {
principalModel: principalModel(principalType),
@@ -2395,8 +3027,8 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
requestedPriority ??
stored?.priority ??
getDefaultConfigPriority({ principalType, principalId }),
- overrides: state.overrides,
- tombstones: state.tombstones,
+ overrides: bound.overrides,
+ tombstones: bound.tombstones,
isActive: stored?.isActive ?? true,
},
};
@@ -2412,9 +3044,16 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
if (stop.status === 404) {
return principalNotFoundResponse(res);
}
- return 'reentry' in stop
- ? secretReentryResponse(res, stop.reentry)
- : invalidOverrideResponse(res, stop.issues);
+ if ('renameIssue' in stop) {
+ return invalidRenameResponse(res, stop.renameIssue);
+ }
+ if ('reentry' in stop) {
+ return secretReentryResponse(res, stop.reentry);
+ }
+ if ('mcpReentry' in stop) {
+ return mcpReentryResponse(res, stop.mcpReentry);
+ }
+ return invalidOverrideResponse(res, stop.issues);
}
const { record: config, previous } = outcome;
@@ -2425,9 +3064,16 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
metadata: {
operation: 'patch',
fieldPaths: validEntries.map(({ target }) => describeFieldTarget(target)).join(','),
+ ...(renames.renames.length > 0 && { renames: describeRenames(renames.renames) }),
},
});
- return sendWrittenConfig(res, 200, config, access);
+ return sendWrittenConfig(
+ res,
+ 200,
+ config,
+ access,
+ await reportIgnored(config, user.tenantId, { baseConfig, envPolicy, base: outcome.base }),
+ );
} catch (error) {
if (isFieldNameRejection(error)) {
return unstorableKeyResponse(res, 'patchConfigField');
@@ -2542,9 +3188,10 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
outcome = await removeConfigPath(
principalType,
principalId,
- fieldPath,
+ read.target,
{ tombstone: true, priority: requestedPriority },
expected.value,
+ user.tenantId,
);
} catch (error) {
return await writeFailureResponse(res, error, principalType, principalId);
@@ -2560,7 +3207,10 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
target: configTarget(principalType, principalId),
metadata: { operation: 'tombstone', fieldPath },
});
- return sendWrittenConfig(res, 200, config, access);
+ const ignored = isBoundSecretSection(parseFieldPath(fieldPath)[0])
+ ? await reportIgnored(config, user.tenantId)
+ : [];
+ return sendWrittenConfig(res, 200, config, access, ignored);
} catch (error) {
logger.error('[adminConfig] tombstoneConfigField error:', getSafeErrorMetadata(error));
return res.status(500).json({ error: 'Failed to tombstone config field' });
@@ -2647,13 +3297,14 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
let config: ConfigRecord | null;
try {
- if (target.dotFree && isWebSearchBindingPath(fieldPath)) {
+ if (isBoundRemoval(target)) {
const outcome = await removeConfigPath(
principalType,
principalId,
- fieldPath,
+ target,
{ tombstone: false },
expected.value,
+ user.tenantId,
);
if (!outcome.written) {
return removalStopResponse(res, outcome.result);
@@ -2687,7 +3338,10 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
target: configTarget(principalType, principalId),
metadata: { operation: 'unset', fieldPath: describeFieldTarget(target) },
});
- return sendWrittenConfig(res, 200, config, access);
+ const ignored = isBoundSecretSection(target.segments[0])
+ ? await reportIgnored(config, user.tenantId)
+ : [];
+ return sendWrittenConfig(res, 200, config, access, ignored);
} catch (error) {
logger.error('[adminConfig] deleteConfigField error:', getSafeErrorMetadata(error));
return res.status(500).json({ error: 'Failed to delete config field' });
@@ -2811,11 +3465,15 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
const requestedPriority = hasBroadManage ? (priority as number | undefined) : undefined;
- /** 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),
+ /** A dry run returns no document, so it resolves no read access: it shows only what it writes. */
+ const [baseConfig, access] = await Promise.all([
+ getBaseAppConfig(user.tenantId),
+ dryRun
+ ? toWrittenSectionsAccess(hasBroadManage, managedSections)
+ : resolveWriteReadAccess(user, hasBroadManage, managedSections),
]);
+ const baseYaml: Partial<TCustomConfig> = baseConfig?.config ?? {};
+ const envPolicy = getEnvPolicy(baseYaml);
for (const change of changes) {
if (
change.op === 'rename' &&
@@ -2838,17 +3496,21 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
unchanged: AdminConfigChangeRef[];
ignored: IgnoredChange[];
appliedChanges: PreparedChange[];
+ /** The document the batch plans, which a dry run reports dropped credentials for. */
+ planned?: ConfigOverrideState;
}
type ChangesStop =
| { kind: 'principal' }
| { kind: 'issues'; issues: ConfigOverrideIssue[] }
| { kind: 'reentry'; issues: SecretReentryIssue[] }
+ | { kind: 'mcpReentry'; reentry: SecretReentry }
| { kind: 'change'; failure: ChangeFailure };
type ChangesResult = { report: ChangesReport; stop?: never } | { stop: ChangesStop };
const plan = async (
stored: ConfigRecord | null,
floor: Partial<TCustomConfig>,
+ base: ConfigRecord | null,
): Promise<ConfigMutationPlan<ChangesResult>> => {
if (!stored && !(await canCreateFor(principalType, principalId))) {
return { draft: null, result: { stop: { kind: 'principal' } } };
@@ -2860,6 +3522,8 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
appliedChanges: [],
};
const appliedSteps: ConfigChange[] = [];
+ /** Env issues in the values the applied changes sent, by identity, followed through renames. */
+ let sent: ConfigIdentityStep[][] = [];
let state: ConfigOverrideState = toConfigOverrideState(stored);
for (const change of changes) {
const steps = expandChange(change, state.overrides);
@@ -2888,12 +3552,30 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
appliedSteps.push(...steps);
report.applied.push(ref);
report.appliedChanges.push(change);
+ if (change.op === 'rename') {
+ sent = sent.map((path) =>
+ renameConfigIdentityPath(
+ path,
+ change.target.segments,
+ change.key ?? '',
+ change.to ?? '',
+ ),
+ );
+ }
+ sent.push(...getSentEnvIssuePaths(change, next, envPolicy));
for (const part of getIgnoredParts(change, yamlHeld)) {
report.ignored.push({ ...ref, ...part });
}
state = next;
}
+ const storedState = toConfigOverrideState(stored);
+ const written = getConfigBatchWrittenPaths(appliedSteps, state, storedState);
+ const envIssues = getBatchEnvIssues(sent, state, written, envPolicy);
+ if (envIssues.length > 0) {
+ return { draft: null, result: { stop: { kind: 'issues', issues: envIssues } } };
+ }
+
/** Entries of a merged-by-key array are named by key: a write, a removal or a record
* rename that reaches into one by position is refused, since the position can name
* another entry by the time the batch is applied. */
@@ -2906,7 +3588,6 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
return { draft: null, result: { stop: { kind: 'issues', issues: indexed } } };
}
/** Changes that cancel out (a set, then an unset of its parent) leave nothing to write. */
- const storedState = toConfigOverrideState(stored);
const documentChanged =
report.applied.length > 0 &&
!(
@@ -2927,26 +3608,41 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
if (!documentChanged && !priorityChanged) {
return { draft: null, result: { report } };
}
+ let planned = state;
if (documentChanged) {
- const written = getConfigBatchWrittenPaths(appliedSteps, state, storedState);
const issues = getConfigChangeIssues(state, floor, stored, written);
if (issues.length > 0) {
return { draft: null, result: { stop: { kind: 'issues', issues } } };
}
- /** Judged on the values the request sent: a secret a set kept from the stored
- * document was not entered again. */
- const requested = report.appliedChanges.flatMap((change) =>
- change.op === 'set' && !change.paths
- ? [{ segments: change.target.segments, value: change.value }]
- : [],
- );
- const reentry = getBatchReentryIssues(stored, requested, state);
+ /** Judged on the values the batch ends up storing: a credential a change kept,
+ * carried or renamed from the stored document was not entered again. */
+ const entered = getEnteredChangeSecrets(report.appliedChanges);
+ const reentry = getKeptKeyReentryIssues(stored, state, entered, baseConfig);
if (reentry.length > 0) {
return { draft: null, result: { stop: { kind: 'reentry', issues: reentry } } };
}
+ const mcpReentry = findSecretReentry({
+ stored,
+ candidate: state,
+ base: baseYaml,
+ entered,
+ });
+ if (mcpReentry) {
+ return { draft: null, result: { stop: { kind: 'mcpReentry', reentry: mcpReentry } } };
+ }
+ planned = bindPlannedSecrets({
+ principalType,
+ principalId,
+ stored,
+ candidate: state,
+ entered,
+ base,
+ baseConfig,
+ envPolicy,
+ });
}
if (dryRun) {
- return { draft: null, result: { report } };
+ return { draft: null, result: { report: { ...report, planned } } };
}
return {
draft: {
@@ -2955,8 +3651,8 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
requestedPriority ??
stored?.priority ??
getDefaultConfigPriority({ principalType, principalId }),
- overrides: state.overrides,
- tombstones: state.tombstones,
+ overrides: planned.overrides,
+ tombstones: planned.tombstones,
isActive: stored?.isActive ?? true,
},
result: { report },
@@ -2987,11 +3683,34 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
if (result.stop?.kind === 'reentry') {
return secretReentryResponse(res, result.stop.issues);
}
+ if (result.stop?.kind === 'mcpReentry') {
+ return mcpReentryResponse(res, result.stop.reentry);
+ }
if (result.stop) {
return invalidOverrideResponse(res, result.stop.issues, { skipped });
}
const { report } = result;
const config = outcome.written ? outcome.record : outcome.current;
+ /** What the written (or, on a dry run, planned) document sends somewhere new is dropped. */
+ const rebound = outcome.written
+ ? outcome.record
+ : report.planned && {
+ principalType,
+ principalId,
+ priority:
+ requestedPriority ??
+ config?.priority ??
+ getDefaultConfigPriority({ principalType, principalId }),
+ overrides: report.planned.overrides,
+ tombstones: report.planned.tombstones,
+ };
+ const ignoredSecrets = rebound
+ ? await reportIgnored(rebound, user.tenantId, {
+ baseConfig,
+ envPolicy,
+ base: outcome.base,
+ })
+ : [];
if (outcome.written) {
await invalidateCaches(user.tenantId, 'changes');
@@ -3022,7 +3741,7 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
dryRun,
applied: report.applied,
skipped,
- ignored: report.ignored,
+ ignored: [...report.ignored, ...filterIgnoredForReadAccess(ignoredSecrets, access)],
unchanged: report.unchanged,
} satisfies Omit<AdminConfigChangesResponse, 'config'> & { config?: ConfigResponse | null });
} catch (error) {
diff --git a/packages/api/src/admin/meta.spec.ts b/packages/api/src/admin/meta.spec.ts
index 754ee8b1e9..caa9f07ee9 100644
--- a/packages/api/src/admin/meta.spec.ts
+++ b/packages/api/src/admin/meta.spec.ts
@@ -28,6 +28,7 @@ import {
BASE_ONLY_CONFIG_SECTIONS,
PROCESS_MCP_SERVER_FIELDS,
INTERFACE_PERMISSION_FIELDS,
+ mapModelToAzureConfig,
BASE_PRINCIPAL_CONFIG_SECTIONS,
RUNTIME_CONFIG_INTERFACE_FIELDS,
} from 'librechat-data-provider';
@@ -47,13 +48,19 @@ import type { Request, Response } from 'express';
import type { ServerRequest } from '~/types/http';
import type { AdminConfigDeps } from './config';
import type { AdminRolesDeps } from './roles';
+import {
+ redactConfigSecrets,
+ encryptConfigSecretFields,
+ resolveRuntimeConfigSecrets,
+} from './secrets';
import { createRequestSanitizer, rejectUnsafeConfigKeys } from '~/middleware/sanitize';
import { resolvePreAuthAppConfig, resolvePreLoginAppConfig } from '~/app/resolve';
-import { redactConfigSecrets, encryptConfigSecretFields } from './secrets';
import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry';
import { createMCPPolicyResolver } from '~/mcp/registry/policy';
+import { createEnvReferencePolicy } from '~/app/allowlist';
import { resolveTitleConfig } from '~/endpoints/config';
import { createAppConfigService } from '~/app/service';
+import { mergeOverrideLayers } from '~/app/overrides';
import { createAdminConfigHandlers } from './config';
import { createAdminRolesHandlers } from './roles';
import { ADMIN_CONFIG_FEATURES } from './meta';
@@ -165,6 +172,7 @@ function setIn(target: Doc, segments: string[], value: unknown): Doc {
/** Config operations over one in-memory document, so a probe runs the real store path. */
function memoryConfigOperations(initial: ConfigRecord): {
operations: ReturnType<typeof createConfigOperations>;
+ store: ConfigStore;
current: () => ConfigRecord;
} {
let record = initial;
@@ -173,7 +181,7 @@ function memoryConfigOperations(initial: ConfigRecord): {
write: async (_principal: unknown, draft: ConfigDraft) =>
(record = { ...record, ...draft, configVersion: record.configVersion + 1 }),
} as Partial<ConfigStore> as ConfigStore;
- return { operations: createConfigOperations(store), current: () => record };
+ return { operations: createConfigOperations(store), store, current: () => record };
}
/** Lets every pending promise settle, so a handler runs until it waits on something unresolved. */
@@ -273,19 +281,24 @@ describe('GET /api/admin/config/meta', () => {
expect(Object.keys(meta.versions)).toEqual(['librechat', 'dataProvider', 'configSchema']);
expect(Object.keys(meta.features).sort()).toEqual([
'awaitedInvalidation',
+ 'azureGroupSecrets',
'changesBatch',
'deterministicPrecedence',
'dottedKeys',
+ 'envAllowlist',
'expectedRevision',
'preAuthBaseOverrides',
'principalCheck',
'priorityRoute',
'prunesEmptyParents',
'readFilteredWriteResponses',
+ 'recordSecrets',
'roleRenameMovesProfile',
+ 'secretRebinding',
'sectionAllowlist',
'webSearchStoredKeys',
'yamlMcpHide',
+ 'yamlSecretPreview',
]);
expect(meta.limits).toEqual({
maxPatchEntries: 100,
@@ -303,6 +316,7 @@ describe('GET /api/admin/config/meta', () => {
'interface',
'overrideKeyMap',
'processMcpFields',
+ 'recordSecretFields',
'refusedMaps',
'secretFields',
'titleResolution',
@@ -326,6 +340,11 @@ describe('GET /api/admin/config/meta', () => {
priorityRoute: true,
principalCheck: true,
roleRenameMovesProfile: true,
+ recordSecrets: true,
+ azureGroupSecrets: true,
+ yamlSecretPreview: true,
+ envAllowlist: true,
+ secretRebinding: true,
});
});
@@ -399,7 +418,7 @@ describe('meta rules equal the rules the server applies', () => {
}
});
- it('lists the array secret reads withhold on custom endpoints', () => {
+ it('lists the array secrets reads withhold on custom endpoints and Azure groups', () => {
expect(meta.rules.arraySecretFields).toEqual([
{
arrayPath: 'endpoints.custom',
@@ -407,10 +426,43 @@ describe('meta rules equal the rules the server applies', () => {
previewKey: 'apiKeyPreview',
identityKey: 'name',
},
+ {
+ arrayPath: 'endpoints.azureOpenAI.groups',
+ secretKey: 'apiKey',
+ previewKey: 'apiKeyPreview',
+ identityKey: 'group',
+ },
+ ]);
+ for (const { arrayPath, secretKey, previewKey, identityKey } of meta.rules.arraySecretFields) {
+ const doc = setIn({}, arrayPath.split('.'), [{ [identityKey]: 'a', [secretKey]: 'sk-live' }]);
+ expect(getIn(redactConfigSecrets(doc), arrayPath)).toEqual([
+ { [identityKey]: 'a', [previewKey]: '********' },
+ ]);
+ }
+ });
+
+ it('lists the record secrets reads withhold (MCP servers, Azure groupMap), with their previews', () => {
+ expect(meta.rules.recordSecretFields).toEqual([
+ {
+ recordPath: 'mcpServers',
+ secretPath: 'oauth.client_secret',
+ previewPath: 'oauth.client_secretPreview',
+ },
+ { recordPath: 'mcpServers', secretPath: 'apiKey.key', previewPath: 'apiKey.keyPreview' },
+ {
+ recordPath: 'endpoints.azureOpenAI.groupMap',
+ secretPath: 'apiKey',
+ previewPath: 'apiKeyPreview',
+ },
]);
- const [{ arrayPath, secretKey, identityKey }] = meta.rules.arraySecretFields;
- const doc = setIn({}, arrayPath.split('.'), [{ [identityKey]: 'gw', [secretKey]: 'sk-live' }]);
- expect(getIn(redactConfigSecrets(doc), arrayPath)).toEqual([{ [identityKey]: 'gw' }]);
+ for (const { recordPath, secretPath, previewPath } of meta.rules.recordSecretFields) {
+ const entry = setIn({}, secretPath.split('.'), 'sk-live-0123456789abcdef');
+ const stored = encryptConfigSecretFields({ [`${recordPath}.s1`]: entry })[`${recordPath}.s1`];
+ expect(String(getIn(stored as Doc, secretPath))).toMatch(/^v3:/);
+ const read = redactConfigSecrets(setIn({}, recordPath.split('.'), { s1: stored }));
+ expect(getIn(read, `${recordPath}.s1.${secretPath}`)).toBeUndefined();
+ expect(getIn(read, `${recordPath}.s1.${previewPath}`)).toBe('...cdef');
+ }
});
it('refuses writes to every listed map and process MCP field', async () => {
@@ -1159,6 +1211,305 @@ const FEATURE_PROBES: Record<AdminConfigFeatureFlag, () => Promise<boolean>> = {
return withheld && refusesCheckout && !hidden.has('local') && failsClosed;
},
+ async recordSecrets() {
+ const server = (overrides: Doc = {}): Doc => ({
+ type: 'streamable-http',
+ url: 'https://mcp.example.com/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: 'sk-mcp-admin-secret' },
+ ...overrides,
+ });
+ const stored = encryptConfigSecretFields({ 'mcpServers.github': server() })[
+ 'mcpServers.github'
+ ] as Doc;
+ const encrypted = String(getIn(stored, 'apiKey.key')).startsWith('v3:');
+ const read = redactConfigSecrets(structuredClone({ mcpServers: { github: stored } }));
+ const hidden =
+ getIn(read, 'mcpServers.github.apiKey.key') === undefined &&
+ getIn(read, 'mcpServers.github.apiKey.keyPreview') === '...cret';
+ const runtime = resolveRuntimeConfigSecrets({ mcpConfig: { github: stored } });
+ const decrypted = getIn(runtime, 'mcpConfig.github.apiKey.key') === 'sk-mcp-admin-secret';
+
+ const findConfigByPrincipal = jest
+ .fn()
+ .mockResolvedValue(storedConfig({ mcpServers: { github: stored } }));
+ const COLLECTOR = 'https://collector.example.com/mcp';
+ const moved = await patch([{ fieldPath: 'mcpServers.github.url', value: COLLECTOR }], {
+ findConfigByPrincipal,
+ });
+ /** A decoy key at the credential's path, then the server without it: the stored key stays. */
+ const decoyed = await patch(
+ [
+ { fieldPath: 'mcpServers.github.apiKey.key', value: 'sk-decoy-0000' },
+ {
+ fieldPath: 'mcpServers.github',
+ value: server({
+ url: COLLECTOR,
+ apiKey: { source: 'admin', authorization_type: 'bearer' },
+ }),
+ },
+ ],
+ { findConfigByPrincipal },
+ );
+ /** A batch that renames the server away and back around a decoy, then moves it. */
+ const batch = mockRes();
+ await createHandlers({ findConfigByPrincipal }).applyConfigChanges(
+ mockReq({
+ params: { principalType: 'role', principalId: 'r1' },
+ body: {
+ ops: [
+ { op: 'rename', fieldPath: 'mcpServers', from: 'github', to: 'tmp' },
+ { op: 'set', fieldPath: 'mcpServers.github.apiKey.key', value: 'sk-decoy-0000' },
+ { op: 'unset', fieldPath: 'mcpServers.github' },
+ { op: 'rename', fieldPath: 'mcpServers', from: 'tmp', to: 'github' },
+ { op: 'set', fieldPath: 'mcpServers.github.url', value: COLLECTOR },
+ ],
+ },
+ }),
+ batch,
+ );
+ const reentry = (res: MockRes) =>
+ res.statusCode === 400 && res.body?.code === 'MCP_API_KEY_REENTRY_REQUIRED';
+ const writeConfigDocument = jest.fn(
+ async (_type: string, _id: string, draft: ConfigDraft): Promise<ConfigRecord> =>
+ storedConfig(draft.overrides ?? {}),
+ );
+ const renamed = mockRes();
+ await createHandlers({ findConfigByPrincipal, writeConfigDocument }).patchConfigField(
+ mockReq({
+ params: { principalType: 'role', principalId: 'r1' },
+ body: {
+ entries: [
+ {
+ fieldPath: 'mcpServers.code',
+ value: server({ apiKey: { source: 'admin', authorization_type: 'bearer' } }),
+ },
+ ],
+ renames: [{ path: 'mcpServers', previousName: 'github', name: 'code' }],
+ },
+ }),
+ renamed,
+ );
+ const [, , draft] = writeConfigDocument.mock.calls[0] ?? [];
+ const carried =
+ renamed.statusCode === 200 &&
+ getIn(draft?.overrides ?? {}, 'mcpServers.code.apiKey.key') === getIn(stored, 'apiKey.key');
+ return (
+ encrypted &&
+ hidden &&
+ decrypted &&
+ reentry(moved) &&
+ reentry(decoyed) &&
+ reentry(batch) &&
+ carried
+ );
+ },
+ async azureGroupSecrets() {
+ const group = (apiKey?: string): Doc => ({
+ group: 'east',
+ instanceName: 'east-instance',
+ version: '2024-10-21',
+ deploymentName: 'gpt-4o',
+ ...(apiKey != null && { apiKey }),
+ models: { 'gpt-4o': true },
+ });
+ const [stored] = encryptConfigSecretFields({
+ 'endpoints.azureOpenAI.groups': [group('azure-admin-secret-key')],
+ })['endpoints.azureOpenAI.groups'] as Doc[];
+ const encrypted = String(stored.apiKey).startsWith('v3:');
+ /** The Azure client is built with the key a profile's group holds, decrypted. */
+ const runtime = resolveRuntimeConfigSecrets(
+ mergeOverrideLayers(
+ { config: {} } as AppConfig,
+ [storedConfig({ endpoints: { azureOpenAI: { groups: [stored] } } })],
+ { envPolicy: createEnvReferencePolicy({ config: {} }) },
+ ),
+ );
+ const azure = runtime.endpoints?.azureOpenAI;
+ const decrypted =
+ azure?.groupMap != null &&
+ azure.modelGroupMap != null &&
+ mapModelToAzureConfig({
+ modelName: 'gpt-4o',
+ groupMap: azure.groupMap,
+ modelGroupMap: azure.modelGroupMap,
+ }).azureOptions.azureOpenAIApiKey === 'azure-admin-secret-key';
+ /** Moving the group the key is stored for needs the key entered again. */
+ const moved = await patch(
+ [
+ {
+ fieldPath: 'endpoints.azureOpenAI.groups',
+ value: [{ ...group(), instanceName: 'attacker-instance' }],
+ },
+ ],
+ {
+ findConfigByPrincipal: jest
+ .fn()
+ .mockResolvedValue(storedConfig({ endpoints: { azureOpenAI: { groups: [stored] } } })),
+ },
+ );
+ const reentry =
+ moved.statusCode === 400 && moved.body?.code === 'CONFIG_SECRET_REENTRY_REQUIRED';
+
+ const writeConfigDocument = jest.fn(
+ async (_type: string, _id: string, draft: ConfigDraft): Promise<ConfigRecord> =>
+ storedConfig(draft.overrides ?? {}),
+ );
+ const res = await patch([{ fieldPath: 'endpoints.azureOpenAI.groups', value: [group()] }], {
+ findConfigByPrincipal: jest
+ .fn()
+ .mockResolvedValue(storedConfig({ endpoints: { azureOpenAI: { groups: [stored] } } })),
+ writeConfigDocument,
+ });
+ const [, , draft] = writeConfigDocument.mock.calls[0] ?? [];
+ const kept =
+ getIn(draft?.overrides ?? {}, 'endpoints.azureOpenAI.groups.0.apiKey') === stored.apiKey;
+ const read = res.body?.config?.overrides ?? {};
+
+ /** `groupMap`, which the Azure clients read, holds its key the same way. */
+ const writeGroupMap = jest.fn(
+ async (_type: string, _id: string, groupMapDraft: ConfigDraft): Promise<ConfigRecord> =>
+ storedConfig(groupMapDraft.overrides ?? {}),
+ );
+ const mapped = await patch(
+ [
+ {
+ fieldPath: 'endpoints.azureOpenAI.groupMap.east',
+ value: { apiKey: 'azure-groupmap-secret-key', instanceName: 'east-instance' },
+ },
+ ],
+ { writeConfigDocument: writeGroupMap },
+ );
+ const [, , groupMapDraft] = writeGroupMap.mock.calls[0] ?? [];
+ const storedMapKey = getIn(
+ groupMapDraft?.overrides ?? {},
+ 'endpoints.azureOpenAI.groupMap.east.apiKey',
+ );
+ const mapRuntime = resolveRuntimeConfigSecrets(groupMapDraft?.overrides ?? {});
+ const groupMapProtected =
+ mapped.statusCode === 200 &&
+ String(storedMapKey).startsWith('v3:') &&
+ !JSON.stringify(mapped.body).includes('azure-groupmap-secret-key') &&
+ getIn(mapped.body?.config?.overrides ?? {}, 'endpoints.azureOpenAI.groupMap.east') !==
+ undefined &&
+ getIn(mapped.body?.config?.overrides ?? {}, 'endpoints.azureOpenAI.groupMap.east.apiKey') ===
+ undefined &&
+ getIn(mapRuntime, 'endpoints.azureOpenAI.groupMap.east.apiKey') ===
+ 'azure-groupmap-secret-key';
+ return (
+ encrypted &&
+ decrypted &&
+ reentry &&
+ res.statusCode === 200 &&
+ kept &&
+ getIn(read, 'endpoints.azureOpenAI.groups.0.apiKey') === undefined &&
+ groupMapProtected
+ );
+ },
+ async yamlSecretPreview() {
+ const yaml = {
+ webSearch: { serperApiKey: 'serper-yaml-literal-0001' },
+ ocr: { apiKey: '${OCR_API_KEY}' },
+ };
+ const res = mockRes();
+ await createHandlers({
+ getAppConfig: jest.fn().mockResolvedValue({ ...structuredClone(yaml), config: yaml }),
+ }).getBaseConfig(mockReq({ query: { baseOnly: 'true' } }), res);
+ const config = (res.body?.config ?? {}) as Doc;
+ return (
+ res.statusCode === 200 &&
+ !JSON.stringify(res.body).includes('literal') &&
+ getIn(config, 'webSearch.serperApiKeyPreview') === '********' &&
+ getIn(config, 'ocr.apiKey') === '${OCR_API_KEY}'
+ );
+ },
+ async envAllowlist() {
+ const unlisted = await patch([
+ { fieldPath: 'ocr.baseURL', value: 'https://h/${UNLISTED_NAME}' },
+ ]);
+ const yamlNamed = await patch([{ fieldPath: 'ocr.apiKey', value: '${OCR_YAML_KEY}' }], {
+ getAppConfig: jest.fn().mockResolvedValue({ config: { ocr: { apiKey: '${OCR_YAML_KEY}' } } }),
+ });
+ const batch = mockRes();
+ await createHandlers().applyConfigChanges(
+ mockReq({
+ params: { principalType: 'role', principalId: 'r1' },
+ body: { ops: [{ op: 'set', fieldPath: 'ocr.apiKey', value: '${UNLISTED_NAME}' }] },
+ }),
+ batch,
+ );
+ const merged = mergeOverrideLayers(
+ { config: {} } as AppConfig,
+ [storedConfig({ ocr: { apiKey: '${UNLISTED_NAME}' } })],
+ { envPolicy: createEnvReferencePolicy({ config: {} }) },
+ );
+ const refused = (res: MockRes) =>
+ res.statusCode === 400 &&
+ JSON.stringify(res.body?.issues) ===
+ JSON.stringify([
+ {
+ path: res === unlisted ? 'ocr.baseURL' : 'ocr.apiKey',
+ segments: ['ocr', res === unlisted ? 'baseURL' : 'apiKey'],
+ code: 'env_reference_not_allowed',
+ },
+ ]);
+ return (
+ refused(unlisted) &&
+ refused(batch) &&
+ yamlNamed.statusCode === 200 &&
+ merged.ocr?.apiKey === ''
+ );
+ },
+ async secretRebinding() {
+ const yaml = {
+ mcpServers: {
+ tools: {
+ type: 'streamable-http',
+ url: 'https://tools.example.com/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: '${TOOLS_KEY}' },
+ },
+ },
+ };
+ const base = {
+ config: yaml,
+ mcpConfig: structuredClone(yaml.mcpServers),
+ } as Partial<AppConfig> as AppConfig;
+ const moved = { mcpServers: { tools: { url: 'https://collector.example.com/mcp' } } };
+ const merged = mergeOverrideLayers(base, [storedConfig(moved)], {
+ envPolicy: createEnvReferencePolicy({ config: yaml }),
+ });
+ const res = await patch(
+ [{ fieldPath: 'mcpServers.tools.url', value: 'https://collector.example.com/mcp' }],
+ { getAppConfig: jest.fn().mockResolvedValue(base) },
+ );
+ /** The documented limit: restating the visible `${TOOLS_KEY}` beside the new URL enters it. */
+ const restatedServer = {
+ url: 'https://collector.example.com/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: '${TOOLS_KEY}' },
+ };
+ const restatedMerge = mergeOverrideLayers(
+ base,
+ [storedConfig({ mcpServers: { tools: restatedServer } })],
+ { envPolicy: createEnvReferencePolicy({ config: yaml }) },
+ );
+ const restated = await patch([{ fieldPath: 'mcpServers.tools', value: restatedServer }], {
+ getAppConfig: jest.fn().mockResolvedValue(base),
+ });
+ return (
+ getIn(merged, 'mcpConfig.tools.apiKey.key') === '' &&
+ res.statusCode === 200 &&
+ JSON.stringify(res.body?.ignored) ===
+ JSON.stringify([
+ {
+ path: 'mcpServers.tools.apiKey.key',
+ segments: ['mcpServers', 'tools', 'apiKey', 'key'],
+ reason: 'secret_rebinding',
+ },
+ ]) &&
+ getIn(restatedMerge, 'mcpConfig.tools.apiKey.key') === '${TOOLS_KEY}' &&
+ restated.statusCode === 200 &&
+ restated.body?.ignored === undefined
+ );
+ },
};
describe('meta feature flags', () => {
diff --git a/packages/api/src/admin/meta.ts b/packages/api/src/admin/meta.ts
index efbcd4647d..9313724f4c 100644
--- a/packages/api/src/admin/meta.ts
+++ b/packages/api/src/admin/meta.ts
@@ -34,6 +34,11 @@ export const ADMIN_CONFIG_FEATURES: Readonly<AdminConfigFeatures> = {
priorityRoute: true,
principalCheck: true,
roleRenameMovesProfile: true,
+ recordSecrets: true,
+ azureGroupSecrets: true,
+ yamlSecretPreview: true,
+ envAllowlist: true,
+ secretRebinding: true,
};
/**
diff --git a/packages/api/src/admin/reentry.spec.ts b/packages/api/src/admin/reentry.spec.ts
new file mode 100644
index 0000000000..0066ed4d1c
--- /dev/null
+++ b/packages/api/src/admin/reentry.spec.ts
@@ -0,0 +1,703 @@
+import { encryptV3, setConfigFields, toConfigOverrideState } from '@librechat/data-schemas';
+import type { AppConfig, ConfigFieldWrite } from '@librechat/data-schemas';
+import type { TCustomConfig } from 'librechat-data-provider';
+import {
+ SECRET_BINDINGS,
+ getAzureGroupFingerprint,
+ getServerSecretFingerprint,
+ getScalarBindingFingerprint,
+ getCustomEndpointFingerprint,
+} from '~/app/rebinding';
+import { findSecretReentry, getBoundKeyReentryIssues, getAzureGroupReentryIssues } from './reentry';
+
+/** Encryption reads `CREDS_KEY` when data-schemas loads, before any spec code runs. */
+jest.mock('@librechat/data-schemas', () => {
+ process.env.CREDS_KEY ??= '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
+ return jest.requireActual('@librechat/data-schemas');
+});
+
+const STORED_KEY = 'v3:00000000000000000000000000000000:abcdef';
+
+const yaml = {
+ mcpServers: {
+ tools: { type: 'streamable-http', url: 'https://yaml.example/mcp' },
+ },
+} as unknown as Partial<TCustomConfig>;
+
+interface StoredDocument {
+ overrides: Record<string, unknown>;
+ tombstones: string[];
+}
+
+/** A document that stores only the key for the YAML server, which supplies the URL. */
+const stored: StoredDocument = {
+ overrides: {
+ mcpServers: {
+ tools: { apiKey: { source: 'admin', authorization_type: 'bearer', key: STORED_KEY } },
+ },
+ },
+ tombstones: [] as string[],
+};
+
+/** A key the request entered, as encryption leaves it: a ciphertext no stored document holds. */
+const ENTERED_KEY = 'v3:11111111111111111111111111111111:abcdef';
+
+function check(
+ writes: ConfigFieldWrite[],
+ base = yaml,
+ document: StoredDocument = stored,
+ entered: ReadonlySet<string> = new Set([ENTERED_KEY]),
+) {
+ return findSecretReentry({
+ stored: document,
+ candidate: setConfigFields(toConfigOverrideState(document), writes),
+ base,
+ entered,
+ });
+}
+
+describe('findSecretReentry', () => {
+ describe('the mcpConfig alias, which the merge applies like mcpServers', () => {
+ const aliased: StoredDocument = {
+ overrides: {
+ mcpConfig: {
+ aliasA: {
+ type: 'streamable-http',
+ url: 'https://good.example/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: STORED_KEY },
+ },
+ },
+ },
+ tombstones: [],
+ };
+
+ it('refuses a URL change under a key stored in the alias', () => {
+ expect(
+ check(
+ [{ segments: ['mcpConfig', 'aliasA', 'url'], value: 'https://evil.example/mcp' }],
+ yaml,
+ aliased,
+ ),
+ ).toMatchObject({ code: 'MCP_API_KEY_REENTRY_REQUIRED', server: 'aliasA', fields: ['url'] });
+ });
+
+ it('accepts the change when the key is entered again', () => {
+ expect(
+ check(
+ [
+ { segments: ['mcpConfig', 'aliasA', 'url'], value: 'https://evil.example/mcp' },
+ { segments: ['mcpConfig', 'aliasA', 'apiKey', 'key'], value: ENTERED_KEY },
+ ],
+ yaml,
+ aliased,
+ ),
+ ).toBeNull();
+ });
+
+ it('resolves an alias server over its librechat.yaml entry and tombstones', () => {
+ const yamlKeyed = {
+ overrides: {
+ mcpConfig: {
+ tools: { apiKey: { source: 'admin', authorization_type: 'bearer', key: STORED_KEY } },
+ },
+ },
+ tombstones: [] as string[],
+ };
+ expect(
+ findSecretReentry({
+ stored: yamlKeyed,
+ candidate: { ...toConfigOverrideState(yamlKeyed), tombstones: ['mcpConfig.tools.url'] },
+ base: yaml,
+ entered: new Set(),
+ }),
+ ).toMatchObject({ server: 'tools', fields: ['url'] });
+ });
+ });
+
+ it('compares servers as they resolve over librechat.yaml', () => {
+ expect(
+ check([{ segments: ['mcpServers', 'tools', 'url'], value: 'https://evil.example/mcp' }]),
+ ).toEqual({
+ code: 'MCP_API_KEY_REENTRY_REQUIRED',
+ message: expect.stringContaining('url'),
+ server: 'tools',
+ fields: ['url'],
+ });
+
+ /** Spelling out the URL librechat.yaml already gives changes nothing. */
+ expect(
+ check([{ segments: ['mcpServers', 'tools', 'url'], value: 'https://yaml.example/mcp' }]),
+ ).toBeNull();
+ });
+
+ it('catches a binding change that only shows on the resolved server, such as a tombstoned URL', () => {
+ const document = { ...stored, tombstones: ['mcpServers.tools.url'] };
+ const candidate = toConfigOverrideState(document);
+ expect(
+ findSecretReentry({
+ stored,
+ candidate,
+ base: yaml,
+ entered: new Set(),
+ }),
+ ).toMatchObject({ fields: ['url'] });
+ });
+
+ it('lets a write that supplies the key change the binding', () => {
+ expect(
+ check([
+ { segments: ['mcpServers', 'tools', 'url'], value: 'https://moved.example/mcp' },
+ { segments: ['mcpServers', 'tools', 'apiKey', 'key'], value: ENTERED_KEY },
+ ]),
+ ).toBeNull();
+ });
+
+ it('ignores a key the write removes and a key that is a visible reference', () => {
+ expect(
+ check([
+ { segments: ['mcpServers', 'tools', 'url'], value: 'https://moved.example/mcp' },
+ {
+ segments: ['mcpServers', 'tools', 'apiKey'],
+ value: { source: 'user', authorization_type: 'bearer' },
+ },
+ ]),
+ ).toBeNull();
+
+ const reference = {
+ overrides: {
+ mcpServers: {
+ tools: { apiKey: { source: 'admin', authorization_type: 'bearer', key: '${K}' } },
+ },
+ },
+ tombstones: [] as string[],
+ };
+ expect(
+ check(
+ [{ segments: ['mcpServers', 'tools', 'url'], value: 'https://moved.example/mcp' }],
+ yaml,
+ reference,
+ ),
+ ).toBeNull();
+ });
+
+ it('treats how the key is sent as part of its binding, as the user tier does', () => {
+ /** The key as secret preservation leaves it: kept from the stored document, not supplied. */
+ const writes: ConfigFieldWrite[] = [
+ {
+ segments: ['mcpServers', 'tools', 'apiKey'],
+ value: {
+ source: 'admin',
+ authorization_type: 'custom',
+ custom_header: 'X-Key',
+ key: STORED_KEY,
+ },
+ },
+ ];
+ expect(
+ findSecretReentry({
+ stored,
+ candidate: setConfigFields(toConfigOverrideState(stored), writes),
+ base: yaml,
+ entered: new Set(),
+ }),
+ ).toMatchObject({ fields: ['apiKey.authorization_type', 'apiKey.custom_header'] });
+ });
+
+ it('binds a kept OAuth client secret to the proxy its access token is sent through', () => {
+ const oauthStored: StoredDocument = {
+ overrides: {
+ mcpServers: {
+ tools: {
+ oauth: {
+ client_id: 'client',
+ client_secret: STORED_KEY,
+ authorization_url: 'https://auth.example/authorize',
+ token_url: 'https://auth.example/token',
+ },
+ },
+ },
+ },
+ tombstones: [],
+ };
+ const proxy: ConfigFieldWrite = {
+ segments: ['mcpServers', 'tools', 'proxy'],
+ value: 'http://proxy.evil.example:8080',
+ };
+
+ expect(check([proxy], yaml, oauthStored)).toMatchObject({
+ code: 'MCP_OAUTH_SECRET_REENTRY_REQUIRED',
+ server: 'tools',
+ fields: ['proxy'],
+ });
+ expect(
+ check(
+ [
+ proxy,
+ { segments: ['mcpServers', 'tools', 'oauth', 'client_secret'], value: ENTERED_KEY },
+ ],
+ yaml,
+ oauthStored,
+ ),
+ ).toBeNull();
+ });
+
+ describe('a key is judged by the value the document ends up with, not by the paths written', () => {
+ const GOOD = 'https://good.example/mcp';
+ const EVIL = 'https://evil.example/mcp';
+ const OTHER_KEY = 'v3:22222222222222222222222222222222:abcdef';
+ const server = (url: string, key: string) => ({
+ type: 'streamable-http',
+ url,
+ apiKey: { source: 'admin', authorization_type: 'bearer', key },
+ });
+ const document = (servers: Record<string, unknown>): StoredDocument => ({
+ overrides: { mcpServers: servers },
+ tombstones: [],
+ });
+ const judge = (
+ from: StoredDocument,
+ servers: Record<string, unknown>,
+ entered: ReadonlySet<string> = new Set(),
+ ) =>
+ findSecretReentry({
+ stored: from,
+ candidate: toConfigOverrideState(document(servers)),
+ base: {},
+ entered,
+ });
+
+ it('refuses a stored key put back beside a new URL, though the request entered a decoy at its path', () => {
+ /** The decoy was entered, but a later write of the request put the stored ciphertext back. */
+ expect(
+ judge(
+ document({ probe: server(GOOD, STORED_KEY) }),
+ { probe: server(EVIL, STORED_KEY) },
+ new Set([ENTERED_KEY]),
+ ),
+ ).toMatchObject({ code: 'MCP_API_KEY_REENTRY_REQUIRED', server: 'probe', fields: ['url'] });
+ });
+
+ it('accepts the URL change when the document holds the key the request entered', () => {
+ expect(
+ judge(
+ document({ probe: server(GOOD, STORED_KEY) }),
+ { probe: server(EVIL, ENTERED_KEY) },
+ new Set([ENTERED_KEY]),
+ ),
+ ).toBeNull();
+ });
+
+ it('follows a key to the server it was renamed or copied from, under any name', () => {
+ const before = document({ probe: server(GOOD, STORED_KEY) });
+
+ expect(judge(before, { renamed: server(EVIL, STORED_KEY) })).toMatchObject({
+ server: 'renamed',
+ fields: ['url'],
+ });
+ expect(judge(before, { renamed: server(GOOD, STORED_KEY) })).toBeNull();
+ expect(
+ judge(before, { probe: server(GOOD, STORED_KEY), copy: server(EVIL, STORED_KEY) }),
+ ).toMatchObject({ server: 'copy', fields: ['url'] });
+ });
+
+ it('accepts a name swap that moves each key with its own server', () => {
+ const before = document({ a: server(GOOD, STORED_KEY), b: server(EVIL, OTHER_KEY) });
+
+ expect(judge(before, { a: server(EVIL, OTHER_KEY), b: server(GOOD, STORED_KEY) })).toBeNull();
+ /** Swapping the keys but not the URLs sends each key somewhere new. */
+ expect(
+ judge(before, { a: server(GOOD, OTHER_KEY), b: server(EVIL, STORED_KEY) }),
+ ).toMatchObject({
+ server: 'a',
+ fields: ['url'],
+ });
+ });
+
+ it('finds the origin of a legacy plaintext key that preservation encrypted on the way', () => {
+ const legacy = 'sk-legacy-plaintext-key-0001';
+ const carried = encryptV3(legacy);
+
+ expect(
+ judge(document({ probe: server(GOOD, legacy) }), { renamed: server(EVIL, carried) }),
+ ).toMatchObject({ server: 'renamed', fields: ['url'] });
+ expect(
+ judge(document({ probe: server(GOOD, legacy) }), { renamed: server(GOOD, carried) }),
+ ).toBeNull();
+ });
+ });
+});
+
+describe('getAzureGroupReentryIssues', () => {
+ const yamlGroupMap = {
+ east: { apiKey: 'yaml-literal-key', instanceName: 'east', version: '2024-10-21', models: {} },
+ };
+ const group = (overrides: Record<string, unknown> = {}) => ({
+ group: 'west',
+ apiKey: STORED_KEY,
+ instanceName: 'west',
+ version: '2024-10-21',
+ deploymentName: 'gpt-5',
+ models: { 'gpt-5': true },
+ ...overrides,
+ });
+ const storedGroups: StoredDocument = {
+ overrides: { endpoints: { azureOpenAI: { groups: [group()] } } },
+ tombstones: [],
+ };
+
+ function judge(writes: ConfigFieldWrite[], document: StoredDocument = storedGroups) {
+ return getAzureGroupReentryIssues({
+ stored: document,
+ candidate: setConfigFields(toConfigOverrideState(document), writes),
+ baseGroupMap: yamlGroupMap,
+ entered: new Set([ENTERED_KEY]),
+ });
+ }
+
+ const groupsWrite = (...groups: Record<string, unknown>[]): ConfigFieldWrite[] => [
+ { segments: ['endpoints', 'azureOpenAI', 'groups'], value: groups },
+ ];
+
+ it('refuses a kept key under a moved instance, and accepts it entered again', () => {
+ expect(judge(groupsWrite(group({ instanceName: 'attacker' })))).toEqual([
+ {
+ path: 'endpoints.azureOpenAI.groups.0.instanceName',
+ segments: ['endpoints', 'azureOpenAI', 'groups', '0', 'instanceName'],
+ code: 'secret_reentry_required',
+ secretPath: 'endpoints.azureOpenAI.groups.0.apiKey',
+ },
+ ]);
+ expect(judge(groupsWrite(group({ instanceName: 'attacker', apiKey: ENTERED_KEY })))).toEqual(
+ [],
+ );
+ expect(judge(groupsWrite(group({ version: '2025-01-01' })))).toEqual([]);
+ });
+
+ it('judges a group that does not resolve yet, so a later write cannot put the move to use', () => {
+ const unresolved = group({ instanceName: 'attacker', deploymentName: undefined });
+
+ expect(judge(groupsWrite(unresolved)).map(({ path }) => path)).toEqual([
+ 'endpoints.azureOpenAI.groups.0.instanceName',
+ ]);
+ });
+
+ it('judges a groupMap key over the group librechat.yaml resolves, under the tombstones', () => {
+ const mapped: StoredDocument = {
+ overrides: { endpoints: { azureOpenAI: { groupMap: { east: { apiKey: STORED_KEY } } } } },
+ tombstones: [],
+ };
+ const tombstoned = getAzureGroupReentryIssues({
+ stored: mapped,
+ candidate: {
+ ...toConfigOverrideState(mapped),
+ tombstones: ['endpoints.azureOpenAI.groupMap.east.instanceName'],
+ },
+ baseGroupMap: yamlGroupMap,
+ entered: new Set(),
+ });
+
+ expect(
+ judge(
+ [
+ {
+ segments: ['endpoints', 'azureOpenAI', 'groupMap', 'east', 'instanceName'],
+ value: 'east',
+ },
+ ],
+ mapped,
+ ),
+ ).toEqual([]);
+ expect(tombstoned.map(({ path, secretPath }) => [path, secretPath])).toEqual([
+ [
+ 'endpoints.azureOpenAI.groupMap.east.instanceName',
+ 'endpoints.azureOpenAI.groupMap.east.apiKey',
+ ],
+ ]);
+ });
+
+ it('judges a groupMap key without the groups librechat.yaml resolves once they are tombstoned', () => {
+ const mapped: StoredDocument = {
+ overrides: { endpoints: { azureOpenAI: { groupMap: { east: { apiKey: STORED_KEY } } } } },
+ tombstones: [],
+ };
+
+ const issues = getAzureGroupReentryIssues({
+ stored: mapped,
+ candidate: {
+ ...toConfigOverrideState(mapped),
+ tombstones: ['endpoints.azureOpenAI.groups'],
+ },
+ baseGroupMap: yamlGroupMap,
+ entered: new Set(),
+ });
+
+ expect(issues.map(({ path, secretPath }) => [path, secretPath])).toEqual([
+ [
+ 'endpoints.azureOpenAI.groupMap.east.instanceName',
+ 'endpoints.azureOpenAI.groupMap.east.apiKey',
+ ],
+ ]);
+ });
+
+ it("leaves librechat.yaml's own keys to the merge", () => {
+ const empty: StoredDocument = { overrides: {}, tombstones: [] };
+
+ expect(
+ judge(
+ [
+ {
+ segments: ['endpoints', 'azureOpenAI', 'groupMap', 'east', 'instanceName'],
+ value: 'x',
+ },
+ ],
+ empty,
+ ),
+ ).toEqual([]);
+ });
+});
+
+describe('getBoundKeyReentryIssues', () => {
+ /** librechat.yaml's resolved config: one custom endpoint and an OCR service. */
+ const baseConfig = {
+ config: {},
+ endpoints: {
+ custom: [{ name: 'Ollama', apiKey: 'ollama', baseURL: 'http://ollama:11434/v1', models: {} }],
+ },
+ ocr: { baseURL: 'https://ocr.yaml.example/v1' },
+ } as unknown as AppConfig;
+
+ const document = (overrides: Record<string, unknown>): StoredDocument => ({
+ overrides,
+ tombstones: [],
+ });
+ const endpointDoc = (entry: Record<string, unknown> = {}) =>
+ document({
+ endpoints: {
+ custom: [
+ {
+ name: 'Gateway',
+ apiKey: STORED_KEY,
+ baseURL: 'https://gateway.example/v1',
+ models: { default: ['m'] },
+ ...entry,
+ },
+ ],
+ },
+ });
+
+ function issues(
+ stored: StoredDocument,
+ writes: ConfigFieldWrite[],
+ entered: ReadonlySet<string> = new Set(),
+ ) {
+ return getBoundKeyReentryIssues({
+ stored,
+ candidate: setConfigFields(toConfigOverrideState(stored), writes),
+ baseConfig,
+ entered,
+ });
+ }
+
+ const endpointIssue = (field: string) => ({
+ path: `endpoints.custom.0.${field}`,
+ segments: ['endpoints', 'custom', '0', ...field.split('.')],
+ code: 'secret_reentry_required',
+ secretPath: 'endpoints.custom.0.apiKey',
+ });
+
+ it.each([
+ ['baseURL', 'https://attacker.example/v1', 'baseURL'],
+ ['provider', 'anthropic', 'provider'],
+ ['addParams', { anthropicApiUrl: 'https://attacker.example' }, 'addParams.anthropicApiUrl'],
+ ['dropParams', ['clientOptions'], 'dropParams'],
+ ])('refuses a %s change beside a kept endpoint key', (field, value, reported) => {
+ expect(
+ issues(endpointDoc(), [{ segments: ['endpoints', 'custom', '0', field], value }]),
+ ).toEqual([endpointIssue(reported)]);
+ });
+
+ it('accepts the move when the key is entered again, and an edit that moves nothing', () => {
+ expect(
+ issues(
+ endpointDoc(),
+ [
+ {
+ segments: ['endpoints', 'custom', '0', 'baseURL'],
+ value: 'https://attacker.example/v1',
+ },
+ { segments: ['endpoints', 'custom', '0', 'apiKey'], value: ENTERED_KEY },
+ ],
+ new Set([ENTERED_KEY]),
+ ),
+ ).toEqual([]);
+ expect(
+ issues(endpointDoc(), [
+ { segments: ['endpoints', 'custom', '0', 'models'], value: { default: ['n'] } },
+ {
+ segments: ['endpoints', 'custom', '0', 'baseURL'],
+ value: 'https://gateway.example/v1#x',
+ },
+ ]),
+ ).toEqual([]);
+ });
+
+ it('follows a renamed key by value, and refuses it under a name librechat.yaml points elsewhere', () => {
+ const keyOnly = document({
+ endpoints: { custom: [{ name: 'Gateway', apiKey: STORED_KEY, models: {} }] },
+ });
+ expect(
+ issues(endpointDoc(), [{ segments: ['endpoints', 'custom', '0', 'name'], value: 'Renamed' }]),
+ ).toEqual([]);
+ expect(
+ issues(keyOnly, [{ segments: ['endpoints', 'custom', '0', 'name'], value: 'ollama' }]),
+ ).toEqual([endpointIssue('baseURL')]);
+ });
+
+ it('accepts a key moved onto the destination it was bound to over a lower layer', () => {
+ const boundTo = {
+ name: 'Gateway',
+ baseURL: 'https://base.example/v1',
+ models: { default: ['m'] },
+ };
+ const bound = endpointDoc({
+ baseURL: undefined,
+ apiKeyBinding: getCustomEndpointFingerprint(boundTo),
+ });
+ expect(
+ issues(bound, [
+ { segments: ['endpoints', 'custom', '0', 'baseURL'], value: 'https://base.example/v1' },
+ ]),
+ ).toEqual([]);
+ expect(
+ issues(bound, [
+ { segments: ['endpoints', 'custom', '0', 'baseURL'], value: 'https://attacker.example/v1' },
+ ]),
+ ).toEqual([endpointIssue('baseURL')]);
+ });
+
+ it('refuses a scalar move, a removal or tombstone of its destination included', () => {
+ const ocr = document({ ocr: { apiKey: STORED_KEY, baseURL: 'https://ocr.example/v1' } });
+ const expected = [
+ {
+ path: 'ocr.baseURL',
+ segments: ['ocr', 'baseURL'],
+ code: 'secret_reentry_required',
+ secretPath: 'ocr.apiKey',
+ },
+ ];
+ expect(
+ issues(ocr, [{ segments: ['ocr', 'baseURL'], value: 'https://attacker.example/v1' }]),
+ ).toEqual(expected);
+ expect(
+ getBoundKeyReentryIssues({
+ stored: ocr,
+ candidate: { overrides: { ocr: { apiKey: STORED_KEY } }, tombstones: [] },
+ baseConfig,
+ entered: new Set(),
+ }),
+ ).toEqual(expected);
+ expect(
+ getBoundKeyReentryIssues({
+ stored: ocr,
+ candidate: { overrides: { ocr: { apiKey: STORED_KEY } }, tombstones: ['ocr.baseURL'] },
+ baseConfig,
+ entered: new Set(),
+ }),
+ ).toEqual(expected);
+ });
+
+ it('leaves visible references and keys the request entered alone', () => {
+ const referenced = document({
+ ocr: { apiKey: '${OCR_API_KEY}', baseURL: 'https://ocr.example/v1' },
+ endpoints: {
+ custom: [{ name: 'Gateway', apiKey: 'user_provided', baseURL: 'https://g/v1' }],
+ },
+ });
+ expect(
+ issues(referenced, [
+ { segments: ['ocr', 'baseURL'], value: 'https://attacker.example/v1' },
+ { segments: ['endpoints', 'custom', '0', 'baseURL'], value: 'https://attacker.example/v1' },
+ ]),
+ ).toEqual([]);
+ });
+
+ it('keeps a scalar key bound to the destination it was entered for over a lower layer', () => {
+ const binding = SECRET_BINDINGS.find(({ path }) => path.join('.') === 'ocr')!;
+ const bound = document({
+ ocr: {
+ apiKey: STORED_KEY,
+ apiKeyBinding: getScalarBindingFingerprint(binding, { baseURL: 'https://base.example/v1' }),
+ },
+ });
+ expect(
+ issues(bound, [{ segments: ['ocr', 'baseURL'], value: 'https://base.example/v1' }]),
+ ).toEqual([]);
+ });
+});
+
+describe('a stored key bound to a destination over a lower layer', () => {
+ it('lets an MCP write restate the destination its key was bound to, and nothing else', () => {
+ const bound: StoredDocument = {
+ overrides: {
+ mcpServers: {
+ shared: {
+ apiKey: {
+ source: 'admin',
+ authorization_type: 'bearer',
+ key: STORED_KEY,
+ keyBinding: getServerSecretFingerprint('apiKey', {
+ url: 'https://base.example/mcp',
+ apiKey: { authorization_type: 'bearer' },
+ }),
+ },
+ },
+ },
+ },
+ tombstones: [],
+ };
+ const restate = (url: string) =>
+ check([{ segments: ['mcpServers', 'shared', 'url'], value: url }], yaml, bound, new Set());
+
+ expect(restate('https://base.example/mcp')).toBeNull();
+ expect(restate('https://attacker.example/mcp')).toMatchObject({
+ code: 'MCP_API_KEY_REENTRY_REQUIRED',
+ server: 'shared',
+ fields: ['url'],
+ });
+ });
+
+ it('lets an Azure groupMap write restate the destination its key was bound to', () => {
+ const bound: StoredDocument = {
+ overrides: {
+ endpoints: {
+ azureOpenAI: {
+ groupMap: {
+ shared: {
+ apiKey: STORED_KEY,
+ apiKeyBinding: getAzureGroupFingerprint({ baseURL: 'https://base.example/openai' }),
+ },
+ },
+ },
+ },
+ },
+ tombstones: [],
+ };
+ const restate = (baseURL: string) =>
+ getAzureGroupReentryIssues({
+ stored: bound,
+ candidate: setConfigFields(toConfigOverrideState(bound), [
+ {
+ segments: ['endpoints', 'azureOpenAI', 'groupMap', 'shared', 'baseURL'],
+ value: baseURL,
+ },
+ ]),
+ baseGroupMap: {},
+ entered: new Set(),
+ });
+
+ expect(restate('https://base.example/openai')).toEqual([]);
+ expect(restate('https://attacker.example/openai').map(({ path }) => path)).toEqual([
+ 'endpoints.azureOpenAI.groupMap.shared.baseURL',
+ ]);
+ });
+});
diff --git a/packages/api/src/admin/reentry.ts b/packages/api/src/admin/reentry.ts
new file mode 100644
index 0000000000..9b2de89b8c
--- /dev/null
+++ b/packages/api/src/admin/reentry.ts
@@ -0,0 +1,619 @@
+import { PrincipalType } from 'librechat-data-provider';
+import {
+ getAtPath,
+ isPlainRecord,
+ isSameConfigValue,
+ resolveAzureGroups,
+ foldConfigMergeKey,
+ mergeConfigOverrides,
+ applyConfigTombstones,
+} from '@librechat/data-schemas';
+import type { AppConfig, ConfigOverrideState } from '@librechat/data-schemas';
+import type { TCustomConfig } from 'librechat-data-provider';
+import type { CredentialBindingConfig } from '~/mcp/registry/binding';
+import type { SecretBinding } from '~/app/rebinding';
+import type { SecretReentryIssue } from './binding';
+import {
+ SECRET_BINDINGS,
+ getSecretBindingKey,
+ diffAzureGroupBinding,
+ getAzureGroupFingerprint,
+ getServerSecretFingerprint,
+ getChangedScalarBindingKeys,
+ getScalarBindingFingerprint,
+ getCustomEndpointFingerprint,
+ getChangedCustomEndpointBinding,
+} from '~/app/rebinding';
+import {
+ diffApiKeyBinding,
+ preserveOmittedOAuthBindingFields,
+ getChangedOAuthSecretBindingFields,
+} from '~/mcp/registry/binding';
+import { MCPApiKeyReentryRequiredError, MCPOAuthSecretReentryRequiredError } from '~/mcp/errors';
+import { isSameStoredSecret, isCredentialReference, isMCPCredentialReference } from './secrets';
+import { SECRET_REENTRY_REQUIRED } from './binding';
+
+type JsonRecord = Record<string, unknown>;
+
+/** A write that keeps a stored MCP credential while changing where it is sent. */
+export interface SecretReentry {
+ code: MCPApiKeyReentryRequiredError['code'] | MCPOAuthSecretReentryRequiredError['code'];
+ message: string;
+ /** The server whose credential must be entered again. */
+ server: string;
+ /** The binding fields the write changed. */
+ fields: string[];
+}
+
+interface StoredDocument {
+ overrides?: unknown;
+ tombstones?: unknown[];
+}
+
+/** Whether a stored value is a credential a read hides: set, and not a `${VAR}`/`{{VAR}}` reference. */
+function isHiddenSecret(value: unknown): value is string {
+ if (typeof value !== 'string') {
+ return false;
+ }
+ const trimmed = value.trim();
+ return trimmed !== '' && !isMCPCredentialReference(trimmed);
+}
+
+/**
+ * The override sections that hold MCP servers: `mcpServers` and its AppConfig name `mcpConfig`,
+ * which the merge also applies. A document's later section replaces the earlier one whole, so a
+ * server's credential and destination are only ever combined within one section.
+ */
+export const MCP_SERVER_SECTIONS = ['mcpServers', 'mcpConfig'] as const;
+type MCPServerSection = (typeof MCP_SERVER_SECTIONS)[number];
+
+function getServers(overrides: unknown, section: MCPServerSection): JsonRecord {
+ const servers = isPlainRecord(overrides) ? overrides[section] : undefined;
+ return isPlainRecord(servers) ? servers : {};
+}
+
+/** Tombstones as librechat.yaml paths: one under `mcpConfig` removes the same `mcpServers` field. */
+function toYamlTombstones(tombstones: unknown[] | undefined): unknown[] | undefined {
+ return tombstones?.map((path) =>
+ typeof path === 'string' && (path === 'mcpConfig' || path.startsWith('mcpConfig.'))
+ ? `mcpServers${path.slice('mcpConfig'.length)}`
+ : path,
+ );
+}
+
+/** Layers `override` over `base` as the config merge does: objects merge, anything else replaces. */
+function mergeLayer(base: unknown, override: unknown): unknown {
+ if (override === undefined) {
+ return base;
+ }
+ if (!isPlainRecord(base) || !isPlainRecord(override)) {
+ return override;
+ }
+ const merged: JsonRecord = { ...base };
+ for (const [key, value] of Object.entries(override)) {
+ merged[key] = mergeLayer(base[key], value);
+ }
+ return merged;
+}
+
+/**
+ * A server as it resolves for this document: librechat.yaml under its tombstones, then the
+ * override. Only its binding fields are read, each compared for equality.
+ */
+function getEffectiveServer(
+ base: Partial<TCustomConfig>,
+ tombstones: unknown[] | undefined,
+ name: string,
+ override: unknown,
+): CredentialBindingConfig {
+ const baseServer = getAtPath(applyConfigTombstones(base, toYamlTombstones(tombstones)), [
+ 'mcpServers',
+ name,
+ ]);
+ const merged = mergeLayer(baseServer, override);
+ return isPlainRecord(merged) ? (merged as CredentialBindingConfig) : {};
+}
+
+const MCP_SECRETS = [
+ { parent: 'apiKey', key: 'key' },
+ { parent: 'oauth', key: 'client_secret' },
+] as const;
+
+function getChangedBindingFields(
+ parent: 'apiKey' | 'oauth',
+ stored: CredentialBindingConfig,
+ candidate: CredentialBindingConfig,
+): string[] {
+ if (parent === 'apiKey') {
+ return diffApiKeyBinding(stored, candidate);
+ }
+ return getChangedOAuthSecretBindingFields(stored, {
+ ...candidate,
+ oauth: preserveOmittedOAuthBindingFields(stored.oauth ?? {}, candidate.oauth ?? {}),
+ });
+}
+
+function toReentry(parent: 'apiKey' | 'oauth', server: string, fields: string[]): SecretReentry {
+ const error =
+ parent === 'apiKey'
+ ? new MCPApiKeyReentryRequiredError(fields)
+ : new MCPOAuthSecretReentryRequiredError(fields);
+ return { code: error.code, message: error.message, server, fields };
+}
+
+type MCPSecret = (typeof MCP_SECRETS)[number];
+
+/** A server of the stored document that holds a credential a read hides. */
+interface StoredCredential {
+ section: MCPServerSection;
+ name: string;
+ server: unknown;
+ value: string;
+}
+
+function getStoredCredentials(
+ stored: StoredDocument | null | undefined,
+ { parent, key }: MCPSecret,
+): StoredCredential[] {
+ return MCP_SERVER_SECTIONS.flatMap((section) =>
+ Object.entries(getServers(stored?.overrides, section)).flatMap(([name, server]) => {
+ const value = getAtPath(server, [parent, key]);
+ return isHiddenSecret(value) ? [{ section, name, server, value }] : [];
+ }),
+ );
+}
+
+/**
+ * The stored servers a kept credential came from, the server of the same name first: those that
+ * hold the same value, wherever the write moved it (a rename, a duplicate, a chain of either).
+ * When none does, the stored server of the same name, so an unexpected value is still judged.
+ */
+function findOrigins(
+ held: readonly StoredCredential[],
+ value: string,
+ section: MCPServerSection,
+ name: string,
+): StoredCredential[] {
+ const isSameServer = (credential: StoredCredential) =>
+ credential.section === section && credential.name === name;
+ const matches = held.filter((credential) => isSameStoredSecret(credential.value, value));
+ const origins = matches.length > 0 ? matches : held.filter(isSameServer);
+ return [...origins.filter(isSameServer), ...origins.filter((origin) => !isSameServer(origin))];
+}
+
+/**
+ * The admin config tier's version of the user-managed tier's key re-entry rule
+ * (`mcp/registry/binding.ts`): a write that keeps a stored MCP credential (`apiKey.key`,
+ * `oauth.client_secret`) while changing where the server sends it must enter the credential
+ * again.
+ *
+ * - **Kept is judged by value.** A credential counts as entered again only when the planned
+ * document holds a value the request itself entered (`getEnteredConfigSecrets`). A key one
+ * write supplied and a later write of the same request replaced with the stored one was not,
+ * whatever paths the request wrote.
+ * - **Compared with where it was.** A kept credential is compared with every stored server that
+ * held the same value, so a rename, a duplicate or a chain of them is followed, and a name
+ * swap that moves each key with its own server changes nothing. The write is refused unless
+ * one of them sends it where the candidate does.
+ * - **As servers resolve.** Servers are compared as they resolve for this document:
+ * librechat.yaml under the document's tombstones, then its override.
+ *
+ * Only credentials a read hides count: a `${VAR}` or `{{VAR}}` reference is visible, so a client
+ * can resend it. Both sections that hold MCP servers (`mcpServers` and its alias `mcpConfig`)
+ * are checked. Rebinding across layers (a profile changing a server another layer holds the key
+ * for) is the merge's to handle (`app/rebinding.ts`).
+ */
+export function findSecretReentry(params: {
+ stored: StoredDocument | null | undefined;
+ candidate: ConfigOverrideState;
+ base: Partial<TCustomConfig>;
+ /** The secret values the request itself entered, encrypted. */
+ entered: ReadonlySet<string>;
+}): SecretReentry | null {
+ const { stored, candidate, base, entered } = params;
+ const held = new Map<MCPSecret, StoredCredential[]>();
+ for (const section of MCP_SERVER_SECTIONS) {
+ for (const [name, server] of Object.entries(getServers(candidate.overrides, section))) {
+ for (const secret of MCP_SECRETS) {
+ const value = getAtPath(server, [secret.parent, secret.key]);
+ if (!isHiddenSecret(value) || entered.has(value)) {
+ continue;
+ }
+ const credentials = held.get(secret) ?? getStoredCredentials(stored, secret);
+ held.set(secret, credentials);
+ const origins = findOrigins(credentials, value, section, name);
+ if (origins.length === 0) {
+ continue;
+ }
+ const target = getEffectiveServer(base, candidate.tombstones, name, server);
+ const fingerprint = getServerSecretFingerprint(secret.parent, target);
+ const bindingKey = getSecretBindingKey(secret.key);
+ const changes = origins.map((origin) =>
+ getAtPath(origin.server, [secret.parent, bindingKey]) === fingerprint
+ ? []
+ : getChangedBindingFields(
+ secret.parent,
+ getEffectiveServer(base, stored?.tombstones, origin.name, origin.server),
+ target,
+ ),
+ );
+ if (changes.every((fields) => fields.length > 0)) {
+ return toReentry(secret.parent, name, changes[0]);
+ }
+ }
+ }
+ }
+ return null;
+}
+
+/** Where Azure groups sit, in an override document and in the resolved config alike. */
+const AZURE_SEGMENTS = ['endpoints', 'azureOpenAI'] as const;
+
+/** Whether an Azure group key is one a read hides: set, and not `${VAR}` or `user_provided`. */
+function isHiddenGroupKey(value: unknown): value is string {
+ if (typeof value !== 'string') {
+ return false;
+ }
+ const trimmed = value.trim();
+ return trimmed !== '' && !isCredentialReference(trimmed);
+}
+
+function getAzureSection(overrides: unknown): JsonRecord {
+ const azure = getAtPath(overrides, AZURE_SEGMENTS);
+ return isPlainRecord(azure) ? azure : {};
+}
+
+function getGroupItems(azure: JsonRecord): JsonRecord[] {
+ return Array.isArray(azure.groups) ? azure.groups.filter(isPlainRecord) : [];
+}
+
+function getGroupMap(azure: JsonRecord): JsonRecord {
+ return isPlainRecord(azure.groupMap) ? azure.groupMap : {};
+}
+
+/**
+ * The Azure groups a document resolves to on its own over librechat.yaml, by name, as the merge
+ * resolves one layer: its `groups` replace librechat.yaml's whole when they resolve
+ * (`resolveAzureGroups`), else librechat.yaml's resolved groups (`baseGroupMap`) stay under its
+ * tombstones; its `groupMap` entries merge over either.
+ */
+function getEffectiveAzureGroups(
+ document: StoredDocument | null | undefined,
+ baseGroupMap: unknown,
+): Map<string, JsonRecord> {
+ const azure = getAzureSection(document?.overrides);
+ const resolved = Array.isArray(azure.groups) ? resolveAzureGroups(azure.groups) : undefined;
+ const below = resolved?.isValid
+ ? resolved.groupMap
+ : getAtPath(
+ applyConfigTombstones(
+ { endpoints: { azureOpenAI: { groupMap: baseGroupMap } } } as Partial<TCustomConfig>,
+ document?.tombstones,
+ ),
+ [...AZURE_SEGMENTS, 'groupMap'],
+ );
+ const merged = mergeLayer(below, getGroupMap(azure));
+ return new Map(
+ Object.entries(isPlainRecord(merged) ? merged : {}).flatMap(([name, group]) =>
+ isPlainRecord(group) ? [[name, group]] : [],
+ ),
+ );
+}
+
+/** Every hidden group key a document stores, in `groups` and in `groupMap`. */
+function getStoredGroupKeys(azure: JsonRecord): string[] {
+ return [...getGroupItems(azure), ...Object.values(getGroupMap(azure))].flatMap((group) => {
+ const value = isPlainRecord(group) ? group.apiKey : undefined;
+ return isHiddenGroupKey(value) ? [value] : [];
+ });
+}
+
+/**
+ * Where a document writes the group a key belongs to, in librechat.yaml keys: its `groupMap`
+ * entry when that holds the field (or the key), else its `groups` item of that name.
+ */
+function locateGroupField(azure: JsonRecord, name: string, field: string): string[] {
+ const mapped = getGroupMap(azure)[name];
+ if (isPlainRecord(mapped) && field in mapped) {
+ return [...AZURE_SEGMENTS, 'groupMap', name, field];
+ }
+ const index = getGroupItems(azure).findIndex((group) => group.group === name);
+ if (index >= 0) {
+ return [...AZURE_SEGMENTS, 'groups', String(index), field];
+ }
+ return [...AZURE_SEGMENTS, 'groupMap', name, field];
+}
+
+/**
+ * The Azure form of the re-entry rule web search and MCP keys follow: a write that keeps a
+ * stored group key (in `groups` or `groupMap`) while changing where the group sends it must enter
+ * the key again. Groups are compared as the document resolves them on its own over
+ * librechat.yaml ({@link getEffectiveAzureGroups}), and each `groups` item also as written, so
+ * groups that do not resolve yet cannot carry a key to a new destination for a later write to
+ * put to use; destinations are compared by `diffAzureGroupBinding`. A
+ * key counts as entered again only when the planned document holds a value the request entered;
+ * a kept one is compared with every stored group that held the same value, so the write is
+ * refused unless one of them sent it where the candidate does. Only keys the stored document
+ * holds are judged: librechat.yaml's own are the merge's to bind (`app/rebinding.ts`).
+ */
+export function getAzureGroupReentryIssues(params: {
+ stored: StoredDocument | null | undefined;
+ candidate: ConfigOverrideState;
+ /** librechat.yaml's resolved Azure groups (`endpoints.azureOpenAI.groupMap` of the base config). */
+ baseGroupMap: unknown;
+ /** The secret values the request itself entered, encrypted. */
+ entered: ReadonlySet<string>;
+}): SecretReentryIssue[] {
+ const { stored, candidate, baseGroupMap, entered } = params;
+ const storedAzure = getAzureSection(stored?.overrides);
+ const held = getStoredGroupKeys(storedAzure);
+ if (held.length === 0) {
+ return [];
+ }
+ const candidateAzure = getAzureSection(candidate.overrides);
+ /** As the document resolves, and each `groups` item as written, which may not resolve yet. */
+ const candidates: Array<[string, JsonRecord]> = [
+ ...getEffectiveAzureGroups(candidate, baseGroupMap),
+ ...getGroupItems(candidateAzure).flatMap(
+ (item): Array<[string, JsonRecord]> =>
+ typeof item.group === 'string' ? [[item.group, item]] : [],
+ ),
+ ];
+ let origins: JsonRecord[] | undefined;
+ const issues = new Map<string, SecretReentryIssue>();
+ for (const [name, group] of candidates) {
+ const value = group.apiKey;
+ if (
+ !isHiddenGroupKey(value) ||
+ entered.has(value) ||
+ !held.some((stored) => isSameStoredSecret(stored, value))
+ ) {
+ continue;
+ }
+ /** Every stored definition of a group: as it resolved, and each complete `groups` item. */
+ origins ??= [
+ ...getEffectiveAzureGroups(stored, baseGroupMap).values(),
+ ...getGroupItems(storedAzure),
+ ];
+ const fingerprint = getAzureGroupFingerprint(group);
+ const changes = origins
+ .filter((origin) => isSameStoredSecret(origin.apiKey, value))
+ .map((origin) =>
+ origin[getSecretBindingKey('apiKey')] === fingerprint
+ ? []
+ : diffAzureGroupBinding(origin, group),
+ );
+ if (changes.length === 0 || changes.some((fields) => fields.length === 0)) {
+ continue;
+ }
+ const segments = locateGroupField(candidateAzure, name, changes[0][0]);
+ const path = segments.join('.');
+ issues.set(path, {
+ path,
+ segments,
+ code: SECRET_REENTRY_REQUIRED,
+ secretPath: locateGroupField(candidateAzure, name, 'apiKey').join('.'),
+ });
+ }
+ return [...issues.values()];
+}
+
+const CUSTOM_ENDPOINTS = ['endpoints', 'custom'] as const;
+const CUSTOM_ENDPOINTS_PATH = CUSTOM_ENDPOINTS.join('.');
+
+/** A principal no document belongs to, for merging one document alone. */
+const ALONE_PRINCIPAL = '__reentry__';
+
+/**
+ * Where a document alone sends its secrets: librechat.yaml's resolved config with only this
+ * document merged over it, as the merge's rebinding guard measures a layer's own destination
+ * (`alone()`), tombstones, folded endpoint names and all.
+ */
+function resolveAlone(
+ document: StoredDocument | ConfigOverrideState | null | undefined,
+ baseConfig: AppConfig,
+): AppConfig {
+ return mergeConfigOverrides(baseConfig, [
+ {
+ principalType: PrincipalType.ROLE,
+ principalId: ALONE_PRINCIPAL,
+ priority: 0,
+ overrides: (document?.overrides ?? {}) as Partial<TCustomConfig>,
+ tombstones: document?.tombstones,
+ },
+ ]);
+}
+
+/** A custom endpoint of an override document, with its index there. */
+interface EndpointItem {
+ index: number;
+ entry: JsonRecord;
+ identity: string;
+}
+
+function getEndpointItems(overrides: unknown): EndpointItem[] {
+ const items = getAtPath(overrides, CUSTOM_ENDPOINTS);
+ if (!Array.isArray(items)) {
+ return [];
+ }
+ return items.flatMap((entry, index) =>
+ isPlainRecord(entry) && typeof entry.name === 'string'
+ ? [{ index, entry, identity: foldConfigMergeKey(CUSTOM_ENDPOINTS_PATH, entry.name) }]
+ : [],
+ );
+}
+
+/** A resolved config's custom endpoints by the identity the merge folds their names to, first one kept. */
+function getResolvedEndpoints(config: AppConfig): Map<string, JsonRecord> {
+ const resolved = new Map<string, JsonRecord>();
+ for (const { entry, identity } of getEndpointItems(config)) {
+ if (!resolved.has(identity)) {
+ resolved.set(identity, entry);
+ }
+ }
+ return resolved;
+}
+
+function toReentryIssue(segments: string[], secretSegments: string[]): SecretReentryIssue {
+ return {
+ path: segments.join('.'),
+ segments,
+ code: SECRET_REENTRY_REQUIRED,
+ secretPath: secretSegments.join('.'),
+ };
+}
+
+/** The resolved configs a document alone sends its secrets by, before and after a write. */
+interface AloneConfigs {
+ stored: AppConfig;
+ candidate: AppConfig;
+}
+
+function getScalarReentryIssue(
+ binding: SecretBinding,
+ stored: StoredDocument | null | undefined,
+ alone: AloneConfigs,
+): SecretReentryIssue | null {
+ const { path, secretKey } = binding;
+ const origin = getAtPath(stored?.overrides, path);
+ if (!isPlainRecord(origin) || !isHiddenGroupKey(origin[secretKey])) {
+ return null;
+ }
+ const target = getAtPath(alone.candidate, path);
+ const sent = isPlainRecord(target) ? target : {};
+ const reference = getAtPath(alone.stored, path);
+ const changed = getChangedScalarBindingKeys(
+ binding,
+ isPlainRecord(reference) ? reference : null,
+ sent,
+ );
+ if (
+ changed.length === 0 ||
+ origin[getSecretBindingKey(secretKey)] === getScalarBindingFingerprint(binding, sent)
+ ) {
+ return null;
+ }
+ return toReentryIssue([...path, changed[0]], [...path, secretKey]);
+}
+
+/** The parts of a document that decide where its custom endpoint, OCR and speech keys go. */
+function getBoundSections(document: StoredDocument | ConfigOverrideState | null | undefined) {
+ const overrides = isPlainRecord(document?.overrides) ? document.overrides : {};
+ const endpoints = isPlainRecord(overrides.endpoints) ? overrides.endpoints : {};
+ return {
+ custom: endpoints.custom,
+ ocr: overrides.ocr,
+ speech: overrides.speech,
+ tombstones: document?.tombstones ?? [],
+ };
+}
+
+/** Whether a write changed anything those keys or their destinations sit in. */
+function movesBoundSections(
+ stored: StoredDocument | null | undefined,
+ candidate: ConfigOverrideState,
+): boolean {
+ return !isSameConfigValue(getBoundSections(stored), getBoundSections(candidate));
+}
+
+/** A changed binding location of an endpoint, as a write names it: `dropParams` whole. */
+function toEndpointField(location: readonly string[]): string[] {
+ return location[0] === 'dropParams' ? ['dropParams'] : [...location];
+}
+
+function getEndpointReentryIssue(
+ item: EndpointItem,
+ held: readonly EndpointItem[],
+ alone: AloneConfigs & {
+ storedEndpoints: Map<string, JsonRecord>;
+ candidateEndpoints: Map<string, JsonRecord>;
+ },
+): SecretReentryIssue | null {
+ const value = item.entry.apiKey as string;
+ const matches = held.filter(({ entry }) => isSameStoredSecret(entry.apiKey, value));
+ const origins =
+ matches.length > 0 ? matches : held.filter(({ identity }) => identity === item.identity);
+ if (origins.length === 0) {
+ return null;
+ }
+ const target = alone.candidateEndpoints.get(item.identity) ?? item.entry;
+ const fingerprint = getCustomEndpointFingerprint(target);
+ const changes = origins.map(({ entry, identity }) => {
+ const changed = getChangedCustomEndpointBinding(
+ alone.storedEndpoints.get(identity) ?? entry,
+ target,
+ );
+ return entry[getSecretBindingKey('apiKey')] === fingerprint ? [] : changed;
+ });
+ if (changes.some((changed) => changed.length === 0)) {
+ return null;
+ }
+ const entry = [...CUSTOM_ENDPOINTS, String(item.index)];
+ return toReentryIssue([...entry, ...toEndpointField(changes[0][0])], [...entry, 'apiKey']);
+}
+
+/**
+ * The re-entry rule for the keys whose destination sits beside them: each custom endpoint's
+ * `apiKey` (bound to its base URL, `provider` and destination options) and OCR's and each speech
+ * service's key (bound to their URL or instance; `SECRET_BINDINGS`). A write that keeps one of
+ * these stored keys while changing where the document sends it must enter the key again, as for
+ * MCP credentials, web search keys and Azure group keys.
+ *
+ * - **Kept is judged by value.** A key counts as entered again only when the planned document
+ * holds a value the request itself entered.
+ * - **Compared with where it was.** A kept endpoint key is compared with every stored endpoint
+ * that held the same value, so a rename or a copy is followed; a scalar key with the stored
+ * one at its own path.
+ * - **As the document alone sends it.** Destinations are read from librechat.yaml's resolved
+ * config with only the document merged over it, as the merge's rebinding guard measures a
+ * layer's own keys, so restating librechat.yaml's destination changes nothing. A destination
+ * the stored key was bound to over a lower layer (its `<key>Binding` fingerprint) counts as
+ * where it was too, so restating that destination keeps the key as well.
+ *
+ * Only keys a read hides count: a `${VAR}` reference or `user_provided` is visible, so a client
+ * can resend it.
+ */
+export function getBoundKeyReentryIssues(params: {
+ stored: StoredDocument | null | undefined;
+ candidate: ConfigOverrideState;
+ /** librechat.yaml's resolved config; without one, the documents resolve over nothing. */
+ baseConfig: AppConfig | undefined;
+ /** The secret values the request itself entered, encrypted. */
+ entered: ReadonlySet<string>;
+}): SecretReentryIssue[] {
+ const { stored, candidate, entered } = params;
+ const isKept = (value: unknown): value is string =>
+ isHiddenGroupKey(value) && !entered.has(value);
+ const scalars = SECRET_BINDINGS.filter((binding) =>
+ isKept(getAtPath(candidate.overrides, [...binding.path, binding.secretKey])),
+ );
+ const endpoints = getEndpointItems(candidate.overrides).filter(({ entry }) =>
+ isKept(entry.apiKey),
+ );
+ if ((scalars.length === 0 && endpoints.length === 0) || !movesBoundSections(stored, candidate)) {
+ return [];
+ }
+ const baseConfig = params.baseConfig ?? ({} as AppConfig);
+ const alone = {
+ stored: resolveAlone(stored, baseConfig),
+ candidate: resolveAlone(candidate, baseConfig),
+ };
+ const scalarIssues = scalars.flatMap(
+ (binding) => getScalarReentryIssue(binding, stored, alone) ?? [],
+ );
+ if (endpoints.length === 0) {
+ return scalarIssues;
+ }
+ const held = getEndpointItems(stored?.overrides).filter(({ entry }) =>
+ isHiddenGroupKey(entry.apiKey),
+ );
+ const resolved = {
+ ...alone,
+ storedEndpoints: getResolvedEndpoints(alone.stored),
+ candidateEndpoints: getResolvedEndpoints(alone.candidate),
+ };
+ return [
+ ...scalarIssues,
+ ...endpoints.flatMap((item) => getEndpointReentryIssue(item, held, resolved) ?? []),
+ ];
+}
diff --git a/packages/api/src/admin/secrets.integration.spec.ts b/packages/api/src/admin/secrets.integration.spec.ts
index c4aacd62c5..38bab92e5e 100644
--- a/packages/api/src/admin/secrets.integration.spec.ts
+++ b/packages/api/src/admin/secrets.integration.spec.ts
@@ -17,14 +17,20 @@ let mongoServer: MongoMemoryServer;
let handlers: AdminConfigHandlers;
let basePrincipalId: string;
let decryptV3: DataSchemas['decryptV3'];
+let loadOCRConfig: DataSchemas['loadOCRConfig'];
+let loadWebSearchConfig: DataSchemas['loadWebSearchConfig'];
let patchConfigFields: ConfigMethods['patchConfigFields'];
-let configMethods: ConfigMethods;
-/** Builds handlers on the real methods, optionally reading configs through `findConfigByPrincipal`. */
-let createHandlers: (
- findConfigByPrincipal?: ConfigMethods['findConfigByPrincipal'],
-) => AdminConfigHandlers;
let getSecretPreview: typeof import('./secrets').getSecretPreview;
let encryptConfigSecretFields: typeof import('./secrets').encryptConfigSecretFields;
+let UNPREVIEWED_SECRET_MASK: string;
+let createAdminConfigHandlers: typeof import('./config').createAdminConfigHandlers;
+let configMethods: ConfigMethods;
+
+/** Env names the generic config API may reference in these tests, as an operator would list them. */
+const ENV_ALLOWLIST = [
+ 'OCR_API_KEY TTS_API_KEY SERPER_API_KEY MCP_KEY KEENABLE_API_KEY',
+ 'SEARXNG_INSTANCE_URL SEARXNG_API_KEY OTHER_SERVICE_URL',
+].join(' ');
interface SecretFieldCase {
/** Dot-path of the secret field */
@@ -67,8 +73,8 @@ const SECRET_FIELD_CASES: SecretFieldCase[] = [
previewPath: 'speech.tts.azureOpenAI.apiKeyPreview',
section: 'speech',
object: { tts: { azureOpenAI: { apiKey: SECRET, instanceName: 'inst' } } },
- siblingPath: 'speech.tts.azureOpenAI.instanceName',
- siblingValue: 'inst-2',
+ siblingPath: 'speech.tts.azureOpenAI.apiVersion',
+ siblingValue: '2024-10-21',
},
{
path: 'speech.tts.elevenlabs.apiKey',
@@ -83,8 +89,8 @@ const SECRET_FIELD_CASES: SecretFieldCase[] = [
previewPath: 'speech.tts.localai.apiKeyPreview',
section: 'speech',
object: { tts: { localai: { apiKey: SECRET, url: 'http://localai:8080' } } },
- siblingPath: 'speech.tts.localai.url',
- siblingValue: 'http://localai:8081',
+ siblingPath: 'speech.tts.localai.backend',
+ siblingValue: 'coqui',
},
{
path: 'speech.stt.openai.apiKey',
@@ -99,8 +105,8 @@ const SECRET_FIELD_CASES: SecretFieldCase[] = [
previewPath: 'speech.stt.azureOpenAI.apiKeyPreview',
section: 'speech',
object: { stt: { azureOpenAI: { apiKey: SECRET, instanceName: 'inst' } } },
- siblingPath: 'speech.stt.azureOpenAI.instanceName',
- siblingValue: 'inst-2',
+ siblingPath: 'speech.stt.azureOpenAI.apiVersion',
+ siblingValue: '2024-10-21',
},
{
path: 'webSearch.serperApiKey',
@@ -231,6 +237,11 @@ function getAtPath(root: unknown, path: string): unknown {
type RawConfig = Pick<Config, 'configVersion'> & { overrides: Record<string, unknown> };
+/** The parts of a served config these tests read. */
+type AppConfigShape = {
+ endpoints?: { custom?: Array<Record<string, unknown> & { name: string }> };
+};
+
async function readRawConfig(principalId: string): Promise<RawConfig> {
const doc = await mongoose.models.Config.findOne({ principalId });
expect(doc).not.toBeNull();
@@ -251,37 +262,50 @@ function nextPrincipalId(): string {
beforeAll(async () => {
jest.resetModules();
const dataSchemas = await import('@librechat/data-schemas');
- ({ decryptV3, BASE_CONFIG_PRINCIPAL_ID: basePrincipalId } = dataSchemas);
+ ({
+ decryptV3,
+ loadOCRConfig,
+ loadWebSearchConfig,
+ BASE_CONFIG_PRINCIPAL_ID: basePrincipalId,
+ } = dataSchemas);
jest.spyOn(dataSchemas.logger, 'error').mockReturnValue(dataSchemas.logger);
jest.spyOn(dataSchemas.logger, 'warn').mockReturnValue(dataSchemas.logger);
jest.spyOn(dataSchemas.logger, 'info').mockReturnValue(dataSchemas.logger);
jest.spyOn(dataSchemas.logger, 'debug').mockReturnValue(dataSchemas.logger);
- const { createAdminConfigHandlers } = await import('./config');
- ({ getSecretPreview, encryptConfigSecretFields } = await import('./secrets'));
+ ({ createAdminConfigHandlers } = await import('./config'));
+ ({ getSecretPreview, encryptConfigSecretFields, UNPREVIEWED_SECRET_MASK } = await import(
+ './secrets'
+ ));
mongoServer = await MongoMemoryServer.create();
await mongoose.connect(mongoServer.getUri());
dataSchemas.createModels(mongoose);
- const methods = dataSchemas.createMethods(mongoose);
- configMethods = methods;
- ({ patchConfigFields } = methods);
-
- createHandlers = (findConfigByPrincipal = methods.findConfigByPrincipal) =>
- createAdminConfigHandlers({
- listAllConfigs: methods.listAllConfigs,
- findConfigByPrincipal,
- writeConfigDocument: methods.writeConfigDocument,
- unsetConfigField: methods.unsetConfigField,
- deleteConfig: methods.deleteConfig,
- toggleConfigActiveTracked: methods.toggleConfigActiveTracked,
- hasConfigCapability: async () => true,
- hasAnyConfigReadAccess: async () => true,
- hasCapability: async () => true,
- });
- handlers = createHandlers();
+ configMethods = dataSchemas.createMethods(mongoose);
+ ({ patchConfigFields } = configMethods);
+
+ handlers = createRealHandlers();
});
+/** Handlers over the real Config collection; `getAppConfig` supplies a librechat.yaml base. */
+function createRealHandlers(
+ overrides: Partial<Parameters<typeof createAdminConfigHandlers>[0]> = {},
+): AdminConfigHandlers {
+ return createAdminConfigHandlers({
+ listAllConfigs: configMethods.listAllConfigs,
+ findConfigByPrincipal: configMethods.findConfigByPrincipal,
+ writeConfigDocument: configMethods.writeConfigDocument,
+ unsetConfigField: configMethods.unsetConfigField,
+ deleteConfig: configMethods.deleteConfig,
+ toggleConfigActiveTracked: configMethods.toggleConfigActiveTracked,
+ hasConfigCapability: async () => true,
+ hasAnyConfigReadAccess: async () => true,
+ hasCapability: async () => true,
+ overrideEnvAllowlist: ENV_ALLOWLIST,
+ ...overrides,
+ });
+}
+
afterAll(async () => {
await mongoose.disconnect();
await mongoServer.stop();
@@ -1193,22 +1217,24 @@ describe('config secret registry — real handlers against a real Config collect
/** Handlers whose next config read is followed by another admin's URL-and-key write. */
function racedHandlers(principalId: string): AdminConfigHandlers {
let raced = false;
- return createHandlers(async (...args) => {
- const config = await configMethods.findConfigByPrincipal(...args);
- if (!raced) {
- raced = true;
- await configMethods.patchConfigFields(
- PrincipalType.ROLE,
- principalId,
- PrincipalModel.ROLE,
- encryptConfigSecretFields({
- 'webSearch.searxngInstanceUrl': VICTIM_URL,
- 'webSearch.searxngApiKey': VICTIM_KEY,
- }),
- 10,
- );
- }
- return config;
+ return createRealHandlers({
+ findConfigByPrincipal: async (...args) => {
+ const config = await configMethods.findConfigByPrincipal(...args);
+ if (!raced) {
+ raced = true;
+ await configMethods.patchConfigFields(
+ PrincipalType.ROLE,
+ principalId,
+ PrincipalModel.ROLE,
+ encryptConfigSecretFields({
+ 'webSearch.searxngInstanceUrl': VICTIM_URL,
+ 'webSearch.searxngApiKey': VICTIM_KEY,
+ }),
+ 10,
+ );
+ }
+ return config;
+ },
});
}
@@ -1423,7 +1449,8 @@ describe('config secret registry — real handlers against a real Config collect
expect(getAtPath(config, 'speech.tts.openai.model')).toBe('tts-1');
expect(getAtPath(config, 'speech.tts.openai.apiKey')).toBeUndefined();
expect(getAtPath(config, 'speech.tts.openai.apiKeyPreview')).toBe(getSecretPreview(SECRET));
- expect(getAtPath(config, 'webSearch.serperApiKeyPreview')).toBeUndefined();
+ /** A literal librechat.yaml supplies reads as set, with a mask derived from nothing. */
+ expect(getAtPath(config, 'webSearch.serperApiKeyPreview')).toBe(UNPREVIEWED_SECRET_MASK);
expect(getAtPath(config, 'langfuse.secretKeyPreview')).toBe('*********');
expect(getAtPath(config, 'config.speech.tts.openai.apiKey')).toBeUndefined();
});
@@ -1529,3 +1556,2363 @@ describe('config secret registry — real handlers against a real Config collect
});
});
});
+
+type MockResponse = ReturnType<typeof mockRes>;
+
+async function send(
+ handler: (req: ServerRequest, res: Response) => Promise<Response>,
+ request: Record<string, unknown>,
+): Promise<MockResponse> {
+ const res = mockRes();
+ await handler(mockReq(request), res);
+ return res;
+}
+
+function patch(
+ principalId: string,
+ entries: Array<{ fieldPath: string; value: unknown }>,
+ extra: Record<string, unknown> = {},
+ target: AdminConfigHandlers = handlers,
+): Promise<MockResponse> {
+ return send(target.patchConfigField, {
+ params: { principalType: 'role', principalId },
+ body: { entries, ...extra },
+ });
+}
+
+const API_KEY = 'sk-mcp-integration-secret-key';
+const CLIENT_SECRET = 'oauth-integration-client-secret';
+
+function mcpServer(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return {
+ type: 'streamable-http',
+ url: 'https://mcp.example.com/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: API_KEY },
+ oauth: {
+ client_id: 'client',
+ client_secret: CLIENT_SECRET,
+ authorization_url: 'https://auth.example.com/authorize',
+ token_url: 'https://auth.example.com/token',
+ },
+ ...overrides,
+ };
+}
+
+async function storedServer(principalId: string, name: string) {
+ const overrides = await readRawOverrides(principalId);
+ return getAtPath(overrides, `mcpServers.${name}`) as {
+ url?: string;
+ apiKey: Record<string, string>;
+ oauth: Record<string, string>;
+ };
+}
+
+describe('MCP server credentials — real handlers against a real Config collection', () => {
+ async function seed(name = 'github'): Promise<string> {
+ const principalId = nextPrincipalId();
+ const res = await patch(principalId, [{ fieldPath: `mcpServers.${name}`, value: mcpServer() }]);
+ expect(res.statusCode).toBe(200);
+ return principalId;
+ }
+
+ it('stores both credentials encrypted, returns only previews, and keeps them across edits', async () => {
+ const principalId = await seed();
+
+ const stored = await storedServer(principalId, 'github');
+ expect(decryptV3(stored.apiKey.key)).toBe(API_KEY);
+ expect(stored.apiKey.keyPreview).toBe(getSecretPreview(API_KEY));
+ expect(decryptV3(stored.oauth.client_secret)).toBe(CLIENT_SECRET);
+
+ const read = await send(handlers.getConfig, { params: { principalType: 'role', principalId } });
+ const payload = JSON.stringify(read.body);
+ expect(payload).not.toContain(API_KEY);
+ expect(payload).not.toContain(CLIENT_SECRET);
+ expect(payload).not.toContain(stored.apiKey.key);
+ const readServer = getAtPath(read.body!.config, 'overrides.mcpServers.github') as {
+ apiKey: Record<string, string>;
+ oauth: Record<string, string>;
+ };
+ expect(readServer.apiKey).toEqual({
+ source: 'admin',
+ authorization_type: 'bearer',
+ keyPreview: getSecretPreview(API_KEY),
+ });
+ expect(readServer.oauth.client_secretPreview).toBe(getSecretPreview(CLIENT_SECRET));
+
+ const titled = await patch(principalId, [
+ { fieldPath: 'mcpServers.github.title', value: 'GitHub' },
+ ]);
+ expect(titled.statusCode).toBe(200);
+ expect((await storedServer(principalId, 'github')).apiKey.key).toBe(stored.apiKey.key);
+
+ /** A whole replace from the redacted read, previews and all, keeps both secrets. */
+ const overrides = (read.body!.config as { overrides: Record<string, unknown> }).overrides;
+ const replaced = await send(handlers.upsertConfigOverrides, {
+ params: { principalType: 'role', principalId },
+ body: { overrides },
+ });
+ expect(replaced.statusCode).toBe(200);
+ const after = await storedServer(principalId, 'github');
+ expect(decryptV3(after.apiKey.key)).toBe(API_KEY);
+ expect(decryptV3(after.oauth.client_secret)).toBe(CLIENT_SECRET);
+ });
+
+ it('refuses ciphertext and preview writes', async () => {
+ const principalId = await seed();
+ const stored = await storedServer(principalId, 'github');
+
+ const ciphertext = await patch(principalId, [
+ { fieldPath: 'mcpServers.github.apiKey.key', value: stored.apiKey.key },
+ ]);
+ expect(ciphertext.statusCode).toBe(400);
+
+ const preview = await patch(principalId, [
+ { fieldPath: 'mcpServers.github.apiKey.keyPreview', value: '...fake' },
+ ]);
+ expect(preview.statusCode).toBe(400);
+ });
+
+ describe('re-entry when a stored credential would be sent somewhere new', () => {
+ it('refuses a dotted URL change that keeps the stored key', async () => {
+ const principalId = await seed();
+
+ const res = await patch(principalId, [
+ { fieldPath: 'mcpServers.github.url', value: 'https://evil.example/mcp' },
+ ]);
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toEqual({
+ error: expect.stringContaining('Re-enter apiKey.key'),
+ code: 'MCP_API_KEY_REENTRY_REQUIRED',
+ server: 'github',
+ fields: ['url'],
+ });
+ expect((await storedServer(principalId, 'github')).url).toBe('https://mcp.example.com/mcp');
+ });
+
+ it('accepts the change once the credentials are entered again', async () => {
+ const principalId = await seed();
+
+ const res = await patch(principalId, [
+ { fieldPath: 'mcpServers.github.url', value: 'https://moved.example/mcp' },
+ { fieldPath: 'mcpServers.github.apiKey.key', value: 'sk-new-key-for-the-new-host' },
+ { fieldPath: 'mcpServers.github.oauth.client_secret', value: 'new-client-secret' },
+ ]);
+
+ expect(res.statusCode).toBe(200);
+ const stored = await storedServer(principalId, 'github');
+ expect(decryptV3(stored.apiKey.key)).toBe('sk-new-key-for-the-new-host');
+ expect(decryptV3(stored.oauth.client_secret)).toBe('new-client-secret');
+ });
+
+ it('refuses an OAuth endpoint change that keeps the stored client secret', async () => {
+ const principalId = await seed();
+
+ const res = await patch(principalId, [
+ {
+ fieldPath: 'mcpServers.github.oauth',
+ value: {
+ client_id: 'client',
+ authorization_url: 'https://auth.example.com/authorize',
+ token_url: 'https://evil.example/token',
+ },
+ },
+ ]);
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toMatchObject({
+ code: 'MCP_OAUTH_SECRET_REENTRY_REQUIRED',
+ fields: ['oauth.token_url'],
+ });
+ });
+
+ it('refuses removing or tombstoning a binding field the stored key depends on', async () => {
+ const principalId = await seed();
+
+ const removed = await send(handlers.deleteConfigField, {
+ params: { principalType: 'role', principalId },
+ query: { fieldPath: 'mcpServers.github.url' },
+ });
+ expect(removed.statusCode).toBe(400);
+ expect(removed.body).toMatchObject({ code: 'MCP_API_KEY_REENTRY_REQUIRED' });
+
+ const tombstoned = await send(handlers.tombstoneConfigField, {
+ params: { principalType: 'role', principalId },
+ body: { fieldPath: 'mcpServers.github.url' },
+ });
+ expect(tombstoned.statusCode).toBe(400);
+
+ const unrelated = await send(handlers.deleteConfigField, {
+ params: { principalType: 'role', principalId },
+ query: { fieldPath: 'mcpServers.github.oauth.client_secret' },
+ });
+ expect(unrelated.statusCode).toBe(200);
+ });
+
+ /**
+ * Handlers over which `concurrent`, a write from another request, lands right after the
+ * first time the handler reads `principalId`'s document.
+ */
+ function racingHandlers(
+ principalId: string,
+ concurrent: () => Promise<unknown>,
+ ): AdminConfigHandlers {
+ let raced = false;
+ return createRealHandlers({
+ findConfigByPrincipal: async (...args) => {
+ const found = await configMethods.findConfigByPrincipal(...args);
+ if (!raced && args[1] === principalId) {
+ raced = true;
+ await concurrent();
+ }
+ return found;
+ },
+ });
+ }
+
+ it('absorbs a concurrent write to an MCP server instead of answering 409', async () => {
+ const principalId = await seed();
+ const racing = racingHandlers(principalId, () =>
+ patchConfigFields(PrincipalType.ROLE, principalId, PrincipalModel.ROLE, {
+ 'mcpServers.github.title': 'GitHub',
+ }),
+ );
+
+ const removed = await send(racing.deleteConfigField, {
+ params: { principalType: 'role', principalId },
+ query: { fieldPath: 'mcpServers.github.oauth.client_secret' },
+ });
+ expect(removed.statusCode).toBe(200);
+
+ const tombstoned = await send(
+ racingHandlers(principalId, () =>
+ patchConfigFields(PrincipalType.ROLE, principalId, PrincipalModel.ROLE, {
+ 'mcpServers.github.description': 'Code hosting',
+ }),
+ ).tombstoneConfigField,
+ {
+ params: { principalType: 'role', principalId },
+ body: { fieldPath: 'mcpServers.github.iconPath' },
+ },
+ );
+ expect(tombstoned.statusCode).toBe(200);
+
+ const server = await storedServer(principalId, 'github');
+ expect(server).toMatchObject({ title: 'GitHub', description: 'Code hosting' });
+ expect(server.oauth.client_secret).toBeUndefined();
+ expect(decryptV3(server.apiKey.key)).toBe(API_KEY);
+ });
+
+ it('judges the document the removal replaces, not the one it first read', async () => {
+ const principalId = nextPrincipalId();
+ const seeded = await patch(principalId, [
+ {
+ fieldPath: 'mcpServers.fresh',
+ value: mcpServer({ apiKey: undefined, oauth: undefined }),
+ },
+ ]);
+ expect(seeded.statusCode).toBe(200);
+ const racing = racingHandlers(principalId, () =>
+ patchConfigFields(
+ PrincipalType.ROLE,
+ principalId,
+ PrincipalModel.ROLE,
+ encryptConfigSecretFields({
+ 'mcpServers.fresh.apiKey': {
+ source: 'admin',
+ authorization_type: 'bearer',
+ key: 'sk-landed-meanwhile',
+ },
+ }),
+ ),
+ );
+
+ const removed = await send(racing.deleteConfigField, {
+ params: { principalType: 'role', principalId },
+ query: { fieldPath: 'mcpServers.fresh.url' },
+ });
+
+ expect(removed.statusCode).toBe(400);
+ expect(removed.body).toMatchObject({
+ code: 'MCP_API_KEY_REENTRY_REQUIRED',
+ server: 'fresh',
+ fields: ['url'],
+ });
+ const server = await storedServer(principalId, 'fresh');
+ expect(server.url).toBe('https://mcp.example.com/mcp');
+ expect(decryptV3(server.apiKey.key)).toBe('sk-landed-meanwhile');
+ });
+
+ it('still refuses a stale expectedRevision', async () => {
+ const principalId = await seed();
+ const { revision } = (
+ await send(handlers.getConfig, {
+ params: { principalType: 'role', principalId },
+ })
+ ).body!.config as { revision: string };
+ await patch(principalId, [{ fieldPath: 'mcpServers.github.title', value: 'GitHub' }]);
+
+ const removed = await send(handlers.deleteConfigField, {
+ params: { principalType: 'role', principalId },
+ query: { fieldPath: 'mcpServers.github.oauth.client_secret', expectedRevision: revision },
+ });
+
+ expect(removed.statusCode).toBe(409);
+ });
+
+ it('refuses writes under the mcpConfig alias, and withholds a legacy document key there', async () => {
+ const principalId = nextPrincipalId();
+ const patched = await patch(principalId, [
+ { fieldPath: 'mcpConfig.aliasA', value: mcpServer({ oauth: undefined }) },
+ ]);
+ expect(patched.statusCode).toBe(400);
+ expect(patched.body).toMatchObject({ code: 'UNKNOWN_SECTION' });
+
+ const replaced = await send(handlers.upsertConfigOverrides, {
+ params: { principalType: 'role', principalId },
+ body: { overrides: { mcpConfig: { aliasA: mcpServer({ oauth: undefined }) } } },
+ });
+ expect(replaced.statusCode).toBe(400);
+ expect(replaced.body).toMatchObject({ code: 'CONFIG_OVERRIDE_INVALID' });
+ expect(await mongoose.models.Config.countDocuments({ principalId })).toBe(0);
+
+ /** Stored before the section allowlist: the merge ignores it, and reads still withhold its key. */
+ await mongoose.models.Config.create({
+ principalType: 'role',
+ principalId,
+ principalModel: 'Role',
+ priority: 10,
+ overrides: { mcpConfig: { aliasA: mcpServer({ oauth: undefined }) } },
+ });
+ const read = await send(handlers.getConfig, {
+ params: { principalType: 'role', principalId },
+ });
+ expect(read.statusCode).toBe(200);
+ expect(JSON.stringify(read.body)).not.toContain(API_KEY);
+ expect(getAtPath(read.body!.config, 'overrides.mcpConfig.aliasA.apiKey.key')).toBeUndefined();
+
+ const removed = await send(handlers.deleteConfigField, {
+ params: { principalType: 'role', principalId },
+ query: { fieldPath: 'mcpConfig.aliasA' },
+ });
+ expect(removed.statusCode).toBe(200);
+ expect(getAtPath(await readRawOverrides(principalId), 'mcpConfig.aliasA')).toBeUndefined();
+ });
+
+ it('does not ask again for a visible `${ENV}` reference', async () => {
+ const principalId = nextPrincipalId();
+ await patch(principalId, [
+ {
+ fieldPath: 'mcpServers.ref',
+ value: mcpServer({
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: '${MCP_KEY}' },
+ oauth: undefined,
+ }),
+ },
+ ]);
+
+ const res = await patch(principalId, [
+ { fieldPath: 'mcpServers.ref.url', value: 'https://moved.example/mcp' },
+ ]);
+ expect(res.statusCode).toBe(200);
+ });
+ });
+
+ it('validates after preservation: dropping client_id while the secret is kept is refused', async () => {
+ const principalId = await seed();
+
+ const res = await patch(principalId, [
+ {
+ fieldPath: 'mcpServers.github.oauth',
+ value: {
+ authorization_url: 'https://auth.example.com/authorize',
+ token_url: 'https://auth.example.com/token',
+ },
+ },
+ ]);
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toMatchObject({ code: 'CONFIG_OVERRIDE_INVALID' });
+ expect((res.body as { issues: Array<{ path: string }> }).issues).toEqual([
+ expect.objectContaining({ path: 'mcpServers.github.oauth.client_secret' }),
+ ]);
+ });
+
+ describe('rename hints', () => {
+ const renamed = () =>
+ mcpServer({
+ apiKey: { source: 'admin', authorization_type: 'bearer' },
+ oauth: {
+ client_id: 'client',
+ authorization_url: 'https://auth.example.com/authorize',
+ token_url: 'https://auth.example.com/token',
+ },
+ });
+
+ it('carries both stored credentials to the new name and leaves the old server alone', async () => {
+ const principalId = await seed();
+ const source = await storedServer(principalId, 'github');
+
+ const res = await patch(principalId, [{ fieldPath: 'mcpServers.code', value: renamed() }], {
+ renames: [{ path: 'mcpServers', previousName: 'github', name: 'code' }],
+ });
+
+ expect(res.statusCode).toBe(200);
+ const copy = await storedServer(principalId, 'code');
+ expect(copy.apiKey.key).toBe(source.apiKey.key);
+ expect(copy.oauth.client_secret).toBe(source.oauth.client_secret);
+ expect(copy.apiKey.keyPreview).toBe(getSecretPreview(API_KEY));
+ expect((await storedServer(principalId, 'github')).apiKey.key).toBe(source.apiKey.key);
+ });
+
+ it('requires re-entry when the renamed server points somewhere else', async () => {
+ const principalId = await seed();
+
+ const res = await patch(
+ principalId,
+ [
+ {
+ fieldPath: 'mcpServers.code',
+ value: { ...renamed(), url: 'https://evil.example/mcp' },
+ },
+ ],
+ { renames: [{ path: 'mcpServers', previousName: 'github', name: 'code' }] },
+ );
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toMatchObject({ code: 'MCP_API_KEY_REENTRY_REQUIRED', server: 'code' });
+ });
+
+ it('without a hint, a renamed server keeps no credential', async () => {
+ const principalId = await seed();
+
+ const res = await patch(principalId, [{ fieldPath: 'mcpServers.code', value: renamed() }]);
+
+ expect(res.statusCode).toBe(200);
+ const copy = await storedServer(principalId, 'code');
+ expect(copy.apiKey.key).toBeUndefined();
+ });
+
+ it('rejects hints it cannot apply', async () => {
+ const principalId = await seed();
+ const write = [{ fieldPath: 'mcpServers.code', value: renamed() }];
+
+ const cases: Array<[unknown, string]> = [
+ [[{ path: 'endpoints.custom', previousName: 'github', name: 'code' }], 'unsupported_path'],
+ [[{ path: 'mcpServers', previousName: 'github', name: 'github' }], 'invalid_name'],
+ [[{ path: 'mcpServers', previousName: '__proto__', name: 'code' }], 'invalid_name'],
+ [[{ path: 'mcpServers', previousName: 'missing', name: 'code' }], 'source_not_found'],
+ [[{ path: 'mcpServers', previousName: 'github', name: 'other' }], 'target_not_written'],
+ ['not-an-array', 'invalid_renames'],
+ ];
+ for (const [renames, reason] of cases) {
+ const res = await patch(principalId, write, { renames });
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toEqual({
+ error: 'Invalid rename hint',
+ code: 'CONFIG_RENAME_INVALID',
+ reason,
+ });
+ }
+ });
+ });
+});
+
+describe('env reference allowlist on admin writes', () => {
+ it('refuses a reference to a name outside the allowlist, by path, on PATCH and PUT', async () => {
+ const principalId = nextPrincipalId();
+
+ const patched = await patch(principalId, [
+ { fieldPath: 'mcpServers.x', value: mcpServer({ url: 'https://h.example/${HOME}' }) },
+ ]);
+ expect(patched.statusCode).toBe(400);
+ expect(patched.body).toEqual({
+ error: 'Invalid config override',
+ code: 'CONFIG_OVERRIDE_INVALID',
+ issues: [
+ {
+ path: 'mcpServers.x.url',
+ segments: ['mcpServers', 'x', 'url'],
+ code: 'env_reference_not_allowed',
+ },
+ ],
+ });
+
+ const replaced = await send(handlers.upsertConfigOverrides, {
+ params: { principalType: 'role', principalId },
+ body: {
+ overrides: {
+ endpoints: {
+ custom: [
+ {
+ name: 'Exfil',
+ apiKey: '${CREDS_KEY}',
+ baseURL: 'https://evil.example/v1',
+ models: { default: ['m'] },
+ },
+ ],
+ },
+ },
+ },
+ });
+ expect(replaced.statusCode).toBe(400);
+ expect(replaced.body).toMatchObject({
+ issues: [
+ {
+ path: 'endpoints.custom.0.apiKey',
+ segments: ['endpoints', 'custom', '0', 'apiKey'],
+ code: 'env_reference_not_allowed',
+ },
+ ],
+ });
+ expect(await mongoose.models.Config.findOne({ principalId })).toBeNull();
+ });
+
+ it('accepts names librechat.yaml references and names the operator lists', async () => {
+ const yamlHandlers = createRealHandlers({
+ overrideEnvAllowlist: 'EXTRA_GATEWAY_KEY',
+ getAppConfig: async () => ({ config: { ocr: { baseURL: '${YAML_OCR_URL}' } } }) as never,
+ });
+ const principalId = nextPrincipalId();
+
+ const res = await patch(
+ principalId,
+ [
+ { fieldPath: 'ocr.baseURL', value: '${YAML_OCR_URL}' },
+ { fieldPath: 'ocr.apiKey', value: '${EXTRA_GATEWAY_KEY}' },
+ { fieldPath: 'webSearch.serperApiKey', value: '${OPENAI_API_KEY}' },
+ ],
+ {},
+ yamlHandlers,
+ );
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('accepts the OCR key reference GET /base returns when librechat.yaml sets no OCR key', async () => {
+ const yamlOCR = { baseURL: 'https://ocr.yaml.example/v1', mistralModel: 'mistral-ocr-latest' };
+ const yamlHandlers = createRealHandlers({
+ overrideEnvAllowlist: '',
+ getAppConfig: async () =>
+ ({ config: { ocr: yamlOCR }, ocr: loadOCRConfig(yamlOCR) }) as never,
+ });
+ const base = await send(yamlHandlers.getBaseConfig, {});
+ const ocr = (base.body!.config as { ocr: Record<string, unknown> }).ocr;
+ expect(ocr.apiKey).toBe('${OCR_API_KEY}');
+
+ const principalId = nextPrincipalId();
+ const res = await patch(principalId, [{ fieldPath: 'ocr', value: ocr }], {}, yamlHandlers);
+ expect(res.statusCode).toBe(200);
+ expect(getAtPath(await readRawOverrides(principalId), 'ocr.apiKey')).toBe('${OCR_API_KEY}');
+
+ const unconfigured = createRealHandlers({
+ overrideEnvAllowlist: '',
+ getAppConfig: async () => ({ config: {} }) as never,
+ });
+ const refused = await patch(
+ nextPrincipalId(),
+ [{ fieldPath: 'ocr', value: ocr }],
+ {},
+ unconfigured,
+ );
+ expect(refused.statusCode).toBe(400);
+ expect(refused.body).toMatchObject({
+ issues: [{ path: 'ocr.apiKey', code: 'env_reference_not_allowed' }],
+ });
+ });
+
+ it('accepts the web search section GET /base returns, with the defaults loading fills in', async () => {
+ const yamlHandlers = createRealHandlers({
+ overrideEnvAllowlist: '',
+ getAppConfig: async () =>
+ ({ config: {}, webSearch: loadWebSearchConfig(undefined) }) as never,
+ });
+ const base = await send(yamlHandlers.getBaseConfig, {});
+ const webSearch = (base.body!.config as { webSearch: Record<string, unknown> }).webSearch;
+ expect(webSearch.searxngInstanceUrl).toBe('${SEARXNG_INSTANCE_URL}');
+
+ const principalId = nextPrincipalId();
+ const patched = await patch(
+ principalId,
+ [{ fieldPath: 'webSearch', value: webSearch }],
+ {},
+ yamlHandlers,
+ );
+ expect(patched.statusCode).toBe(200);
+ const batch = await send(yamlHandlers.applyConfigChanges, {
+ params: { principalType: 'role', principalId },
+ body: { ops: [{ op: 'set', fieldPath: 'webSearch', value: webSearch }] },
+ });
+ expect(batch.statusCode).toBe(200);
+ expect(getAtPath(await readRawOverrides(principalId), 'webSearch.searxngInstanceUrl')).toBe(
+ '${SEARXNG_INSTANCE_URL}',
+ );
+
+ const elsewhere = await patch(
+ nextPrincipalId(),
+ [{ fieldPath: 'webSearch.firecrawlApiUrl', value: '${SEARXNG_INSTANCE_URL}' }],
+ {},
+ yamlHandlers,
+ );
+ expect(elsewhere.statusCode).toBe(400);
+ expect(elsewhere.body).toMatchObject({
+ issues: [{ path: 'webSearch.firecrawlApiUrl', code: 'env_reference_not_allowed' }],
+ });
+ });
+
+ it('accepts `${...}` inside a key read as is, and refuses it inside one a client expands', async () => {
+ const principalId = nextPrincipalId();
+ const credential = 'pa${LC8_UNLISTED_NAME}ss';
+
+ const opaque = await patch(principalId, [
+ { fieldPath: 'ocr.apiKey', value: credential },
+ { fieldPath: 'speech.tts.openai', value: { apiKey: credential, voices: ['alloy'] } },
+ ]);
+ expect(opaque.statusCode).toBe(200);
+ const batch = await send(handlers.applyConfigChanges, {
+ params: { principalType: 'role', principalId },
+ body: { ops: [{ op: 'set', fieldPath: 'webSearch.serperApiKey', value: credential }] },
+ });
+ expect(batch.statusCode).toBe(200);
+ const stored = await readRawOverrides(principalId);
+ for (const path of ['ocr.apiKey', 'speech.tts.openai.apiKey', 'webSearch.serperApiKey']) {
+ expect(decryptV3(getAtPath(stored, path) as string)).toBe(credential);
+ }
+
+ const reference = await patch(principalId, [
+ { fieldPath: 'ocr.apiKey', value: '${LC8_UNLISTED_NAME}' },
+ ]);
+ expect(reference.statusCode).toBe(400);
+ expect(reference.body).toMatchObject({
+ issues: [{ path: 'ocr.apiKey', code: 'env_reference_not_allowed' }],
+ });
+
+ const expanded = await patch(principalId, [
+ {
+ fieldPath: 'endpoints.custom',
+ value: [
+ {
+ name: 'Gateway',
+ apiKey: credential,
+ baseURL: 'https://gateway.example/v1',
+ models: { default: ['m'] },
+ },
+ ],
+ },
+ {
+ fieldPath: 'mcpServers.tools',
+ value: mcpServer({
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: credential },
+ }),
+ },
+ ]);
+ expect(expanded.statusCode).toBe(400);
+ expect(expanded.body).toMatchObject({
+ issues: [
+ { path: 'endpoints.custom.0.apiKey', code: 'env_reference_not_allowed' },
+ { path: 'mcpServers.tools.apiKey.key', code: 'env_reference_not_allowed' },
+ ],
+ });
+ expect(getAtPath(await readRawOverrides(principalId), 'endpoints')).toBeUndefined();
+ });
+
+ it('accepts the Azure base URL templates in a group, on PATCH and change batches', async () => {
+ const principalId = nextPrincipalId();
+ const baseURL =
+ 'https://${INSTANCE_NAME}.openai.azure.com/openai/deployments/${DEPLOYMENT_NAME}';
+ const group = {
+ group: 'east',
+ apiKey: '${AZURE_API_KEY}',
+ instanceName: 'east-instance',
+ version: '2024-10-21',
+ baseURL,
+ models: { 'gpt-4o': true },
+ };
+
+ const patched = await patch(principalId, [
+ { fieldPath: 'endpoints.azureOpenAI', value: { groups: [group] } },
+ ]);
+ expect(patched.statusCode).toBe(200);
+ const batch = await send(handlers.applyConfigChanges, {
+ params: { principalType: 'role', principalId },
+ body: {
+ ops: [
+ {
+ op: 'set',
+ fieldPath: 'endpoints.azureOpenAI.groups',
+ value: [group, { ...group, group: 'west', instanceName: 'west-instance' }],
+ },
+ ],
+ },
+ });
+ expect(batch.statusCode).toBe(200);
+ expect(
+ getAtPath(await readRawOverrides(principalId), 'endpoints.azureOpenAI.groups'),
+ ).toMatchObject([{ baseURL }, { baseURL }]);
+
+ const elsewhere = await patch(principalId, [
+ { fieldPath: 'ocr.baseURL', value: 'https://${INSTANCE_NAME}.example.com' },
+ ]);
+ expect(elsewhere.statusCode).toBe(400);
+ expect(elsewhere.body).toMatchObject({
+ issues: [{ path: 'ocr.baseURL', code: 'env_reference_not_allowed' }],
+ });
+ });
+
+ it('checks prompt-named keys in maps a reader expands; only prompt fields are text', async () => {
+ const principalId = nextPrincipalId();
+
+ const headers = await patch(principalId, [
+ {
+ fieldPath: 'mcpServers.envleak',
+ value: mcpServer({
+ oauth: undefined,
+ headers: { 'X-Prompt': '${HOME}', instructions: 'Bearer ${HOME}' },
+ oauth_headers: { 'X-System-Prompt': '${HOME}' },
+ }),
+ },
+ ]);
+ expect(headers.statusCode).toBe(400);
+ expect(headers.body).toEqual({
+ error: 'Invalid config override',
+ code: 'CONFIG_OVERRIDE_INVALID',
+ issues: [
+ {
+ path: 'mcpServers.envleak.headers.X-Prompt',
+ segments: ['mcpServers', 'envleak', 'headers', 'X-Prompt'],
+ code: 'env_reference_not_allowed',
+ },
+ {
+ path: 'mcpServers.envleak.headers.instructions',
+ segments: ['mcpServers', 'envleak', 'headers', 'instructions'],
+ code: 'env_reference_not_allowed',
+ },
+ {
+ path: 'mcpServers.envleak.oauth_headers.X-System-Prompt',
+ segments: ['mcpServers', 'envleak', 'oauth_headers', 'X-System-Prompt'],
+ code: 'env_reference_not_allowed',
+ },
+ ],
+ });
+
+ const endpoint = (extra: Record<string, unknown>) => ({
+ overrides: {
+ endpoints: {
+ custom: [
+ {
+ name: 'Leak',
+ apiKey: 'sk-own-gateway-key',
+ baseURL: 'https://evil.example/v1',
+ models: { default: ['m'] },
+ titlePrompt: 'Title for ${convo}',
+ ...extra,
+ },
+ ],
+ },
+ },
+ });
+ const custom = await send(handlers.upsertConfigOverrides, {
+ params: { principalType: 'role', principalId },
+ body: endpoint({
+ headers: { 'X-System-Prompt': '${HOME}' },
+ addParams: { instructions: '${HOME}' },
+ }),
+ });
+ expect(custom.statusCode).toBe(400);
+ expect(custom.body).toMatchObject({
+ issues: [
+ {
+ path: 'endpoints.custom.0.headers.X-System-Prompt',
+ segments: ['endpoints', 'custom', '0', 'headers', 'X-System-Prompt'],
+ code: 'env_reference_not_allowed',
+ },
+ {
+ path: 'endpoints.custom.0.addParams.instructions',
+ segments: ['endpoints', 'custom', '0', 'addParams', 'instructions'],
+ code: 'env_reference_not_allowed',
+ },
+ ],
+ });
+ expect(await mongoose.models.Config.findOne({ principalId })).toBeNull();
+
+ const prose = await send(handlers.upsertConfigOverrides, {
+ params: { principalType: 'role', principalId },
+ body: endpoint({}),
+ });
+ expect(prose.statusCode).toBe(201);
+ });
+});
+
+describe('Azure OpenAI group keys — real handlers against a real Config collection', () => {
+ const group = (apiKey?: string) => ({
+ group: 'east',
+ instanceName: 'east-instance',
+ version: '2024-10-21',
+ models: { 'gpt-4o': true },
+ ...(apiKey !== undefined && { apiKey }),
+ });
+
+ it('encrypts group keys written through the endpoint object and keeps them when omitted', async () => {
+ const principalId = nextPrincipalId();
+
+ const written = await patch(principalId, [
+ { fieldPath: 'endpoints.azureOpenAI', value: { groups: [group('azure-east-key-00001234')] } },
+ ]);
+ expect(written.statusCode).toBe(200);
+ const stored = getAtPath(
+ await readRawOverrides(principalId),
+ 'endpoints.azureOpenAI.groups',
+ ) as Array<Record<string, string>> | undefined;
+ expect(decryptV3(stored![0].apiKey)).toBe('azure-east-key-00001234');
+ expect(JSON.stringify(written.body)).not.toContain('azure-east-key-00001234');
+
+ /** `apiKey` is required on a group: validation runs after the omitted key is kept. */
+ const kept = await patch(principalId, [
+ { fieldPath: 'endpoints.azureOpenAI.groups', value: [group()] },
+ ]);
+ expect(kept.statusCode).toBe(200);
+ const after = getAtPath(await readRawOverrides(principalId), 'endpoints.azureOpenAI.groups') as
+ | Array<Record<string, string>>
+ | undefined;
+ expect(after![0].apiKey).toBe(stored![0].apiKey);
+ });
+
+ describe('a stored group key kept beside a destination the write changes', () => {
+ const KEY = 'azure-east-admin-key-00009876';
+ /** A group the merge resolves: each model has a deployment and a version. */
+ const servable = (apiKey?: string) => ({ ...group(apiKey), deploymentName: 'gpt-4o' });
+ const reentryIssue = (field: string, secret = 'endpoints.azureOpenAI.groups.0.apiKey') => ({
+ code: 'CONFIG_SECRET_REENTRY_REQUIRED',
+ issues: [
+ {
+ path: `endpoints.azureOpenAI.groups.0.${field}`,
+ segments: ['endpoints', 'azureOpenAI', 'groups', '0', field],
+ code: 'secret_reentry_required',
+ secretPath: secret,
+ },
+ ],
+ });
+
+ async function storeGroup(): Promise<{ principalId: string; stored: unknown }> {
+ const principalId = nextPrincipalId();
+ const written = await patch(principalId, [
+ { fieldPath: 'endpoints.azureOpenAI.groups', value: [servable(KEY)] },
+ ]);
+ expect(written.statusCode).toBe(200);
+ return { principalId, stored: await readRawOverrides(principalId) };
+ }
+
+ it('must be entered again on PATCH, PUT and change batches (dry runs included)', async () => {
+ const { principalId, stored } = await storeGroup();
+ const moved = [{ ...servable(), instanceName: 'attacker-instance' }];
+ const params = { principalType: 'role', principalId };
+
+ const patched = await patch(principalId, [
+ { fieldPath: 'endpoints.azureOpenAI.groups', value: moved },
+ ]);
+ const replaced = await send(handlers.upsertConfigOverrides, {
+ params,
+ body: { overrides: { endpoints: { azureOpenAI: { groups: moved } } } },
+ });
+ const batch = (dryRun: boolean) =>
+ send(handlers.applyConfigChanges, {
+ params,
+ body: {
+ dryRun,
+ ops: [{ op: 'set', fieldPath: 'endpoints.azureOpenAI.groups', value: moved }],
+ },
+ });
+ for (const res of [patched, replaced, await batch(true), await batch(false)]) {
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toMatchObject(reentryIssue('instanceName'));
+ }
+ expect(await readRawOverrides(principalId)).toEqual(stored);
+
+ const entered = await patch(principalId, [
+ {
+ fieldPath: 'endpoints.azureOpenAI.groups',
+ value: [{ ...servable('azure-new-instance-key-0001'), instanceName: 'new-instance' }],
+ },
+ ]);
+ expect(entered.statusCode).toBe(200);
+ });
+
+ it('stays with edits that leave its destination alone', async () => {
+ const { principalId } = await storeGroup();
+
+ const res = await patch(principalId, [
+ {
+ fieldPath: 'endpoints.azureOpenAI.groups',
+ value: [{ ...servable(), version: '2025-01-01', models: { 'gpt-4o': true, o3: true } }],
+ },
+ ]);
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('must be entered again when a groupMap entry, a field delete or a tombstone moves it', async () => {
+ const { principalId, stored } = await storeGroup();
+ const groupMapBaseURL = 'endpoints.azureOpenAI.groupMap.east.baseURL';
+
+ const mapped = await patch(principalId, [
+ { fieldPath: groupMapBaseURL, value: 'https://attacker.example/openai' },
+ ]);
+ expect(mapped.statusCode).toBe(400);
+ expect(mapped.body).toMatchObject({
+ code: 'CONFIG_SECRET_REENTRY_REQUIRED',
+ issues: [{ path: groupMapBaseURL, secretPath: 'endpoints.azureOpenAI.groups.0.apiKey' }],
+ });
+ expect(await readRawOverrides(principalId)).toEqual(stored);
+
+ const mapPrincipalId = nextPrincipalId();
+ const withMap = await patch(mapPrincipalId, [
+ {
+ fieldPath: 'endpoints.azureOpenAI.groupMap.east',
+ value: { apiKey: KEY, instanceName: 'east-instance', baseURL: 'https://own.example' },
+ },
+ ]);
+ expect(withMap.statusCode).toBe(200);
+ const mapStored = await readRawOverrides(mapPrincipalId);
+ const mapParams = { principalType: 'role', principalId: mapPrincipalId };
+ const removed = await send(handlers.deleteConfigField, {
+ params: mapParams,
+ query: { fieldPath: 'endpoints.azureOpenAI.groupMap.east.baseURL' },
+ });
+ const tombstoned = await send(handlers.tombstoneConfigField, {
+ params: mapParams,
+ body: { fieldPath: 'endpoints.azureOpenAI.groupMap.east.instanceName' },
+ });
+ for (const res of [removed, tombstoned]) {
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toMatchObject({ code: 'CONFIG_SECRET_REENTRY_REQUIRED' });
+ }
+ expect(await readRawOverrides(mapPrincipalId)).toEqual(mapStored);
+ });
+ });
+
+ it('encrypts a groupMap key, which the Azure clients read, and never returns it', async () => {
+ const principalId = nextPrincipalId();
+ const key = 'azure-groupmap-plaintext-key-5678';
+ const params = { principalType: 'role', principalId };
+
+ const written = await patch(principalId, [
+ {
+ fieldPath: 'endpoints.azureOpenAI.groupMap',
+ value: { g1: { apiKey: key, instanceName: 'g1-instance' } },
+ },
+ ]);
+ expect(written.statusCode).toBe(200);
+ const stored = getAtPath(
+ await readRawOverrides(principalId),
+ 'endpoints.azureOpenAI.groupMap.g1',
+ ) as Record<string, string>;
+ expect(decryptV3(stored.apiKey)).toBe(key);
+ expect(stored.apiKeyPreview).toBe('...5678');
+
+ const read = await send(handlers.getConfig, { params });
+ for (const res of [written, read]) {
+ expect(JSON.stringify(res.body)).not.toContain(key);
+ expect(JSON.stringify(res.body)).not.toContain(stored.apiKey);
+ expect(getAtPath(res.body!.config, 'overrides.endpoints.azureOpenAI.groupMap.g1')).toEqual({
+ apiKeyPreview: '...5678',
+ instanceName: 'g1-instance',
+ });
+ }
+
+ const kept = await patch(principalId, [
+ { fieldPath: 'endpoints.azureOpenAI.groupMap.g1', value: { instanceName: 'g1-instance' } },
+ ]);
+ const replace = (g1: Record<string, string>) =>
+ send(handlers.upsertConfigOverrides, {
+ params,
+ body: { overrides: { endpoints: { azureOpenAI: { groupMap: { g1 } } } } },
+ });
+ /** A replace that leaves the instance out sends the kept key to another host. */
+ const moved = await replace({ version: 'v' });
+ const replaced = await replace({ instanceName: 'g1-instance', version: 'v' });
+ expect(kept.statusCode).toBe(200);
+ expect(moved.statusCode).toBe(400);
+ expect(moved.body).toMatchObject({
+ code: 'CONFIG_SECRET_REENTRY_REQUIRED',
+ issues: [
+ {
+ path: 'endpoints.azureOpenAI.groupMap.g1.instanceName',
+ secretPath: 'endpoints.azureOpenAI.groupMap.g1.apiKey',
+ },
+ ],
+ });
+ expect(replaced.statusCode).toBe(200);
+ expect(
+ getAtPath(await readRawOverrides(principalId), 'endpoints.azureOpenAI.groupMap.g1'),
+ ).toEqual({
+ apiKey: stored.apiKey,
+ apiKeyPreview: '...5678',
+ instanceName: 'g1-instance',
+ version: 'v',
+ });
+ });
+});
+
+describe('inherited secrets a profile rebinds (`ignored` in write responses)', () => {
+ const yaml = {
+ endpoints: {
+ custom: [
+ {
+ name: 'Gateway',
+ apiKey: '${GATEWAY_KEY}',
+ baseURL: 'https://gateway.example.com/v1',
+ models: { default: ['gpt-4o'] },
+ },
+ ],
+ },
+ mcpServers: {
+ tools: {
+ type: 'streamable-http',
+ url: 'https://tools.example.com/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: '${TOOLS_KEY}' },
+ },
+ },
+ };
+ const baseAppConfig = {
+ config: yaml,
+ endpoints: { custom: structuredClone(yaml.endpoints.custom) },
+ mcpConfig: structuredClone(yaml.mcpServers),
+ };
+
+ it('reports the inherited key a profile URL change drops, and nothing for other edits', async () => {
+ const yamlHandlers = createRealHandlers({ getAppConfig: async () => baseAppConfig as never });
+ const principalId = nextPrincipalId();
+
+ const moved = await patch(
+ principalId,
+ [
+ { fieldPath: 'mcpServers.tools.url', value: 'https://moved.example/mcp' },
+ {
+ fieldPath: 'endpoints.custom',
+ value: [{ name: 'Gateway', baseURL: 'https://moved.example/v1' }],
+ },
+ ],
+ {},
+ yamlHandlers,
+ );
+
+ expect(moved.statusCode).toBe(200);
+ expect(moved.body!.ignored).toEqual([
+ {
+ path: 'endpoints.custom["Gateway"].apiKey',
+ segments: ['endpoints', 'custom', 'Gateway', 'apiKey'],
+ reason: 'secret_rebinding',
+ },
+ {
+ path: 'mcpServers.tools.apiKey.key',
+ segments: ['mcpServers', 'tools', 'apiKey', 'key'],
+ reason: 'secret_rebinding',
+ },
+ ]);
+
+ const other = nextPrincipalId();
+ const titled = await patch(
+ other,
+ [{ fieldPath: 'mcpServers.tools.title', value: 'Tools' }],
+ {},
+ yamlHandlers,
+ );
+ expect(titled.statusCode).toBe(200);
+ expect(titled.body!.ignored).toBeUndefined();
+ });
+
+ it("reports a key moved by the native client's own URL option or under a folded name", async () => {
+ const custom = [
+ {
+ name: 'Claude',
+ provider: 'anthropic',
+ apiKey: 'yaml-literal-claude-key',
+ baseURL: 'https://gateway.example.com/anthropic',
+ models: { default: ['claude-x'] },
+ },
+ {
+ name: 'Ollama',
+ apiKey: 'yaml-literal-ollama-key',
+ baseURL: 'http://ollama.internal:11434/v1',
+ models: { default: ['llama3'] },
+ },
+ ];
+ const endpointHandlers = createRealHandlers({
+ getAppConfig: async () =>
+ ({
+ config: { endpoints: { custom } },
+ endpoints: { custom: structuredClone(custom) },
+ }) as never,
+ });
+ const ignoredKey = (name: string) => ({
+ path: `endpoints.custom[${JSON.stringify(name)}].apiKey`,
+ segments: ['endpoints', 'custom', name, 'apiKey'],
+ reason: 'secret_rebinding',
+ });
+ const redirected = {
+ name: 'Claude',
+ addParams: { anthropicApiUrl: 'https://attacker.example' },
+ };
+ const respelled = { name: 'ollama', baseURL: 'https://attacker.example/v1' };
+
+ const patched = await patch(
+ nextPrincipalId(),
+ [{ fieldPath: 'endpoints.custom', value: [redirected, respelled] }],
+ {},
+ endpointHandlers,
+ );
+ expect(patched.statusCode).toBe(200);
+ expect(patched.body!.ignored).toEqual([ignoredKey('Claude'), ignoredKey('Ollama')]);
+
+ const params = { principalType: 'role', principalId: nextPrincipalId() };
+ for (const [entry, name] of [
+ [redirected, 'Claude'],
+ [respelled, 'Ollama'],
+ ] as const) {
+ const batch = await send(endpointHandlers.applyConfigChanges, {
+ params,
+ body: { dryRun: true, ops: [{ op: 'upsertEntry', fieldPath: 'endpoints.custom', entry }] },
+ });
+ expect(batch.statusCode).toBe(200);
+ expect(batch.body!.ignored).toEqual([ignoredKey(name)]);
+ }
+
+ const shaped = await patch(
+ nextPrincipalId(),
+ [
+ {
+ fieldPath: 'endpoints.custom',
+ value: [
+ { name: 'Claude', addParams: { promptCache: true } },
+ { name: 'ollama', models: { default: ['llama3.1'] } },
+ ],
+ },
+ ],
+ {},
+ endpointHandlers,
+ );
+ expect(shaped.statusCode).toBe(200);
+ expect(shaped.body!.ignored).toBeUndefined();
+ });
+
+ it('lists only the sections a section manager can read, on every write route', async () => {
+ const broad = createRealHandlers({ getAppConfig: async () => baseAppConfig as never });
+ const principalId = nextPrincipalId();
+ const params = { principalType: 'role', principalId };
+ const mcpIgnored = {
+ path: 'mcpServers.tools.apiKey.key',
+ segments: ['mcpServers', 'tools', 'apiKey', 'key'],
+ reason: 'secret_rebinding',
+ };
+ const endpointIgnored = {
+ path: 'endpoints.custom["Gateway"].apiKey',
+ segments: ['endpoints', 'custom', 'Gateway', 'apiKey'],
+ reason: 'secret_rebinding',
+ };
+ /** A broad manager moves the MCP server: the document drops its inherited key from then on. */
+ const moved = await patch(
+ principalId,
+ [{ fieldPath: 'mcpServers.tools.url', value: 'https://moved.example/mcp' }],
+ {},
+ broad,
+ );
+ expect(moved.body!.ignored).toEqual([mcpIgnored]);
+
+ const scoped = createRealHandlers({
+ getAppConfig: async () => baseAppConfig as never,
+ hasConfigCapability: async (_user, section) => section === 'endpoints',
+ });
+ const movedEndpoint = [{ name: 'Gateway', baseURL: 'https://moved.example/v1' }];
+ const patched = await patch(
+ principalId,
+ [{ fieldPath: 'endpoints.custom', value: movedEndpoint }],
+ {},
+ scoped,
+ );
+ expect(patched.statusCode).toBe(200);
+ expect(patched.body!.ignored).toEqual([endpointIgnored]);
+ expect(Object.keys((patched.body!.config as { overrides: object }).overrides)).toEqual([
+ 'endpoints',
+ ]);
+
+ const tombstoned = await send(scoped.tombstoneConfigField, {
+ params,
+ body: { fieldPath: 'endpoints.custom' },
+ });
+ expect(tombstoned.statusCode).toBe(200);
+ expect(tombstoned.body!.ignored).toBeUndefined();
+
+ for (const dryRun of [true, false]) {
+ const batch = await send(scoped.applyConfigChanges, {
+ params,
+ body: {
+ dryRun,
+ ops: [{ op: 'set', fieldPath: 'endpoints.custom', value: movedEndpoint }],
+ },
+ });
+ expect(batch.statusCode).toBe(200);
+ expect(batch.body!.ignored).toEqual([endpointIgnored]);
+ }
+
+ const all = await send(broad.applyConfigChanges, {
+ params,
+ body: { dryRun: true, ops: [{ op: 'unset', fieldPath: 'endpoints.custom' }] },
+ });
+ expect(all.body!.ignored).toEqual([mcpIgnored]);
+ });
+});
+
+describe('destinations with a deployment credential (`ignored` in write responses)', () => {
+ it('reports a summarization URL a profile sets without its own key', async () => {
+ const yamlHandlers = createRealHandlers({
+ getAppConfig: async () => ({ config: {} }) as never,
+ });
+ const principalId = nextPrincipalId();
+
+ const moved = await patch(
+ principalId,
+ [
+ { fieldPath: 'summarization.provider', value: 'openAI' },
+ { fieldPath: 'summarization.parameters.baseURL', value: 'https://evil.example/v1' },
+ ],
+ {},
+ yamlHandlers,
+ );
+ expect(moved.statusCode).toBe(200);
+ expect(moved.body!.ignored).toEqual([
+ {
+ path: 'summarization.parameters.baseURL',
+ segments: ['summarization', 'parameters', 'baseURL'],
+ reason: 'secret_rebinding',
+ },
+ ]);
+
+ const keyed = await patch(
+ principalId,
+ [{ fieldPath: 'summarization.parameters.apiKey', value: 'sk-profile-summary-key' }],
+ {},
+ yamlHandlers,
+ );
+ expect(keyed.statusCode).toBe(200);
+ expect(keyed.body!.ignored).toBeUndefined();
+ });
+
+ it('reports nothing for firstPartyEndpoint, which is not a destination', async () => {
+ const yamlHandlers = createRealHandlers({
+ getAppConfig: async () => ({ config: {} }) as never,
+ });
+
+ const res = await patch(
+ nextPrincipalId(),
+ [
+ { fieldPath: 'summarization.provider', value: 'openAI' },
+ { fieldPath: 'summarization.parameters.firstPartyEndpoint', value: false },
+ ],
+ {},
+ yamlHandlers,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body!.ignored).toBeUndefined();
+ });
+
+ const summarizationIgnored = (...keys: string[]) =>
+ keys.map((key) => ({
+ path: `summarization.parameters.${key}`,
+ segments: ['summarization', 'parameters', key],
+ reason: 'secret_rebinding',
+ }));
+
+ it.each([1, 0, true, false])(
+ 'reports a summarization URL a profile sets with a key of %p, which no client sends',
+ async (apiKey) => {
+ const yamlHandlers = createRealHandlers({
+ getAppConfig: async () => ({ config: {} }) as never,
+ });
+
+ const res = await patch(
+ nextPrincipalId(),
+ [
+ { fieldPath: 'summarization.provider', value: 'azureOpenAI' },
+ { fieldPath: 'summarization.model', value: 'gpt-4o' },
+ { fieldPath: 'summarization.parameters.baseURL', value: 'https://evil.example/openai' },
+ { fieldPath: 'summarization.parameters.apiKey', value: apiKey },
+ ],
+ {},
+ yamlHandlers,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body!.ignored).toEqual(summarizationIgnored('baseURL'));
+ },
+ );
+
+ it('reports a summarization destination set with a key its provider does not send', async () => {
+ const yamlHandlers = createRealHandlers({
+ getAppConfig: async () => ({ config: {} }) as never,
+ });
+
+ const bedrock = await patch(
+ nextPrincipalId(),
+ [
+ { fieldPath: 'summarization.provider', value: 'bedrock' },
+ { fieldPath: 'summarization.parameters.endpointHost', value: 'evil.example' },
+ { fieldPath: 'summarization.parameters.apiKey', value: 'sk-profile-summary-key' },
+ ],
+ {},
+ yamlHandlers,
+ );
+ expect(bedrock.statusCode).toBe(200);
+ expect(bedrock.body!.ignored).toEqual(summarizationIgnored('endpointHost'));
+
+ const providerless = await patch(
+ nextPrincipalId(),
+ [
+ { fieldPath: 'summarization.parameters.baseURL', value: 'https://evil.example/v1' },
+ { fieldPath: 'summarization.parameters.apiKey', value: 'sk-profile-summary-key' },
+ ],
+ {},
+ yamlHandlers,
+ );
+ expect(providerless.statusCode).toBe(200);
+ expect(providerless.body!.ignored).toEqual(summarizationIgnored('baseURL'));
+ });
+
+ it("reports librechat.yaml's summarization gateway once a profile changes the credential it receives", async () => {
+ const summarization = {
+ provider: 'azureOpenAI',
+ model: 'gpt-4o',
+ parameters: { baseURL: 'https://yaml-gateway.example/openai', apiKey: 'yaml-gateway-key' },
+ };
+ const yamlHandlers = createRealHandlers({
+ getAppConfig: async () =>
+ ({
+ config: { summarization },
+ summarization: structuredClone(summarization),
+ }) as never,
+ });
+
+ const tombstoned = await send(yamlHandlers.tombstoneConfigField, {
+ params: { principalType: 'role', principalId: nextPrincipalId() },
+ body: { fieldPath: 'summarization.parameters.apiKey' },
+ });
+ expect(tombstoned.statusCode).toBe(200);
+ expect(tombstoned.body!.ignored).toEqual(summarizationIgnored('baseURL'));
+
+ const unkeyed = { provider: 'openAI', parameters: { baseURL: 'https://yaml-gateway.example' } };
+ const unkeyedHandlers = createRealHandlers({
+ getAppConfig: async () =>
+ ({ config: { summarization: unkeyed }, summarization: structuredClone(unkeyed) }) as never,
+ });
+ const switched = await patch(
+ nextPrincipalId(),
+ [{ fieldPath: 'summarization.provider', value: 'azureOpenAI' }],
+ {},
+ unkeyedHandlers,
+ );
+ expect(switched.statusCode).toBe(200);
+ expect(switched.body!.ignored).toEqual(summarizationIgnored('baseURL'));
+
+ const tuned = await patch(
+ nextPrincipalId(),
+ [{ fieldPath: 'summarization.parameters.temperature', value: 0.2 }],
+ {},
+ unkeyedHandlers,
+ );
+ expect(tuned.statusCode).toBe(200);
+ expect(tuned.body!.ignored).toBeUndefined();
+ });
+
+ it('reports the key of a resolved Azure group an override points elsewhere', async () => {
+ const yaml = {
+ endpoints: {
+ azureOpenAI: {
+ groups: [
+ {
+ group: 'east',
+ apiKey: '${AZURE_EAST_KEY}',
+ instanceName: 'east',
+ version: '2024-10-21',
+ models: { 'gpt-4o': true },
+ },
+ ],
+ },
+ },
+ };
+ const baseAppConfig = {
+ config: yaml,
+ endpoints: {
+ azureOpenAI: {
+ groupMap: { east: { apiKey: '${AZURE_EAST_KEY}', instanceName: 'east' } },
+ modelGroupMap: { 'gpt-4o': { group: 'east' } },
+ },
+ },
+ };
+ const yamlHandlers = createRealHandlers({ getAppConfig: async () => baseAppConfig as never });
+
+ const res = await patch(
+ nextPrincipalId(),
+ [
+ {
+ fieldPath: 'endpoints.azureOpenAI.groupMap.east.baseURL',
+ value: 'https://evil.example/openai',
+ },
+ ],
+ {},
+ yamlHandlers,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body!.ignored).toEqual([
+ {
+ path: 'endpoints.azureOpenAI.groupMap.east.apiKey',
+ segments: ['endpoints', 'azureOpenAI', 'groupMap', 'east', 'apiKey'],
+ reason: 'secret_rebinding',
+ },
+ ]);
+ });
+});
+
+describe('secrets a layer below moved (`ignored` in write responses)', () => {
+ const yaml = {
+ mcpServers: {
+ tools: {
+ type: 'streamable-http',
+ url: 'https://tools.example.com/mcp',
+ proxy: 'http://proxy.corp.example:8080',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: '${TOOLS_KEY}' },
+ },
+ },
+ };
+ const baseAppConfig = { config: yaml, mcpConfig: structuredClone(yaml.mcpServers) };
+ const ownKey = {
+ fieldPath: 'mcpServers.tools.apiKey',
+ value: { source: 'admin', authorization_type: 'bearer', key: 'sk-profile-own-key' },
+ };
+
+ afterEach(async () => {
+ await mongoose.models.Config.deleteOne({ principalId: basePrincipalId });
+ });
+
+ it("binds a profile's own key to the server Base points it at, and reports it once Base moves it", async () => {
+ const yamlHandlers = createRealHandlers({ getAppConfig: async () => baseAppConfig as never });
+ const baseMoved = await patch(
+ basePrincipalId,
+ [{ fieldPath: 'mcpServers.tools.url', value: 'https://base.example/mcp' }],
+ {},
+ yamlHandlers,
+ );
+ expect(baseMoved.statusCode).toBe(200);
+
+ /** Entered over the server as Base defines it, the key is bound there. */
+ const principalId = nextPrincipalId();
+ const keyed = await patch(principalId, [ownKey], {}, yamlHandlers);
+ expect(keyed.statusCode).toBe(200);
+ expect(keyed.body!.ignored).toBeUndefined();
+ const stored = await readRawOverrides(principalId);
+ expect(getAtPath(stored, 'mcpServers.tools.apiKey.keyBinding')).toMatch(/^[0-9a-f]{64}$/);
+ expect(JSON.stringify(keyed.body)).not.toContain('keyBinding');
+
+ const baseMovedAgain = await patch(
+ basePrincipalId,
+ [{ fieldPath: 'mcpServers.tools.url', value: 'https://attacker.example/mcp' }],
+ {},
+ yamlHandlers,
+ );
+ expect(baseMovedAgain.statusCode).toBe(200);
+ const retitled = await patch(
+ principalId,
+ [{ fieldPath: 'mcpServers.tools.title', value: 'Tools' }],
+ {},
+ yamlHandlers,
+ );
+ expect(retitled.statusCode).toBe(200);
+ expect(retitled.body!.ignored).toEqual([
+ {
+ path: 'mcpServers.tools.apiKey.key',
+ segments: ['mcpServers', 'tools', 'apiKey', 'key'],
+ reason: 'secret_rebinding',
+ },
+ ]);
+ expect(
+ getAtPath(await readRawOverrides(principalId), 'mcpServers.tools.apiKey.keyBinding'),
+ ).toBe(getAtPath(stored, 'mcpServers.tools.apiKey.keyBinding'));
+
+ /** Pinning the destination in the same profile keeps the key, with nothing to bind. */
+ const pinnedId = nextPrincipalId();
+ const pinned = await patch(
+ pinnedId,
+ [ownKey, { fieldPath: 'mcpServers.tools.url', value: 'https://tools.example.com/mcp' }],
+ {},
+ yamlHandlers,
+ );
+ expect(pinned.statusCode).toBe(200);
+ expect(pinned.body!.ignored).toBeUndefined();
+ expect(
+ getAtPath(await readRawOverrides(pinnedId), 'mcpServers.tools.apiKey.keyBinding'),
+ ).toBeUndefined();
+ });
+
+ it('drops the key Base stores for an endpoint a profile moves, whatever their priorities', async () => {
+ const yamlHandlers = createRealHandlers({
+ getAppConfig: async () => ({ config: {} }) as never,
+ });
+ const baseKeyed = await patch(
+ basePrincipalId,
+ [
+ {
+ fieldPath: 'endpoints.custom',
+ value: [
+ {
+ name: 'Gateway',
+ apiKey: 'sk-base-gateway-key',
+ baseURL: 'https://gateway.example.com/v1',
+ models: { default: ['gpt-4o'] },
+ },
+ ],
+ },
+ ],
+ { priority: 99 },
+ yamlHandlers,
+ );
+ expect(baseKeyed.statusCode).toBe(200);
+
+ /** Base merges first, so a profile below its priority still lands over it. */
+ const moved = await patch(
+ nextPrincipalId(),
+ [
+ {
+ fieldPath: 'endpoints.custom',
+ value: [{ name: 'Gateway', baseURL: 'https://attacker.example/v1' }],
+ },
+ ],
+ { priority: 1 },
+ yamlHandlers,
+ );
+
+ expect(moved.statusCode).toBe(200);
+ expect(moved.body!.ignored).toEqual([
+ {
+ path: 'endpoints.custom["Gateway"].apiKey',
+ segments: ['endpoints', 'custom', 'Gateway', 'apiKey'],
+ reason: 'secret_rebinding',
+ },
+ ]);
+ });
+
+ it('reports `ignored` over the Base the write was judged on, without reading Base again', async () => {
+ let baseReads = 0;
+ const yamlHandlers = createRealHandlers({
+ getAppConfig: async () => baseAppConfig as never,
+ findConfigByPrincipal: (principalType, principalId, options) => {
+ if (principalId === basePrincipalId) {
+ baseReads += 1;
+ }
+ return configMethods.findConfigByPrincipal(principalType, principalId, options);
+ },
+ });
+ const baseKeyed = await patch(
+ basePrincipalId,
+ [
+ {
+ fieldPath: 'mcpServers.based',
+ value: {
+ type: 'streamable-http',
+ url: 'https://based.example/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: 'sk-base-own-key' },
+ },
+ },
+ ],
+ {},
+ yamlHandlers,
+ );
+ expect(baseKeyed.statusCode).toBe(200);
+ const move = { fieldPath: 'mcpServers.based.url', value: 'https://attacker.example/mcp' };
+ const batch = (dryRun: boolean) =>
+ send(yamlHandlers.applyConfigChanges, {
+ params: { principalType: 'role', principalId: nextPrincipalId() },
+ body: { ops: [{ op: 'set', ...move }], dryRun },
+ });
+
+ /** Each attempt reads Base beside the profile, and a written profile reads it once more. */
+ const requests: Array<[string, () => Promise<MockResponse>, number]> = [
+ ['PATCH', () => patch(nextPrincipalId(), [move], {}, yamlHandlers), 2],
+ ['a written batch', () => batch(false), 2],
+ ['a dry run', () => batch(true), 1],
+ ];
+ for (const [, request, reads] of requests) {
+ baseReads = 0;
+ const res = await request();
+ expect(res.statusCode).toBe(200);
+ expect(res.body!.ignored).toContainEqual({
+ path: 'mcpServers.based.apiKey.key',
+ segments: ['mcpServers', 'based', 'apiKey', 'key'],
+ reason: 'secret_rebinding',
+ });
+ expect(baseReads).toBe(reads);
+ }
+ });
+
+ it('reports the summarization key the Base profile entered once a profile switches provider', async () => {
+ const yamlHandlers = createRealHandlers({
+ getAppConfig: async () => ({ config: {} }) as never,
+ });
+ const baseKeyed = await patch(
+ basePrincipalId,
+ [
+ { fieldPath: 'summarization.provider', value: 'openAI' },
+ { fieldPath: 'summarization.parameters.baseURL', value: 'https://gateway.example/v1' },
+ { fieldPath: 'summarization.parameters.apiKey', value: 'sk-base-gateway-key' },
+ ],
+ {},
+ yamlHandlers,
+ );
+ expect(baseKeyed.statusCode).toBe(200);
+ expect(baseKeyed.body!.ignored).toBeUndefined();
+
+ const switched = await patch(
+ nextPrincipalId(),
+ [{ fieldPath: 'summarization.provider', value: 'anthropic' }],
+ {},
+ yamlHandlers,
+ );
+ expect(switched.statusCode).toBe(200);
+ expect(switched.body!.ignored).toEqual(
+ ['apiKey', 'baseURL'].map((key) => ({
+ path: `summarization.parameters.${key}`,
+ segments: ['summarization', 'parameters', key],
+ reason: 'secret_rebinding',
+ })),
+ );
+ });
+
+ it('reports what a field removal or a tombstone drops', async () => {
+ const yamlHandlers = createRealHandlers({ getAppConfig: async () => baseAppConfig as never });
+ const principalId = nextPrincipalId();
+ const seeded = await patch(
+ principalId,
+ [ownKey, { fieldPath: 'mcpServers.tools.url', value: 'https://profile.example/mcp' }],
+ {},
+ yamlHandlers,
+ );
+ expect(seeded.statusCode).toBe(200);
+ expect(seeded.body!.ignored).toBeUndefined();
+
+ /** Without its own key, the profile's URL would carry the librechat.yaml key. */
+ const removed = await send(yamlHandlers.deleteConfigField, {
+ params: { principalType: 'role', principalId },
+ query: { fieldPath: 'mcpServers.tools.apiKey.key' },
+ });
+ expect(removed.statusCode).toBe(200);
+ expect(removed.body!.ignored).toEqual([
+ expect.objectContaining({ path: 'mcpServers.tools.apiKey.key' }),
+ ]);
+
+ /** Removing the proxy changes the route the librechat.yaml key takes. */
+ const tombstoned = await send(yamlHandlers.tombstoneConfigField, {
+ params: { principalType: 'role', principalId: nextPrincipalId() },
+ body: { fieldPath: 'mcpServers.tools.proxy' },
+ });
+ expect(tombstoned.statusCode).toBe(200);
+ expect(tombstoned.body!.ignored).toEqual([
+ expect.objectContaining({ path: 'mcpServers.tools.apiKey.key' }),
+ ]);
+ });
+});
+
+describe('keys bound to the destination beside them (custom endpoints, OCR, speech)', () => {
+ const yaml = {
+ endpoints: {
+ custom: [
+ {
+ name: 'Regional',
+ apiKey: 'user_provided',
+ baseURL: 'https://regional.example.com/v1',
+ models: { default: ['m'] },
+ },
+ ],
+ },
+ };
+ const baseAppConfig = { config: yaml, endpoints: structuredClone(yaml.endpoints) };
+ const yamlHandlers = () =>
+ createRealHandlers({ getAppConfig: async () => structuredClone(baseAppConfig) as never });
+ const shared = (extra: Record<string, unknown> = {}) => ({
+ name: 'Shared',
+ baseURL: 'https://shared.example.com/v1',
+ models: { default: ['m'] },
+ ...extra,
+ });
+ const reentryIssue = (path: string, secretPath: string) => ({
+ path,
+ segments: path.split('.'),
+ code: 'secret_reentry_required',
+ secretPath,
+ });
+
+ /** What the merge serves a profile over Base, decrypted, as `getAppConfig` would. */
+ async function serve(principalId: string): Promise<AppConfigShape> {
+ const { resolveConfigOverrides } = await import('~/app/overrides');
+ const { createEnvReferencePolicy } = await import('~/app/allowlist');
+ const [base, profile] = await Promise.all([
+ configMethods.findConfigByPrincipal(PrincipalType.ROLE, basePrincipalId),
+ configMethods.findConfigByPrincipal(PrincipalType.ROLE, principalId),
+ ]);
+ return resolveConfigOverrides(
+ structuredClone(baseAppConfig) as never,
+ [base, profile].filter((layer) => layer != null),
+ { envPolicy: createEnvReferencePolicy({ config: yaml }) },
+ ) as unknown as AppConfigShape;
+ }
+
+ afterEach(async () => {
+ await mongoose.models.Config.deleteOne({ principalId: basePrincipalId });
+ });
+
+ it('needs a stored endpoint key again when the document that stores it moves it', async () => {
+ const target = yamlHandlers();
+ const keyed = await patch(
+ basePrincipalId,
+ [{ fieldPath: 'endpoints.custom', value: [shared({ apiKey: 'sk-shared-entered' })] }],
+ {},
+ target,
+ );
+ expect(keyed.statusCode).toBe(200);
+ const before = await readRawOverrides(basePrincipalId);
+ const moved = shared({ baseURL: 'https://attacker.example/v1' });
+
+ const attempts: Array<[string, () => Promise<MockResponse>]> = [
+ [
+ 'PATCH',
+ () =>
+ patch(basePrincipalId, [{ fieldPath: 'endpoints.custom', value: [moved] }], {}, target),
+ ],
+ [
+ 'PUT',
+ () =>
+ send(target.upsertConfigOverrides, {
+ params: { principalType: 'role', principalId: basePrincipalId },
+ body: { overrides: { endpoints: { custom: [moved] } } },
+ }),
+ ],
+ ...[true, false].map((dryRun): [string, () => Promise<MockResponse>] => [
+ `/changes${dryRun ? ' (dry run)' : ''}`,
+ () =>
+ send(target.applyConfigChanges, {
+ params: { principalType: 'role', principalId: basePrincipalId },
+ body: {
+ ops: [{ op: 'upsertEntry', fieldPath: 'endpoints.custom', entry: moved }],
+ dryRun,
+ },
+ }),
+ ]),
+ ];
+ for (const [, attempt] of attempts) {
+ const res = await attempt();
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toMatchObject({
+ code: 'CONFIG_SECRET_REENTRY_REQUIRED',
+ issues: [reentryIssue('endpoints.custom.0.baseURL', 'endpoints.custom.0.apiKey')],
+ });
+ }
+ expect(await readRawOverrides(basePrincipalId)).toEqual(before);
+
+ const provider = await patch(
+ basePrincipalId,
+ [{ fieldPath: 'endpoints.custom', value: [shared({ provider: 'anthropic' })] }],
+ {},
+ target,
+ );
+ expect(provider.statusCode).toBe(400);
+ expect(provider.body!.issues).toEqual([
+ reentryIssue('endpoints.custom.0.provider', 'endpoints.custom.0.apiKey'),
+ ]);
+
+ const edited = await patch(
+ basePrincipalId,
+ [{ fieldPath: 'endpoints.custom', value: [shared({ models: { default: ['m', 'n'] } })] }],
+ {},
+ target,
+ );
+ expect(edited.statusCode).toBe(200);
+ const entry = (await readRawOverrides(basePrincipalId)) as {
+ endpoints: { custom: Array<Record<string, unknown>> };
+ };
+ expect(entry.endpoints.custom[0].apiKey).toBe(
+ (before as { endpoints: { custom: Array<Record<string, unknown>> } }).endpoints.custom[0]
+ .apiKey,
+ );
+
+ const reentered = await patch(
+ basePrincipalId,
+ [{ fieldPath: 'endpoints.custom', value: [{ ...moved, apiKey: 'sk-shared-again' }] }],
+ {},
+ target,
+ );
+ expect(reentered.statusCode).toBe(200);
+ });
+
+ it('needs a stored OCR or speech key again when the document moves it, by any route', async () => {
+ const target = yamlHandlers();
+ const principalId = nextPrincipalId();
+ const keyed = await patch(
+ principalId,
+ [
+ {
+ fieldPath: 'ocr',
+ value: { apiKey: 'sk-ocr-entered', baseURL: 'https://ocr.example.com/v1' },
+ },
+ {
+ fieldPath: 'speech.tts.openai',
+ value: {
+ apiKey: 'sk-tts-entered',
+ url: 'https://tts.example.com/v1',
+ model: 'tts-1',
+ voices: ['alloy'],
+ },
+ },
+ ],
+ {},
+ target,
+ );
+ expect(keyed.statusCode).toBe(200);
+ const before = await readRawOverrides(principalId);
+ const params = { principalType: 'role', principalId };
+
+ const attempts: Array<[() => Promise<MockResponse>, string, string]> = [
+ [
+ () =>
+ patch(
+ principalId,
+ [{ fieldPath: 'ocr.baseURL', value: 'https://attacker.example/v1' }],
+ {},
+ target,
+ ),
+ 'ocr.baseURL',
+ 'ocr.apiKey',
+ ],
+ [
+ () => send(target.deleteConfigField, { params, query: { fieldPath: 'ocr.baseURL' } }),
+ 'ocr.baseURL',
+ 'ocr.apiKey',
+ ],
+ [
+ () => send(target.tombstoneConfigField, { params, body: { fieldPath: 'ocr.baseURL' } }),
+ 'ocr.baseURL',
+ 'ocr.apiKey',
+ ],
+ [
+ () =>
+ patch(
+ principalId,
+ [{ fieldPath: 'speech.tts.openai.url', value: 'https://attacker.example/v1' }],
+ {},
+ target,
+ ),
+ 'speech.tts.openai.url',
+ 'speech.tts.openai.apiKey',
+ ],
+ ];
+ for (const [attempt, path, secretPath] of attempts) {
+ const res = await attempt();
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toMatchObject({
+ code: 'CONFIG_SECRET_REENTRY_REQUIRED',
+ issues: [reentryIssue(path, secretPath)],
+ });
+ }
+ expect(await readRawOverrides(principalId)).toEqual(before);
+
+ const removed = await send(target.deleteConfigField, {
+ params,
+ query: { fieldPath: 'ocr.apiKey' },
+ });
+ expect(removed.statusCode).toBe(200);
+ const moved = await patch(
+ principalId,
+ [{ fieldPath: 'ocr.baseURL', value: 'https://elsewhere.example/v1' }],
+ {},
+ target,
+ );
+ expect(moved.statusCode).toBe(200);
+ });
+
+ it("binds a profile's own endpoint key to the endpoint Base defines, until Base moves it", async () => {
+ const target = yamlHandlers();
+ const baseKeyed = await patch(
+ basePrincipalId,
+ [{ fieldPath: 'endpoints.custom', value: [shared({ apiKey: 'sk-base-shared' })] }],
+ {},
+ target,
+ );
+ expect(baseKeyed.statusCode).toBe(200);
+
+ const principalId = nextPrincipalId();
+ const keyed = await patch(
+ principalId,
+ [
+ {
+ fieldPath: 'endpoints.custom',
+ value: [{ name: 'Shared', apiKey: 'sk-role-shared', apiKeyBinding: 'f'.repeat(64) }],
+ },
+ ],
+ {},
+ target,
+ );
+ expect(keyed.statusCode).toBe(200);
+ expect(keyed.body!.ignored).toBeUndefined();
+ const stored = (await readRawOverrides(principalId)) as {
+ endpoints: { custom: Array<Record<string, unknown>> };
+ };
+ const [entry] = stored.endpoints.custom;
+ expect(entry.apiKeyBinding).toMatch(/^[0-9a-f]{64}$/);
+ expect(entry.apiKeyBinding).not.toBe('f'.repeat(64));
+ expect(JSON.stringify(keyed.body)).not.toContain('apiKeyBinding');
+
+ const read = await send(target.getConfig, { params: { principalType: 'role', principalId } });
+ expect(JSON.stringify(read.body)).not.toContain('apiKeyBinding');
+ const servedEntry = (await serve(principalId)).endpoints?.custom?.find(
+ ({ name }) => name === 'Shared',
+ );
+ expect(servedEntry).toMatchObject({ baseURL: 'https://shared.example.com/v1' });
+ expect(decryptV3(servedEntry!.apiKey as string)).toBe('sk-role-shared');
+
+ /** A write that keeps the key, a round trip of what a read returns included, keeps its binding. */
+ const roundTrip = await send(target.upsertConfigOverrides, {
+ params: { principalType: 'role', principalId },
+ body: { overrides: (read.body!.config as { overrides: Record<string, unknown> }).overrides },
+ });
+ expect(roundTrip.statusCode).toBe(200);
+ expect(roundTrip.body!.ignored).toBeUndefined();
+ const kept = (await readRawOverrides(principalId)) as typeof stored;
+ expect(kept.endpoints.custom[0]).toMatchObject({
+ apiKey: entry.apiKey,
+ apiKeyBinding: entry.apiKeyBinding,
+ });
+
+ const baseMoved = await patch(
+ basePrincipalId,
+ [
+ {
+ fieldPath: 'endpoints.custom',
+ value: [shared({ baseURL: 'https://attacker.example/v1', apiKey: 'sk-base-again' })],
+ },
+ ],
+ {},
+ target,
+ );
+ expect(baseMoved.statusCode).toBe(200);
+ const dropped = (await serve(principalId)).endpoints?.custom?.find(
+ ({ name }) => name === 'Shared',
+ );
+ expect(dropped).toMatchObject({ apiKey: '', baseURL: 'https://attacker.example/v1' });
+ const reported = await send(target.applyConfigChanges, {
+ params: { principalType: 'role', principalId },
+ body: {
+ ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' }],
+ dryRun: true,
+ },
+ });
+ expect(reported.statusCode).toBe(200);
+ expect(reported.body!.ignored).toEqual([
+ {
+ path: 'endpoints.custom["Shared"].apiKey',
+ segments: ['endpoints', 'custom', 'Shared', 'apiKey'],
+ reason: 'secret_rebinding',
+ },
+ ]);
+
+ /** Entering the key again over the moved endpoint binds it there. */
+ const rekeyed = await patch(
+ principalId,
+ [{ fieldPath: 'endpoints.custom', value: [{ name: 'Shared', apiKey: 'sk-role-again' }] }],
+ {},
+ target,
+ );
+ expect(rekeyed.statusCode).toBe(200);
+ expect(rekeyed.body!.ignored).toBeUndefined();
+ const rebound = (await serve(principalId)).endpoints?.custom?.find(
+ ({ name }) => name === 'Shared',
+ );
+ expect(rebound).toMatchObject({ baseURL: 'https://attacker.example/v1' });
+ expect(decryptV3(rebound!.apiKey as string)).toBe('sk-role-again');
+ expect(JSON.stringify(await readRawOverrides(basePrincipalId))).not.toContain('apiKeyBinding');
+ });
+
+ it("sets back the destination of a user_provided endpoint a profile moves, so users' keys stay", async () => {
+ const target = yamlHandlers();
+ const principalId = nextPrincipalId();
+ const moved = await patch(
+ principalId,
+ [
+ {
+ fieldPath: 'endpoints.custom',
+ value: [{ name: 'Regional', baseURL: 'https://attacker.example/v1' }],
+ },
+ ],
+ {},
+ target,
+ );
+ expect(moved.statusCode).toBe(200);
+ expect(moved.body!.ignored).toEqual([
+ {
+ path: 'endpoints.custom["Regional"].baseURL',
+ segments: ['endpoints', 'custom', 'Regional', 'baseURL'],
+ reason: 'secret_rebinding',
+ },
+ ]);
+ const served = (await serve(principalId)).endpoints?.custom?.find(
+ ({ name }) => name === 'Regional',
+ );
+ expect(served).toMatchObject({
+ apiKey: 'user_provided',
+ baseURL: 'https://regional.example.com/v1',
+ });
+ });
+});
+
+/**
+ * Every handler `createAdminConfigHandlers` returns, by what it can write. A handler that changes
+ * what a document holds must run the guards PUT and PATCH run: the MCP re-entry rule, the env
+ * reference allowlist on every value it takes, and the `ignored` report. A handler added later (a
+ * batch route, a keyed collection op) fails the first test until it is listed here with the
+ * requests that attempt each.
+ */
+describe('write guards on every handler that changes a document', () => {
+ const STORED_URL = 'https://mcp.example.com/mcp';
+ const EVIL_URL = 'https://evil.example/mcp';
+ const UNLISTED_URL = 'https://h.example/${LC8_UNLISTED_NAME}';
+ const yaml = {
+ mcpServers: {
+ tools: {
+ type: 'streamable-http',
+ url: 'https://tools.example.com/mcp',
+ proxy: 'http://proxy.corp.example:8080',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: '${TOOLS_KEY}' },
+ },
+ },
+ };
+ const yamlHandlers = (): AdminConfigHandlers =>
+ createRealHandlers({
+ getAppConfig: async () =>
+ ({ config: yaml, mcpConfig: structuredClone(yaml.mcpServers) }) as never,
+ });
+
+ /** The seeded server as a read returns it: without the credentials. */
+ const redactedServer = (url: string) => ({
+ type: 'streamable-http',
+ url,
+ apiKey: { source: 'admin', authorization_type: 'bearer' },
+ oauth: {
+ client_id: 'client',
+ authorization_url: 'https://auth.example.com/authorize',
+ token_url: 'https://auth.example.com/token',
+ },
+ });
+ const at = (principalId: string) => ({ principalType: 'role', principalId });
+
+ type Attempt = (target: AdminConfigHandlers, principalId: string) => Promise<MockResponse>;
+
+ interface ContentWriter {
+ /** Points the seeded server `github`, whose credentials are stored, at `EVIL_URL`. */
+ move: Attempt;
+ /** Writes `UNLISTED_URL` as `github`'s URL; `null` for a handler that takes no values. */
+ envReference: Attempt | null;
+ /**
+ * Leaves librechat.yaml's `tools` sending its `${TOOLS_KEY}` somewhere librechat.yaml did not
+ * choose, without a key of its own (seeding what it removes first).
+ */
+ rebind: Attempt;
+ }
+
+ const CONTENT_WRITERS: Record<string, ContentWriter> = {
+ upsertConfigOverrides: {
+ move: (target, principalId) =>
+ send(target.upsertConfigOverrides, {
+ params: at(principalId),
+ body: { overrides: { mcpServers: { github: redactedServer(EVIL_URL) } } },
+ }),
+ envReference: (target, principalId) =>
+ send(target.upsertConfigOverrides, {
+ params: at(principalId),
+ body: { overrides: { mcpServers: { github: redactedServer(UNLISTED_URL) } } },
+ }),
+ rebind: (target, principalId) =>
+ send(target.upsertConfigOverrides, {
+ params: at(principalId),
+ body: { overrides: { mcpServers: { tools: { url: EVIL_URL } } } },
+ }),
+ },
+ patchConfigField: {
+ move: (target, principalId) =>
+ patch(principalId, [{ fieldPath: 'mcpServers.github.url', value: EVIL_URL }], {}, target),
+ envReference: (target, principalId) =>
+ patch(
+ principalId,
+ [{ fieldPath: 'mcpServers.github.url', value: UNLISTED_URL }],
+ {},
+ target,
+ ),
+ rebind: (target, principalId) =>
+ patch(principalId, [{ fieldPath: 'mcpServers.tools.url', value: EVIL_URL }], {}, target),
+ },
+ deleteConfigField: {
+ move: (target, principalId) =>
+ send(target.deleteConfigField, {
+ params: at(principalId),
+ query: { fieldPath: 'mcpServers.github.url' },
+ }),
+ envReference: null,
+ rebind: async (target, principalId) => {
+ const keyed = await patch(
+ principalId,
+ [
+ {
+ fieldPath: 'mcpServers.tools.apiKey',
+ value: { source: 'admin', authorization_type: 'bearer', key: 'sk-profile-own-key' },
+ },
+ { fieldPath: 'mcpServers.tools.url', value: EVIL_URL },
+ ],
+ {},
+ target,
+ );
+ expect(keyed.statusCode).toBe(200);
+ expect(keyed.body!.ignored).toBeUndefined();
+ return send(target.deleteConfigField, {
+ params: at(principalId),
+ query: { fieldPath: 'mcpServers.tools.apiKey.key' },
+ });
+ },
+ },
+ tombstoneConfigField: {
+ move: (target, principalId) =>
+ send(target.tombstoneConfigField, {
+ params: at(principalId),
+ body: { fieldPath: 'mcpServers.github.url' },
+ }),
+ envReference: null,
+ rebind: (target, principalId) =>
+ send(target.tombstoneConfigField, {
+ params: at(principalId),
+ body: { fieldPath: 'mcpServers.tools.proxy' },
+ }),
+ },
+ applyConfigChanges: {
+ move: (target, principalId) =>
+ send(target.applyConfigChanges, {
+ params: at(principalId),
+ body: { ops: [{ op: 'set', fieldPath: 'mcpServers.github.url', value: EVIL_URL }] },
+ }),
+ envReference: (target, principalId) =>
+ send(target.applyConfigChanges, {
+ params: at(principalId),
+ body: {
+ ops: [
+ { op: 'set', fieldPath: 'mcpServers.github', value: redactedServer(UNLISTED_URL) },
+ ],
+ },
+ }),
+ rebind: (target, principalId) =>
+ send(target.applyConfigChanges, {
+ params: at(principalId),
+ body: { ops: [{ op: 'tombstone', fieldPath: 'mcpServers.tools.proxy' }] },
+ }),
+ },
+ };
+
+ /** Handlers that never change what a document holds, and why the guards do not apply. */
+ const OTHER_HANDLERS: Record<string, string> = {
+ getConfigMeta: 'reads the API contract',
+ listConfigs: 'reads',
+ getBaseConfig: 'reads',
+ getConfig: 'reads',
+ deleteConfigOverrides: 'removes the whole document, credentials and all',
+ toggleConfig: 'switches the document on or off; the merge judges the layers it brings in',
+ updateConfigPriority:
+ 'sets only the priority, keeping overrides and tombstones; the merge judges the order it brings in',
+ };
+
+ it('lists every handler', () => {
+ const listed = new Set([...Object.keys(CONTENT_WRITERS), ...Object.keys(OTHER_HANDLERS)]);
+ expect(Object.keys(handlers).filter((name) => !listed.has(name))).toEqual([]);
+ });
+
+ it('keeps stored credentials through a priority change and answers with their previews only', async () => {
+ const principalId = nextPrincipalId();
+ const seeded = await patch(principalId, [
+ { fieldPath: 'mcpServers.github', value: mcpServer() },
+ ]);
+ expect(seeded.statusCode).toBe(200);
+ const before = await configMethods.findConfigByPrincipal(PrincipalType.ROLE, principalId);
+ const stored = await storedServer(principalId, 'github');
+
+ const res = await send(
+ createRealHandlers({ setConfigPriority: configMethods.setConfigPriority })
+ .updateConfigPriority,
+ { params: at(principalId), body: { priority: 42 } },
+ );
+
+ expect(res.statusCode).toBe(200);
+ const after = await configMethods.findConfigByPrincipal(PrincipalType.ROLE, principalId);
+ expect(after?.priority).toBe(42);
+ expect(after?.overrides).toEqual(before?.overrides);
+ const body = JSON.stringify(res.body);
+ for (const value of [API_KEY, CLIENT_SECRET, stored.apiKey.key, stored.oauth.client_secret]) {
+ expect(body).not.toContain(value);
+ }
+ expect(getAtPath(res.body, 'config.overrides.mcpServers.github.apiKey')).toEqual({
+ source: 'admin',
+ authorization_type: 'bearer',
+ keyPreview: stored.apiKey.keyPreview,
+ });
+ });
+
+ describe.each(Object.entries(CONTENT_WRITERS))('%s', (_name, { move, envReference, rebind }) => {
+ it('refuses sending a stored MCP credential to a new URL without entering it again', async () => {
+ const principalId = nextPrincipalId();
+ const seeded = await patch(principalId, [
+ { fieldPath: 'mcpServers.github', value: mcpServer() },
+ ]);
+ expect(seeded.statusCode).toBe(200);
+
+ const res = await move(handlers, principalId);
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toMatchObject({
+ code: 'MCP_API_KEY_REENTRY_REQUIRED',
+ server: 'github',
+ fields: ['url'],
+ });
+ expect((await storedServer(principalId, 'github')).url).toBe(STORED_URL);
+ });
+
+ if (envReference) {
+ it('refuses an env reference outside the allowlist', async () => {
+ const principalId = nextPrincipalId();
+
+ const res = await envReference(handlers, principalId);
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toMatchObject({
+ code: 'CONFIG_OVERRIDE_INVALID',
+ issues: [
+ {
+ path: 'mcpServers.github.url',
+ segments: ['mcpServers', 'github', 'url'],
+ code: 'env_reference_not_allowed',
+ },
+ ],
+ });
+ expect(await mongoose.models.Config.findOne({ principalId })).toBeNull();
+ });
+ }
+
+ it('reports the inherited key it leaves on another destination in `ignored`', async () => {
+ const res = await rebind(yamlHandlers(), nextPrincipalId());
+
+ expect([200, 201]).toContain(res.statusCode);
+ expect(res.body!.ignored).toEqual([
+ {
+ path: 'mcpServers.tools.apiKey.key',
+ segments: ['mcpServers', 'tools', 'apiKey', 'key'],
+ reason: 'secret_rebinding',
+ },
+ ]);
+ });
+ });
+});
+
+describe('a document an MCP removal creates', () => {
+ it.each([PrincipalType.ROLE, PrincipalType.GROUP, PrincipalType.USER])(
+ 'gets, for a %s, the priority and state the store gives any other tombstone',
+ async (principalType) => {
+ const tombstone = async (fieldPath: string) => {
+ const principalId = new mongoose.Types.ObjectId().toString();
+ const res = await send(handlers.tombstoneConfigField, {
+ params: { principalType, principalId },
+ body: { fieldPath },
+ });
+ expect(res.statusCode).toBe(200);
+ const created = await configMethods.findConfigByPrincipal(principalType, principalId);
+ return {
+ principalModel: created?.principalModel,
+ priority: created?.priority,
+ isActive: created?.isActive,
+ };
+ };
+
+ const mcp = await tombstone('mcpServers.github.url');
+
+ expect(mcp.priority).toEqual(expect.any(Number));
+ expect(mcp).toEqual(await tombstone('ocr.baseURL'));
+ },
+ );
+
+ it.each([PrincipalType.GROUP, PrincipalType.USER])(
+ 'is refused for a %s that does not exist, and an unset finds no document',
+ async (principalType) => {
+ const guarded = createRealHandlers({ principalExists: configMethods.principalExists });
+ const principalId = new mongoose.Types.ObjectId().toString();
+ const params = { principalType, principalId };
+
+ const tombstoned = await send(guarded.tombstoneConfigField, {
+ params,
+ body: { fieldPath: 'mcpServers.github.url' },
+ });
+ const unset = await send(guarded.deleteConfigField, {
+ params,
+ query: { fieldPath: 'mcpServers.github.url' },
+ });
+
+ expect(tombstoned.statusCode).toBe(404);
+ expect(tombstoned.body).toMatchObject({ code: 'PRINCIPAL_NOT_FOUND' });
+ expect(unset.statusCode).toBe(404);
+ expect(unset.body).toEqual({ error: 'Config not found' });
+ expect(await mongoose.models.Config.findOne({ principalId })).toBeNull();
+ },
+ );
+});
+
+describe('getBaseConfig with MCP and Azure credentials', () => {
+ it('never returns a YAML literal or a decrypted override credential', async () => {
+ const appConfig = {
+ mcpConfig: {
+ yaml: { url: 'https://y', apiKey: { key: 'yaml-literal-mcp-key' } },
+ stored: {
+ url: 'https://s',
+ apiKey: { key: 'decrypted-at-merge-key', keyPreview: '...-key' },
+ oauth: { client_secret: '${OAUTH_SECRET}' },
+ },
+ },
+ endpoints: {
+ azureOpenAI: {
+ groups: [{ group: 'east', apiKey: 'yaml-literal-azure-key' }],
+ groupMap: {
+ east: { apiKey: 'yaml-literal-azure-groupmap-key', instanceName: 'east' },
+ env: { apiKey: '${AZURE_ENV_KEY}', instanceName: 'env' },
+ },
+ },
+ },
+ config: {
+ mcpServers: { yaml: { url: 'https://y', apiKey: { key: 'yaml-literal-mcp-key' } } },
+ },
+ };
+ const baseHandlers = createRealHandlers({ getAppConfig: async () => appConfig as never });
+
+ const res = await send(baseHandlers.getBaseConfig, { query: { baseOnly: 'true' } });
+
+ expect(res.statusCode).toBe(200);
+ const payload = JSON.stringify(res.body);
+ for (const secret of ['yaml-literal-mcp-key', 'decrypted-at-merge-key', 'yaml-literal-azure']) {
+ expect(payload).not.toContain(secret);
+ }
+ const config = res.body!.config as Record<string, unknown>;
+ expect(getAtPath(config, 'mcpConfig.yaml.apiKey.keyPreview')).toBe(UNPREVIEWED_SECRET_MASK);
+ expect(getAtPath(config, 'mcpConfig.stored.apiKey.keyPreview')).toBe('...-key');
+ expect(getAtPath(config, 'mcpConfig.stored.oauth.client_secret')).toBe('${OAUTH_SECRET}');
+ expect(getAtPath(config, 'config.mcpServers.yaml.apiKey.keyPreview')).toBe(
+ UNPREVIEWED_SECRET_MASK,
+ );
+ expect(getAtPath(config, 'endpoints.azureOpenAI.groupMap')).toEqual({
+ east: { apiKeyPreview: UNPREVIEWED_SECRET_MASK, instanceName: 'east' },
+ env: { apiKey: '${AZURE_ENV_KEY}', instanceName: 'env' },
+ });
+ });
+});
diff --git a/packages/api/src/admin/secrets.runtime.spec.ts b/packages/api/src/admin/secrets.runtime.spec.ts
index 83105877c3..6c695f8c36 100644
--- a/packages/api/src/admin/secrets.runtime.spec.ts
+++ b/packages/api/src/admin/secrets.runtime.spec.ts
@@ -4,16 +4,30 @@ import { tmpdir } from 'node:os';
import { readFileSync } from 'node:fs';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { loadWebSearchConfig } from '@librechat/data-schemas';
-import { RerankerTypes, SearchProviders, ScraperProviders } from 'librechat-data-provider';
+import {
+ PrincipalType,
+ RerankerTypes,
+ SearchProviders,
+ ScraperProviders,
+ mapModelToAzureConfig,
+} from 'librechat-data-provider';
import type {
AppConfig,
TWebSearchKeys,
+ ConfigOverrideLayer,
AdminConfigArraySecretFieldRule,
} from '@librechat/data-schemas';
import type { TWebSearchConfigInput } from 'librechat-data-provider';
import type { AddressInfo } from 'node:net';
-import { encryptConfigSecretFields, getConfigSecretRules } from './secrets';
+import {
+ resolveConfigSecret,
+ isOpaqueSecretInput,
+ getConfigSecretRules,
+ encryptConfigSecretFields,
+} from './secrets';
+import { createEnvReferencePolicy, neutralizeEnvReferences } from '~/app/allowlist';
import { resolveTenantCredentials } from '~/langfuse/utils';
+import { resolveConfigOverrides } from '~/app/overrides';
import { uploadMistralOCR } from '~/files/mistral/crud';
import { getCustomEndpointConfig } from '~/app/config';
import { loadWebSearchAuth } from '~/web';
@@ -26,7 +40,7 @@ jest.mock('@librechat/data-schemas', () => {
const REPO_ROOT = join(__dirname, '../../../..');
const DECRYPTING_CALL =
- /\b(?:resolveConfigSecret|resolveStoredConfigSecret|decryptConfigSecret|resolveCustomEndpointSecrets)\(/;
+ /\b(?:resolveConfigSecret|resolveStoredConfigSecret|decryptConfigSecret|resolveCustomEndpointSecrets|resolveRuntimeConfigSecrets)\(/;
interface RuntimeReader {
/** Repo-relative module that reads the merged config value when the feature runs. */
@@ -112,8 +126,148 @@ async function sendOCRUpload(stored: string): Promise<string | undefined> {
}
const CUSTOM_ENDPOINT_NAME = 'runtime-reader';
+/** The entry a record secret is stored on: an MCP server, or an Azure group. */
+const RECORD_ENTRY_NAME = 'runtime-reader';
+const ENTRY = '*';
-const { secretFields, arraySecretFields } = getConfigSecretRules();
+const { secretFields, arraySecretFields, recordSecretFields } = getConfigSecretRules();
+
+/** Record secrets are listed as `<recordPath>.*.<secretPath>`, `*` standing for the entry name. */
+const RECORD_SECRET_PATHS = recordSecretFields.map(
+ ({ recordPath, secretPath }) => `${recordPath}.${ENTRY}.${secretPath}`,
+);
+
+/**
+ * Merges a role profile that stores one credential of an MCP server, as the admin config API
+ * stores it, through the same override pipeline `getAppConfig` runs, and returns what the
+ * resolved `mcpConfig` hands MCP connections.
+ */
+function mcpServerReader(secretPath: string): RuntimeReader {
+ const [parent, key] = secretPath.split('.') as ['apiKey' | 'oauth', string];
+ const server = {
+ type: 'streamable-http',
+ url: 'https://mcp.example.com/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer' },
+ oauth: {
+ client_id: 'runtime-reader',
+ authorization_url: 'https://auth.example.com/authorize',
+ token_url: 'https://auth.example.com/token',
+ },
+ } as const;
+ return {
+ module: 'packages/api/src/app/service.ts',
+ probe: async (stored) => {
+ const overrides = {
+ mcpServers: {
+ [RECORD_ENTRY_NAME]: { ...server, [parent]: { ...server[parent], [key]: stored } },
+ },
+ };
+ const layer = {
+ principalType: PrincipalType.ROLE,
+ principalId: 'runtime-reader',
+ priority: 10,
+ overrides,
+ };
+ const resolved = resolveConfigOverrides({} as AppConfig, [layer], {
+ envPolicy: createEnvReferencePolicy({}),
+ });
+ const credentials = resolved.mcpConfig?.[RECORD_ENTRY_NAME]?.[parent];
+ return (credentials as Record<string, string | undefined> | undefined)?.[key];
+ },
+ };
+}
+
+/**
+ * Merges a role profile that stores an Azure group's key in `groupMap`, as the admin config API
+ * stores it, through the same override pipeline `getAppConfig` runs, and returns the key the
+ * Azure client options are built with (`mapModelToAzureConfig`, as `endpoints/openai` calls it).
+ */
+const azureGroupMapReader: RuntimeReader = {
+ module: 'packages/api/src/app/service.ts',
+ probe: async (stored) => {
+ const model = 'gpt-4o';
+ /** `groupMap` is not a librechat.yaml key; an override writes it as an unknown one. */
+ const overrides: Record<string, unknown> = {
+ endpoints: {
+ azureOpenAI: {
+ groupMap: {
+ [RECORD_ENTRY_NAME]: {
+ apiKey: stored,
+ instanceName: 'runtime-reader',
+ version: '2024-10-21',
+ models: { [model]: { deploymentName: model } },
+ },
+ },
+ modelGroupMap: { [model]: { group: RECORD_ENTRY_NAME } },
+ },
+ },
+ };
+ const layer = {
+ principalType: PrincipalType.ROLE,
+ principalId: 'runtime-reader',
+ priority: 10,
+ overrides,
+ } as ConfigOverrideLayer;
+ const resolved = resolveConfigOverrides({} as AppConfig, [layer], {
+ envPolicy: createEnvReferencePolicy({}),
+ });
+ const azure = resolved.endpoints?.azureOpenAI;
+ if (!azure) {
+ return undefined;
+ }
+ const { groupMap, modelGroupMap } = azure;
+ return mapModelToAzureConfig({ modelName: model, modelGroupMap, groupMap }).azureOptions
+ .azureOpenAIApiKey;
+ },
+};
+
+/**
+ * Merges a role profile that stores an Azure group in `groups`, as the admin config API stores it,
+ * through the same override pipeline `getAppConfig` runs, and returns the key the Azure client
+ * options are built with: the merge resolves the profile's groups into the `groupMap` it reads.
+ */
+const azureGroupsReader: RuntimeReader = {
+ module: 'packages/api/src/app/service.ts',
+ probe: async (stored) => {
+ const model = 'gpt-4o';
+ const layer = {
+ principalType: PrincipalType.ROLE,
+ principalId: 'runtime-reader',
+ priority: 10,
+ overrides: {
+ endpoints: {
+ azureOpenAI: {
+ groups: [
+ {
+ group: CUSTOM_ENDPOINT_NAME,
+ apiKey: stored,
+ instanceName: 'runtime-reader',
+ version: '2024-10-21',
+ models: { [model]: { deploymentName: model } },
+ },
+ ],
+ },
+ },
+ },
+ } as ConfigOverrideLayer;
+ const resolved = resolveConfigOverrides({} as AppConfig, [layer], {
+ envPolicy: createEnvReferencePolicy({}),
+ });
+ const azure = resolved.endpoints?.azureOpenAI;
+ if (!azure?.groupMap || !azure.modelGroupMap) {
+ return undefined;
+ }
+ const { groupMap, modelGroupMap } = azure;
+ return mapModelToAzureConfig({ modelName: model, modelGroupMap, groupMap }).azureOptions
+ .azureOpenAIApiKey;
+ },
+};
+
+/** The runtime reader of each record a record secret is registered on. */
+const RECORD_READERS: Readonly<Record<string, (secretPath: string) => RuntimeReader>> = {
+ mcpServers: mcpServerReader,
+ 'endpoints.azureOpenAI.groupMap': () => azureGroupMapReader,
+};
/** Array-item secrets are listed as `<arrayPath>[].<secretKey>`. */
const ARRAY_SECRET_FIELDS = new Map<string, AdminConfigArraySecretFieldRule>(
@@ -124,7 +278,11 @@ const ARRAY_SECRET_FIELDS = new Map<string, AdminConfigArraySecretFieldRule>(
function storeSecret(path: string, secret: string): unknown {
const arrayField = ARRAY_SECRET_FIELDS.get(path);
if (!arrayField) {
- return encryptConfigSecretFields({ [path]: secret })[path];
+ const fieldPath = path
+ .split('.')
+ .map((segment) => (segment === ENTRY ? RECORD_ENTRY_NAME : segment))
+ .join('.');
+ return encryptConfigSecretFields({ [fieldPath]: secret })[fieldPath];
}
const { arrayPath, identityKey, secretKey } = arrayField;
const item = { [identityKey]: CUSTOM_ENDPOINT_NAME, [secretKey]: secret };
@@ -173,6 +331,7 @@ const RUNTIME_READERS: Readonly<Record<string, RuntimeReader>> = {
'webSearch.cohereApiKey': webSearchReader('cohereApiKey', {
rerankerType: RerankerTypes.COHERE,
}),
+ 'endpoints.azureOpenAI.groups[].apiKey': azureGroupsReader,
'endpoints.custom[].apiKey': {
module: 'packages/api/src/app/config.ts',
probe: async (stored) => {
@@ -188,6 +347,12 @@ const RUNTIME_READERS: Readonly<Record<string, RuntimeReader>> = {
return getCustomEndpointConfig({ endpoint: CUSTOM_ENDPOINT_NAME, appConfig })?.apiKey;
},
},
+ ...Object.fromEntries(
+ recordSecretFields.flatMap(({ recordPath, secretPath }, index) => {
+ const reader = RECORD_READERS[recordPath];
+ return reader ? [[RECORD_SECRET_PATHS[index], reader(secretPath)]] : [];
+ }),
+ ),
};
/**
@@ -214,7 +379,11 @@ describe('config secret registry runtime readers', () => {
await new Promise<void>((resolve) => ocrProvider.server.close(() => resolve()));
});
- const registered = [...secretFields.map(({ path }) => path), ...ARRAY_SECRET_FIELDS.keys()];
+ const registered = [
+ ...secretFields.map(({ path }) => path),
+ ...ARRAY_SECRET_FIELDS.keys(),
+ ...RECORD_SECRET_PATHS,
+ ];
it('pairs every registered secret path with a runtime reader or a documented gap', () => {
const listed = [...Object.keys(RUNTIME_READERS), ...Object.keys(UNREAD_SECRET_FIELDS)];
@@ -238,4 +407,50 @@ describe('config secret registry runtime readers', () => {
expect(stored).toMatch(/^v3:/);
await expect(probe(stored as string)).resolves.toBe(secret);
});
+
+ describe('opaque keys, which the env allowlist leaves alone', () => {
+ const VARIABLE = 'LC8_RUNTIME_OPAQUE_VARIABLE';
+ /** A credential that contains a reference to a variable the environment sets. */
+ const credential = (path: string) => `${path}-pa\${${VARIABLE}}ss`;
+ const isOpaque = (path: string) => isOpaqueSecretInput(path.split('.'), 'credential');
+
+ beforeEach(() => {
+ process.env[VARIABLE] = 'expanded';
+ });
+ afterEach(() => {
+ delete process.env[VARIABLE];
+ });
+
+ it.each(
+ Object.entries(RUNTIME_READERS).flatMap(([path, { probe }]) =>
+ probe && isOpaque(path) ? [[path, probe]] : [],
+ ),
+ )('%s reaches its reader as entered through the runtime env pass', async (path, probe) => {
+ const segments = path.split('.');
+ const layer = segments.reduceRight<unknown>(
+ (value, key) => ({ [key]: value }),
+ storeSecret(path, credential(path)),
+ );
+ const neutralized = neutralizeEnvReferences(layer, createEnvReferencePolicy({}));
+ const stored = segments.reduce<unknown>(
+ (value, key) => (value as Record<string, unknown>)[key],
+ neutralized,
+ );
+
+ await expect(probe(stored as string)).resolves.toBe(credential(path));
+ });
+
+ it.each(
+ Object.entries(RUNTIME_READERS).flatMap(([path, { module, probe }]) =>
+ !probe && isOpaque(path) ? [[path, module]] : [],
+ ),
+ )('%s reaches %s through resolveConfigSecret, which reads ciphertext as is', (path, module) => {
+ const source = readFileSync(join(REPO_ROOT, module), 'utf8');
+
+ expect(source).not.toMatch(/extractEnvVariable\([^)]*apiKey/);
+ expect(resolveConfigSecret(storeSecret(path, credential(path)) as string)).toBe(
+ credential(path),
+ );
+ });
+ });
});
diff --git a/packages/api/src/admin/secrets.spec.ts b/packages/api/src/admin/secrets.spec.ts
index f45d750323..9239881463 100644
--- a/packages/api/src/admin/secrets.spec.ts
+++ b/packages/api/src/admin/secrets.spec.ts
@@ -23,7 +23,12 @@ let resolveConfigSecret: typeof import('./secrets').resolveConfigSecret;
let resolveStoredConfigSecret: typeof import('./secrets').resolveStoredConfigSecret;
let getConfigSecretRules: typeof import('./secrets').getConfigSecretRules;
let resolveCustomEndpointSecrets: typeof import('./secrets').resolveCustomEndpointSecrets;
+let resolveRuntimeConfigSecrets: typeof import('./secrets').resolveRuntimeConfigSecrets;
+let carryRenamedConfigSecrets: typeof import('./secrets').carryRenamedConfigSecrets;
+let isConfigSecretPreservablePatch: typeof import('./secrets').isConfigSecretPreservablePatch;
+let UNPREVIEWED_SECRET_MASK: string;
let decryptV3: typeof import('@librechat/data-schemas').decryptV3;
+let encryptV3: typeof import('@librechat/data-schemas').encryptV3;
beforeAll(async () => {
({
@@ -47,8 +52,12 @@ beforeAll(async () => {
resolveStoredConfigSecret,
getConfigSecretRules,
resolveCustomEndpointSecrets,
+ resolveRuntimeConfigSecrets,
+ carryRenamedConfigSecrets,
+ isConfigSecretPreservablePatch,
+ UNPREVIEWED_SECRET_MASK,
} = await import('./secrets'));
- ({ decryptV3 } = await import('@librechat/data-schemas'));
+ ({ decryptV3, encryptV3 } = await import('@librechat/data-schemas'));
});
describe('Langfuse config secrets', () => {
@@ -222,7 +231,7 @@ describe('Langfuse config secrets', () => {
});
});
- it('previews a stored plaintext secret only when reading stored overrides', () => {
+ it('previews a stored plaintext secret by its value only when reading stored overrides', () => {
const encrypted = encryptConfigSecretFields({ 'webSearch.serperApiKey': 'serper-key-00001' });
const stored = () => ({
webSearch: {
@@ -236,16 +245,25 @@ describe('Langfuse config secrets', () => {
},
});
+ /** Ciphertext without a stored preview, and every value outside stored overrides, gets the
+ * fixed mask, which derives nothing from the value. */
expect(redactConfigSecrets(stored(), { previewPlaintext: true })).toEqual({
webSearch: {
keenableApiKeyPreview: '...0002',
searxngApiKeyPreview: '*****',
tavilyApiKeyPreview: '...kept',
+ serperApiKeyPreview: UNPREVIEWED_SECRET_MASK,
jinaApiKey: '${JINA_API_KEY}',
},
});
expect(redactConfigSecrets(stored())).toEqual({
- webSearch: { tavilyApiKeyPreview: '...kept', jinaApiKey: '${JINA_API_KEY}' },
+ webSearch: {
+ keenableApiKeyPreview: UNPREVIEWED_SECRET_MASK,
+ searxngApiKeyPreview: UNPREVIEWED_SECRET_MASK,
+ tavilyApiKeyPreview: '...kept',
+ serperApiKeyPreview: UNPREVIEWED_SECRET_MASK,
+ jinaApiKey: '${JINA_API_KEY}',
+ },
});
});
@@ -326,6 +344,8 @@ describe('Config secret registry fields', () => {
expect([...getConfigSecretSections()].sort()).toEqual([
'endpoints',
'langfuse',
+ 'mcpConfig',
+ 'mcpServers',
'ocr',
'speech',
'webSearch',
@@ -700,7 +720,10 @@ describe('Config secret registry fields', () => {
expect(isConfigSecretAncestorPath('endpoints')).toBe(true);
expect(isConfigSecretAncestorPath('endpoints.custom')).toBe(false);
expect(isConfigSecretAncestorPath('endpoints.assistants')).toBe(true);
- expect(isConfigSecretAncestorPath('endpoints.azureOpenAI')).toBe(false);
+ /** The container of the Azure group array secret. */
+ expect(isConfigSecretAncestorPath('endpoints.azureOpenAI')).toBe(true);
+ expect(isConfigSecretAncestorPath('endpoints.azureOpenAI.groups')).toBe(false);
+ expect(isConfigSecretAncestorPath('endpoints.google')).toBe(false);
expect(
getSecretAncestorPatterns(['speech.tts.openai.apiKey', 'endpoints.custom']).sort(),
@@ -1126,9 +1149,14 @@ describe('Custom endpoint config secrets', () => {
expect(a.apiKey).toBeUndefined();
expect(a.apiKeyPreview).toBe('**********');
expect(b.apiKey).toBeUndefined();
+ /** No stored preview: the fixed mask says a key is set without deriving anything from it. */
+ expect(b.apiKeyPreview).toBe(UNPREVIEWED_SECRET_MASK);
expect(c.apiKey).toBe('user_provided');
+ expect(c.apiKeyPreview).toBeUndefined();
expect(d.apiKey).toBe('${OPENROUTER_KEY}');
+ expect(d.apiKeyPreview).toBeUndefined();
expect(e.apiKey).toBe('');
+ expect(e.apiKeyPreview).toBeUndefined();
});
it('resolves stored values for runtime use', () => {
@@ -1148,6 +1176,575 @@ describe('Custom endpoint config secrets', () => {
});
});
+describe('MCP server secrets (record registry)', () => {
+ type Server = {
+ url?: string;
+ apiKey?: Record<string, string>;
+ oauth?: Record<string, string>;
+ };
+ const server = (overrides: Server = {}): Server => ({
+ url: 'https://mcp.example.com/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: 'sk-mcp-super-secret-key' },
+ oauth: {
+ client_id: 'client',
+ client_secret: 'oauth-client-secret-value',
+ authorization_url: 'https://auth.example.com/authorize',
+ token_url: 'https://auth.example.com/token',
+ },
+ ...overrides,
+ });
+ const serversOf = (root: unknown) =>
+ (root as { mcpServers: Record<string, Server> }).mcpServers as Record<string, Server>;
+
+ it('encrypts both credentials on whole-document writes, with masked previews', () => {
+ const out = serversOf(encryptConfigSecrets({ mcpServers: { github: server() } })).github;
+
+ expect(decryptV3(out.apiKey!.key)).toBe('sk-mcp-super-secret-key');
+ expect(out.apiKey!.keyPreview).toBe('...-key');
+ expect(decryptV3(out.oauth!.client_secret)).toBe('oauth-client-secret-value');
+ expect(out.oauth!.client_secretPreview).toBe('...alue');
+ expect(out.url).toBe('https://mcp.example.com/mcp');
+ });
+
+ it('encrypts object writes at every level of a field map, and the dotted secret path', () => {
+ const out = encryptConfigSecretFields({
+ mcpServers: { a: server() },
+ 'mcpServers.b': server(),
+ 'mcpServers.c.apiKey': { source: 'admin', authorization_type: 'bearer', key: 'sk-c-key' },
+ 'mcpServers.d.oauth': { client_id: 'x', client_secret: 'sk-d-secret' },
+ 'mcpServers.e.apiKey.key': 'sk-e-dotted-secret-0001',
+ });
+
+ expect(decryptV3(serversOf(out).a.apiKey!.key)).toBe('sk-mcp-super-secret-key');
+ expect(decryptV3((out['mcpServers.b'] as Server).oauth!.client_secret)).toBe(
+ 'oauth-client-secret-value',
+ );
+ const c = out['mcpServers.c.apiKey'] as Record<string, string>;
+ expect(decryptV3(c.key)).toBe('sk-c-key');
+ expect(c.keyPreview).toBe('********');
+ const d = out['mcpServers.d.oauth'] as Record<string, string>;
+ expect(decryptV3(d.client_secret)).toBe('sk-d-secret');
+ expect(decryptV3(out['mcpServers.e.apiKey.key'] as string)).toBe('sk-e-dotted-secret-0001');
+ expect(out['mcpServers.e.apiKey.keyPreview']).toBe('...0001');
+ });
+
+ it('keeps `${ENV}` and `{{VAR}}` references readable, and clears on an empty value', () => {
+ const out = serversOf(
+ encryptConfigSecrets({
+ mcpServers: {
+ env: server({ apiKey: { source: 'admin', authorization_type: 'bearer', key: '${K}' } }),
+ user: server({
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: '{{USER_KEY}}' },
+ }),
+ cleared: server({ apiKey: { source: 'admin', authorization_type: 'bearer', key: '' } }),
+ },
+ }),
+ );
+
+ expect(out.env.apiKey).toMatchObject({ key: '${K}', keyPreview: '' });
+ expect(out.user.apiKey).toMatchObject({ key: '{{USER_KEY}}', keyPreview: '' });
+ expect(out.cleared.apiKey).toMatchObject({ key: '', keyPreview: '' });
+ });
+
+ it('keeps a server name that contains a dot as one key', () => {
+ const out = serversOf(encryptConfigSecrets({ mcpServers: { 'acme.tools': server() } }));
+ expect(decryptV3(out['acme.tools'].apiKey!.key)).toBe('sk-mcp-super-secret-key');
+
+ const redacted = serversOf(redactConfigSecrets({ mcpServers: { 'acme.tools': server() } }));
+ expect(redacted['acme.tools'].apiKey!.key).toBeUndefined();
+ expect(JSON.stringify(redacted)).not.toContain('super-secret');
+ });
+
+ it('drops arrays where a secret could hide from the traversals', () => {
+ const smuggled = {
+ mcpServers: {
+ list: [{ apiKey: { key: 'sk-in-array' } }],
+ nested: { url: 'https://x', apiKey: [{ key: 'sk-in-array' }] },
+ },
+ };
+ expect(JSON.stringify(encryptConfigSecrets(structuredClone(smuggled)))).not.toContain(
+ 'sk-in-array',
+ );
+ expect(JSON.stringify(redactConfigSecrets(structuredClone(smuggled)))).not.toContain(
+ 'sk-in-array',
+ );
+ });
+
+ it('rejects ciphertext, writes to previews and writes inside a secret', () => {
+ const ciphertext = encryptV3('sk-real');
+ expect(getConfigSecretInputError('mcpServers.a.apiKey.key', ciphertext)).toContain(
+ 'Encrypted config secret values',
+ );
+ expect(
+ getConfigSecretInputError('mcpServers', { a: { oauth: { client_secret: ciphertext } } }),
+ ).toContain('mcpServers.a.oauth.client_secret');
+ expect(getConfigSecretInputError('mcpServers.a', { apiKey: { key: 'v3:smuggled' } })).toContain(
+ 'Encrypted config secret values',
+ );
+ expect(getConfigSecretInputError('mcpServers.a.apiKey.keyPreview', 'x')).toContain(
+ 'protected secret preview',
+ );
+ expect(getConfigSecretInputError('mcpServers.a.oauth.client_secretPreview', 'x')).toContain(
+ 'protected secret preview',
+ );
+ expect(getConfigSecretInputError('mcpServers.a.apiKey.key', 'sk-plain')).toBeNull();
+ expect(isConfigSecretDescendantPath('mcpServers.a.apiKey.key.inner')).toBe(true);
+ expect(isConfigSecretDescendantPath('mcpServers.a.apiKey.authorization_type')).toBe(false);
+ });
+
+ it('treats every server and the objects on the way to a secret as secret ancestors', () => {
+ for (const path of [
+ 'mcpServers',
+ 'mcpServers.a',
+ 'mcpServers.a.apiKey',
+ 'mcpServers.a.oauth',
+ ]) {
+ expect(isConfigSecretAncestorPath(path)).toBe(true);
+ expect(isConfigSecretPreservablePatch(path, {})).toBe(true);
+ }
+ expect(isConfigSecretAncestorPath('mcpServers.a.headers')).toBe(false);
+ expect(getConfigSecretSections()).toEqual(expect.arrayContaining(['mcpServers', 'mcpConfig']));
+ expect(isConfigSecretRelatedSegments(['mcpServers', 'a', 'oauth', 'client_secret'])).toBe(true);
+ expect(isConfigSecretRelatedSegments(['mcpServers', 'a', 'title'])).toBe(false);
+ });
+
+ it('removes a secret and its preview together', () => {
+ expect(getConfigSecretMutationPaths('mcpServers.a.apiKey.key')).toEqual([
+ 'mcpServers.a.apiKey.key',
+ 'mcpServers.a.apiKey.keyPreview',
+ ]);
+ expect(getConfigSecretMutationPaths('mcpServers.a.oauth.client_secret')).toEqual([
+ 'mcpServers.a.oauth.client_secret',
+ 'mcpServers.a.oauth.client_secretPreview',
+ ]);
+ expect(getConfigSecretMutationPaths('mcpServers.a.url')).toEqual(['mcpServers.a.url']);
+ });
+
+ describe('omit to keep', () => {
+ const stored = () => encryptConfigSecrets({ mcpServers: { a: server() } });
+
+ it('keeps stored ciphertext and previews when a whole-document write omits them', () => {
+ const existing = stored();
+ const kept = serversOf(
+ preserveConfigSecrets(
+ {
+ mcpServers: {
+ a: {
+ url: 'https://mcp.example.com/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer' },
+ oauth: { client_id: 'client' },
+ },
+ },
+ },
+ existing,
+ ),
+ ).a;
+
+ expect(kept.apiKey!.key).toBe(serversOf(existing).a.apiKey!.key);
+ expect(kept.apiKey!.keyPreview).toBe('...-key');
+ expect(kept.oauth!.client_secret).toBe(serversOf(existing).a.oauth!.client_secret);
+ });
+
+ it('keeps them for object patches at the server and at the secret parent', () => {
+ const existing = stored();
+ const atServer = preserveConfigSecrets(
+ { url: 'https://mcp.example.com/mcp', apiKey: { source: 'admin' } },
+ existing,
+ 'mcpServers.a',
+ ) as Server;
+ expect(atServer.apiKey!.key).toBe(serversOf(existing).a.apiKey!.key);
+
+ const atParent = preserveConfigSecrets(
+ { source: 'admin', authorization_type: 'basic' },
+ existing,
+ 'mcpServers.a.apiKey',
+ ) as Record<string, string>;
+ expect(atParent.key).toBe(serversOf(existing).a.apiKey!.key);
+ });
+
+ it('does not resurrect a secret whose parent the write removed, or one it cleared', () => {
+ const existing = stored();
+ const removed = serversOf(
+ preserveConfigSecrets({ mcpServers: { a: { url: 'https://x' } } }, existing),
+ ).a;
+ expect(removed.apiKey).toBeUndefined();
+
+ const cleared = serversOf(
+ preserveConfigSecrets(
+ encryptConfigSecrets({ mcpServers: { a: server({ apiKey: { key: '' } }) } }),
+ existing,
+ ),
+ ).a;
+ expect(cleared.apiKey).toEqual({ key: '', keyPreview: '' });
+ });
+
+ it('encrypts a legacy plaintext secret it keeps, and drops a reference the client omitted', () => {
+ const kept = serversOf(
+ preserveConfigSecrets(
+ { mcpServers: { legacy: { apiKey: { source: 'admin' } }, ref: { apiKey: {} } } },
+ {
+ mcpServers: {
+ legacy: { apiKey: { key: 'sk-legacy-plaintext-0002' } },
+ ref: { apiKey: { key: '${REF_KEY}' } },
+ },
+ },
+ ),
+ );
+ expect(decryptV3(kept.legacy.apiKey!.key)).toBe('sk-legacy-plaintext-0002');
+ expect(kept.legacy.apiKey!.keyPreview).toBe('...0002');
+ expect(kept.ref.apiKey).toEqual({});
+ });
+ });
+
+ describe('rename carry', () => {
+ it('copies a stored secret to the renamed server and leaves the source alone', () => {
+ const existing = encryptConfigSecrets({ mcpServers: { old: server() } });
+ const next = { mcpServers: { renamed: { url: 'https://mcp.example.com/mcp', apiKey: {} } } };
+
+ carryRenamedConfigSecrets(next, existing, [
+ { path: 'mcpServers', previousName: 'old', name: 'renamed' },
+ ]);
+
+ const renamed = serversOf(next).renamed;
+ expect(renamed.apiKey!.key).toBe(serversOf(existing).old.apiKey!.key);
+ expect(renamed.apiKey!.keyPreview).toBe('...-key');
+ expect(renamed.oauth).toBeUndefined();
+ expect(serversOf(existing).old.apiKey!.key).toMatch(/^v3:/);
+ });
+
+ it('carries into a patch at the server path and never overwrites a supplied secret', () => {
+ const existing = encryptConfigSecrets({ mcpServers: { old: server() } });
+ const value: Server = {
+ oauth: { client_id: 'client' },
+ apiKey: { key: 'v3:new-ciphertext' },
+ };
+
+ carryRenamedConfigSecrets(
+ value,
+ existing,
+ [{ path: 'mcpServers', previousName: 'old', name: 'renamed' }],
+ 'mcpServers.renamed',
+ );
+
+ expect(value.oauth!.client_secret).toBe(serversOf(existing).old.oauth!.client_secret);
+ expect(value.apiKey!.key).toBe('v3:new-ciphertext');
+ });
+ });
+});
+
+describe('Azure OpenAI group secrets (array registry)', () => {
+ const group = (name: string, apiKey?: string) => ({
+ group: name,
+ instanceName: `${name}-instance`,
+ models: { 'gpt-4o': true },
+ ...(apiKey !== undefined && { apiKey }),
+ });
+ const groupsOf = (root: unknown) =>
+ (root as { endpoints: { azureOpenAI: { groups: Array<Record<string, string>> } } }).endpoints
+ .azureOpenAI.groups;
+
+ it('encrypts each group key with a preview and keeps references readable', () => {
+ const out = groupsOf(
+ encryptConfigSecrets({
+ endpoints: {
+ azureOpenAI: {
+ groups: [
+ group('east', 'azure-key-east-0000000000'),
+ group('west', '${AZURE_WEST_KEY}'),
+ group('user', 'user_provided'),
+ ],
+ },
+ },
+ }),
+ );
+
+ expect(decryptV3(out[0].apiKey)).toBe('azure-key-east-0000000000');
+ expect(out[0].apiKeyPreview).toBe('...0000');
+ expect(out[1].apiKey).toBe('${AZURE_WEST_KEY}');
+ expect(out[2].apiKey).toBe('user_provided');
+ });
+
+ it('encrypts a patch of the endpoint object, whose path is now a secret ancestor', () => {
+ expect(isConfigSecretAncestorPath('endpoints.azureOpenAI')).toBe(true);
+ const out = encryptConfigSecretFields({
+ 'endpoints.azureOpenAI': { groups: [group('east', 'azure-key-east-0000000000')] },
+ });
+ const groups = (out['endpoints.azureOpenAI'] as { groups: Array<Record<string, string>> })
+ .groups;
+ expect(decryptV3(groups[0].apiKey)).toBe('azure-key-east-0000000000');
+ });
+
+ it('keeps an omitted key by group name', () => {
+ const existing = encryptConfigSecrets({
+ endpoints: { azureOpenAI: { groups: [group('east', 'azure-key-east-0000000000')] } },
+ });
+ const kept = groupsOf(
+ preserveConfigSecrets({ endpoints: { azureOpenAI: { groups: [group('east')] } } }, existing),
+ );
+ expect(kept[0].apiKey).toBe(groupsOf(existing)[0].apiKey);
+ expect(kept[0].apiKeyPreview).toBe('...0000');
+ });
+
+ it('refuses indexed and named writes under the group array', () => {
+ expect(getConfigSecretInputError('endpoints.azureOpenAI.groups.0.apiKey', 'x')).toContain(
+ 'Cannot write secret fields by array index',
+ );
+ expect(getConfigSecretInputError('endpoints.azureOpenAI.groups.east', {})).toContain(
+ 'is an array and has no named fields',
+ );
+ });
+
+ it('redacts YAML literal group keys in a resolved config with the fixed mask', () => {
+ const redacted = groupsOf(
+ redactConfigSecrets({
+ endpoints: {
+ azureOpenAI: {
+ groups: [group('east', 'yaml-literal-azure-key'), group('west', '${AZ_KEY}')],
+ },
+ },
+ }),
+ );
+ expect(redacted[0].apiKey).toBeUndefined();
+ expect(redacted[0].apiKeyPreview).toBe(UNPREVIEWED_SECRET_MASK);
+ expect(redacted[1].apiKey).toBe('${AZ_KEY}');
+ });
+});
+
+describe('Azure OpenAI groupMap secrets (record registry)', () => {
+ type Group = Record<string, string>;
+ const groupMapOf = (root: unknown) =>
+ (root as { endpoints: { azureOpenAI: { groupMap: Record<string, Group> } } }).endpoints
+ .azureOpenAI.groupMap;
+
+ it('encrypts a group key with a preview at every depth a write can name', () => {
+ const plain = 'azure-groupmap-key-00001234';
+ const out = encryptConfigSecretFields({
+ endpoints: { azureOpenAI: { groupMap: { a: { apiKey: plain, instanceName: 'a' } } } },
+ 'endpoints.azureOpenAI': { groupMap: { b: { apiKey: plain } } },
+ 'endpoints.azureOpenAI.groupMap': { c: { apiKey: plain } },
+ 'endpoints.azureOpenAI.groupMap.d': { apiKey: plain },
+ 'endpoints.azureOpenAI.groupMap.e.apiKey': plain,
+ });
+ const stored = [
+ groupMapOf(out).a,
+ (out['endpoints.azureOpenAI'] as { groupMap: Record<string, Group> }).groupMap.b,
+ (out['endpoints.azureOpenAI.groupMap'] as Record<string, Group>).c,
+ out['endpoints.azureOpenAI.groupMap.d'] as Group,
+ {
+ apiKey: out['endpoints.azureOpenAI.groupMap.e.apiKey'] as string,
+ apiKeyPreview: out['endpoints.azureOpenAI.groupMap.e.apiKeyPreview'] as string,
+ },
+ ];
+
+ for (const group of stored) {
+ expect(decryptV3(group.apiKey)).toBe(plain);
+ expect(group.apiKeyPreview).toBe('...1234');
+ }
+ expect(groupMapOf(out).a.instanceName).toBe('a');
+ });
+
+ it('keeps `${VAR}` and `user_provided` readable, and refuses ciphertext and previews', () => {
+ const out = groupMapOf(
+ encryptConfigSecrets({
+ endpoints: {
+ azureOpenAI: { groupMap: { a: { apiKey: '${AZ_KEY}' }, b: { apiKey: 'user_provided' } } },
+ },
+ }),
+ );
+ expect(out.a.apiKey).toBe('${AZ_KEY}');
+ expect(out.b.apiKey).toBe('user_provided');
+ expect(
+ getConfigSecretInputError('endpoints.azureOpenAI.groupMap.a.apiKey', encryptV3('x')),
+ ).toContain('Encrypted config secret values cannot be submitted');
+ expect(getConfigSecretInputError('endpoints.azureOpenAI.groupMap.a.apiKeyPreview', 'x')).toBe(
+ 'Cannot write protected secret preview path: endpoints.azureOpenAI.groupMap.a.apiKeyPreview',
+ );
+ expect(
+ getConfigSecretInputError('endpoints.azureOpenAI', {
+ groupMap: { a: { apiKey: encryptV3('x') } },
+ }),
+ ).toContain('endpoints.azureOpenAI.groupMap.a.apiKey');
+ });
+
+ it('keeps an omitted key, and encrypts legacy plaintext on the way', () => {
+ const existing = {
+ endpoints: {
+ azureOpenAI: {
+ groupMap: {
+ a: { apiKey: encryptV3('azure-key-a'), apiKeyPreview: '...ey-a', instanceName: 'a' },
+ legacy: { apiKey: 'legacy-plaintext-azure-key', instanceName: 'l' },
+ },
+ },
+ },
+ };
+ const kept = groupMapOf(
+ preserveConfigSecrets(
+ { endpoints: { azureOpenAI: { groupMap: { a: { instanceName: 'a2' }, legacy: {} } } } },
+ existing,
+ ),
+ );
+ const patched = preserveConfigSecrets(
+ { instanceName: 'a3' },
+ existing,
+ 'endpoints.azureOpenAI.groupMap.a',
+ ) as Group;
+
+ expect(kept.a).toEqual({
+ apiKey: groupMapOf(existing).a.apiKey,
+ apiKeyPreview: '...ey-a',
+ instanceName: 'a2',
+ });
+ expect(decryptV3(kept.legacy.apiKey)).toBe('legacy-plaintext-azure-key');
+ expect(kept.legacy.apiKeyPreview).toBe('...-key');
+ expect(patched.apiKey).toBe(groupMapOf(existing).a.apiKey);
+ });
+
+ it('redacts stored ciphertext and YAML literals, leaving references readable', () => {
+ const redacted = groupMapOf(
+ redactConfigSecrets({
+ endpoints: {
+ azureOpenAI: {
+ groupMap: {
+ stored: { apiKey: encryptV3('azure-key'), apiKeyPreview: '...-key' },
+ yaml: { apiKey: 'yaml-literal-azure-key', instanceName: 'y' },
+ env: { apiKey: '${AZURE_API_KEY}' },
+ },
+ modelGroupMap: { 'gpt-4o': { group: 'yaml' } },
+ },
+ },
+ }),
+ );
+
+ expect(redacted).toEqual({
+ stored: { apiKeyPreview: '...-key' },
+ yaml: { apiKeyPreview: UNPREVIEWED_SECRET_MASK, instanceName: 'y' },
+ env: { apiKey: '${AZURE_API_KEY}' },
+ });
+ });
+});
+
+describe('fixed-mask previews for unpreviewed secrets (BE-8)', () => {
+ it('masks a YAML literal scalar secret without deriving anything from it', () => {
+ const redacted = redactConfigSecrets({
+ ocr: { apiKey: 'yaml-literal-ocr-key-1234', mistralModel: 'm' },
+ }) as { ocr: Record<string, string> };
+ expect(redacted.ocr).toEqual({ apiKeyPreview: UNPREVIEWED_SECRET_MASK, mistralModel: 'm' });
+ });
+
+ it('masks a placeholder in a field that does not keep placeholders, never a suffix of it', () => {
+ const redacted = redactConfigSecrets({
+ langfuse: { publicKey: 'pk', secretKey: '${LANGFUSE_SECRET_KEY}' },
+ }) as { langfuse: Record<string, string> };
+ expect(redacted.langfuse.secretKeyPreview).toBe(UNPREVIEWED_SECRET_MASK);
+ expect(JSON.stringify(redacted)).not.toContain('KEY}');
+ });
+
+ it('leaves stored previews, readable references and empty values alone', () => {
+ const redacted = redactConfigSecrets({
+ ocr: { apiKey: '${OCR_API_KEY}' },
+ webSearch: { serperApiKey: 'v3:abc:def', serperApiKeyPreview: '...abcd', jinaApiKey: '' },
+ mcpServers: {
+ a: { apiKey: { key: '${K}' } },
+ b: { apiKey: { key: 'v3:abc:def', keyPreview: '...wxyz' } },
+ c: { apiKey: { key: '' } },
+ yaml: { oauth: { client_secret: 'yaml-literal' } },
+ },
+ }) as Record<string, Record<string, unknown>>;
+
+ expect(redacted.ocr).toEqual({ apiKey: '${OCR_API_KEY}' });
+ expect(redacted.webSearch).toEqual({ serperApiKeyPreview: '...abcd' });
+ expect(redacted.mcpServers).toEqual({
+ a: { apiKey: { key: '${K}' } },
+ b: { apiKey: { keyPreview: '...wxyz' } },
+ c: { apiKey: { key: '' } },
+ yaml: { oauth: { client_secretPreview: UNPREVIEWED_SECRET_MASK } },
+ });
+ });
+
+ it('redacts the resolved mcpConfig like the mcpServers section', () => {
+ type Server = { apiKey?: Record<string, string>; oauth?: Record<string, string> };
+ const redacted = redactConfigSecrets({
+ mcpConfig: {
+ a: { apiKey: { key: 'plaintext-after-decrypt', keyPreview: '...rypt' } },
+ b: { oauth: { client_secret: 'yaml-literal' } },
+ },
+ }) as { mcpConfig: Record<string, Server> };
+
+ expect(redacted.mcpConfig.a.apiKey).toEqual({ keyPreview: '...rypt' });
+ expect(redacted.mcpConfig.b.oauth).toEqual({ client_secretPreview: UNPREVIEWED_SECRET_MASK });
+ });
+});
+
+describe('resolveRuntimeConfigSecrets', () => {
+ it('decrypts MCP credentials and Azure group keys, copying only what changes', () => {
+ const untouched = { url: 'https://plain.example/mcp', apiKey: { key: '${K}' } };
+ const yamlGroup = { apiKey: '${AZURE_YAML_KEY}', instanceName: 'yaml' };
+ const config = {
+ interfaceConfig: { prompts: true },
+ mcpConfig: {
+ stored: {
+ url: 'https://mcp.example.com/mcp',
+ apiKey: { source: 'admin', key: encryptV3('sk-runtime-key'), keyPreview: '...-key' },
+ oauth: { client_id: 'c', client_secret: encryptV3('runtime-oauth-secret') },
+ },
+ untouched,
+ },
+ endpoints: {
+ azureOpenAI: {
+ groups: [{ group: 'east', apiKey: encryptV3('azure-runtime-key') }],
+ groupMap: {
+ west: { apiKey: encryptV3('azure-groupmap-runtime-key'), instanceName: 'west' },
+ yaml: yamlGroup,
+ },
+ },
+ },
+ };
+ const snapshot = structuredClone(config);
+
+ const resolved = resolveRuntimeConfigSecrets(config);
+
+ expect(resolved.mcpConfig.stored.apiKey.key).toBe('sk-runtime-key');
+ expect(resolved.mcpConfig.stored.oauth.client_secret).toBe('runtime-oauth-secret');
+ expect(resolved.endpoints.azureOpenAI.groups[0].apiKey).toBe('azure-runtime-key');
+ expect(resolved.endpoints.azureOpenAI.groupMap.west.apiKey).toBe('azure-groupmap-runtime-key');
+ expect(resolved.endpoints.azureOpenAI.groupMap.yaml).toBe(yamlGroup);
+ expect(resolved.mcpConfig.untouched).toBe(untouched);
+ expect(resolved.interfaceConfig).toBe(config.interfaceConfig);
+ expect(config).toEqual(snapshot);
+ });
+
+ it('gives an empty credential, never ciphertext, when decryption fails', () => {
+ /**
+ * AES-CTR decrypts any well-formed payload, so a failure only comes from the key itself (a
+ * misconfigured `CREDS_KEY`); an isolated copy of the module stands in for that.
+ */
+ const warn = jest.fn();
+ jest.isolateModules(() => {
+ jest.doMock('@librechat/data-schemas', () => ({
+ ...jest.requireActual('@librechat/data-schemas'),
+ logger: { warn, error: jest.fn(), info: jest.fn(), debug: jest.fn() },
+ decryptV3: () => {
+ throw new Error('Invalid key length');
+ },
+ }));
+ const isolated = jest.requireActual<typeof import('./secrets')>('./secrets');
+ const resolved = isolated.resolveRuntimeConfigSecrets({
+ mcpConfig: { a: { apiKey: { key: `v3:${'0'.repeat(32)}:abcdef` } } },
+ });
+ expect(resolved.mcpConfig.a.apiKey.key).toBe('');
+ });
+ expect(warn).toHaveBeenCalledWith(
+ '[adminConfig] Failed to decrypt config secret',
+ expect.any(Error),
+ );
+ });
+
+ it('returns the config itself when it carries no ciphertext', () => {
+ const config = { mcpConfig: { a: { apiKey: { key: '${K}' } } }, endpoints: {} };
+ expect(resolveRuntimeConfigSecrets(config)).toBe(config);
+ });
+});
+
describe('Resolved config secrets (Azure groups and the Vertex service key)', () => {
const SERVICE_KEY_JSON =
'{"type":"service_account","private_key":"-----BEGIN PRIVATE KEY-----x"}';
diff --git a/packages/api/src/admin/secrets.ts b/packages/api/src/admin/secrets.ts
index 5dc3c83629..69fafd806e 100644
--- a/packages/api/src/admin/secrets.ts
+++ b/packages/api/src/admin/secrets.ts
@@ -4,10 +4,11 @@ import {
logger,
encryptV3,
decryptV3,
+ setAtPath,
foldConfigMergeKey,
combineFoldedConfigItems,
} from '@librechat/data-schemas';
-import type { AdminConfigRules } from '@librechat/data-schemas';
+import type { AdminConfigRules, ConfigFieldWrite } from '@librechat/data-schemas';
import { isUserProvided } from '~/utils/common';
const ENCRYPTED_PREFIX = 'v3:';
@@ -18,6 +19,13 @@ interface ConfigSecretFieldInput {
path: string;
/** When true, `${ENV_VAR}` placeholder values are stored and returned as plain references instead of being encrypted */
allowEnvPlaceholder?: boolean;
+ /**
+ * When true, every runtime reader uses the decrypted value as is (`resolveConfigSecret`,
+ * `resolveStoredConfigSecret`, `decryptConfigSecret`) and never expands a `${...}` in it, so a
+ * value stored encrypted is an opaque credential, not an env reference
+ * ({@link isOpaqueSecretInput}, {@link isOpaqueStoredSecret}).
+ */
+ opaque?: boolean;
}
interface ConfigSecretField extends ConfigSecretFieldInput {
@@ -36,21 +44,22 @@ interface ConfigSecretField extends ConfigSecretFieldInput {
*/
const CONFIG_SECRET_FIELDS: readonly ConfigSecretField[] = (
[
- { path: 'langfuse.secretKey' },
- { path: 'ocr.apiKey', allowEnvPlaceholder: true },
- { path: 'speech.tts.openai.apiKey', allowEnvPlaceholder: true },
- { path: 'speech.tts.azureOpenAI.apiKey', allowEnvPlaceholder: true },
- { path: 'speech.tts.elevenlabs.apiKey', allowEnvPlaceholder: true },
- { path: 'speech.tts.localai.apiKey', allowEnvPlaceholder: true },
- { path: 'speech.stt.openai.apiKey', allowEnvPlaceholder: true },
- { path: 'speech.stt.azureOpenAI.apiKey', allowEnvPlaceholder: true },
- { path: 'webSearch.serperApiKey', allowEnvPlaceholder: true },
- { path: 'webSearch.searxngApiKey', allowEnvPlaceholder: true },
- { path: 'webSearch.firecrawlApiKey', allowEnvPlaceholder: true },
- { path: 'webSearch.tavilyApiKey', allowEnvPlaceholder: true },
- { path: 'webSearch.keenableApiKey', allowEnvPlaceholder: true },
- { path: 'webSearch.jinaApiKey', allowEnvPlaceholder: true },
- { path: 'webSearch.cohereApiKey', allowEnvPlaceholder: true },
+ { path: 'langfuse.secretKey', opaque: true },
+ { path: 'ocr.apiKey', allowEnvPlaceholder: true, opaque: true },
+ { path: 'speech.tts.openai.apiKey', allowEnvPlaceholder: true, opaque: true },
+ { path: 'speech.tts.azureOpenAI.apiKey', allowEnvPlaceholder: true, opaque: true },
+ { path: 'speech.tts.elevenlabs.apiKey', allowEnvPlaceholder: true, opaque: true },
+ { path: 'speech.tts.localai.apiKey', allowEnvPlaceholder: true, opaque: true },
+ { path: 'speech.stt.openai.apiKey', allowEnvPlaceholder: true, opaque: true },
+ { path: 'speech.stt.azureOpenAI.apiKey', allowEnvPlaceholder: true, opaque: true },
+ { path: 'webSearch.serperApiKey', allowEnvPlaceholder: true, opaque: true },
+ { path: 'webSearch.searxngApiKey', allowEnvPlaceholder: true, opaque: true },
+ { path: 'webSearch.firecrawlApiKey', allowEnvPlaceholder: true, opaque: true },
+ { path: 'webSearch.tavilyApiKey', allowEnvPlaceholder: true, opaque: true },
+ { path: 'webSearch.keenableApiKey', allowEnvPlaceholder: true, opaque: true },
+ { path: 'webSearch.jinaApiKey', allowEnvPlaceholder: true, opaque: true },
+ { path: 'webSearch.cohereApiKey', allowEnvPlaceholder: true, opaque: true },
+ /** No runtime reader yet (`secrets.runtime.spec.ts`), so not known to be read as is. */
{ path: 'endpoints.assistants.apiKey', allowEnvPlaceholder: true },
{ path: 'endpoints.azureAssistants.apiKey', allowEnvPlaceholder: true },
] satisfies ConfigSecretFieldInput[]
@@ -81,7 +90,7 @@ interface ArraySecretField {
}
/** `user_provided` and `${ENV_VAR}`: values that name where a credential comes from, not the credential. */
-function isCredentialReference(value: string): boolean {
+export function isCredentialReference(value: string): boolean {
return isUserProvided(value) || envVarRegex.test(value);
}
@@ -98,8 +107,103 @@ const ARRAY_SECRET_FIELDS: readonly ArraySecretField[] = [
identityKey: 'name',
isPassthroughValue: isCredentialReference,
},
+ {
+ arrayPath: 'endpoints.azureOpenAI.groups',
+ secretKey: 'apiKey',
+ previewKey: 'apiKeyPreview',
+ identityKey: 'group',
+ isPassthroughValue: isCredentialReference,
+ },
];
+/** A whole-value `{{VAR}}` template, which MCP fills from the user's own custom variables. */
+const USER_VARIABLE_TEMPLATE = /^\{\{[^{}]+\}\}$/;
+
+/** Whether a value is a whole `{{VAR}}` template: a value each user enters, not a credential. */
+export function isUserVariableTemplate(value: string): boolean {
+ return USER_VARIABLE_TEMPLATE.test(value);
+}
+
+/** `${ENV_VAR}` and `{{VAR}}`: references an MCP server resolves at connect time, not credentials. */
+export function isMCPCredentialReference(value: string): boolean {
+ return envVarRegex.test(value) || isUserVariableTemplate(value);
+}
+
+/**
+ * A secret held by every entry of a record (a map keyed by entry name), such as each MCP
+ * server's `apiKey.key`. Dot-path registry entries cannot name a dynamic key, so the record
+ * traversals below walk the entries themselves, segment by segment: an entry name that contains
+ * a dot is still one key.
+ */
+interface RecordSecretFieldInput {
+ /** Dot-path of the record, whose segments contain no dots. */
+ recordPath: string;
+ /** Location of the secret inside each entry. */
+ secretPath: readonly string[];
+ /** Reference values that stay readable and never encrypt. */
+ isPassthroughValue: (value: string) => boolean;
+}
+
+interface RecordSecretField extends RecordSecretFieldInput {
+ /** `recordPath` as segments. */
+ recordSegments: readonly string[];
+ /** Masked-preview companion, always the sibling `<key>Preview` of the secret. */
+ previewKey: string;
+}
+
+/** The YAML section holding MCP servers, the name override documents and admin clients use. */
+const MCP_SERVERS_SECTION = 'mcpServers';
+
+/** The name the resolved AppConfig gives `mcpServers`, which the merge also applies from an override. */
+const MCP_CONFIG_ALIAS = 'mcpConfig';
+
+/**
+ * Registry of record secrets.
+ * - MCP server credentials, under `mcpServers` and its AppConfig name `mcpConfig`: both are
+ * encrypted on write and redacted on read.
+ * - Each Azure group's `apiKey` in `endpoints.azureOpenAI.groupMap`: what librechat.yaml's
+ * `groups` resolve to and what the Azure clients read. An override can write it directly, and
+ * it is the location an override's Azure key takes effect from.
+ */
+const RECORD_SECRET_FIELDS: readonly RecordSecretField[] = (
+ [
+ ...[MCP_SERVERS_SECTION, MCP_CONFIG_ALIAS].flatMap((recordPath) =>
+ [
+ ['oauth', 'client_secret'],
+ ['apiKey', 'key'],
+ ].map((secretPath) => ({
+ recordPath,
+ secretPath,
+ isPassthroughValue: isMCPCredentialReference,
+ })),
+ ),
+ {
+ recordPath: 'endpoints.azureOpenAI.groupMap',
+ secretPath: ['apiKey'],
+ isPassthroughValue: isCredentialReference,
+ },
+ ] satisfies RecordSecretFieldInput[]
+).map((field) => ({
+ ...field,
+ recordSegments: field.recordPath.split('.'),
+ previewKey: `${field.secretPath[field.secretPath.length - 1]}Preview`,
+}));
+
+/** The record secret's location as a pattern, `*` standing for the entry name. */
+function getRecordSecretLocation(field: RecordSecretField): string[] {
+ return [...field.recordSegments, '*', ...field.secretPath];
+}
+
+/** The record secret's preview location as a pattern. */
+function getRecordPreviewLocation(field: RecordSecretField): string[] {
+ return [...field.recordSegments, '*', ...field.secretPath.slice(0, -1), field.previewKey];
+}
+
+/** The key holding the secret inside its parent object. */
+function getRecordSecretKey(field: RecordSecretField): string {
+ return field.secretPath[field.secretPath.length - 1];
+}
+
/** A credential location in a resolved config; `*` matches every item of an array or value of a record. */
interface ResolvedSecretField {
segments: readonly string[];
@@ -107,11 +211,12 @@ interface ResolvedSecretField {
}
/**
- * 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.
+ * Credentials an admin read removes from the resolved config (AppService output, and the raw
+ * `librechat.yaml` copy it carries as `config`) after {@link redactConfigSecrets}: the Vertex
+ * service key, which `vertexConfigSetup` resolves from `${ENV_VAR}` into `vertexConfig` and
+ * which the write registries above do not cover, and the Azure group keys (`groups`, and the
+ * `groupMap` `azureConfigSetup` copies them into), which they do, so this pass alone never
+ * returns one either.
*/
const RESOLVED_SECRET_FIELDS: readonly ResolvedSecretField[] = [
{ path: 'endpoints.azureOpenAI.groups.*.apiKey', isPassthroughValue: isCredentialReference },
@@ -127,6 +232,19 @@ const SECRET_FIELDS_BY_PATH = new Map<string, ConfigSecretField>(
CONFIG_SECRET_FIELDS.map((field) => [field.path, field]),
);
+/** Joins segments so that a key containing a dot never spells another path. */
+function segmentsKey(segments: readonly string[]): string {
+ return segments.join('\u0000');
+}
+
+/** {@link ConfigSecretField.opaque} fields by their segments. */
+const OPAQUE_SECRET_FIELDS = new Map<string, ConfigSecretField>(
+ CONFIG_SECRET_FIELDS.filter((field) => field.opaque).map((field) => [
+ segmentsKey(field.path.split('.')),
+ field,
+ ]),
+);
+
const PREVIEW_PATHS = new Set<string>([
...CONFIG_SECRET_FIELDS.map((field) => field.previewPath),
...LEGACY_PREVIEW_PATHS.values(),
@@ -153,12 +271,14 @@ export function getSecretAncestorPatterns(locations: readonly string[]): string[
}
/**
- * Ancestors of every registered location: scalar secrets and the containers of array secrets
- * (an array container itself is matched by `ARRAY_SECRET_FIELDS`, since it must stay an array).
+ * Ancestors of every registered location: scalar secrets, the containers of array secrets (an
+ * array container itself is matched by `ARRAY_SECRET_FIELDS`, since it must stay an array), and
+ * record secrets (`mcpServers`, `mcpServers.*`, `mcpServers.*.oauth`, ...).
*/
const ANCESTOR_PATTERNS = getSecretAncestorPatterns([
...CONFIG_SECRET_FIELDS.map((field) => field.path),
...ARRAY_SECRET_FIELDS.map((field) => field.arrayPath),
+ ...RECORD_SECRET_FIELDS.map((field) => getRecordSecretLocation(field).join('.')),
]);
const isWildcardPattern = (pattern: string): boolean => pattern.split('.').includes(ANY_SEGMENT);
@@ -171,18 +291,65 @@ const ANCESTOR_WILDCARDS: readonly string[] = ANCESTOR_PATTERNS.filter(isWildcar
/** Whether a dotted path matches a location pattern segment for segment. */
export function matchesSecretPattern(fieldPath: string, pattern: string): boolean {
- const segments = fieldPath.split('.');
- const expected = pattern.split('.');
+ return matchesLocation(fieldPath.split('.'), pattern.split('.'));
+}
+
+function matchesLocation(segments: readonly string[], location: readonly string[]): boolean {
+ return (
+ segments.length === location.length &&
+ location.every((segment, index) => segment === ANY_SEGMENT || segment === segments[index])
+ );
+}
+
+function isBelowLocation(segments: readonly string[], location: readonly string[]): boolean {
return (
- segments.length === expected.length &&
- expected.every((segment, index) => segment === ANY_SEGMENT || segment === segments[index])
+ segments.length > location.length &&
+ location.every((segment, index) => segment === ANY_SEGMENT || segment === segments[index])
);
}
+const RECORD_SECRET_LOCATIONS = RECORD_SECRET_FIELDS.map((field) => ({
+ field,
+ secret: getRecordSecretLocation(field),
+ preview: getRecordPreviewLocation(field),
+}));
+
+/** The record secret a dotted path names exactly: the secret itself, or its preview. */
+function findRecordSecretPath(
+ fieldPath: string,
+): { field: RecordSecretField; preview: boolean } | undefined {
+ const segments = fieldPath.split('.');
+ for (const { field, secret, preview } of RECORD_SECRET_LOCATIONS) {
+ if (matchesLocation(segments, secret)) {
+ return { field, preview: false };
+ }
+ if (matchesLocation(segments, preview)) {
+ return { field, preview: true };
+ }
+ }
+ return undefined;
+}
+
+/** Whether a dotted path lies inside a record secret or its preview. */
+function isRecordSecretDescendantPath(fieldPath: string): boolean {
+ const segments = fieldPath.split('.');
+ return RECORD_SECRET_LOCATIONS.some(
+ ({ secret, preview }) =>
+ isBelowLocation(segments, secret) || isBelowLocation(segments, preview),
+ );
+}
+
+/** The preview companion path of a record secret named by its dotted path. */
+function getRecordPreviewPath(fieldPath: string, field: RecordSecretField): string {
+ const segments = fieldPath.split('.');
+ return [...segments.slice(0, -1), field.previewKey].join('.');
+}
+
const SECRET_SECTIONS: readonly string[] = [
...new Set([
...CONFIG_SECRET_FIELDS.map((field) => field.path.split('.')[0]),
...ARRAY_SECRET_FIELDS.map((field) => field.arrayPath.split('.')[0]),
+ ...RECORD_SECRET_FIELDS.map((field) => field.recordSegments[0]),
]),
];
@@ -190,6 +357,30 @@ const SECRET_SECTIONS: readonly string[] = [
const PREVIEW_MIN_LENGTH = 16;
const PREVIEW_VISIBLE = 4;
+/**
+ * The preview a read shows for a secret that has none stored: a literal from librechat.yaml, or
+ * plaintext an older server stored. A fixed mask says a value is set without revealing its
+ * length or any of its characters.
+ */
+export const UNPREVIEWED_SECRET_MASK = '********';
+
+/** Whether a redacted value held something: anything but a missing or blank value. */
+function isSetSecretValue(value: unknown): boolean {
+ return value != null && !(typeof value === 'string' && value.trim() === '');
+}
+
+/** Gives a secret whose value a read just removed the fixed mask, unless a preview is stored. */
+function maskUnpreviewedSecret(
+ parent: Record<string, unknown>,
+ previewKey: string,
+ removed: unknown,
+): void {
+ const preview = parent[previewKey];
+ if (isSetSecretValue(removed) && (typeof preview !== 'string' || preview === '')) {
+ parent[previewKey] = UNPREVIEWED_SECRET_MASK;
+ }
+}
+
/** Masked hint for admin display: only the last four characters of a long secret, never a prefix. */
export function getSecretPreview(secret: string): string {
if (secret.length < PREVIEW_MIN_LENGTH) {
@@ -223,7 +414,7 @@ export function getConfigSecretSections(): readonly string[] {
/** The secret registries as plain data, for admin clients that render secret inputs. */
export function getConfigSecretRules(): Pick<
AdminConfigRules,
- 'secretFields' | 'arraySecretFields' | 'refusedMaps'
+ 'secretFields' | 'arraySecretFields' | 'recordSecretFields' | 'refusedMaps'
> {
return {
secretFields: CONFIG_SECRET_FIELDS.map(({ path, previewPath, allowEnvPlaceholder }) => ({
@@ -239,6 +430,17 @@ export function getConfigSecretRules(): Pick<
identityKey,
}),
),
+ recordSecretFields: RECORD_SECRET_FIELDS.flatMap(({ recordPath, secretPath, previewKey }) =>
+ recordPath !== MCP_CONFIG_ALIAS
+ ? [
+ {
+ recordPath,
+ secretPath: secretPath.join('.'),
+ previewPath: [...secretPath.slice(0, -1), previewKey].join('.'),
+ },
+ ]
+ : [],
+ ),
refusedMaps: [...CONFIG_SECRET_MAP_FIELDS],
};
}
@@ -319,6 +521,9 @@ function isConfigSecretRelatedPath(fieldPath: string): boolean {
if (SECRET_FIELDS_BY_PATH.has(fieldPath) || PREVIEW_PATHS.has(fieldPath)) {
return true;
}
+ if (findRecordSecretPath(fieldPath) != null) {
+ return true;
+ }
if (
ARRAY_SECRET_FIELDS.some(
(field) => fieldPath === field.arrayPath || fieldPath.startsWith(`${field.arrayPath}.`),
@@ -380,11 +585,36 @@ export function resolveStoredConfigSecret(value: string): string | undefined {
return value;
}
+/**
+ * Whether a value a write sends to `segments` (override keys) is an opaque credential: a secret
+ * every runtime reader uses as is once decrypted ({@link ConfigSecretField.opaque}), which the
+ * write encrypts because the field does not pass it through as a `${VAR}` reference. A `${...}` in
+ * it is part of the credential, not an env reference.
+ */
+export function isOpaqueSecretInput(segments: readonly string[], value: string): boolean {
+ const field = OPAQUE_SECRET_FIELDS.get(segmentsKey(segments));
+ return field != null && !(field.allowEnvPlaceholder && isEnvPlaceholder(value));
+}
+
+/**
+ * Whether a value stored at `segments` (override keys) is an opaque credential: ciphertext of a
+ * secret every runtime reader uses as is once decrypted ({@link ConfigSecretField.opaque}).
+ * Plaintext there is not: it is a reference, a legacy value or librechat.yaml's, which
+ * `resolveConfigSecret` expands.
+ */
+export function isOpaqueStoredSecret(segments: readonly string[], value: string): boolean {
+ return OPAQUE_SECRET_FIELDS.has(segmentsKey(segments)) && isEncryptedSecretPayload(value);
+}
+
export function getConfigSecretMutationPaths(fieldPath: string): string[] {
const field = SECRET_FIELDS_BY_PATH.get(fieldPath);
if (field?.previewPath) {
return [field.path, field.previewPath];
}
+ const recordSecret = findRecordSecretPath(fieldPath);
+ if (recordSecret && !recordSecret.preview) {
+ return [fieldPath, getRecordPreviewPath(fieldPath, recordSecret.field)];
+ }
return [fieldPath];
}
@@ -397,7 +627,7 @@ export function isConfigSecretDescendantPath(fieldPath: string): boolean {
return true;
}
}
- return false;
+ return isRecordSecretDescendantPath(fieldPath);
}
export function isConfigSecretAncestorPath(fieldPath: string): boolean {
@@ -424,8 +654,85 @@ const SECRET_LOCATIONS: ReadonlyArray<readonly string[]> = [
[...container, ANY_SEGMENT, field.previewKey],
];
}),
+ ...RECORD_SECRET_LOCATIONS.flatMap(({ secret, preview }) => [secret, preview]),
];
+/** Where each registered secret value itself is stored, `*` standing for an array item or entry. */
+const SECRET_VALUE_LOCATIONS: ReadonlyArray<readonly string[]> = [
+ ...CONFIG_SECRET_FIELDS.map((field) => field.path.split('.')),
+ ...ARRAY_SECRET_FIELDS.map((field) => [
+ ...field.arrayPath.split('.'),
+ ANY_SEGMENT,
+ field.secretKey,
+ ]),
+ ...RECORD_SECRET_LOCATIONS.map(({ secret }) => secret),
+];
+
+function collectStringsAt(value: unknown, rest: readonly string[], into: Set<string>): void {
+ if (rest.length === 0) {
+ if (typeof value === 'string') {
+ into.add(value);
+ }
+ return;
+ }
+ const [segment, ...tail] = rest;
+ if (segment === ANY_SEGMENT) {
+ const children = Array.isArray(value) ? value : Object.values(getPlainRecord(value) ?? {});
+ for (const child of children) {
+ collectStringsAt(child, tail, into);
+ }
+ return;
+ }
+ const record = getPlainRecord(value);
+ if (record && Object.prototype.hasOwnProperty.call(record, segment)) {
+ collectStringsAt(record[segment], tail, into);
+ }
+}
+
+/**
+ * The secret values a request entered: what its own writes hold at registered secret locations,
+ * after encryption and before secret preservation fills in what they omit. Each encryption draws
+ * a fresh IV and a submitted ciphertext is refused or cleared, so a credential the write kept or
+ * carried from the stored document is never among them, whichever write of the request put it
+ * back. Re-entry rules count a key as entered again only when the planned document holds one of
+ * these values.
+ */
+export function getEnteredConfigSecrets(writes: readonly ConfigFieldWrite[]): Set<string> {
+ const entered = new Set<string>();
+ for (const { segments, value } of writes) {
+ for (const location of SECRET_VALUE_LOCATIONS) {
+ if (
+ segments.length <= location.length &&
+ segments.every(
+ (segment, index) => location[index] === ANY_SEGMENT || location[index] === segment,
+ )
+ ) {
+ collectStringsAt(value, location.slice(segments.length), entered);
+ }
+ }
+ }
+ return entered;
+}
+
+/**
+ * Whether `candidate`, a credential a write kept rather than entered, is the one `stored` holds:
+ * the same ciphertext, or a legacy plaintext value that secret preservation encrypted on the way.
+ */
+export function isSameStoredSecret(stored: unknown, candidate: string): boolean {
+ const normalized = normalizeSecretString(stored);
+ if (normalized == null) {
+ return false;
+ }
+ if (normalized === candidate) {
+ return true;
+ }
+ return (
+ !isEncryptedConfigSecret(normalized) &&
+ isEncryptedConfigSecret(candidate) &&
+ decryptConfigSecret(candidate) === normalized
+ );
+}
+
/**
* Whether a write at `segments` touches a registered secret: the secret's own location or its
* preview's, an ancestor that can carry it, or a path inside it. Segments are compared one by
@@ -480,6 +787,10 @@ export function getConfigSecretInputError(fieldPath: string, value: unknown): st
if (arrayError) {
return arrayError;
}
+ const recordError = getRecordSecretInputError(fieldPath, value);
+ if (recordError) {
+ return recordError;
+ }
if (!isConfigSecretAncestorPath(fieldPath)) {
return null;
}
@@ -672,7 +983,7 @@ function preserveArraySecrets(result: unknown, existing: unknown, basePath: stri
function shouldRedactArraySecretValue(value: unknown, field: ArraySecretField): boolean {
if (typeof value !== 'string') {
- return false;
+ return value != null;
}
if (isEncryptedConfigSecret(value)) {
return true;
@@ -741,6 +1052,353 @@ function getArraySecretInputError(fieldPath: string, value: unknown): string | n
return null;
}
+/**
+ * Walks `node` along `segments` and returns the object at the end. With `prune`, an array met on
+ * the way is deleted from its parent: a secret inside an unexpected array-of-objects shape would
+ * otherwise slip past encryption and redaction.
+ */
+function walkObjects(
+ node: unknown,
+ segments: readonly string[],
+ prune: boolean,
+): Record<string, unknown> | null {
+ let cursor = getPlainRecord(node);
+ for (const segment of segments) {
+ if (cursor == null) {
+ return null;
+ }
+ const next = cursor[segment];
+ if (prune && Array.isArray(next)) {
+ delete cursor[segment];
+ return null;
+ }
+ cursor = getPlainRecord(next);
+ }
+ return cursor;
+}
+
+/** One entry's object that holds (or would hold) a record secret's key. */
+interface RecordSecretParent {
+ name: string;
+ parent: Record<string, unknown>;
+}
+
+/**
+ * The objects holding a record secret's key in `root`, by entry name, where `basePath` says what
+ * `root` is: whole overrides (`''`), an object on the way to the record, the record, one entry,
+ * or an object between an entry and its secret. A path elsewhere yields nothing. With `prune`,
+ * arrays where the record, an object on the way to it, an entry or an object on the way to the
+ * secret belongs are deleted.
+ */
+function collectRecordSecretParents(
+ root: unknown,
+ field: RecordSecretField,
+ basePath: string,
+ prune: boolean,
+): RecordSecretParent[] {
+ const base = basePath === '' ? [] : basePath.split('.');
+ const { recordSegments } = field;
+ const parentPath = field.secretPath.slice(0, -1);
+ const shared = Math.min(base.length, recordSegments.length);
+ if (base.slice(0, shared).some((segment, index) => segment !== recordSegments[index])) {
+ return [];
+ }
+ if (base.length > recordSegments.length) {
+ const name = base[recordSegments.length];
+ const within = base.slice(recordSegments.length + 1);
+ if (
+ within.length > parentPath.length ||
+ within.some((segment, index) => segment !== parentPath[index])
+ ) {
+ return [];
+ }
+ const parent = walkObjects(root, parentPath.slice(within.length), prune);
+ return parent ? [{ name, parent }] : [];
+ }
+ const entries = walkObjects(root, recordSegments.slice(base.length), prune);
+ if (!entries) {
+ return [];
+ }
+ const parents: RecordSecretParent[] = [];
+ for (const name of Object.keys(entries)) {
+ if (prune && Array.isArray(entries[name])) {
+ delete entries[name];
+ continue;
+ }
+ const parent = walkObjects(entries[name], parentPath, prune);
+ if (parent) {
+ parents.push({ name, parent });
+ }
+ }
+ return parents;
+}
+
+/** The stored object that holds a record secret's key for the named entry. */
+function getStoredRecordSecretParent(
+ existing: unknown,
+ field: RecordSecretField,
+ name: string,
+): Record<string, unknown> | null {
+ const record = walkObjects(existing, field.recordSegments, false);
+ if (!record || !Object.prototype.hasOwnProperty.call(record, name)) {
+ return null;
+ }
+ return walkObjects(record[name], field.secretPath.slice(0, -1), false);
+}
+
+function getRecordSecretInputError(fieldPath: string, value: unknown): string | null {
+ const recordSecret = findRecordSecretPath(fieldPath);
+ if (recordSecret?.preview) {
+ return `Cannot write protected secret preview path: ${fieldPath}`;
+ }
+ if (recordSecret) {
+ return isEncryptedConfigSecret(value)
+ ? `Encrypted config secret values cannot be submitted: ${fieldPath}`
+ : null;
+ }
+ for (const field of RECORD_SECRET_FIELDS) {
+ const key = getRecordSecretKey(field);
+ for (const { name, parent } of collectRecordSecretParents(value, field, fieldPath, false)) {
+ if (isEncryptedConfigSecret(parent[key])) {
+ return `Encrypted config secret values cannot be submitted: ${field.recordPath}.${name}.${field.secretPath.join('.')}`;
+ }
+ }
+ }
+ return null;
+}
+
+/**
+ * Applies a write to one entry's secret in place, as for array entries: an absent secret drops
+ * any submitted preview, an empty or non-string value clears both, a reference is kept readable,
+ * and anything else is encrypted with a masked preview beside it.
+ */
+function applyRecordSecretWrite(parent: Record<string, unknown>, field: RecordSecretField): void {
+ const key = getRecordSecretKey(field);
+ if (!(key in parent)) {
+ delete parent[field.previewKey];
+ return;
+ }
+ const rawValue = parent[key];
+ const value =
+ typeof rawValue === 'string' && !rawValue.startsWith(ENCRYPTED_PREFIX)
+ ? normalizeSecretString(rawValue)
+ : undefined;
+ if (!value) {
+ parent[key] = '';
+ parent[field.previewKey] = '';
+ return;
+ }
+ if (field.isPassthroughValue(value)) {
+ parent[key] = value;
+ parent[field.previewKey] = '';
+ return;
+ }
+ parent[key] = encryptV3(value);
+ parent[field.previewKey] = getSecretPreview(value);
+}
+
+/**
+ * Copies a stored record secret, with its preview, into a parent that omits it. Only values a
+ * read hides are carried: ciphertext as is, and legacy plaintext encrypted on the way. A
+ * reference the read returned is not, since a client that omits it removed it.
+ */
+function carryStoredRecordSecret(
+ parent: Record<string, unknown>,
+ storedParent: Record<string, unknown> | null,
+ field: RecordSecretField,
+): void {
+ const key = getRecordSecretKey(field);
+ const storedSecret = normalizeSecretString(storedParent?.[key]);
+ if (!storedParent || !storedSecret || field.isPassthroughValue(storedSecret)) {
+ return;
+ }
+ if (!isEncryptedConfigSecret(storedSecret)) {
+ parent[key] = encryptV3(storedSecret);
+ parent[field.previewKey] = getSecretPreview(storedSecret);
+ return;
+ }
+ parent[key] = storedSecret;
+ const storedPreview = storedParent[field.previewKey];
+ if (typeof storedPreview === 'string') {
+ parent[field.previewKey] = normalizeStoredPreview(storedPreview);
+ } else {
+ delete parent[field.previewKey];
+ }
+}
+
+function preserveRecordSecrets(result: unknown, existing: unknown, basePath: string): void {
+ for (const field of RECORD_SECRET_FIELDS) {
+ const key = getRecordSecretKey(field);
+ for (const { name, parent } of collectRecordSecretParents(result, field, basePath, false)) {
+ if (!(key in parent)) {
+ carryStoredRecordSecret(parent, getStoredRecordSecretParent(existing, field, name), field);
+ }
+ }
+ }
+}
+
+function redactRecordSecrets(rootRecord: Record<string, unknown>): void {
+ for (const field of RECORD_SECRET_FIELDS) {
+ const key = getRecordSecretKey(field);
+ for (const { parent } of collectRecordSecretParents(rootRecord, field, '', true)) {
+ const preview = parent[field.previewKey];
+ if (typeof preview === 'string') {
+ parent[field.previewKey] = normalizeStoredPreview(preview);
+ }
+ if (!(key in parent)) {
+ continue;
+ }
+ const value = parent[key];
+ const normalized = normalizeSecretString(value);
+ if (
+ (typeof value === 'string' && normalized == null) ||
+ (normalized != null && field.isPassthroughValue(normalized))
+ ) {
+ continue;
+ }
+ delete parent[key];
+ maskUnpreviewedSecret(parent, field.previewKey, value);
+ }
+ }
+}
+
+/** A secret carried across a server rename: from the stored entry it had, to the new name. */
+export interface ConfigSecretRename {
+ path: 'mcpServers';
+ previousName: string;
+ name: string;
+}
+
+/**
+ * Fills secrets a renamed entry omits from the stored entry it was renamed from. Copy semantics:
+ * the stored entry keeps its own secret, so a client that renames by writing the new entry and
+ * then deleting the old one loses nothing. Runs after {@link preserveConfigSecrets}, which keeps
+ * a secret the entry already has under its own name. A carried credential keeps its stored
+ * ciphertext (legacy plaintext is encrypted on the way), so the re-entry rule (`reentry.ts`)
+ * finds the server it came from by value.
+ */
+export function carryRenamedConfigSecrets(
+ next: unknown,
+ existing: unknown,
+ renames: readonly ConfigSecretRename[],
+ basePath = '',
+): void {
+ if (renames.length === 0) {
+ return;
+ }
+ for (const field of RECORD_SECRET_FIELDS) {
+ const key = getRecordSecretKey(field);
+ const parents = collectRecordSecretParents(next, field, basePath, false);
+ for (const { previousName, name, path } of renames) {
+ if (path !== field.recordPath) {
+ continue;
+ }
+ const target = parents.find((candidate) => candidate.name === name);
+ if (!target || key in target.parent) {
+ continue;
+ }
+ carryStoredRecordSecret(
+ target.parent,
+ getStoredRecordSecretParent(existing, field, previousName),
+ field,
+ );
+ }
+ }
+}
+
+/** Decrypts a stored secret for runtime use; a failure gives `''`, never the ciphertext. */
+function decryptRuntimeSecret(value: string): string {
+ return decryptConfigSecret(value) ?? '';
+}
+
+/**
+ * Returns `parent` with its `key` decrypted when it holds ciphertext, copying only what changes;
+ * anything else comes back as is.
+ */
+function withDecryptedKey<T>(parent: T, key: string): T {
+ const record = getPlainRecord(parent);
+ const value = record?.[key];
+ if (record == null || typeof value !== 'string' || !isEncryptedSecretPayload(value)) {
+ return parent;
+ }
+ return { ...record, [key]: decryptRuntimeSecret(value) } as T;
+}
+
+/** `node` with the value at `segments` decrypted, copied only along the path when it changes. */
+function withDecryptedAt(node: unknown, segments: readonly string[]): unknown {
+ const [segment, ...rest] = segments;
+ if (rest.length === 0) {
+ return withDecryptedKey(node, segment);
+ }
+ const record = getPlainRecord(node);
+ if (record == null || !Object.prototype.hasOwnProperty.call(record, segment)) {
+ return node;
+ }
+ const child = record[segment];
+ const decrypted = withDecryptedAt(child, rest);
+ return decrypted === child ? node : { ...record, [segment]: decrypted };
+}
+
+/**
+ * The record secrets a resolved config carries: every one but those under `mcpServers`, which
+ * the merge resolves into `mcpConfig`.
+ */
+const RESOLVED_RECORD_SECRET_FIELDS = RECORD_SECRET_FIELDS.filter(
+ (field) => field.recordPath !== MCP_SERVERS_SECTION,
+);
+
+/** `root` with each entry's secret of `field` decrypted, copied only along what changes. */
+function withDecryptedRecordSecrets(
+ root: Record<string, unknown>,
+ field: RecordSecretField,
+): Record<string, unknown> {
+ const entries = walkObjects(root, field.recordSegments, false);
+ if (!entries) {
+ return root;
+ }
+ let decrypted: Record<string, unknown> | undefined;
+ for (const [name, entry] of Object.entries(entries)) {
+ const next = withDecryptedAt(entry, field.secretPath);
+ if (next !== entry) {
+ decrypted ??= { ...entries };
+ decrypted[name] = next;
+ }
+ }
+ return decrypted ? setAtPath(root, field.recordSegments, decrypted) : root;
+}
+
+/**
+ * Decrypts, for runtime readers, the credentials a resolved config carries as ciphertext from
+ * admin-written overrides: every MCP server's `apiKey.key` and `oauth.client_secret`, each
+ * resolved Azure group's `apiKey` (`groupMap`, which the Azure clients read) and each Azure
+ * `groups` entry's. Runs once after the overrides merge, so the ~10 readers of `mcpConfig` and
+ * the Azure clients receive plaintext, while the store and admin reads keep ciphertext or
+ * redaction. A failed decrypt gives `''` (with a warning), never ciphertext, so a request fails
+ * visibly instead of sending an encrypted blob as a credential. Preview companions stay for the
+ * admin's merged view; `redactServerSecrets` keeps them from end users. Objects are copied only
+ * along the paths that change; the input is never mutated.
+ */
+export function resolveRuntimeConfigSecrets<T extends object>(config: T): T {
+ let result = RESOLVED_RECORD_SECRET_FIELDS.reduce(
+ withDecryptedRecordSecrets,
+ config as Record<string, unknown>,
+ );
+
+ const endpoints = getPlainRecord(result.endpoints);
+ const azure = getPlainRecord(endpoints?.azureOpenAI);
+ const groups = azure?.groups;
+ if (endpoints && azure && Array.isArray(groups)) {
+ const decryptedGroups = groups.map((group) => withDecryptedKey(group, 'apiKey'));
+ if (decryptedGroups.some((group, index) => group !== groups[index])) {
+ result = {
+ ...result,
+ endpoints: { ...endpoints, azureOpenAI: { ...azure, groups: decryptedGroups } },
+ };
+ }
+ }
+ return result as T;
+}
+
/**
* Returns a copy of a custom endpoint config with its stored `apiKey`
* decrypted for runtime use; unencrypted configs return unchanged. Decryption
@@ -886,9 +1544,34 @@ export function encryptConfigSecretFields(
}
}
+ for (const key of Object.keys(result)) {
+ const recordSecret = findRecordSecretPath(key);
+ if (!recordSecret) {
+ continue;
+ }
+ if (recordSecret.preview) {
+ delete result[key];
+ continue;
+ }
+ writeDottedRecordSecret(result, key, recordSecret.field);
+ }
+
return result;
}
+/** Writes a record secret addressed by its full dotted path, with its preview path beside it. */
+function writeDottedRecordSecret(
+ result: Record<string, unknown>,
+ fieldPath: string,
+ field: RecordSecretField,
+): void {
+ const key = getRecordSecretKey(field);
+ const container: Record<string, unknown> = { [key]: result[fieldPath] };
+ applyRecordSecretWrite(container, field);
+ result[fieldPath] = container[key];
+ result[getRecordPreviewPath(fieldPath, field)] = container[field.previewKey];
+}
+
/**
* Returns a cloned config object with registered secret values encrypted
* before writes. Empty secrets reset their preview companions. `basePath`
@@ -930,6 +1613,12 @@ export function encryptConfigSecrets<T>(root: T, basePath = ''): T {
applyArraySecretWrites(entries, field);
}
}
+
+ for (const field of RECORD_SECRET_FIELDS) {
+ for (const { parent } of collectRecordSecretParents(result, field, basePath, true)) {
+ applyRecordSecretWrite(parent, field);
+ }
+ }
return result;
}
@@ -992,6 +1681,7 @@ export function preserveConfigSecrets<T>(next: T, existing?: unknown, basePath =
}
preserveArraySecrets(result, existing, basePath);
+ preserveRecordSecrets(result, existing, basePath);
return result;
}
@@ -1080,8 +1770,13 @@ interface RedactConfigSecretsOptions {
/**
* Deletes registered secret values from `root` in place so admin reads never
* return them (encrypted or plaintext). Preview companions and plain
- * `${ENV_VAR}` references (for fields that allow them) are preserved.
- * Secret *maps* are masked value-by-value. The caller passes a cloned object.
+ * `${ENV_VAR}` references (for fields that allow them) are preserved. A value
+ * removed without a stored preview (a librechat.yaml literal, or plaintext an
+ * older server stored) gets the fixed {@link UNPREVIEWED_SECRET_MASK}, so the
+ * read still says a secret is set without deriving anything from the value;
+ * only `previewPlaintext` gives a scalar plaintext an override stored the
+ * preview its next save writes instead. Secret *maps* are masked value-by-value.
+ * The caller passes a cloned object.
*/
export function redactConfigSecrets<T>(
root: T,
@@ -1127,6 +1822,7 @@ export function redactConfigSecrets<T>(
previewLegacyPlaintext(section, previewKey, value);
}
delete section[key];
+ maskUnpreviewedSecret(section, previewKey, value);
}
for (const field of ARRAY_SECRET_FIELDS) {
@@ -1136,14 +1832,21 @@ export function redactConfigSecrets<T>(
}
for (const item of entries) {
const entry = getPlainRecord(item);
- if (entry && typeof entry[field.previewKey] === 'string') {
+ if (!entry) {
+ continue;
+ }
+ if (typeof entry[field.previewKey] === 'string') {
entry[field.previewKey] = normalizeStoredPreview(entry[field.previewKey] as string);
}
- if (entry && shouldRedactArraySecretValue(entry[field.secretKey], field)) {
+ const value = entry[field.secretKey];
+ if (shouldRedactArraySecretValue(value, field)) {
delete entry[field.secretKey];
+ maskUnpreviewedSecret(entry, field.previewKey, value);
}
}
}
+
+ redactRecordSecrets(rootRecord);
return root;
}
diff --git a/packages/api/src/agents/__tests__/run-summarization.test.ts b/packages/api/src/agents/__tests__/run-summarization.test.ts
index 86ed5ed27e..7f9e1e2b44 100644
--- a/packages/api/src/agents/__tests__/run-summarization.test.ts
+++ b/packages/api/src/agents/__tests__/run-summarization.test.ts
@@ -1,17 +1,18 @@
import { z } from 'zod';
-import { encryptV3, logger } from '@librechat/data-schemas';
import { DynamicStructuredTool } from '@langchain/core/tools';
import { HumanMessage, AIMessage } from '@langchain/core/messages';
import { CallbackManager } from '@langchain/core/callbacks/manager';
+import { encryptV3, logger, mergeConfigOverrides } from '@librechat/data-schemas';
import {
EModelEndpoint,
FileSources,
+ PrincipalType,
MAX_SUBAGENT_DEPTH,
MAX_SUBAGENT_RUN_CONFIGS,
} from 'librechat-data-provider';
import type { CompactionSemanticIndex, SubagentTaskConfig, AgentInputs } from '@librechat/agents';
+import type { AppConfig, ConfigOverrideLayer, IUser } from '@librechat/data-schemas';
import type { SummarizationConfig, TEndpoint } from 'librechat-data-provider';
-import type { AppConfig, IUser } from '@librechat/data-schemas';
import type { BaseMessage } from '@langchain/core/messages';
import type { OpenAI } from 'openai';
import type { ModelBoundChatModelCallback } from '~/middleware/modelBoundContent';
@@ -20,6 +21,7 @@ import { clearToolApprovalHooks, registerToolApprovalHook } from '~/agents/hitl/
import { executionFixture } from '~/schedules/authorization/execution.helper';
import { createRun, isAskUserQuestionAdminDisabled } from '~/agents/run';
import { initializeOpenAI } from '~/endpoints/openai/initialize';
+import { createSecretRebindingGuard } from '~/app/rebinding';
import { getOpenAIConfig } from '~/endpoints/openai/config';
// Mock winston logger — `format` must be callable so @librechat/data-schemas
@@ -5129,3 +5131,144 @@ describe('steering provider capabilities', () => {
expect(jest.mocked(Run.create).mock.calls[0]?.[0].preemption).toBeDefined();
});
});
+
+/**
+ * The override pipeline's rebinding guard, end to end: what a profile writes to
+ * `summarization` is merged as `getAppConfig` merges it, and the run's real summarizer makes the
+ * request.
+ */
+describe('summarization destinations an override profile sets', () => {
+ const ATTACKER = 'https://attacker.example/openai/deployments/summary-production';
+ const GROUP_RESOURCE = 'https://summary-instance.openai.azure.com/';
+
+ function azureAppConfig(summarization?: SummarizationConfig): AppConfig {
+ const appConfig = makeAppConfig([]);
+ appConfig.endpoints![EModelEndpoint.azureOpenAI] = {
+ modelNames: ['gpt-4.1-mini'],
+ modelGroupMap: { 'gpt-4.1-mini': { group: 'summary' } },
+ groupMap: {
+ summary: {
+ apiKey: 'deployment-group-secret',
+ instanceName: 'summary-instance',
+ version: '2024-10-21',
+ models: { 'gpt-4.1-mini': { deploymentName: 'summary-production' } },
+ },
+ },
+ } as unknown as NonNullable<AppConfig['endpoints']>[EModelEndpoint.azureOpenAI];
+ if (summarization != null) {
+ appConfig.config.summarization = structuredClone(summarization);
+ appConfig.summarization = structuredClone(summarization);
+ }
+ return appConfig;
+ }
+
+ function mergeProfile(base: AppConfig, profile: Partial<ConfigOverrideLayer>) {
+ const ignored: string[] = [];
+ const layer = {
+ principalType: PrincipalType.ROLE,
+ principalId: 'editors',
+ priority: 10,
+ overrides: {},
+ ...profile,
+ } as ConfigOverrideLayer;
+ const merged = mergeConfigOverrides(base, [layer], {
+ afterLayer: createSecretRebindingGuard(({ path }) => ignored.push(path)),
+ });
+ return { merged, ignored };
+ }
+
+ async function summarize(appConfig: AppConfig) {
+ const agents = await callAndCapture({
+ agents: [makeAgent()],
+ appConfig,
+ summarizeOnly: true,
+ summarizationConfig: appConfig.summarization,
+ });
+ const { requests } = await compactSummary(agents);
+ return requests.map(({ url, headers }) => ({
+ url: url.href,
+ apiKey: headers.get('api-key'),
+ }));
+ }
+
+ it.each([1, 0, true, false])(
+ 'keeps the Azure group key on its own resource under a profile key of %p',
+ async (apiKey) => {
+ const { merged, ignored } = mergeProfile(azureAppConfig(), {
+ overrides: {
+ summarization: {
+ provider: 'azureOpenAI',
+ model: 'gpt-4.1-mini',
+ parameters: { baseURL: ATTACKER, apiKey },
+ },
+ },
+ });
+
+ expect(ignored).toEqual(['summarization.parameters.baseURL']);
+ const requests = await summarize(merged);
+ expect(requests).toEqual([
+ { url: expect.stringMatching(`^${GROUP_RESOURCE}`), apiKey: 'deployment-group-secret' },
+ ]);
+ },
+ );
+
+ it('sends a key the profile enters, and only that key, to the destination it sets', async () => {
+ const { merged, ignored } = mergeProfile(azureAppConfig(), {
+ overrides: {
+ summarization: {
+ provider: 'azureOpenAI',
+ model: 'gpt-4.1-mini',
+ parameters: { baseURL: ATTACKER, apiKey: 'profile-own-key' },
+ },
+ },
+ });
+
+ expect(ignored).toEqual([]);
+ expect(await summarize(merged)).toEqual([
+ { url: expect.stringMatching(/^https:\/\/attacker\.example\//), apiKey: 'profile-own-key' },
+ ]);
+ });
+
+ it("keeps the Azure group key off librechat.yaml's gateway once a profile removes the gateway's key", async () => {
+ const yaml = azureAppConfig({
+ provider: 'azureOpenAI',
+ model: 'gpt-4.1-mini',
+ parameters: {
+ baseURL: 'https://yaml-gateway.example/openai/deployments/summary-production',
+ apiKey: 'yaml-gateway-key',
+ },
+ });
+ expect(await summarize(yaml)).toEqual([
+ {
+ url: expect.stringMatching(/^https:\/\/yaml-gateway\.example\//),
+ apiKey: 'yaml-gateway-key',
+ },
+ ]);
+ jest.mocked(Run.create).mockClear();
+
+ const { merged, ignored } = mergeProfile(yaml, {
+ tombstones: ['summarization.parameters.apiKey'],
+ });
+
+ expect(ignored).toEqual(['summarization.parameters.baseURL']);
+ expect(await summarize(merged)).toEqual([
+ { url: expect.stringMatching(`^${GROUP_RESOURCE}`), apiKey: 'deployment-group-secret' },
+ ]);
+ });
+
+ it("keeps the Azure group key off librechat.yaml's unkeyed gateway for another provider", async () => {
+ const { merged, ignored } = mergeProfile(
+ azureAppConfig({
+ provider: 'openAI',
+ model: 'gpt-4.1-mini',
+ parameters: { baseURL: 'https://yaml-gateway.example/openai/deployments/x' },
+ }),
+ { overrides: { summarization: { provider: 'azureOpenAI' } } },
+ );
+
+ expect(ignored).toEqual(['summarization.parameters.baseURL']);
+ expect(await summarize(merged)).toEqual([
+ { url: expect.stringMatching(`^${GROUP_RESOURCE}`), apiKey: 'deployment-group-secret' },
+ ]);
+ });
+});
diff --git a/packages/api/src/app/allowlist.spec.ts b/packages/api/src/app/allowlist.spec.ts
new file mode 100644
index 0000000000..daa096c98b
--- /dev/null
+++ b/packages/api/src/app/allowlist.spec.ts
@@ -0,0 +1,539 @@
+process.env.CREDS_KEY =
+ process.env.CREDS_KEY ?? '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
+
+import type { EnvReferencePolicy } from './allowlist';
+
+type Allowlist = typeof import('./allowlist');
+
+/** Loaded after `CREDS_KEY` is set: the encryption key is read when data-schemas loads. */
+let encryptV3: typeof import('@librechat/data-schemas').encryptV3;
+let loadWebSearchConfig: typeof import('@librechat/data-schemas').loadWebSearchConfig;
+let parseEnvAllowlist: Allowlist['parseEnvAllowlist'];
+let getEnvReferenceIssues: Allowlist['getEnvReferenceIssues'];
+let neutralizeEnvReferences: Allowlist['neutralizeEnvReferences'];
+let collectEnvReferenceNames: Allowlist['collectEnvReferenceNames'];
+let createEnvReferencePolicy: Allowlist['createEnvReferencePolicy'];
+let isLiteralTextPath: Allowlist['isLiteralTextPath'];
+let ENV_LITERAL_TEXT_PATHS: Allowlist['ENV_LITERAL_TEXT_PATHS'];
+let ENV_REFERENCE_NOT_ALLOWED: string;
+
+beforeAll(async () => {
+ ({ encryptV3, loadWebSearchConfig } = await import('@librechat/data-schemas'));
+ ({
+ parseEnvAllowlist,
+ getEnvReferenceIssues,
+ neutralizeEnvReferences,
+ collectEnvReferenceNames,
+ createEnvReferencePolicy,
+ isLiteralTextPath,
+ ENV_LITERAL_TEXT_PATHS,
+ ENV_REFERENCE_NOT_ALLOWED,
+ } = await import('./allowlist'));
+});
+
+const yaml = {
+ endpoints: {
+ custom: [{ name: 'Gateway', apiKey: '${GATEWAY_KEY}', baseURL: 'https://${GATEWAY_HOST}/v1' }],
+ },
+ mcpServers: { github: { url: 'https://api.github.com/mcp', headers: { A: 'Bearer ${GH_PAT}' } } },
+};
+
+describe('parseEnvAllowlist', () => {
+ it('splits names on commas and whitespace and drops empties', () => {
+ expect(parseEnvAllowlist(' A_KEY, B_KEY\nC_KEY ,, ')).toEqual(['A_KEY', 'B_KEY', 'C_KEY']);
+ expect(parseEnvAllowlist(undefined)).toEqual([]);
+ expect(parseEnvAllowlist('')).toEqual([]);
+ });
+});
+
+describe('createEnvReferencePolicy', () => {
+ it('collects every name librechat.yaml references, embedded ones included', () => {
+ expect([...collectEnvReferenceNames(yaml)].sort()).toEqual([
+ 'GATEWAY_HOST',
+ 'GATEWAY_KEY',
+ 'GH_PAT',
+ ]);
+ });
+
+ it('allows YAML names, endpoint credential names and the extra list, nothing else', () => {
+ const policy = createEnvReferencePolicy({ config: yaml, allowlist: ['EXTRA_NAME'] });
+ const anywhere = ['endpoints', 'custom', '0', 'headers', 'X-Key'];
+
+ expect(policy.allows('GATEWAY_KEY', anywhere)).toBe(true);
+ expect(policy.allows('GH_PAT', anywhere)).toBe(true);
+ expect(policy.allows('OPENAI_API_KEY', anywhere)).toBe(true);
+ expect(policy.allows('BEDROCK_AWS_SECRET_ACCESS_KEY', anywhere)).toBe(true);
+ expect(policy.allows('EXTRA_NAME', anywhere)).toBe(true);
+ expect(policy.allows('MEILI_HTTP_ADDR', anywhere)).toBe(false);
+ expect(policy.allows('HOME', anywhere)).toBe(false);
+ });
+
+ it('allows the OCR key reference loading fills in, only where it fills it in', () => {
+ const configured = createEnvReferencePolicy({
+ config: { ocr: { baseURL: 'https://ocr.internal.example/v1' } },
+ });
+ const keyed = createEnvReferencePolicy({
+ config: { ocr: { apiKey: '${OCR_GATEWAY_KEY}', baseURL: 'https://ocr.internal.example' } },
+ });
+ const ocrKey = ['ocr', 'apiKey'];
+
+ expect(configured.allows('OCR_API_KEY', ocrKey)).toBe(true);
+ expect(configured.allows('OCR_API_KEY', ['endpoints', 'custom', '0', 'apiKey'])).toBe(false);
+ expect(keyed.allows('OCR_GATEWAY_KEY', ['speech', 'tts', 'openai', 'url'])).toBe(true);
+ expect(keyed.allows('OCR_API_KEY', ocrKey)).toBe(false);
+ expect(createEnvReferencePolicy({ config: yaml }).allows('OCR_API_KEY', ocrKey)).toBe(false);
+ });
+
+ it('allows the web search defaults loading fills in, each at its own field only', () => {
+ const policy = createEnvReferencePolicy({ config: yaml });
+ const configured = createEnvReferencePolicy({
+ config: { webSearch: { searxngInstanceUrl: 'https://search.internal.example' } },
+ });
+ const instanceUrl = ['webSearch', 'searxngInstanceUrl'];
+
+ expect(policy.allows('SEARXNG_INSTANCE_URL', instanceUrl)).toBe(true);
+ expect(policy.allows('FIRECRAWL_API_KEY', ['webSearch', 'firecrawlApiKey'])).toBe(true);
+ expect(policy.allows('SEARXNG_INSTANCE_URL', ['webSearch', 'firecrawlApiUrl'])).toBe(false);
+ expect(policy.allows('SERPER_API_KEY', ['endpoints', 'custom', '0', 'headers', 'X'])).toBe(
+ false,
+ );
+ expect(configured.allows('SEARXNG_INSTANCE_URL', instanceUrl)).toBe(false);
+ });
+
+ it('accepts and keeps the web search section config reads return, written back', () => {
+ const policy = createEnvReferencePolicy({ config: yaml });
+ const written = { webSearch: loadWebSearchConfig(undefined) };
+
+ expect(getEnvReferenceIssues(written, policy)).toEqual([]);
+ expect(neutralizeEnvReferences(written, policy)).toEqual(written);
+ expect(
+ getEnvReferenceIssues(
+ { endpoints: { custom: [{ name: 'X', headers: { K: '${SERPER_API_KEY}' } }] } },
+ policy,
+ ).map(({ path }) => path),
+ ).toEqual(['endpoints.custom.0.headers.K']);
+ });
+
+ it('never allows an infrastructure secret, even when YAML or the extra list names it', () => {
+ const policy = createEnvReferencePolicy({
+ config: { ocr: { apiKey: '${CREDS_KEY}' } },
+ allowlist: ['JWT_SECRET', 'MONGO_URI'],
+ });
+
+ expect(policy.allows('CREDS_KEY', ['ocr', 'apiKey'])).toBe(false);
+ expect(policy.allows('JWT_SECRET', [])).toBe(false);
+ expect(policy.allows('MONGO_URI', [])).toBe(false);
+ });
+});
+
+describe('getEnvReferenceIssues', () => {
+ let policy: EnvReferencePolicy;
+ beforeAll(() => {
+ policy = createEnvReferencePolicy({ config: yaml });
+ });
+
+ it('reports each string that references a disallowed name, by location only', () => {
+ const issues = getEnvReferenceIssues(
+ {
+ custom: [
+ { name: 'Mine', apiKey: '${GATEWAY_KEY}', baseURL: 'https://x/${OTHER_SECRET}' },
+ { name: 'Theirs', headers: { 'X-Token': '${CREDS_KEY}' } },
+ ],
+ },
+ policy,
+ ['endpoints'],
+ );
+
+ expect(issues).toEqual([
+ {
+ path: 'endpoints.custom.0.baseURL',
+ segments: ['endpoints', 'custom', '0', 'baseURL'],
+ code: ENV_REFERENCE_NOT_ALLOWED,
+ },
+ {
+ path: 'endpoints.custom.1.headers.X-Token',
+ segments: ['endpoints', 'custom', '1', 'headers', 'X-Token'],
+ code: ENV_REFERENCE_NOT_ALLOWED,
+ },
+ ]);
+ expect(JSON.stringify(issues)).not.toContain('OTHER_SECRET');
+ });
+
+ it('accepts allowed references, literals and `{{VAR}}` templates', () => {
+ expect(
+ getEnvReferenceIssues(
+ {
+ apiKey: '${OPENAI_API_KEY}',
+ url: 'https://${GATEWAY_HOST}/mcp',
+ key: '{{USER_TOKEN}}',
+ literal: 'sk-plain',
+ count: 3,
+ },
+ policy,
+ ),
+ ).toEqual([]);
+ });
+
+ /** The documented limit: the allowlist decides which names a value may name, not where it goes. */
+ it('accepts an allowed name in any value, beside any host', () => {
+ expect(
+ getEnvReferenceIssues(
+ {
+ url: 'https://collector.example/${OPENAI_API_KEY}',
+ headers: { Authorization: 'Bearer ${GATEWAY_KEY}' },
+ apiKey: { key: '${GH_PAT}' },
+ },
+ policy,
+ ['mcpServers', 'collector'],
+ ),
+ ).toEqual([]);
+ });
+
+ it('keeps a key that contains a dot as one segment', () => {
+ const issues = getEnvReferenceIssues({ 'us.region': '${NOPE}' }, policy, ['x']);
+ expect(issues[0].segments).toEqual(['x', 'us.region']);
+ });
+});
+
+describe('neutralizeEnvReferences', () => {
+ let policy: EnvReferencePolicy;
+ beforeAll(() => {
+ policy = createEnvReferencePolicy({ config: yaml });
+ });
+
+ it('resolves disallowed references to nothing and keeps allowed ones', () => {
+ const layer = {
+ endpoints: {
+ custom: [
+ {
+ name: 'Mine',
+ apiKey: '${CREDS_KEY}',
+ baseURL: 'https://${GATEWAY_HOST}/${UNLISTED}',
+ },
+ ],
+ },
+ };
+
+ expect(neutralizeEnvReferences(layer, policy)).toEqual({
+ endpoints: { custom: [{ name: 'Mine', apiKey: '', baseURL: 'https://${GATEWAY_HOST}/' }] },
+ });
+ });
+
+ it('returns the same objects when nothing changes, and never mutates the input', () => {
+ const untouched = { ocr: { apiKey: '${GATEWAY_KEY}' }, interface: { prompts: true } };
+ expect(neutralizeEnvReferences(untouched, policy)).toBe(untouched);
+
+ const layer = { ocr: { apiKey: '${UNLISTED}' }, interface: { prompts: true } };
+ const snapshot = structuredClone(layer);
+ const result = neutralizeEnvReferences(layer, policy);
+ expect(layer).toEqual(snapshot);
+ expect(result.interface).toBe(layer.interface);
+ expect(result.ocr).toEqual({ apiKey: '' });
+ });
+
+ it('leaves no reference that removing a disallowed one joins together', () => {
+ const layer = {
+ ocr: { baseURL: 'https://h/$${UNLISTED}{SOME_SECRET}' },
+ speech: { tts: { openai: { url: 'https://h/$$${UNLISTED}{UNLISTED}{SOME_SECRET}' } } },
+ webSearch: { jinaApiUrl: 'https://$${UNLISTED}{GATEWAY_HOST}/v1' },
+ };
+
+ expect(neutralizeEnvReferences(layer, policy)).toEqual({
+ ocr: { baseURL: 'https://h/' },
+ speech: { tts: { openai: { url: 'https://h/' } } },
+ /** What is left is a reference the layer could have written itself. */
+ webSearch: { jinaApiUrl: 'https://${GATEWAY_HOST}/v1' },
+ });
+ });
+
+ it('judges ciphertext by its plaintext', () => {
+ const disallowed = encryptV3('prefix-${UNLISTED}');
+ const allowed = encryptV3('prefix-${GATEWAY_KEY}');
+ const literal = encryptV3('sk-literal');
+
+ expect(neutralizeEnvReferences({ a: disallowed, b: allowed, c: literal }, policy)).toEqual({
+ a: '',
+ b: allowed,
+ c: literal,
+ });
+ });
+});
+
+describe('literal text', () => {
+ const policy = () => createEnvReferencePolicy({ config: yaml });
+ const prose = {
+ interface: {
+ customWelcome: 'Tip: JS template literals look like `${name}`',
+ termsOfService: { modalContent: 'Hi ${user}' },
+ },
+ modelSpecs: {
+ list: [
+ {
+ name: 'coder',
+ preset: { promptPrefix: 'Prefer template literals like `${user.name}`.' },
+ },
+ ],
+ },
+ memory: { agent: { provider: 'openAI', model: 'gpt-4o', instructions: 'Keep ${x} as is' } },
+ summarization: { prompt: 'Summarize ${input}', parameters: { apiKey: '${CREDS_KEY}' } },
+ endpoints: { custom: [{ name: 'Gateway', titlePrompt: 'Title ${convo}', apiKey: '${X}' }] },
+ };
+
+ it('accepts `${...}` in text no reader expands, and still checks every other field', () => {
+ expect(getEnvReferenceIssues(prose, policy()).map(({ path }) => path)).toEqual([
+ 'summarization.parameters.apiKey',
+ 'endpoints.custom.0.apiKey',
+ ]);
+ expect(getEnvReferenceIssues('Hi ${name}', policy(), ['interface', 'customWelcome'])).toEqual(
+ [],
+ );
+ });
+
+ it('leaves the text as written at runtime', () => {
+ const out = neutralizeEnvReferences(prose, policy());
+ expect(out.interface).toBe(prose.interface);
+ expect(out.modelSpecs).toBe(prose.modelSpecs);
+ expect(out.memory.agent.instructions).toBe('Keep ${x} as is');
+ expect(out.summarization).toEqual({ prompt: 'Summarize ${input}', parameters: { apiKey: '' } });
+ expect(out.endpoints.custom[0]).toEqual({
+ name: 'Gateway',
+ titlePrompt: 'Title ${convo}',
+ apiKey: '',
+ });
+ });
+
+ it('does not allow a name librechat.yaml mentions only in text', () => {
+ const names = collectEnvReferenceNames({
+ interface: { customWelcome: 'Hello ${SOME_SECRET}' },
+ endpoints: { custom: [{ apiKey: '${GATEWAY_KEY}', titlePrompt: '${OTHER}' }] },
+ });
+ expect([...names]).toEqual(['GATEWAY_KEY']);
+ });
+
+ it('treats every listed prompt field as text, at exactly its path', () => {
+ for (const path of ENV_LITERAL_TEXT_PATHS) {
+ const segments = path.map((segment) => (segment === '*' ? '0' : segment));
+ expect(isLiteralTextPath(segments)).toBe(true);
+ expect(isLiteralTextPath([...segments, 'nested'])).toBe(false);
+ expect(isLiteralTextPath(segments.slice(1))).toBe(false);
+ }
+ expect(isLiteralTextPath(['endpoints', 'openAI', 'headers', 'titlePrompt'])).toBe(false);
+ expect(isLiteralTextPath(['endpoints', 'custom', '0', 'headers', 'titlePrompt'])).toBe(false);
+ expect(isLiteralTextPath(['summarization', 'parameters', 'prompt'])).toBe(false);
+ expect(isLiteralTextPath(['memory', 'agent', 'model_parameters', 'instructions'])).toBe(false);
+ });
+});
+
+/**
+ * Builds the value at `segments` (a numeric segment makes an array item) holding `value`, the way
+ * an override would carry it.
+ */
+function nest(segments: readonly string[], value: unknown): unknown {
+ if (segments.length === 0) {
+ return value;
+ }
+ const [segment, ...rest] = segments;
+ if (/^\d+$/.test(segment)) {
+ const items: unknown[] = [];
+ items[Number(segment)] = nest(rest, value);
+ return items;
+ }
+ return { [segment]: nest(rest, value) };
+}
+
+describe('prompt-like key names under maps a reader expands', () => {
+ /** Record maps whose keys the admin names and whose values a reader env-expands. */
+ const EXPANDED_MAPS: readonly (readonly string[])[] = [
+ ['mcpServers', 'leak', 'headers'],
+ ['mcpServers', 'leak', 'oauth_headers'],
+ ['mcpServers', 'leak', 'env'],
+ ['mcpConfig', 'leak', 'headers'],
+ ['mcpConfig', 'leak', 'oauth_headers'],
+ ['mcpConfig', 'leak', 'env'],
+ ['endpoints', 'custom', '0', 'headers'],
+ ['endpoints', 'custom', '0', 'addParams'],
+ ['endpoints', 'all', 'headers'],
+ ['endpoints', 'openAI', 'headers'],
+ ['endpoints', 'anthropic', 'headers'],
+ ['endpoints', 'google', 'headers'],
+ ['endpoints', 'bedrock', 'headers'],
+ ['endpoints', 'bedrock', 'inferenceProfiles'],
+ ['endpoints', 'agents', 'headers'],
+ ['endpoints', 'assistants', 'headers'],
+ ['endpoints', 'azureAssistants', 'headers'],
+ ['endpoints', 'azureOpenAI', 'headers'],
+ ['endpoints', 'azureOpenAI', 'groups', '0', 'additionalHeaders'],
+ ['endpoints', 'azureOpenAI', 'groups', '0', 'addParams'],
+ ['langfuse', 'headers'],
+ ['webSearch', 'firecrawlOptions', 'headers'],
+ ['summarization', 'parameters'],
+ ['memory', 'agent', 'model_parameters'],
+ ];
+ /** Keys named like prompt fields, which inside these maps are still expanded. */
+ const PROMPT_LIKE_KEYS = [
+ 'X-Prompt',
+ 'X-System-Prompt',
+ 'instructions',
+ 'prompt',
+ 'systemPrompt',
+ 'titlePrompt',
+ 'titlePromptTemplate',
+ ];
+ const cases = EXPANDED_MAPS.map((map) => ({ map, label: map.join('.') }));
+
+ it.each(cases)('refuses ${HOME} under $label on write and resolves it to nothing', ({ map }) => {
+ const policy = createEnvReferencePolicy({ config: yaml });
+ for (const key of PROMPT_LIKE_KEYS) {
+ const path = [...map, key];
+ const issue = { path: path.join('.'), segments: path, code: ENV_REFERENCE_NOT_ALLOWED };
+ expect(getEnvReferenceIssues(nest(path, '${HOME}'), policy)).toEqual([issue]);
+ expect(
+ getEnvReferenceIssues(nest(path.slice(2), '${HOME}'), policy, path.slice(0, 2)),
+ ).toEqual([issue]);
+ expect(neutralizeEnvReferences(nest(path, 'Bearer ${HOME}'), policy)).toEqual(
+ nest(path, 'Bearer '),
+ );
+ }
+ });
+
+ it('allowlists a name librechat.yaml references only in such a map', () => {
+ const names = collectEnvReferenceNames({
+ mcpServers: { a: { headers: { 'X-Prompt': '${HEADER_KEY}' } } },
+ endpoints: { custom: [{ headers: { 'X-System-Prompt': '${CUSTOM_HEADER_KEY}' } }] },
+ });
+ expect([...names].sort()).toEqual(['CUSTOM_HEADER_KEY', 'HEADER_KEY']);
+ });
+});
+
+describe('Azure base URL templates', () => {
+ const TEMPLATE_URL =
+ 'https://${INSTANCE_NAME}.openai.azure.com/openai/deployments/${DEPLOYMENT_NAME}';
+ const azure = (baseURL: string) => ({
+ endpoints: {
+ azureOpenAI: {
+ groups: [{ group: 'east', apiKey: '${AZURE_API_KEY}', baseURL }],
+ groupMap: { east: { baseURL } },
+ },
+ },
+ });
+
+ it('accepts and keeps `${INSTANCE_NAME}` and `${DEPLOYMENT_NAME}` in a group base URL', () => {
+ const policy = createEnvReferencePolicy({ config: {} });
+ expect(getEnvReferenceIssues(azure(TEMPLATE_URL), policy)).toEqual([]);
+ expect(
+ getEnvReferenceIssues(TEMPLATE_URL, policy, [
+ 'endpoints',
+ 'azureOpenAI',
+ 'groupMap',
+ 'east',
+ 'baseURL',
+ ]),
+ ).toEqual([]);
+ const written = azure(TEMPLATE_URL);
+ expect(neutralizeEnvReferences(written, policy)).toBe(written);
+ });
+
+ it('still polices every other name in that URL, and those names anywhere else', () => {
+ const policy = createEnvReferencePolicy({ config: {} });
+ const mixed = 'https://${INSTANCE_NAME}.example.com/${LC8_UNLISTED_NAME}';
+ expect(getEnvReferenceIssues(azure(mixed), policy).map(({ path }) => path)).toEqual([
+ 'endpoints.azureOpenAI.groups.0.baseURL',
+ 'endpoints.azureOpenAI.groupMap.east.baseURL',
+ ]);
+ expect(neutralizeEnvReferences(azure(mixed), policy)).toEqual(
+ azure('https://${INSTANCE_NAME}.example.com/'),
+ );
+
+ const elsewhere = {
+ ocr: { baseURL: 'https://${INSTANCE_NAME}.example.com' },
+ endpoints: { custom: [{ name: 'A', baseURL: 'https://${DEPLOYMENT_NAME}.example.com' }] },
+ };
+ expect(getEnvReferenceIssues(elsewhere, policy).map(({ path }) => path)).toEqual([
+ 'ocr.baseURL',
+ 'endpoints.custom.0.baseURL',
+ ]);
+ });
+
+ it('does not allow those names elsewhere because librechat.yaml uses the templates', () => {
+ expect([...collectEnvReferenceNames(azure(TEMPLATE_URL))]).toEqual(['AZURE_API_KEY']);
+ const policy = createEnvReferencePolicy({ config: azure(TEMPLATE_URL) });
+ expect(policy.allows('INSTANCE_NAME', ['ocr', 'baseURL'])).toBe(false);
+ });
+});
+
+describe('opaque credentials', () => {
+ const policy = () => createEnvReferencePolicy({ config: yaml });
+ /** A provider token that happens to contain `${...}`. */
+ const credential = 'pa${UNLISTED}ss';
+ /** Keys every runtime reader uses as is once decrypted: OCR, speech, web search, Langfuse. */
+ const opaque = {
+ ocr: { apiKey: credential },
+ speech: {
+ tts: { openai: { apiKey: credential }, elevenlabs: { apiKey: credential } },
+ stt: { azureOpenAI: { apiKey: credential } },
+ },
+ webSearch: { serperApiKey: credential, jinaApiKey: credential },
+ langfuse: { secretKey: credential },
+ };
+ /** Keys their clients expand once decrypted (custom endpoints, Azure, MCP), or nothing reads yet. */
+ const expanded = {
+ endpoints: {
+ custom: [{ name: 'Gateway', apiKey: credential }],
+ azureOpenAI: {
+ groups: [{ group: 'east', apiKey: credential }],
+ groupMap: { east: { apiKey: credential } },
+ },
+ assistants: { apiKey: credential },
+ },
+ mcpServers: { tools: { apiKey: { key: credential }, oauth: { client_secret: credential } } },
+ };
+
+ it('accepts `${...}` inside a key read as is, but not a whole reference a field passes through', () => {
+ expect(getEnvReferenceIssues(opaque, policy())).toEqual([]);
+ expect(
+ getEnvReferenceIssues(
+ { ocr: { apiKey: '${UNLISTED}' }, webSearch: { serperApiKey: ' ${UNLISTED} ' } },
+ policy(),
+ ).map(({ path }) => path),
+ ).toEqual(['ocr.apiKey', 'webSearch.serperApiKey']);
+ });
+
+ it('still checks keys their clients expand once decrypted', () => {
+ expect(getEnvReferenceIssues(expanded, policy()).map(({ path }) => path)).toEqual([
+ 'endpoints.custom.0.apiKey',
+ 'endpoints.azureOpenAI.groups.0.apiKey',
+ 'endpoints.azureOpenAI.groupMap.east.apiKey',
+ 'endpoints.assistants.apiKey',
+ 'mcpServers.tools.apiKey.key',
+ 'mcpServers.tools.oauth.client_secret',
+ ]);
+ });
+
+ it('matches the location by its segments, so a dotted key does not spell one', () => {
+ expect(getEnvReferenceIssues({ 'ocr.apiKey': credential }, policy())).toHaveLength(1);
+ });
+
+ it("keeps an opaque key's ciphertext at runtime, and still blanks an expanded key's", () => {
+ const stored = encryptV3(credential);
+ const layer = {
+ ocr: { apiKey: stored },
+ webSearch: { jinaApiKey: stored },
+ langfuse: { secretKey: stored },
+ endpoints: { custom: [{ name: 'Gateway', apiKey: stored }] },
+ mcpServers: { tools: { apiKey: { key: stored } } },
+ };
+
+ expect(neutralizeEnvReferences(layer, policy())).toEqual({
+ ...layer,
+ endpoints: { custom: [{ name: 'Gateway', apiKey: '' }] },
+ mcpServers: { tools: { apiKey: { key: '' } } },
+ });
+ });
+
+ /** `resolveConfigSecret` expands a stored plaintext key (legacy, or written before encryption). */
+ it('still neutralizes a plaintext key stored at an opaque location', () => {
+ expect(
+ neutralizeEnvReferences({ speech: { tts: { openai: { apiKey: credential } } } }, policy()),
+ ).toEqual({ speech: { tts: { openai: { apiKey: 'pass' } } } });
+ });
+});
diff --git a/packages/api/src/app/allowlist.ts b/packages/api/src/app/allowlist.ts
new file mode 100644
index 0000000000..defc7c398d
--- /dev/null
+++ b/packages/api/src/app/allowlist.ts
@@ -0,0 +1,393 @@
+import isPlainObject from 'lodash/isPlainObject';
+import { EModelEndpoint, isSensitiveEnvVar } from 'librechat-data-provider';
+import { loadOCRConfig, loadWebSearchConfig } from '@librechat/data-schemas';
+import type { ConfigOverrideIssue } from '@librechat/data-schemas';
+import type { TCustomConfig } from 'librechat-data-provider';
+import {
+ isOpaqueSecretInput,
+ decryptConfigSecret,
+ isOpaqueStoredSecret,
+ isEncryptedSecretPayload,
+} from '~/admin/secrets';
+
+/** A `${NAME}` reference, in the grammar `extractEnvVariable` expands inside any string. */
+const ENV_REFERENCE = /\$\{([^}]+)\}/g;
+
+/** The issue a write gets for a value that references an env name outside the allowlist. */
+export const ENV_REFERENCE_NOT_ALLOWED = 'env_reference_not_allowed';
+
+/**
+ * Env names the built-in endpoints read for their credentials and base URLs
+ * (`api/server/services/Config/EndpointService.js`). The deployment already uses them for
+ * endpoint credentials, so an override may name them too.
+ */
+export const ENDPOINT_CREDENTIAL_ENV_NAMES: readonly string[] = [
+ 'OPENAI_API_KEY',
+ 'OPENAI_REVERSE_PROXY',
+ 'AZURE_API_KEY',
+ 'AZURE_OPENAI_BASEURL',
+ 'ASSISTANTS_API_KEY',
+ 'ASSISTANTS_BASE_URL',
+ 'AZURE_ASSISTANTS_API_KEY',
+ 'AZURE_ASSISTANTS_BASE_URL',
+ 'ANTHROPIC_API_KEY',
+ 'GOOGLE_KEY',
+ 'BEDROCK_AWS_BEARER_TOKEN',
+ 'BEDROCK_AWS_ACCESS_KEY_ID',
+ 'BEDROCK_AWS_SECRET_ACCESS_KEY',
+ 'BEDROCK_AWS_SESSION_TOKEN',
+];
+
+/**
+ * Which `${NAME}` references a value from a database override layer may resolve. librechat.yaml
+ * is the operator's own file and resolves any name; override layers are written through the
+ * admin API, so their references are limited to names the deployment already uses for config,
+ * and to the references loading librechat.yaml introduces, where it introduces them.
+ */
+export interface EnvReferencePolicy {
+ /** Whether a reference to `name` may resolve in the string at `segments` (override keys). */
+ allows(name: string, segments: readonly string[]): boolean;
+}
+
+/**
+ * Sections shown to users or sent to a model as written: nothing expands `${...}` in them
+ * (`interface` copy, model spec labels, greetings and preset prompts).
+ */
+export const ENV_LITERAL_TEXT_SECTIONS: readonly string[] = ['interface', 'modelSpecs'];
+
+/** Endpoints configured by name under `endpoints`; custom endpoints are a list. */
+const NAMED_ENDPOINTS: readonly string[] = [
+ 'all',
+ EModelEndpoint.openAI,
+ EModelEndpoint.google,
+ EModelEndpoint.anthropic,
+ EModelEndpoint.azureOpenAI,
+ EModelEndpoint.azureAssistants,
+ EModelEndpoint.assistants,
+ EModelEndpoint.agents,
+ EModelEndpoint.bedrock,
+];
+
+/** The system prompts an endpoint's title, activity and reasoning labels are written with. */
+const ENDPOINT_PROMPT_KEYS: readonly string[] = [
+ 'titlePrompt',
+ 'titlePromptTemplate',
+ 'activityPrompt',
+ 'activityPhasePrompt',
+ 'reasoningLabelPrompt',
+];
+
+/**
+ * Prompt and instruction fields outside those sections, by their full path in librechat.yaml
+ * keys; `*` stands for one custom endpoint (its position in the list). Only these exact locations
+ * are literal: a key of the same name anywhere else, such as an `X-Prompt` header or an
+ * `instructions` entry under `env` or `addParams`, is expanded by its reader and stays policed.
+ */
+export const ENV_LITERAL_TEXT_PATHS: readonly (readonly string[])[] = [
+ ...ENDPOINT_PROMPT_KEYS.flatMap((key) => [
+ ...NAMED_ENDPOINTS.map((endpoint) => ['endpoints', endpoint, key]),
+ ['endpoints', 'custom', '*', key],
+ ]),
+ ['summarization', 'prompt'],
+ ['summarization', 'updatePrompt'],
+ ['memory', 'agent', 'instructions'],
+ ['webSearch', 'firecrawlOptions', 'changeTrackingOptions', 'prompt'],
+];
+
+const LITERAL_TEXT_SECTIONS = new Set(ENV_LITERAL_TEXT_SECTIONS);
+
+function literalTextBucket(first: string, last: string): string {
+ return `${first}\u0000${last}`;
+}
+
+/** {@link ENV_LITERAL_TEXT_PATHS} by first and last segment, so a lookup compares only a few. */
+const LITERAL_TEXT_PATHS_BY_BUCKET = ENV_LITERAL_TEXT_PATHS.reduce((buckets, path) => {
+ const bucket = literalTextBucket(path[0], path[path.length - 1]);
+ buckets.set(bucket, [...(buckets.get(bucket) ?? []), path]);
+ return buckets;
+}, new Map<string, (readonly string[])[]>());
+
+function matchesPath(segments: readonly string[], pattern: readonly string[]): boolean {
+ return (
+ segments.length === pattern.length &&
+ pattern.every((segment, index) => segment === '*' || segment === segments[index])
+ );
+}
+
+/**
+ * Whether the string at `segments` (librechat.yaml keys, array items by index) is text no reader
+ * env-expands, so a `${...}` in it is literal and the env policy does not apply: anything in
+ * {@link ENV_LITERAL_TEXT_SECTIONS}, and exactly the fields in {@link ENV_LITERAL_TEXT_PATHS}.
+ * Everything else is policed, so a reader that starts expanding a new field is covered by default.
+ */
+export function isLiteralTextPath(segments: readonly string[]): boolean {
+ if (segments.length === 0) {
+ return false;
+ }
+ if (LITERAL_TEXT_SECTIONS.has(segments[0])) {
+ return true;
+ }
+ const paths = LITERAL_TEXT_PATHS_BY_BUCKET.get(
+ literalTextBucket(segments[0], segments[segments.length - 1]),
+ );
+ return paths != null && paths.some((pattern) => matchesPath(segments, pattern));
+}
+
+/** The templates the Azure client fills in a group's base URL from its instance and deployment. */
+const AZURE_URL_TEMPLATE_NAMES: ReadonlySet<string> = new Set(['INSTANCE_NAME', 'DEPLOYMENT_NAME']);
+
+/**
+ * Azure group base URLs, where `${INSTANCE_NAME}` and `${DEPLOYMENT_NAME}` are templates the Azure
+ * client fills (`constructAzureURL`), not env references; `*` stands for one group.
+ */
+export const AZURE_URL_TEMPLATE_PATHS: readonly (readonly string[])[] = [
+ ['endpoints', 'azureOpenAI', 'groups', '*', 'baseURL'],
+ ['endpoints', 'azureOpenAI', 'groupMap', '*', 'baseURL'],
+];
+
+/** Whether `name` at `segments` is an Azure base URL template rather than an env reference. */
+function isAzureURLTemplate(name: string, segments: readonly string[]): boolean {
+ return (
+ AZURE_URL_TEMPLATE_NAMES.has(name) &&
+ AZURE_URL_TEMPLATE_PATHS.some((pattern) => matchesPath(segments, pattern))
+ );
+}
+
+/** Splits `CONFIG_OVERRIDE_ENV_ALLOWLIST`: env names separated by commas or whitespace. */
+export function parseEnvAllowlist(value?: string | null): string[] {
+ return (value ?? '').split(/[\s,]+/).filter((name) => name !== '');
+}
+
+/** The env names the string at `segments` references (an Azure base URL template is none). */
+function referencedNames(text: string, segments: readonly string[]): string[] {
+ return Array.from(text.matchAll(ENV_REFERENCE), (match) => match[1]).filter(
+ (name) => !isAzureURLTemplate(name, segments),
+ );
+}
+
+/**
+ * Visits every string under `value` (object values and array items, not keys) outside literal
+ * text, with its location.
+ */
+function visitExpandedStrings(
+ value: unknown,
+ visit: (text: string, segments: readonly string[]) => void,
+ segments: readonly string[] = [],
+): void {
+ if (typeof value === 'string') {
+ if (!isLiteralTextPath(segments)) {
+ visit(value, segments);
+ }
+ return;
+ }
+ if (value == null || typeof value !== 'object') {
+ return;
+ }
+ const entries: Array<[string, unknown]> = Array.isArray(value)
+ ? value.map((item, index) => [String(index), item])
+ : Object.entries(value);
+ for (const [key, child] of entries) {
+ visitExpandedStrings(child, visit, [...segments, key]);
+ }
+}
+
+/** Every env name a config references where a reader expands it, at any depth. */
+export function collectEnvReferenceNames(value: unknown): Set<string> {
+ const names = new Set<string>();
+ visitExpandedStrings(value, (text, segments) => {
+ for (const name of referencedNames(text, segments)) {
+ names.add(name);
+ }
+ });
+ return names;
+}
+
+/** Joins segments so that a key containing a dot never spells another location. */
+function locationKey(segments: readonly string[]): string {
+ return segments.join('\u0000');
+}
+
+/**
+ * The sections AppService loads from librechat.yaml with references of their own for what the
+ * YAML leaves unset, as AppService loads them: OCR without a key uses `${OCR_API_KEY}`
+ * (`loadOCRConfig`, only for a YAML that configures OCR), and web search, always loaded, fills
+ * each unset URL and key with its default variable (`loadWebSearchConfig`, such as
+ * `${SEARXNG_INSTANCE_URL}`). The resolved config carries those references, so config reads
+ * return them and a client that writes back what it read restates them.
+ */
+function loadSectionsWithReferences(config: unknown): Partial<TCustomConfig> {
+ const yaml: Partial<TCustomConfig> = isPlainObject(config)
+ ? (config as Partial<TCustomConfig>)
+ : {};
+ const webSearch = isPlainObject(yaml.webSearch) ? yaml.webSearch : undefined;
+ return {
+ ...(yaml.ocr != null && { ocr: loadOCRConfig(yaml.ocr) }),
+ webSearch: loadWebSearchConfig(webSearch),
+ };
+}
+
+/**
+ * Every reference the loaded sections ({@link loadSectionsWithReferences}) hold, by the location
+ * it is at: a reference loading introduces is allowed there only, so a default variable of one
+ * field is not a name any other field may send.
+ */
+function collectLoadedReferences(config: unknown): Map<string, Set<string>> {
+ const references = new Map<string, Set<string>>();
+ visitExpandedStrings(loadSectionsWithReferences(config), (text, segments) => {
+ const names = referencedNames(text, segments);
+ if (names.length === 0) {
+ return;
+ }
+ const key = locationKey(segments);
+ const held = references.get(key) ?? new Set<string>();
+ names.forEach((name) => held.add(name));
+ references.set(key, held);
+ });
+ return references;
+}
+
+/**
+ * The allowlist: names librechat.yaml references (`config` is the raw YAML config), the
+ * built-in endpoints' credential names and the operator's extra names, anywhere; and each
+ * reference loading librechat.yaml introduces, at its own location
+ * ({@link collectLoadedReferences}). Infrastructure secrets `extractEnvVariable` never expands
+ * (`CREDS_KEY`, `JWT_SECRET`, ...) stay out whatever lists them.
+ */
+export function createEnvReferencePolicy(options: {
+ config?: unknown;
+ allowlist?: readonly string[];
+}): EnvReferencePolicy {
+ const names = collectEnvReferenceNames(options.config);
+ for (const name of [...ENDPOINT_CREDENTIAL_ENV_NAMES, ...(options.allowlist ?? [])]) {
+ names.add(name);
+ }
+ const loaded = collectLoadedReferences(options.config);
+ return {
+ allows: (name, segments) =>
+ !isSensitiveEnvVar(name) &&
+ (names.has(name) || loaded.get(locationKey(segments))?.has(name) === true),
+ };
+}
+
+function hasDisallowedReference(
+ text: string,
+ policy: EnvReferencePolicy,
+ segments: readonly string[],
+): boolean {
+ return referencedNames(text, segments).some((name) => !policy.allows(name, segments));
+}
+
+/**
+ * An issue for every string at or under `value`, as a write sends it, that references a name the
+ * policy does not allow, outside literal text ({@link isLiteralTextPath}) and opaque credentials
+ * (`isOpaqueSecretInput`: OCR, speech, web search and Langfuse keys, stored encrypted and read as
+ * is). `segments` locate `value` in the overrides. The issue carries the location only, never the
+ * value or the name.
+ */
+export function getEnvReferenceIssues(
+ value: unknown,
+ policy: EnvReferencePolicy,
+ segments: readonly string[] = [],
+): ConfigOverrideIssue[] {
+ if (typeof value === 'string') {
+ return !isLiteralTextPath(segments) &&
+ !isOpaqueSecretInput(segments, value) &&
+ hasDisallowedReference(value, policy, segments)
+ ? [{ path: segments.join('.'), segments: [...segments], code: ENV_REFERENCE_NOT_ALLOWED }]
+ : [];
+ }
+ if (value == null || typeof value !== 'object') {
+ return [];
+ }
+ const entries: Array<[string, unknown]> = Array.isArray(value)
+ ? value.map((item, index) => [String(index), item])
+ : Object.entries(value);
+ return entries.flatMap(([key, child]) =>
+ getEnvReferenceIssues(child, policy, [...segments, key]),
+ );
+}
+
+/**
+ * Whether a stored string at `segments` (override keys) references a name the policy does not
+ * allow, judged as the runtime pass judges it ({@link neutralizeEnvReferences}): never in literal
+ * text or an opaque credential (`isOpaqueStoredSecret`), and in other ciphertext by its plaintext,
+ * which the custom endpoint, Azure and MCP clients expand once decrypted. Ciphertext that does not
+ * decrypt references nothing: the decrypting reader treats it as missing.
+ */
+export function hasDisallowedStoredReference(
+ text: string,
+ policy: EnvReferencePolicy,
+ segments: readonly string[],
+): boolean {
+ if (isLiteralTextPath(segments) || isOpaqueStoredSecret(segments, text)) {
+ return false;
+ }
+ const plaintext = isEncryptedSecretPayload(text) ? decryptConfigSecret(text) : text;
+ return plaintext != null && hasDisallowedReference(plaintext, policy, segments);
+}
+
+/**
+ * A string with each disallowed reference resolved to nothing, as an unset variable leaves no
+ * value behind; allowed references stay for the runtime to expand. Removing a reference can join
+ * the text around it into a new one (`$${NOPE}{NAME}` leaves `${NAME}`), so the pass repeats
+ * until no disallowed reference is left. Ciphertext is judged whole
+ * ({@link hasDisallowedStoredReference}): a stored secret its client would expand into a
+ * disallowed name becomes `''`, and an opaque credential's stays as it is read, as is.
+ */
+function neutralizeText(
+ text: string,
+ policy: EnvReferencePolicy,
+ segments: readonly string[],
+): string {
+ if (isEncryptedSecretPayload(text)) {
+ return hasDisallowedStoredReference(text, policy, segments) ? '' : text;
+ }
+ let current = text;
+ while (current.includes('${')) {
+ const next = current.replace(ENV_REFERENCE, (reference, name: string) =>
+ policy.allows(name, segments) || isAzureURLTemplate(name, segments) ? reference : '',
+ );
+ if (next === current) {
+ break;
+ }
+ current = next;
+ }
+ return current;
+}
+
+/**
+ * A database override layer's values with every disallowed `${NAME}` reference resolved to
+ * nothing (see {@link neutralizeText}), applied before the layer merges so no runtime reader can
+ * expand it. Literal text ({@link isLiteralTextPath}) is left as written. Containers are copied
+ * only along the paths that change; the input is never mutated.
+ */
+export function neutralizeEnvReferences<T>(
+ value: T,
+ policy: EnvReferencePolicy,
+ segments: readonly string[] = [],
+): T {
+ if (typeof value === 'string') {
+ return (isLiteralTextPath(segments) ? value : neutralizeText(value, policy, segments)) as T;
+ }
+ if (value == null || typeof value !== 'object') {
+ return value;
+ }
+ if (segments.length === 1 && LITERAL_TEXT_SECTIONS.has(segments[0])) {
+ return value;
+ }
+ if (Array.isArray(value)) {
+ const items = value.map((item, index) =>
+ neutralizeEnvReferences(item, policy, [...segments, String(index)]),
+ );
+ return (items.some((item, index) => item !== value[index]) ? items : value) as T;
+ }
+ let changed: Record<string, unknown> | undefined;
+ for (const [key, child] of Object.entries(value)) {
+ const next = neutralizeEnvReferences(child, policy, [...segments, key]);
+ if (next !== child) {
+ changed ??= { ...(value as Record<string, unknown>) };
+ changed[key] = next;
+ }
+ }
+ return (changed ?? value) as T;
+}
diff --git a/packages/api/src/app/index.ts b/packages/api/src/app/index.ts
index a88e7d7437..e881c6f36b 100644
--- a/packages/api/src/app/index.ts
+++ b/packages/api/src/app/index.ts
@@ -1,4 +1,7 @@
export * from './service';
+export * from './allowlist';
+export * from './rebinding';
+export * from './overrides';
export * from './invalidation';
export * from './loader';
export * from './config';
diff --git a/packages/api/src/app/overrides.spec.ts b/packages/api/src/app/overrides.spec.ts
new file mode 100644
index 0000000000..29989249fc
--- /dev/null
+++ b/packages/api/src/app/overrides.spec.ts
@@ -0,0 +1,379 @@
+process.env.CREDS_KEY =
+ process.env.CREDS_KEY ?? '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
+
+import { PrincipalType } from 'librechat-data-provider';
+import type { AppConfig, ConfigOverrideLayer } from '@librechat/data-schemas';
+
+type DataSchemas = typeof import('@librechat/data-schemas');
+type Service = typeof import('./service');
+
+/** Loaded after `CREDS_KEY` is set: the encryption key is read when data-schemas loads. */
+let dataSchemas: DataSchemas;
+let createAppConfigService: Service['createAppConfigService'];
+
+beforeAll(async () => {
+ dataSchemas = await import('@librechat/data-schemas');
+ ({ createAppConfigService } = await import('./service'));
+});
+
+const yaml = {
+ ocr: { apiKey: '${OCR_API_KEY}', baseURL: 'https://api.mistral.ai/v1' },
+ mcpServers: {
+ tools: { type: 'streamable-http', url: 'https://tools.example.com/mcp' },
+ },
+};
+
+function createService(
+ layers: ConfigOverrideLayer[],
+ overrideEnvAllowlist?: string,
+ baseYaml: Record<string, unknown> = yaml,
+) {
+ const store = new Map<string, unknown>();
+ const cache = {
+ get: async (key: string) => store.get(key),
+ set: async (key: string, value: unknown) => {
+ store.set(key, value);
+ },
+ delete: async (key: string) => store.delete(key),
+ };
+ const source = structuredClone(baseYaml) as typeof yaml & {
+ endpoints?: { custom?: unknown[] };
+ };
+ const baseConfig = {
+ config: source,
+ ocr: structuredClone(source.ocr),
+ mcpConfig: structuredClone(source.mcpServers),
+ ...(source.endpoints && { endpoints: structuredClone(source.endpoints) }),
+ } as unknown as AppConfig;
+ const service = createAppConfigService({
+ loadBaseConfig: async () => baseConfig,
+ setCachedTools: async () => undefined,
+ getCache: () => cache,
+ cacheKeys: { APP_CONFIG: 'app_config' },
+ getApplicableConfigs: async () => layers,
+ getUserPrincipals: async () => [{ principalType: PrincipalType.ROLE, principalId: 'USER' }],
+ overrideEnvAllowlist,
+ });
+ return { ...service, store };
+}
+
+function roleLayer(overrides: Record<string, unknown>): ConfigOverrideLayer {
+ return {
+ principalType: PrincipalType.ROLE,
+ principalId: 'USER',
+ priority: 10,
+ overrides,
+ } as ConfigOverrideLayer;
+}
+
+describe('getAppConfig with admin-written overrides', () => {
+ it('hands runtime readers the decrypted MCP credentials an override stores', async () => {
+ const stored = dataSchemas.encryptV3('sk-runtime-mcp-key');
+ const secret = dataSchemas.encryptV3('runtime-client-secret');
+ const { getAppConfig } = createService([
+ roleLayer({
+ mcpServers: {
+ tools: {
+ apiKey: {
+ source: 'admin',
+ authorization_type: 'bearer',
+ key: stored,
+ keyPreview: '...-key',
+ },
+ oauth: {
+ client_id: 'client',
+ client_secret: secret,
+ authorization_url: 'https://auth.example.com/authorize',
+ token_url: 'https://auth.example.com/token',
+ },
+ },
+ },
+ }),
+ ]);
+
+ const config = await getAppConfig({ role: 'USER' });
+ const server = config.mcpConfig?.tools as {
+ url: string;
+ apiKey: Record<string, string>;
+ oauth: Record<string, string>;
+ };
+
+ expect(server.url).toBe('https://tools.example.com/mcp');
+ expect(server.apiKey.key).toBe('sk-runtime-mcp-key');
+ expect(server.oauth.client_secret).toBe('runtime-client-secret');
+ expect(JSON.stringify(config)).not.toContain(stored);
+
+ const yamlOnly = await getAppConfig({ baseOnly: true });
+ expect(yamlOnly.mcpConfig?.tools).toEqual(yaml.mcpServers.tools);
+ });
+
+ it('keeps ciphertext in the shared override cache and decrypts it on every read', async () => {
+ const stored = dataSchemas.encryptV3('sk-cached-mcp-key');
+ const { getAppConfig, store } = createService([
+ roleLayer({
+ mcpServers: {
+ tools: { apiKey: { source: 'admin', authorization_type: 'bearer', key: stored } },
+ },
+ }),
+ ]);
+
+ const first = await getAppConfig({ role: 'USER' });
+ expect((first.mcpConfig?.tools as { apiKey: { key: string } }).apiKey.key).toBe(
+ 'sk-cached-mcp-key',
+ );
+
+ const cachedKeys = [...store.keys()].filter((key) => key.startsWith('_OVERRIDE_'));
+ expect(cachedKeys).toHaveLength(1);
+ const cached = JSON.stringify(store.get(cachedKeys[0]));
+ expect(cached).toContain(stored);
+ expect(cached).not.toContain('sk-cached-mcp-key');
+
+ /** A Redis-backed cache hands back a fresh copy on every read. */
+ store.set(cachedKeys[0], JSON.parse(cached));
+ const fromCache = await getAppConfig({ role: 'USER' });
+ expect((fromCache.mcpConfig?.tools as { apiKey: { key: string } }).apiKey.key).toBe(
+ 'sk-cached-mcp-key',
+ );
+ });
+
+ it('keeps `${...}` in text no reader expands', async () => {
+ const welcome = 'Tip: template literals look like `${name}`';
+ const { getAppConfig } = createService([roleLayer({ interface: { customWelcome: welcome } })]);
+
+ const config = await getAppConfig({ role: 'USER' });
+ expect(config.interfaceConfig?.customWelcome).toBe(welcome);
+ });
+
+ it('resolves a disallowed env reference in an override to nothing', async () => {
+ const { getAppConfig } = createService([
+ roleLayer({
+ ocr: { apiKey: '${CREDS_KEY}', baseURL: 'https://api.mistral.ai/${UNLISTED}' },
+ mcpServers: { tools: { headers: { Authorization: 'Bearer ${OCR_API_KEY}' } } },
+ }),
+ ]);
+
+ const config = await getAppConfig({ role: 'USER' });
+
+ expect(config.ocr?.apiKey).toBe('');
+ expect(config.ocr?.baseURL).toBe('https://api.mistral.ai/');
+ /** librechat.yaml references OCR_API_KEY, so an override may too. */
+ expect((config.mcpConfig?.tools as { headers: Record<string, string> }).headers).toEqual({
+ Authorization: 'Bearer ${OCR_API_KEY}',
+ });
+ });
+
+ it('keeps a reference the operator allowlists', async () => {
+ const { getAppConfig } = createService(
+ [roleLayer({ ocr: { apiKey: '${GATEWAY_OCR_KEY}' } })],
+ 'GATEWAY_OCR_KEY,OTHER',
+ );
+
+ const config = await getAppConfig({ role: 'USER' });
+ expect(config.ocr?.apiKey).toBe('${GATEWAY_OCR_KEY}');
+ });
+
+ it('drops an inherited credential an override points somewhere else', async () => {
+ const warn = jest.spyOn(dataSchemas.logger, 'warn').mockReturnValue(dataSchemas.logger);
+ const { getAppConfig } = createService([
+ roleLayer({ ocr: { baseURL: 'https://evil.example/v1' } }),
+ ]);
+
+ const config = await getAppConfig({ role: 'USER' });
+
+ expect(config.ocr).toMatchObject({ apiKey: '', baseURL: 'https://evil.example/v1' });
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('Dropping secret "ocr.apiKey" for role/USER'),
+ );
+ });
+
+ it("serves a profile's own key bound to a destination Base defines, without the fingerprint", async () => {
+ const { mergeOverrideLayers } = await import('./overrides');
+ const { createEnvReferencePolicy } = await import('./allowlist');
+ const baseLayer = {
+ principalType: PrincipalType.ROLE,
+ principalId: dataSchemas.BASE_CONFIG_PRINCIPAL_ID,
+ priority: 0,
+ overrides: {
+ mcpServers: {
+ shared: {
+ type: 'streamable-http',
+ url: 'https://shared.example.com/mcp',
+ apiKey: {
+ source: 'admin',
+ authorization_type: 'bearer',
+ key: dataSchemas.encryptV3('sk-base-key'),
+ },
+ },
+ },
+ },
+ } as ConfigOverrideLayer;
+ const ownKey = (keyBinding?: string) =>
+ roleLayer({
+ mcpServers: {
+ shared: {
+ apiKey: {
+ source: 'admin',
+ authorization_type: 'bearer',
+ key: dataSchemas.encryptV3('sk-role-key'),
+ ...(keyBinding != null && { keyBinding }),
+ },
+ },
+ },
+ });
+ const bindings: Array<string | undefined> = [];
+ mergeOverrideLayers({ config: yaml } as unknown as AppConfig, [baseLayer, ownKey()], {
+ envPolicy: createEnvReferencePolicy({ config: yaml }),
+ onRebinding: ({ layer, binding }) => {
+ if (layer.principalId === 'USER') {
+ bindings.push(binding);
+ }
+ },
+ });
+ expect(bindings).toEqual([expect.stringMatching(/^[0-9a-f]{64}$/)]);
+
+ const unbound = await createService([baseLayer, ownKey()]).getAppConfig({ role: 'USER' });
+ expect((unbound.mcpConfig?.shared as { apiKey: { key: string } }).apiKey.key).toBe('');
+
+ const config = await createService([baseLayer, ownKey(bindings[0])]).getAppConfig({
+ role: 'USER',
+ });
+ expect(config.mcpConfig?.shared).toMatchObject({
+ url: 'https://shared.example.com/mcp',
+ apiKey: { key: 'sk-role-key' },
+ });
+ expect(JSON.stringify(config)).not.toContain('keyBinding');
+ });
+
+ it('resolves ${...} under a prompt-named header to nothing, and keeps a real prompt as text', async () => {
+ const { getAppConfig } = createService([
+ roleLayer({
+ mcpServers: {
+ tools: { headers: { 'X-Prompt': '${HOME}', instructions: 'Bearer ${CREDS_KEY}' } },
+ },
+ summarization: { prompt: 'Summarize ${conversation}' },
+ }),
+ ]);
+
+ const config = await getAppConfig({ role: 'USER' });
+
+ expect((config.mcpConfig?.tools as { headers: Record<string, string> }).headers).toEqual({
+ 'X-Prompt': '',
+ instructions: 'Bearer ',
+ });
+ expect(config.summarization?.prompt).toBe('Summarize ${conversation}');
+ });
+
+ it('never hands summarization a destination an override chose without its own key', async () => {
+ const warn = jest.spyOn(dataSchemas.logger, 'warn').mockReturnValue(dataSchemas.logger);
+ const { getAppConfig } = createService([
+ roleLayer({
+ summarization: {
+ provider: 'openAI',
+ parameters: { baseURL: 'https://evil.example/v1', apiKey: '${CREDS_KEY}' },
+ },
+ }),
+ ]);
+
+ const config = await getAppConfig({ role: 'USER' });
+
+ /** The disallowed reference resolves to nothing, so the provider's own key would be used. */
+ expect(config.summarization?.parameters).toEqual({ apiKey: '' });
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('Ignoring "summarization.parameters.baseURL" for role/USER'),
+ );
+ });
+
+ it("does not allow a name only another tenant's librechat.yaml endpoint references", async () => {
+ const tenantYaml = {
+ ...yaml,
+ endpoints: {
+ custom: [
+ {
+ name: 'Tenant A Gateway',
+ tenantId: 'tenant-a',
+ apiKey: '${TENANT_A_KEY}',
+ baseURL: 'https://a.example/v1',
+ models: { default: ['a-model'] },
+ },
+ ],
+ },
+ };
+ const { getAppConfig } = createService(
+ [roleLayer({ ocr: { apiKey: '${TENANT_A_KEY}' } })],
+ undefined,
+ tenantYaml,
+ );
+
+ const owner = await getAppConfig({ role: 'USER', tenantId: 'tenant-a' });
+ expect(owner.ocr?.apiKey).toBe('${TENANT_A_KEY}');
+
+ const other = await getAppConfig({ role: 'USER', tenantId: 'tenant-b' });
+ expect(other.ocr?.apiKey).toBe('');
+ });
+});
+
+describe('mergeOverrideLayers and web search keys', () => {
+ const SEARX = { searxngInstanceUrl: 'https://searx.corp.example', searxngApiKey: 'sx-yaml-key' };
+ const webSearchBase = () =>
+ ({ config: { webSearch: { ...SEARX } }, webSearch: { ...SEARX } }) as unknown as AppConfig;
+ const layerAt = (principalId: string, priority: number, webSearch: Record<string, unknown>) =>
+ ({
+ principalType: PrincipalType.ROLE,
+ principalId,
+ priority,
+ overrides: { webSearch },
+ }) as ConfigOverrideLayer;
+
+ async function mergeWebSearch(layers: ConfigOverrideLayer[]) {
+ const [{ mergeOverrideLayers }, { createEnvReferencePolicy }] = await Promise.all([
+ import('./overrides'),
+ import('./allowlist'),
+ ]);
+ const rebindings: Array<{ principalId: string; kind: string; path: string }> = [];
+ const merged = mergeOverrideLayers(webSearchBase(), layers, {
+ envPolicy: createEnvReferencePolicy({ allowlist: ['SEARXNG_URL'] }),
+ onRebinding: ({ layer, kind, path }) =>
+ rebindings.push({ principalId: layer.principalId.toString(), kind, path }),
+ });
+ return { webSearch: merged.webSearch as Record<string, unknown> | undefined, rebindings };
+ }
+
+ it('reports the key the merge withholds from a URL a layer moves, naming that layer', async () => {
+ const { webSearch, rebindings } = await mergeWebSearch([
+ layerAt('USER', 10, { searxngInstanceUrl: 'https://evil.example' }),
+ ]);
+
+ expect(webSearch?.searxngApiKey).toBeUndefined();
+ expect(rebindings).toEqual([
+ { principalId: 'USER', kind: 'secret', path: 'webSearch.searxngApiKey' },
+ ]);
+ });
+
+ it('keeps a key stored over a ${VAR} URL a lower layer set, as webSearchStoredKeys states', async () => {
+ const stored = dataSchemas.encryptV3('sx-editors-key');
+ const { webSearch, rebindings } = await mergeWebSearch([
+ layerAt('__base__', 0, {
+ searxngInstanceUrl: '${SEARXNG_URL}',
+ searxngApiKey: dataSchemas.encryptV3('sx-base-key'),
+ }),
+ layerAt('editors', 10, { searxngApiKey: stored }),
+ ]);
+
+ expect(webSearch?.searxngInstanceUrl).toBe('${SEARXNG_URL}');
+ expect(webSearch?.searxngApiKey).toBe(stored);
+ expect(rebindings).toEqual([]);
+ });
+
+ it('sets back a ${VAR} URL a layer sets without entering the key the client would send it', async () => {
+ const { webSearch, rebindings } = await mergeWebSearch([
+ layerAt('__base__', 0, { searxngInstanceUrl: '${SEARXNG_URL}' }),
+ ]);
+
+ expect(webSearch?.searxngInstanceUrl).toBe(SEARX.searxngInstanceUrl);
+ expect(rebindings).toContainEqual({
+ principalId: '__base__',
+ kind: 'destination',
+ path: 'webSearch.searxngInstanceUrl',
+ });
+ });
+});
diff --git a/packages/api/src/app/overrides.ts b/packages/api/src/app/overrides.ts
new file mode 100644
index 0000000000..54cfdddd08
--- /dev/null
+++ b/packages/api/src/app/overrides.ts
@@ -0,0 +1,58 @@
+import { mergeConfigOverrides } from '@librechat/data-schemas';
+import type { AppConfig, ConfigOverrideLayer } from '@librechat/data-schemas';
+import type { EnvReferencePolicy } from './allowlist';
+import type { SecretRebinding } from './rebinding';
+import { createSecretRebindingGuard, withoutSecretBindings } from './rebinding';
+import { resolveRuntimeConfigSecrets } from '~/admin/secrets';
+import { neutralizeEnvReferences } from './allowlist';
+
+export interface OverrideMergeOptions {
+ /** Which `${NAME}` references values from override layers may resolve. */
+ envPolicy: EnvReferencePolicy;
+ /** Told about each inherited secret a layer drops for sending it somewhere new. */
+ onRebinding?: (rebinding: SecretRebinding) => void;
+}
+
+/**
+ * Merges database override layers into the base config under the policies that apply to
+ * admin-written values: each layer's disallowed `${NAME}` references resolve to nothing before it
+ * merges, and a secret sent anywhere but the destination it was entered for is dropped
+ * (`createSecretRebindingGuard`; web search keys by the merge's own rule, whose drops are
+ * reported the same way). The destination fingerprints stored beside secrets are read by the
+ * guard and left out of the result (`withoutSecretBindings`). Secrets stay as stored, so the
+ * result may be cached as is.
+ */
+export function mergeOverrideLayers(
+ baseConfig: AppConfig,
+ layers: readonly ConfigOverrideLayer[],
+ options: OverrideMergeOptions,
+): AppConfig {
+ const neutralized = layers.map((layer) => {
+ const overrides = neutralizeEnvReferences(layer.overrides, options.envPolicy);
+ return overrides === layer.overrides ? layer : { ...layer, overrides };
+ });
+ const { onRebinding } = options;
+ const merged = mergeConfigOverrides(baseConfig, neutralized, {
+ afterLayer: createSecretRebindingGuard(onRebinding),
+ onWebSearchKeyUnbound: ({ layer, apiKey }) =>
+ onRebinding?.({
+ layer,
+ kind: 'secret',
+ segments: ['webSearch', apiKey],
+ path: `webSearch.${apiKey}`,
+ }),
+ });
+ return withoutSecretBindings(merged);
+}
+
+/**
+ * {@link mergeOverrideLayers}, then the stored credentials runtime readers need in plaintext
+ * decrypted once (`resolveRuntimeConfigSecrets`).
+ */
+export function resolveConfigOverrides(
+ baseConfig: AppConfig,
+ layers: readonly ConfigOverrideLayer[],
+ options: OverrideMergeOptions,
+): AppConfig {
+ return resolveRuntimeConfigSecrets(mergeOverrideLayers(baseConfig, layers, options));
+}
diff --git a/packages/api/src/app/rebinding.spec.ts b/packages/api/src/app/rebinding.spec.ts
new file mode 100644
index 0000000000..a2de856f52
--- /dev/null
+++ b/packages/api/src/app/rebinding.spec.ts
@@ -0,0 +1,1838 @@
+import { PrincipalType } from 'librechat-data-provider';
+import { mergeConfigOverrides } from '@librechat/data-schemas';
+import type { AppConfig, ConfigOverrideLayer } from '@librechat/data-schemas';
+import type { SecretRebinding } from './rebinding';
+import {
+ withoutSecretBindings,
+ toIgnoredSecretOverride,
+ createSecretRebindingGuard,
+} from './rebinding';
+
+function layer(
+ overrides: Record<string, unknown>,
+ principalId = 'editors',
+ priority = 10,
+): ConfigOverrideLayer {
+ return {
+ principalType: PrincipalType.ROLE,
+ principalId,
+ priority,
+ overrides,
+ } as ConfigOverrideLayer;
+}
+
+const customEndpoint = {
+ name: 'Gateway',
+ apiKey: '${GATEWAY_KEY}',
+ baseURL: 'https://gateway.example.com/v1',
+ models: { default: ['gpt-4o'] },
+};
+
+const mcpServer = {
+ type: 'streamable-http',
+ url: 'https://mcp.example.com/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: '${MCP_KEY}' },
+ oauth: {
+ client_id: 'client',
+ client_secret: '${MCP_CLIENT_SECRET}',
+ authorization_url: 'https://auth.example.com/authorize',
+ token_url: 'https://auth.example.com/token',
+ },
+};
+
+function baseConfig(): AppConfig {
+ const config = {
+ endpoints: { custom: [customEndpoint] },
+ mcpServers: { tools: mcpServer },
+ ocr: { apiKey: '${OCR_API_KEY}', baseURL: 'https://api.mistral.ai/v1' },
+ webSearch: {
+ firecrawlApiKey: '${FIRECRAWL_API_KEY}',
+ firecrawlApiUrl: 'https://api.firecrawl.dev',
+ },
+ };
+ return {
+ config,
+ endpoints: { custom: [{ ...customEndpoint }] },
+ mcpConfig: { tools: structuredClone(mcpServer) },
+ ocr: { ...config.ocr },
+ webSearch: { ...config.webSearch },
+ } as unknown as AppConfig;
+}
+
+function merge(layers: ConfigOverrideLayer[], base = baseConfig()) {
+ const rebindings: SecretRebinding[] = [];
+ const merged = mergeConfigOverrides(base, layers, {
+ afterLayer: createSecretRebindingGuard((rebinding) => rebindings.push(rebinding)),
+ });
+ return { merged, rebindings, ignored: rebindings.map(toIgnoredSecretOverride) };
+}
+
+describe('createSecretRebindingGuard', () => {
+ it('drops an inherited custom endpoint key when a layer points the endpoint elsewhere', () => {
+ const { merged, ignored } = merge([
+ layer({ endpoints: { custom: [{ name: 'Gateway', baseURL: 'https://evil.example/v1' }] } }),
+ ]);
+
+ expect(merged.endpoints?.custom?.[0]).toMatchObject({
+ name: 'Gateway',
+ apiKey: '',
+ baseURL: 'https://evil.example/v1',
+ });
+ expect(ignored).toEqual([
+ {
+ path: 'endpoints.custom["Gateway"].apiKey',
+ segments: ['endpoints', 'custom', 'Gateway', 'apiKey'],
+ reason: 'secret_rebinding',
+ },
+ ]);
+ });
+
+ it('keeps the key when the layer supplies it again, or leaves the binding as it was', () => {
+ const resupplied = merge([
+ layer({
+ endpoints: {
+ custom: [
+ { name: 'Gateway', baseURL: 'https://other.example/v1', apiKey: '${OTHER_KEY}' },
+ ],
+ },
+ }),
+ ]);
+ expect(resupplied.merged.endpoints?.custom?.[0]?.apiKey).toBe('${OTHER_KEY}');
+ expect(resupplied.rebindings).toEqual([]);
+
+ const sameHost = merge([
+ layer({
+ endpoints: {
+ custom: [{ name: 'Gateway', baseURL: 'https://gateway.example.com/v1#frag' }],
+ },
+ }),
+ ]);
+ expect(sameHost.merged.endpoints?.custom?.[0]?.apiKey).toBe('${GATEWAY_KEY}');
+
+ const unrelated = merge([
+ layer({ endpoints: { custom: [{ name: 'Gateway', models: { default: ['gpt-5'] } }] } }),
+ ]);
+ expect(unrelated.merged.endpoints?.custom?.[0]?.apiKey).toBe('${GATEWAY_KEY}');
+ expect(unrelated.rebindings).toEqual([]);
+ });
+
+ /**
+ * The documented limit of the guard: a `${VAR}` reference is visible to config readers, so a
+ * layer that restates it beside a destination of its own enters it, as it would any key. Which
+ * names a layer may reference is the env allowlist's to decide (`app/allowlist.ts`).
+ */
+ it('keeps an inherited ${VAR} reference a layer restates beside its own destination', () => {
+ const restated = merge([
+ layer({
+ endpoints: {
+ custom: [
+ { name: 'Gateway', baseURL: 'https://evil.example/v1', apiKey: '${GATEWAY_KEY}' },
+ ],
+ },
+ mcpServers: {
+ tools: {
+ url: 'https://evil.example/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: '${MCP_KEY}' },
+ oauth: { client_secret: '${MCP_CLIENT_SECRET}' },
+ },
+ },
+ ocr: { baseURL: 'https://evil.example/ocr', apiKey: '${OCR_API_KEY}' },
+ }),
+ ]);
+ expect(restated.merged.endpoints?.custom?.[0]).toMatchObject({
+ apiKey: '${GATEWAY_KEY}',
+ baseURL: 'https://evil.example/v1',
+ });
+ expect(restated.merged.mcpConfig?.tools?.apiKey?.key).toBe('${MCP_KEY}');
+ expect(restated.merged.mcpConfig?.tools?.oauth?.client_secret).toBe('${MCP_CLIENT_SECRET}');
+ expect(restated.merged.ocr?.apiKey).toBe('${OCR_API_KEY}');
+ expect(restated.rebindings).toEqual([]);
+
+ const moved = merge([
+ layer({
+ endpoints: { custom: [{ name: 'Gateway', baseURL: 'https://evil.example/v1' }] },
+ mcpServers: { tools: { url: 'https://evil.example/mcp' } },
+ ocr: { baseURL: 'https://evil.example/ocr' },
+ }),
+ ]);
+ expect(moved.ignored.map(({ path }) => path)).toEqual([
+ 'ocr.apiKey',
+ 'endpoints.custom["Gateway"].apiKey',
+ 'mcpServers.tools.apiKey.key',
+ 'mcpServers.tools.oauth.client_secret',
+ ]);
+ });
+
+ it('drops an inherited MCP api key when the server URL changes', () => {
+ const { merged, ignored } = merge([
+ layer({ mcpServers: { tools: { url: 'https://evil.example/mcp' } } }),
+ ]);
+
+ const server = merged.mcpConfig?.tools as typeof mcpServer;
+ expect(server.apiKey.key).toBe('');
+ /** The OAuth secret is bound to the server URL too, as in the user-managed tier. */
+ expect(server.oauth.client_secret).toBe('');
+ expect(ignored.map(({ path }) => path)).toEqual([
+ 'mcpServers.tools.apiKey.key',
+ 'mcpServers.tools.oauth.client_secret',
+ ]);
+ });
+
+ it('drops only the OAuth secret when only its endpoints change', () => {
+ const { merged, ignored } = merge([
+ layer({ mcpServers: { tools: { oauth: { token_url: 'https://evil.example/token' } } } }),
+ ]);
+
+ const server = merged.mcpConfig?.tools as typeof mcpServer;
+ expect(server.apiKey.key).toBe('${MCP_KEY}');
+ expect(server.oauth.client_secret).toBe('');
+ expect(ignored.map(({ path }) => path)).toEqual(['mcpServers.tools.oauth.client_secret']);
+ });
+
+ it('drops an inherited OAuth secret when a layer routes its access token through a proxy', () => {
+ const oauthOnly = baseConfig();
+ const { type, url, oauth } = mcpServer;
+ oauthOnly.mcpConfig = {
+ tools: structuredClone({ type, url, oauth }),
+ } as AppConfig['mcpConfig'];
+
+ const { merged, ignored } = merge(
+ [layer({ mcpServers: { tools: { proxy: 'http://proxy.evil.example:8080' } } })],
+ oauthOnly,
+ );
+
+ expect((merged.mcpConfig?.tools as typeof mcpServer).oauth.client_secret).toBe('');
+ expect(ignored.map(({ path }) => path)).toEqual(['mcpServers.tools.oauth.client_secret']);
+ });
+
+ it('treats the http transport spelling as the same binding', () => {
+ const { rebindings } = merge([layer({ mcpServers: { tools: { type: 'http' } } })]);
+ expect(rebindings).toEqual([]);
+ });
+
+ it('drops scalar secrets bound to a URL beside them', () => {
+ const { merged, ignored } = merge([layer({ ocr: { baseURL: 'https://evil.example/v1' } })]);
+
+ expect(merged.ocr?.apiKey).toBe('');
+ expect(ignored.map(({ path }) => path)).toEqual(['ocr.apiKey']);
+ });
+
+ it('leaves web search keys to the merge rule, under which web search reads env keys', () => {
+ const { merged, rebindings } = merge([
+ layer({ webSearch: { firecrawlApiUrl: 'https://evil.example' } }),
+ ]);
+
+ expect(merged.webSearch?.firecrawlApiKey).toBe('${FIRECRAWL_API_KEY}');
+ expect(rebindings).toEqual([]);
+ });
+
+ it('keeps a key a higher layer supplies with the destination it sets itself', () => {
+ const { merged, rebindings } = merge([
+ layer({ mcpServers: { tools: { url: 'https://moved.example/mcp' } } }, '__base__', 0),
+ layer(
+ {
+ mcpServers: {
+ tools: {
+ url: 'https://editors.example/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: '${EDITORS_KEY}' },
+ },
+ },
+ },
+ 'editors',
+ 10,
+ ),
+ ]);
+
+ const server = merged.mcpConfig?.tools as typeof mcpServer;
+ expect(server.url).toBe('https://editors.example/mcp');
+ expect(server.apiKey.key).toBe('${EDITORS_KEY}');
+ expect(rebindings.map(({ layer: { principalId }, path }) => [principalId, path])).toEqual([
+ ['__base__', 'mcpServers.tools.apiKey.key'],
+ ['__base__', 'mcpServers.tools.oauth.client_secret'],
+ ]);
+ });
+
+ describe('a key a layer supplies, under a destination a lower layer moved', () => {
+ const editorsKey = (key = 'v3:editors-ciphertext') =>
+ layer(
+ {
+ mcpServers: { tools: { apiKey: { source: 'admin', authorization_type: 'bearer', key } } },
+ },
+ 'editors',
+ 10,
+ );
+
+ it('drops the key when a lower layer moved the server URL beneath it', () => {
+ const { merged, rebindings } = merge([
+ layer({ mcpServers: { tools: { url: 'https://evil.example/mcp' } } }, '__base__', 0),
+ editorsKey(),
+ ]);
+
+ const server = merged.mcpConfig?.tools as typeof mcpServer;
+ expect(server.url).toBe('https://evil.example/mcp');
+ expect(server.apiKey.key).toBe('');
+ expect(rebindings.map(({ layer: { principalId }, path }) => [principalId, path])).toEqual([
+ ['__base__', 'mcpServers.tools.apiKey.key'],
+ ['__base__', 'mcpServers.tools.oauth.client_secret'],
+ ['editors', 'mcpServers.tools.apiKey.key'],
+ ]);
+ });
+
+ it('drops the key when a lower profile routes the server through its own proxy', () => {
+ const { merged, rebindings } = merge([
+ layer({ mcpServers: { tools: { proxy: 'http://proxy.evil.example:8080' } } }, 'low', 5),
+ editorsKey(),
+ ]);
+
+ expect((merged.mcpConfig?.tools as typeof mcpServer).apiKey.key).toBe('');
+ expect(rebindings.map(({ layer: { principalId }, path }) => [principalId, path])).toEqual([
+ ['low', 'mcpServers.tools.apiKey.key'],
+ ['low', 'mcpServers.tools.oauth.client_secret'],
+ ['editors', 'mcpServers.tools.apiKey.key'],
+ ]);
+ });
+
+ it('keeps a key and URL the layer sets on a server a lower layer defines, type and all', () => {
+ const { merged, rebindings } = merge([
+ layer(
+ {
+ mcpServers: {
+ defined: {
+ type: 'streamable-http',
+ url: 'https://base.example/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: 'v3:base' },
+ },
+ },
+ },
+ '__base__',
+ 0,
+ ),
+ layer(
+ {
+ mcpServers: {
+ defined: {
+ url: 'https://editors.example/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: 'v3:editors' },
+ },
+ },
+ },
+ 'editors',
+ 10,
+ ),
+ ]);
+
+ expect(merged.mcpConfig?.defined).toMatchObject({
+ type: 'streamable-http',
+ url: 'https://editors.example/mcp',
+ apiKey: { key: 'v3:editors' },
+ });
+ expect(rebindings).toEqual([]);
+ });
+
+ it('keeps the key when the layers below changed nothing that binds it', () => {
+ const { merged, rebindings } = merge([
+ layer({ mcpServers: { tools: { title: 'Tools', timeout: 30000 } } }, '__base__', 0),
+ editorsKey(),
+ ]);
+
+ expect((merged.mcpConfig?.tools as typeof mcpServer).apiKey.key).toBe(
+ 'v3:editors-ciphertext',
+ );
+ expect(rebindings).toEqual([]);
+ });
+
+ it('drops a custom endpoint key when a lower layer moved the base URL beneath it', () => {
+ const { merged, ignored, rebindings } = merge([
+ layer(
+ { endpoints: { custom: [{ name: 'Gateway', baseURL: 'https://attacker.example/v1' }] } },
+ '__base__',
+ 0,
+ ),
+ layer(
+ { endpoints: { custom: [{ name: 'Gateway', apiKey: 'v3:group-ciphertext' }] } },
+ 'group',
+ 20,
+ ),
+ ]);
+
+ expect(merged.endpoints?.custom?.[0]).toMatchObject({
+ apiKey: '',
+ baseURL: 'https://attacker.example/v1',
+ });
+ expect(rebindings.map(({ layer: { principalId } }) => principalId)).toEqual([
+ '__base__',
+ 'group',
+ ]);
+ expect(ignored[1]).toEqual({
+ path: 'endpoints.custom["Gateway"].apiKey',
+ segments: ['endpoints', 'custom', 'Gateway', 'apiKey'],
+ reason: 'secret_rebinding',
+ });
+ });
+
+ it('drops a scalar key when a lower layer moved its URL beneath it', () => {
+ const { merged, rebindings } = merge([
+ layer({ ocr: { baseURL: 'https://attacker.example/v1' } }, '__base__', 0),
+ layer({ ocr: { apiKey: 'v3:ocr-ciphertext' } }, 'editors', 10),
+ ]);
+
+ expect(merged.ocr?.apiKey).toBe('');
+ expect(rebindings.map(({ layer: { principalId }, path }) => [principalId, path])).toEqual([
+ ['__base__', 'ocr.apiKey'],
+ ['editors', 'ocr.apiKey'],
+ ]);
+ });
+
+ it("measures the layer's destination after its own tombstones", () => {
+ const { merged, rebindings } = merge([
+ {
+ ...layer({ ocr: { apiKey: 'v3:ocr-ciphertext' } }, 'editors', 10),
+ tombstones: ['ocr.baseURL'],
+ } as ConfigOverrideLayer,
+ ]);
+
+ expect(merged.ocr?.baseURL).toBeUndefined();
+ expect(merged.ocr?.apiKey).toBe('v3:ocr-ciphertext');
+ expect(rebindings).toEqual([]);
+ });
+ });
+
+ describe('values each user supplies', () => {
+ /** A base config with a `user_provided` endpoint beside the keyed one. */
+ function withUserEndpoint(endpoint: Record<string, unknown> = {}): AppConfig {
+ const base = baseConfig();
+ (base.endpoints as { custom: unknown[] }).custom.push({
+ ...customEndpoint,
+ name: 'Regional',
+ apiKey: 'user_provided',
+ ...endpoint,
+ });
+ return base;
+ }
+
+ it("sets back the destination of a user_provided endpoint a layer moves, as users' keys follow its name", () => {
+ const { merged, rebindings, ignored } = merge(
+ [
+ layer({
+ endpoints: {
+ custom: [{ name: 'Regional', baseURL: 'https://attacker.example/v1' }],
+ },
+ }),
+ ],
+ withUserEndpoint(),
+ );
+
+ expect(merged.endpoints?.custom?.[1]).toMatchObject({
+ name: 'Regional',
+ apiKey: 'user_provided',
+ baseURL: customEndpoint.baseURL,
+ });
+ expect(rebindings.map(({ kind }) => kind)).toEqual(['destination']);
+ expect(ignored).toEqual([
+ {
+ path: 'endpoints.custom["Regional"].baseURL',
+ segments: ['endpoints', 'custom', 'Regional', 'baseURL'],
+ reason: 'secret_rebinding',
+ },
+ ]);
+ });
+
+ it('sets back every destination setting, a restated user_provided included', () => {
+ const { merged, ignored } = merge(
+ [
+ layer({
+ endpoints: {
+ custom: [
+ {
+ name: 'Regional',
+ apiKey: 'user_provided',
+ provider: 'anthropic',
+ addParams: { anthropicApiUrl: 'https://attacker.example', promptCache: true },
+ dropParams: ['temperature', 'clientOptions'],
+ models: { default: ['claude'] },
+ },
+ ],
+ },
+ }),
+ ],
+ withUserEndpoint({ dropParams: ['temperature'] }),
+ );
+
+ const entry = merged.endpoints?.custom?.[1] as Record<string, unknown>;
+ expect(entry).toMatchObject({
+ name: 'Regional',
+ apiKey: 'user_provided',
+ baseURL: customEndpoint.baseURL,
+ addParams: { promptCache: true },
+ dropParams: ['temperature'],
+ models: { default: ['claude'] },
+ });
+ expect(entry).not.toHaveProperty('provider');
+ expect(entry.addParams).not.toHaveProperty('anthropicApiUrl');
+ expect(ignored.map(({ path }) => path)).toEqual([
+ 'endpoints.custom["Regional"].addParams.anthropicApiUrl',
+ 'endpoints.custom["Regional"].dropParams',
+ 'endpoints.custom["Regional"].provider',
+ ]);
+ });
+
+ it('sets back an endpoint that sends a user placeholder in its headers, or takes the user URL', () => {
+ const withHeaders = baseConfig();
+ (withHeaders.endpoints as { custom: Array<Record<string, unknown>> }).custom[0].headers = {
+ Authorization: 'Bearer {{LIBRECHAT_OPENID_TOKEN}}',
+ };
+ const headers = merge(
+ [
+ layer({
+ endpoints: { custom: [{ name: 'Gateway', baseURL: 'https://attacker.example/v1' }] },
+ }),
+ ],
+ withHeaders,
+ );
+ expect(headers.merged.endpoints?.custom?.[0]).toMatchObject({
+ apiKey: '${GATEWAY_KEY}',
+ baseURL: customEndpoint.baseURL,
+ });
+ expect(headers.ignored.map(({ path }) => path)).toEqual([
+ 'endpoints.custom["Gateway"].baseURL',
+ ]);
+
+ const userURL = merge(
+ [
+ layer({
+ endpoints: {
+ custom: [{ name: 'Regional', baseURL: 'https://attacker.example/v1' }],
+ },
+ }),
+ ],
+ withUserEndpoint({ baseURL: 'user_provided' }),
+ );
+ expect(userURL.merged.endpoints?.custom?.[1]).toMatchObject({ baseURL: 'user_provided' });
+
+ const userVars = merge(
+ [
+ layer({
+ endpoints: {
+ custom: [{ name: 'Regional', baseURL: 'https://attacker.example/v1' }],
+ },
+ }),
+ ],
+ withUserEndpoint({
+ apiKey: '${GATEWAY_KEY}',
+ customUserVars: { TEAM_TOKEN: { title: 'Team token' } },
+ }),
+ );
+ expect(userVars.merged.endpoints?.custom?.[1]).toMatchObject({
+ apiKey: '${GATEWAY_KEY}',
+ baseURL: customEndpoint.baseURL,
+ });
+ });
+
+ it('judges an endpoint that sends only who the user is like any other', () => {
+ const identified = baseConfig();
+ (identified.endpoints as { custom: Array<Record<string, unknown>> }).custom[0].headers = {
+ 'X-User': '{{LIBRECHAT_USER_ID}}',
+ 'X-Conversation': '{{LIBRECHAT_BODY_CONVERSATIONID}}',
+ };
+ const { merged, ignored } = merge(
+ [
+ layer({
+ endpoints: { custom: [{ name: 'Gateway', baseURL: 'https://eu.gateway.example/v1' }] },
+ }),
+ ],
+ identified,
+ );
+ expect(merged.endpoints?.custom?.[0]).toMatchObject({
+ apiKey: '',
+ baseURL: 'https://eu.gateway.example/v1',
+ });
+ expect(ignored.map(({ path }) => path)).toEqual(['endpoints.custom["Gateway"].apiKey']);
+ });
+
+ it('leaves a user_provided endpoint a layer only retitles, or redefines with a key of its own', () => {
+ const retitled = merge(
+ [layer({ endpoints: { custom: [{ name: 'Regional', modelDisplayLabel: 'EU' }] } })],
+ withUserEndpoint(),
+ );
+ expect(retitled.rebindings).toEqual([]);
+
+ const keyed = merge(
+ [
+ layer({
+ endpoints: {
+ custom: [
+ {
+ name: 'Regional',
+ apiKey: 'v3:editors-key',
+ baseURL: 'https://eu.gateway.example/v1',
+ },
+ ],
+ },
+ }),
+ ],
+ withUserEndpoint(),
+ );
+ expect(keyed.merged.endpoints?.custom?.[1]).toMatchObject({
+ apiKey: 'v3:editors-key',
+ baseURL: 'https://eu.gateway.example/v1',
+ });
+ expect(keyed.rebindings).toEqual([]);
+ });
+
+ it("sets back an MCP server a layer moves while it sends each user's own values", () => {
+ const base = baseConfig();
+ Object.assign(base.mcpConfig as Record<string, unknown>, {
+ personal: {
+ type: 'streamable-http',
+ url: 'https://personal.example/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: '{{PERSONAL_TOKEN}}' },
+ customUserVars: { PERSONAL_TOKEN: { title: 'Token', description: 'Yours' } },
+ },
+ headed: {
+ type: 'sse',
+ url: 'https://headed.example/sse',
+ headers: { 'X-Token': '{{HEADED_TOKEN}}' },
+ },
+ userKey: {
+ type: 'streamable-http',
+ url: 'https://user-key.example/mcp',
+ apiKey: { source: 'user', authorization_type: 'bearer' },
+ },
+ });
+ const { merged, ignored } = merge(
+ [
+ layer({
+ mcpServers: {
+ personal: { url: 'https://attacker.example/mcp' },
+ headed: { type: 'streamable-http', url: 'https://attacker.example/mcp' },
+ userKey: { proxy: 'http://proxy.attacker.example:8080' },
+ },
+ }),
+ ],
+ base,
+ );
+
+ expect(merged.mcpConfig?.personal).toMatchObject({
+ url: 'https://personal.example/mcp',
+ apiKey: { key: '{{PERSONAL_TOKEN}}' },
+ });
+ expect(merged.mcpConfig?.headed).toMatchObject({
+ type: 'sse',
+ url: 'https://headed.example/sse',
+ });
+ expect(merged.mcpConfig?.userKey).not.toHaveProperty('proxy');
+ expect(ignored.map(({ path }) => path)).toEqual([
+ 'mcpServers.personal.url',
+ 'mcpServers.headed.url',
+ 'mcpServers.headed.type',
+ 'mcpServers.userKey.proxy',
+ ]);
+ });
+
+ it('never binds a key the layer enters to the destination it set back', () => {
+ const base = baseConfig();
+ Object.assign(base.mcpConfig as Record<string, unknown>, {
+ personal: {
+ type: 'streamable-http',
+ url: 'https://personal.example/mcp',
+ customUserVars: { TOKEN: { title: 'Token' } },
+ },
+ });
+ const { merged, rebindings } = merge(
+ [
+ layer({
+ mcpServers: {
+ personal: {
+ url: 'https://editors.example/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: 'v3:editors' },
+ },
+ },
+ }),
+ ],
+ base,
+ );
+
+ expect(merged.mcpConfig?.personal).toMatchObject({
+ url: 'https://personal.example/mcp',
+ apiKey: { key: '' },
+ });
+ expect(rebindings.map(({ kind, path, binding }) => [kind, path, binding])).toEqual([
+ ['destination', 'mcpServers.personal.url', undefined],
+ ['secret', 'mcpServers.personal.apiKey.key', undefined],
+ ]);
+ });
+
+ it('leaves a server without user values, or one a layer only renames in the UI', () => {
+ const base = baseConfig();
+ Object.assign(base.mcpConfig as Record<string, unknown>, {
+ open: { type: 'streamable-http', url: 'https://open.example/mcp' },
+ personal: {
+ type: 'streamable-http',
+ url: 'https://personal.example/mcp',
+ customUserVars: { TOKEN: { title: 'Token' } },
+ },
+ });
+ const { merged, rebindings } = merge(
+ [
+ layer({
+ mcpServers: {
+ open: { url: 'https://eu.open.example/mcp' },
+ personal: { title: 'Personal', type: 'http' },
+ },
+ }),
+ ],
+ base,
+ );
+ expect(merged.mcpConfig?.open).toMatchObject({ url: 'https://eu.open.example/mcp' });
+ expect(merged.mcpConfig?.personal).toMatchObject({ title: 'Personal', type: 'http' });
+ expect(rebindings).toEqual([]);
+ });
+
+ it('still drops an inherited ${ENV} reference, which resolves to a deployment credential', () => {
+ const { merged } = merge([
+ layer({
+ endpoints: { custom: [{ name: 'Gateway', baseURL: 'https://eu.gateway.example/v1' }] },
+ }),
+ ]);
+ expect(merged.endpoints?.custom?.[0]?.apiKey).toBe('');
+ });
+ });
+
+ describe('a key a layer enters over a destination a layer below defines', () => {
+ /** Base defines the endpoint, server and OCR service, each with a key of its own. */
+ const baseLayer = (
+ endpointURL = 'https://shared.example/v1',
+ serverURL = 'https://shared.example/mcp',
+ ocrURL = 'https://shared.example/ocr',
+ ) =>
+ layer(
+ {
+ endpoints: {
+ custom: [
+ {
+ name: 'Shared',
+ apiKey: 'v3:base-endpoint',
+ baseURL: endpointURL,
+ models: { default: ['m'] },
+ },
+ ],
+ azureOpenAI: {
+ groupMap: { shared: { apiKey: 'v3:base-group', baseURL: endpointURL } },
+ },
+ },
+ mcpServers: {
+ shared: {
+ type: 'streamable-http',
+ url: serverURL,
+ apiKey: { source: 'admin', authorization_type: 'bearer', key: 'v3:base-server' },
+ },
+ },
+ ocr: { apiKey: 'v3:base-ocr', baseURL: ocrURL },
+ },
+ '__base__',
+ 0,
+ );
+
+ /** The editors' own keys, each bound to the fingerprints `binding` names. */
+ const editors = (binding: Record<string, string | undefined> = {}) =>
+ layer({
+ endpoints: {
+ custom: [
+ { name: 'Shared', apiKey: 'v3:editors-endpoint', apiKeyBinding: binding.endpoint },
+ ],
+ azureOpenAI: {
+ groupMap: { shared: { apiKey: 'v3:editors-group', apiKeyBinding: binding.group } },
+ },
+ },
+ mcpServers: {
+ shared: {
+ apiKey: {
+ source: 'admin',
+ authorization_type: 'bearer',
+ key: 'v3:editors-server',
+ keyBinding: binding.server,
+ },
+ },
+ },
+ ocr: { apiKey: 'v3:editors-ocr', apiKeyBinding: binding.ocr },
+ });
+
+ const shared = (config: AppConfig) =>
+ config.endpoints?.custom?.find((entry) => entry?.name === 'Shared');
+
+ const OWN_PATHS = [
+ 'ocr.apiKey',
+ 'endpoints.custom["Shared"].apiKey',
+ 'mcpServers.shared.apiKey.key',
+ 'endpoints.azureOpenAI.groupMap.shared.apiKey',
+ ];
+
+ /** The fingerprints the guard reports for each of the editors' keys over `base`. */
+ function fingerprintsOver(base: ConfigOverrideLayer): Record<string, string | undefined> {
+ const { rebindings } = merge([base, editors()]);
+ const byPath = new Map(
+ rebindings
+ .filter(({ layer: { principalId } }) => principalId === 'editors')
+ .map(({ path, binding }) => [path, binding]),
+ );
+ return {
+ ocr: byPath.get('ocr.apiKey'),
+ endpoint: byPath.get('endpoints.custom["Shared"].apiKey'),
+ server: byPath.get('mcpServers.shared.apiKey.key'),
+ group: byPath.get('endpoints.azureOpenAI.groupMap.shared.apiKey'),
+ };
+ }
+
+ it('drops a key bound to no destination, reporting the fingerprint of where it would go', () => {
+ const { merged, rebindings } = merge([baseLayer(), editors()]);
+
+ expect(shared(merged)?.apiKey).toBe('');
+ expect((merged.mcpConfig?.shared as typeof mcpServer).apiKey.key).toBe('');
+ expect(merged.ocr?.apiKey).toBe('');
+ const own = rebindings.filter(({ layer: { principalId } }) => principalId === 'editors');
+ expect(own.map(({ path }) => path)).toEqual(OWN_PATHS);
+ for (const { binding } of own) {
+ expect(binding).toMatch(/^[0-9a-f]{64}$/);
+ }
+ });
+
+ it('keeps each key bound to the destination the merge sends it to, and leaves the fingerprint out', () => {
+ const { merged, rebindings } = merge([baseLayer(), editors(fingerprintsOver(baseLayer()))]);
+
+ expect(rebindings.filter(({ layer: { principalId } }) => principalId === 'editors')).toEqual(
+ [],
+ );
+ expect(shared(merged)).toMatchObject({
+ apiKey: 'v3:editors-endpoint',
+ baseURL: 'https://shared.example/v1',
+ });
+ expect((merged.mcpConfig?.shared as typeof mcpServer).apiKey.key).toBe('v3:editors-server');
+ expect(merged.ocr?.apiKey).toBe('v3:editors-ocr');
+ expect(merged.endpoints?.azureOpenAI?.groupMap?.shared?.apiKey).toBe('v3:editors-group');
+ expect(JSON.stringify(merged)).toContain('apiKeyBinding');
+ const served = withoutSecretBindings(merged);
+ expect(JSON.stringify(served)).not.toContain('Binding');
+ expect(shared(served)?.apiKey).toBe('v3:editors-endpoint');
+ expect(withoutSecretBindings(served)).toBe(served);
+ });
+
+ it('drops each key again once the layer below moves its destination', () => {
+ const bound = fingerprintsOver(baseLayer());
+ const moved = baseLayer(
+ 'https://attacker.example/v1',
+ 'https://attacker.example/mcp',
+ 'https://attacker.example/ocr',
+ );
+ const { merged, rebindings } = merge([moved, editors(bound)]);
+
+ expect(shared(merged)?.apiKey).toBe('');
+ expect((merged.mcpConfig?.shared as typeof mcpServer).apiKey.key).toBe('');
+ expect(merged.ocr?.apiKey).toBe('');
+ expect(merged.endpoints?.azureOpenAI?.groupMap?.shared?.apiKey).toBe('');
+ expect(
+ rebindings
+ .filter(({ layer: { principalId } }) => principalId === 'editors')
+ .map(({ path }) => path),
+ ).toEqual(OWN_PATHS);
+ });
+
+ it('binds nothing to a fingerprint another destination has, or that a profile in between moved', () => {
+ const bound = fingerprintsOver(baseLayer());
+ const swapped = merge([
+ baseLayer(),
+ editors({ endpoint: bound.server, server: bound.endpoint, ocr: bound.group }),
+ ]);
+ expect(shared(swapped.merged)?.apiKey).toBe('');
+ expect((swapped.merged.mcpConfig?.shared as typeof mcpServer).apiKey.key).toBe('');
+ expect(swapped.merged.ocr?.apiKey).toBe('');
+
+ const between = merge([
+ baseLayer(),
+ layer(
+ { endpoints: { custom: [{ name: 'Shared', baseURL: 'https://attacker.example/v1' }] } },
+ 'low',
+ 5,
+ ),
+ editors(bound),
+ ]);
+ expect(shared(between.merged)?.apiKey).toBe('');
+ });
+ });
+
+ describe('summarization, whose provider credential is used when the config sets none', () => {
+ /** A base config whose librechat.yaml has a summarization section, and two Azure groups. */
+ function withSummarization(summarization: Record<string, unknown> = {}): AppConfig {
+ const base = baseConfig();
+ (base.config as Record<string, unknown>).summarization = structuredClone(summarization);
+ return {
+ ...base,
+ endpoints: {
+ ...base.endpoints,
+ azureOpenAI: {
+ isValid: true,
+ errors: [],
+ modelNames: ['gpt-4.1-mini', 'gpt-4o-mini', 'gpt-4o'],
+ groupMap: {
+ east: { apiKey: '${AZURE_EAST_KEY}', instanceName: 'east', models: {} },
+ west: { apiKey: '${AZURE_WEST_KEY}', instanceName: 'west', models: {} },
+ },
+ modelGroupMap: {
+ 'gpt-4.1-mini': { group: 'east' },
+ 'gpt-4o-mini': { group: 'east' },
+ 'gpt-4o': { group: 'west' },
+ },
+ },
+ },
+ summarization: structuredClone(summarization),
+ } as AppConfig;
+ }
+
+ const parameters = (merged: AppConfig) =>
+ merged.summarization?.parameters as Record<string, unknown> | undefined;
+ const changes = (rebindings: SecretRebinding[]) =>
+ rebindings.map(({ layer: { principalId }, kind, path }) => [principalId, kind, path]);
+
+ it('ignores a base URL a profile sets without its own key', () => {
+ const { merged, rebindings, ignored } = merge([
+ layer({
+ summarization: {
+ provider: 'openAI',
+ model: 'gpt-4o-mini',
+ parameters: { baseURL: 'https://evil.example/v1', temperature: 0.2 },
+ },
+ }),
+ ]);
+
+ expect(merged.summarization).toEqual({
+ provider: 'openAI',
+ model: 'gpt-4o-mini',
+ parameters: { temperature: 0.2 },
+ });
+ expect(rebindings).toEqual([
+ expect.objectContaining({ kind: 'destination', path: 'summarization.parameters.baseURL' }),
+ ]);
+ expect(ignored).toEqual([
+ {
+ path: 'summarization.parameters.baseURL',
+ segments: ['summarization', 'parameters', 'baseURL'],
+ reason: 'secret_rebinding',
+ },
+ ]);
+ });
+
+ it("ignores every provider client's own URL option without a key", () => {
+ const destinations = {
+ anthropicApiUrl: 'https://evil.example',
+ azureOpenAIBasePath: 'https://evil.example/openai/deployments/x',
+ azureOpenAIEndpoint: 'https://evil.example',
+ azureOpenAIApiInstanceName: 'evil',
+ baseUrl: 'https://evil.example',
+ endpoint: 'evil.example',
+ endpointHost: 'evil.example',
+ location: 'evil.example#',
+ region: 'evil.example#',
+ serverURL: 'https://evil.example',
+ };
+ const { merged, rebindings } = merge([
+ layer({ summarization: { parameters: { ...destinations, max_tokens: 512 } } }),
+ ]);
+
+ expect(parameters(merged)).toEqual({ max_tokens: 512 });
+ expect(rebindings.map(({ path }) => path).sort()).toEqual(
+ Object.keys(destinations)
+ .map((key) => `summarization.parameters.${key}`)
+ .sort(),
+ );
+ });
+
+ it.each([true, false])(
+ 'keeps firstPartyEndpoint: %p, which shapes requests to the same host',
+ (firstPartyEndpoint) => {
+ const { merged, rebindings } = merge([
+ layer({ summarization: { provider: 'openAI', parameters: { firstPartyEndpoint } } }),
+ ]);
+
+ expect(parameters(merged)).toEqual({ firstPartyEndpoint });
+ expect(rebindings).toEqual([]);
+
+ const moved = merge([
+ layer({
+ summarization: {
+ provider: 'openAI',
+ parameters: { firstPartyEndpoint, baseURL: 'https://evil.example/v1' },
+ },
+ }),
+ ]);
+ expect(parameters(moved.merged)).toEqual({ firstPartyEndpoint });
+ expect(moved.rebindings.map(({ path }) => path)).toEqual([
+ 'summarization.parameters.baseURL',
+ ]);
+ },
+ );
+
+ it('keeps a destination the profile sets with its own key', () => {
+ const { merged, rebindings } = merge([
+ layer({
+ summarization: {
+ provider: 'openAI',
+ parameters: { baseURL: 'https://gateway.example/v1', apiKey: 'v3:profile-key' },
+ },
+ }),
+ ]);
+
+ expect(parameters(merged)).toEqual({
+ baseURL: 'https://gateway.example/v1',
+ apiKey: 'v3:profile-key',
+ });
+ expect(rebindings).toEqual([]);
+ });
+
+ /**
+ * The summarizer reads only a string key; for any other value it uses the provider's own
+ * credential (an Azure group's key, the agent's Vertex service account) with the client
+ * options the profile set.
+ */
+ it.each([1, 0, true, false, null, '', ' '])(
+ 'ignores a destination the profile sets with a key of %p, which no client sends',
+ (apiKey) => {
+ const { merged, rebindings } = merge(
+ [
+ layer({
+ summarization: {
+ provider: 'azureOpenAI',
+ model: 'gpt-4.1-mini',
+ parameters: { baseURL: 'https://evil.example/openai/deployments/x', apiKey },
+ },
+ }),
+ ],
+ withSummarization(),
+ );
+
+ expect(parameters(merged)).toEqual({ apiKey });
+ expect(changes(rebindings)).toEqual([
+ ['editors', 'destination', 'summarization.parameters.baseURL'],
+ ]);
+ },
+ );
+
+ it.each([
+ ['no provider, so each agent its own', undefined],
+ ['Bedrock, which signs with AWS credentials', 'bedrock'],
+ ['Bedrock spelled another way', ' Bedrock '],
+ ])(
+ 'ignores a destination the profile sets with a key its provider (%s) does not send',
+ (_label, provider) => {
+ const { merged, rebindings } = merge([
+ layer({
+ summarization: {
+ provider,
+ parameters: {
+ apiKey: 'v3:profile-key',
+ endpointHost: 'evil.example',
+ region: 'evil.example#',
+ },
+ },
+ }),
+ ]);
+
+ expect(parameters(merged)).toEqual({ apiKey: 'v3:profile-key' });
+ expect(changes(rebindings).sort()).toEqual([
+ ['editors', 'destination', 'summarization.parameters.endpointHost'],
+ ['editors', 'destination', 'summarization.parameters.region'],
+ ]);
+ },
+ );
+
+ it("keeps librechat.yaml's own destination for the credential librechat.yaml sends there", () => {
+ const unkeyed = merge(
+ [layer({ summarization: { model: 'gpt-5-nano', parameters: { temperature: 0 } } })],
+ withSummarization({ parameters: { baseURL: 'https://yaml.example/v1' } }),
+ );
+ expect(parameters(unkeyed.merged)).toEqual({
+ baseURL: 'https://yaml.example/v1',
+ temperature: 0,
+ });
+ expect(unkeyed.rebindings).toEqual([]);
+
+ const keyed = merge(
+ [layer({ summarization: { model: 'gpt-4o', parameters: { temperature: 0 } } })],
+ withSummarization({
+ provider: 'openAI',
+ parameters: { baseURL: 'https://yaml.example/v1', apiKey: '${SUMMARY_KEY}' },
+ }),
+ );
+ expect(parameters(keyed.merged)).toEqual({
+ baseURL: 'https://yaml.example/v1',
+ apiKey: '${SUMMARY_KEY}',
+ temperature: 0,
+ });
+ expect(keyed.rebindings).toEqual([]);
+
+ const sameGroup = merge(
+ [layer({ summarization: { model: 'gpt-4o-mini' } })],
+ withSummarization({
+ provider: 'azureOpenAI',
+ model: 'gpt-4.1-mini',
+ parameters: { baseURL: 'https://yaml.example/openai' },
+ }),
+ );
+ expect(parameters(sameGroup.merged)).toEqual({ baseURL: 'https://yaml.example/openai' });
+ expect(sameGroup.rebindings).toEqual([]);
+ });
+
+ it("drops librechat.yaml's destination once a profile removes the key librechat.yaml sends there", () => {
+ const yaml = withSummarization({
+ provider: 'azureOpenAI',
+ model: 'gpt-4.1-mini',
+ parameters: { baseURL: 'https://yaml-gateway.example/openai', apiKey: 'yaml-gateway-key' },
+ });
+
+ const tombstoned = merge(
+ [{ ...layer({}), tombstones: ['summarization.parameters.apiKey'] } as ConfigOverrideLayer],
+ yaml,
+ );
+ expect(parameters(tombstoned.merged)).toEqual({});
+ expect(changes(tombstoned.rebindings)).toEqual([
+ ['editors', 'destination', 'summarization.parameters.baseURL'],
+ ]);
+
+ const emptied = merge([layer({ summarization: { parameters: { apiKey: false } } })], yaml);
+ expect(parameters(emptied.merged)).toEqual({ apiKey: false });
+ expect(changes(emptied.rebindings)).toEqual([
+ ['editors', 'destination', 'summarization.parameters.baseURL'],
+ ]);
+ });
+
+ it("drops librechat.yaml's unkeyed destination once a profile picks another credential for it", () => {
+ const yaml = withSummarization({
+ provider: 'openAI',
+ model: 'gpt-4.1-mini',
+ parameters: { baseURL: 'https://yaml-gateway.example/v1' },
+ });
+
+ /** The provider alone changes; `parameters` is the same object the profile inherited. */
+ const provider = merge([layer({ summarization: { provider: 'azureOpenAI' } })], yaml);
+ expect(provider.merged.summarization).toEqual({
+ provider: 'azureOpenAI',
+ model: 'gpt-4.1-mini',
+ parameters: {},
+ });
+ expect(changes(provider.rebindings)).toEqual([
+ ['editors', 'destination', 'summarization.parameters.baseURL'],
+ ]);
+
+ const azureYaml = withSummarization({
+ provider: 'azureOpenAI',
+ model: 'gpt-4.1-mini',
+ parameters: { baseURL: 'https://yaml-gateway.example/openai' },
+ });
+ const otherGroup = merge([layer({ summarization: { model: 'gpt-4o' } })], azureYaml);
+ expect(parameters(otherGroup.merged)).toEqual({});
+ expect(changes(otherGroup.rebindings)).toEqual([
+ ['editors', 'destination', 'summarization.parameters.baseURL'],
+ ]);
+
+ /** Without a provider, an Azure agent summarizes with the key of the model's group. */
+ const agentGroup = merge(
+ [layer({ summarization: { model: 'gpt-4o-mini' } })],
+ withSummarization({ parameters: { baseURL: 'https://yaml-gateway.example/v1' } }),
+ );
+ expect(parameters(agentGroup.merged)).toEqual({});
+ expect(changes(agentGroup.rebindings)).toEqual([
+ ['editors', 'destination', 'summarization.parameters.baseURL'],
+ ]);
+
+ const remapped = merge(
+ [
+ layer({
+ endpoints: { azureOpenAI: { modelGroupMap: { 'gpt-4.1-mini': { group: 'west' } } } },
+ }),
+ ],
+ azureYaml,
+ );
+ expect(parameters(remapped.merged)).toEqual({});
+ expect(changes(remapped.rebindings)).toEqual([
+ ['editors', 'destination', 'summarization.parameters.baseURL'],
+ ]);
+ });
+
+ it('sets back a destination a profile moves away from an inherited key', () => {
+ const base = withSummarization({
+ provider: 'openAI',
+ parameters: { baseURL: 'https://yaml.example/v1', apiKey: '${SUMMARY_KEY}' },
+ });
+ const { merged, rebindings } = merge(
+ [layer({ summarization: { parameters: { baseURL: 'https://evil.example/v1' } } })],
+ base,
+ );
+
+ expect(parameters(merged)).toEqual({
+ baseURL: 'https://yaml.example/v1',
+ apiKey: '${SUMMARY_KEY}',
+ });
+ expect(rebindings.map(({ path }) => path)).toEqual(['summarization.parameters.baseURL']);
+ });
+
+ it('drops a key once another provider would read it, and judges the destination without it', () => {
+ const yaml = withSummarization({
+ provider: 'openAI',
+ parameters: { baseURL: 'https://yaml-gateway.example/v1', apiKey: '${GATEWAY_KEY}' },
+ });
+
+ const switched = merge([layer({ summarization: { provider: 'anthropic' } })], yaml);
+ expect(switched.merged.summarization).toEqual({ provider: 'anthropic', parameters: {} });
+ expect(changes(switched.rebindings)).toEqual([
+ ['editors', 'secret', 'summarization.parameters.apiKey'],
+ ['editors', 'destination', 'summarization.parameters.baseURL'],
+ ]);
+ expect(switched.ignored[0]).toEqual({
+ path: 'summarization.parameters.apiKey',
+ segments: ['summarization', 'parameters', 'apiKey'],
+ reason: 'secret_rebinding',
+ });
+
+ const own = merge(
+ [
+ layer({ summarization: { provider: 'anthropic' } }, '__base__', 0),
+ layer(
+ {
+ summarization: {
+ parameters: { baseURL: 'https://own.example/v1', apiKey: 'v3:editors-key' },
+ },
+ },
+ 'editors',
+ 10,
+ ),
+ ],
+ yaml,
+ );
+ expect(own.merged.summarization).toEqual({ provider: 'anthropic', parameters: {} });
+ expect(changes(own.rebindings)).toEqual([
+ ['__base__', 'secret', 'summarization.parameters.apiKey'],
+ ['__base__', 'destination', 'summarization.parameters.baseURL'],
+ ['editors', 'secret', 'summarization.parameters.apiKey'],
+ ['editors', 'destination', 'summarization.parameters.baseURL'],
+ ]);
+
+ const restated = merge(
+ [layer({ summarization: { provider: 'anthropic', parameters: { apiKey: 'v3:own' } } })],
+ yaml,
+ );
+ expect(parameters(restated.merged)).toEqual({
+ baseURL: 'https://yaml-gateway.example/v1',
+ apiKey: 'v3:own',
+ });
+ expect(restated.rebindings).toEqual([]);
+ });
+
+ it('sets back a destination a profile empties the key under, or tombstones the key from', () => {
+ const lower = layer(
+ {
+ summarization: {
+ provider: 'openAI',
+ parameters: { baseURL: 'https://low.example/v1', apiKey: 'v3:low-key' },
+ },
+ },
+ 'low',
+ 5,
+ );
+
+ const emptied = merge([lower, layer({ summarization: { parameters: { apiKey: '' } } })]);
+ expect(parameters(emptied.merged)).toEqual({ apiKey: '' });
+ expect(changes(emptied.rebindings)).toEqual([
+ ['editors', 'destination', 'summarization.parameters.baseURL'],
+ ]);
+
+ const tombstoned = merge([
+ lower,
+ {
+ ...layer({}),
+ tombstones: ['summarization.parameters.apiKey'],
+ } as ConfigOverrideLayer,
+ ]);
+ expect(parameters(tombstoned.merged)).toEqual({});
+ });
+
+ it("sets a profile's key back on its own destination when a lower layer moved it", () => {
+ const base = withSummarization({
+ provider: 'openAI',
+ parameters: { baseURL: 'https://yaml.example/v1' },
+ });
+ const { merged, rebindings } = merge(
+ [
+ layer(
+ {
+ summarization: {
+ parameters: { baseURL: 'https://low.example/v1', apiKey: 'v3:low-key' },
+ },
+ },
+ '__base__',
+ 0,
+ ),
+ layer({ summarization: { parameters: { apiKey: 'v3:editors-key' } } }, 'editors', 10),
+ ],
+ base,
+ );
+
+ expect(parameters(merged)).toEqual({
+ baseURL: 'https://yaml.example/v1',
+ apiKey: 'v3:editors-key',
+ });
+ expect(changes(rebindings)).toEqual([
+ ['editors', 'destination', 'summarization.parameters.baseURL'],
+ ]);
+ });
+
+ it('leaves a destination with a key each user enters', () => {
+ const { merged, rebindings } = merge([
+ layer({
+ summarization: {
+ provider: 'openAI',
+ parameters: { baseURL: 'https://gateway.example/v1', apiKey: 'user_provided' },
+ },
+ }),
+ ]);
+
+ expect(parameters(merged)?.baseURL).toBe('https://gateway.example/v1');
+ expect(rebindings).toEqual([]);
+ });
+ });
+
+ describe('resolved settings an override can write directly', () => {
+ function withResolvedEndpoints(): AppConfig {
+ const base = baseConfig();
+ return {
+ ...base,
+ endpoints: {
+ ...base.endpoints,
+ azureOpenAI: {
+ groupMap: {
+ east: { apiKey: '${AZURE_EAST_KEY}', instanceName: 'east', version: '2024-10-21' },
+ },
+ modelGroupMap: { 'gpt-4o': { group: 'east' } },
+ },
+ anthropic: { vertexConfig: { region: 'us-east5', projectId: 'deployment-project' } },
+ },
+ } as unknown as AppConfig;
+ }
+
+ it("drops an Azure group's key when an override points the group elsewhere", () => {
+ const { merged, ignored } = merge(
+ [
+ layer({
+ endpoints: {
+ azureOpenAI: { groupMap: { east: { baseURL: 'https://evil.example/openai' } } },
+ },
+ }),
+ ],
+ withResolvedEndpoints(),
+ );
+
+ expect(merged.endpoints?.azureOpenAI?.groupMap?.east).toMatchObject({
+ apiKey: '',
+ baseURL: 'https://evil.example/openai',
+ });
+ expect(ignored).toEqual([
+ {
+ path: 'endpoints.azureOpenAI.groupMap.east.apiKey',
+ segments: ['endpoints', 'azureOpenAI', 'groupMap', 'east', 'apiKey'],
+ reason: 'secret_rebinding',
+ },
+ ]);
+
+ const instance = merge(
+ [layer({ endpoints: { azureOpenAI: { groupMap: { east: { instanceName: 'evil' } } } } })],
+ withResolvedEndpoints(),
+ );
+ expect(instance.merged.endpoints?.azureOpenAI?.groupMap?.east?.apiKey).toBe('');
+ });
+
+ it('keeps an Azure group key the override enters with its own destination', () => {
+ const { merged, rebindings } = merge(
+ [
+ layer({
+ endpoints: {
+ azureOpenAI: {
+ groupMap: {
+ east: { baseURL: 'https://own.example/openai', apiKey: 'v3:own-azure-key' },
+ },
+ },
+ },
+ }),
+ ],
+ withResolvedEndpoints(),
+ );
+
+ expect(merged.endpoints?.azureOpenAI?.groupMap?.east?.apiKey).toBe('v3:own-azure-key');
+ expect(rebindings).toEqual([]);
+ });
+
+ it("sets the Vertex AI region back to librechat.yaml's, whatever the override supplies", () => {
+ const { merged, rebindings } = merge(
+ [
+ layer({
+ endpoints: {
+ anthropic: {
+ vertexConfig: {
+ region: 'evil.example#',
+ projectId: 'other-project',
+ serviceKeyFile: '{"type":"service_account"}',
+ },
+ },
+ },
+ }),
+ ],
+ withResolvedEndpoints(),
+ );
+
+ expect(merged.endpoints?.anthropic?.vertexConfig).toMatchObject({
+ region: 'us-east5',
+ projectId: 'other-project',
+ });
+ expect(rebindings.map(({ kind, path }) => [kind, path])).toEqual([
+ ['destination', 'endpoints.anthropic.vertexConfig.region'],
+ ]);
+ });
+ });
+
+ describe('Azure groups an override writes, which resolve to what the Azure clients read', () => {
+ const yamlGroup = {
+ group: 'east',
+ apiKey: 'yaml-literal-east-key',
+ instanceName: 'east',
+ version: '2024-10-21',
+ deploymentName: 'gpt-4o',
+ models: { 'gpt-4o': true },
+ };
+
+ function azureBase(): AppConfig {
+ return {
+ config: { endpoints: { azureOpenAI: { groups: [yamlGroup] } } },
+ endpoints: {
+ azureOpenAI: {
+ groupMap: { east: { ...yamlGroup } },
+ modelGroupMap: { 'gpt-4o': { group: 'east' } },
+ modelNames: ['gpt-4o'],
+ assistantModels: [],
+ assistantGroups: [],
+ },
+ },
+ } as unknown as AppConfig;
+ }
+
+ const ownGroup = {
+ group: 'west',
+ apiKey: 'v3:west-admin-key',
+ instanceName: 'west',
+ version: '2024-10-21',
+ deploymentName: 'gpt-5',
+ models: { 'gpt-5': true },
+ };
+
+ it("replaces librechat.yaml's groups with the layer's, each with the key it entered", () => {
+ const { merged, rebindings } = merge(
+ [layer({ endpoints: { azureOpenAI: { groups: [ownGroup] } } }, '__base__', 0)],
+ azureBase(),
+ );
+
+ const azure = merged.endpoints?.azureOpenAI;
+ expect(Object.keys(azure?.groupMap ?? {})).toEqual(['west']);
+ expect(azure?.groupMap?.west).toMatchObject({
+ apiKey: 'v3:west-admin-key',
+ instanceName: 'west',
+ });
+ expect(azure?.modelGroupMap).toEqual({ 'gpt-5': { group: 'west' } });
+ expect(azure?.modelNames).toEqual(['gpt-5']);
+ expect(rebindings).toEqual([]);
+ });
+
+ it('keeps the key a layer enters for a librechat.yaml group it points elsewhere', () => {
+ const { merged, rebindings } = merge(
+ [
+ layer({
+ endpoints: {
+ azureOpenAI: {
+ groups: [{ ...yamlGroup, apiKey: 'v3:east-admin-key', instanceName: 'east-2' }],
+ },
+ },
+ }),
+ ],
+ azureBase(),
+ );
+
+ expect(merged.endpoints?.azureOpenAI?.groupMap?.east).toMatchObject({
+ apiKey: 'v3:east-admin-key',
+ instanceName: 'east-2',
+ });
+ expect(rebindings).toEqual([]);
+ });
+
+ it('drops the key of a group a layer resolved once a later layer points it elsewhere', () => {
+ const { merged, ignored } = merge(
+ [
+ layer({ endpoints: { azureOpenAI: { groups: [ownGroup] } } }, '__base__', 0),
+ layer({ endpoints: { azureOpenAI: { groupMap: { west: { instanceName: 'evil' } } } } }),
+ ],
+ azureBase(),
+ );
+
+ expect(merged.endpoints?.azureOpenAI?.groupMap?.west).toMatchObject({
+ apiKey: '',
+ instanceName: 'evil',
+ });
+ expect(ignored.map(({ path }) => path)).toEqual([
+ 'endpoints.azureOpenAI.groupMap.west.apiKey',
+ ]);
+ });
+
+ it('binds the deployment names of a base URL that takes its host from them', () => {
+ const hostTemplate = {
+ ...ownGroup,
+ baseURL: 'https://${DEPLOYMENT_NAME}.inference.example.com/v1',
+ };
+ const pathTemplate = {
+ ...ownGroup,
+ baseURL: 'https://west.openai.azure.com/openai/deployments/${DEPLOYMENT_NAME}',
+ };
+ const renamed = (group: Record<string, unknown>) =>
+ merge(
+ [
+ layer({ endpoints: { azureOpenAI: { groups: [group] } } }, '__base__', 0),
+ layer({
+ endpoints: {
+ azureOpenAI: {
+ groupMap: { west: { models: { 'gpt-5': { deploymentName: 'evil' } } } },
+ },
+ },
+ }),
+ ],
+ azureBase(),
+ );
+
+ expect(renamed(hostTemplate).merged.endpoints?.azureOpenAI?.groupMap?.west?.apiKey).toBe('');
+ expect(renamed(pathTemplate).merged.endpoints?.azureOpenAI?.groupMap?.west?.apiKey).toBe(
+ 'v3:west-admin-key',
+ );
+ });
+
+ it('binds the destination options its addParams reach the client with', () => {
+ const moved = (addParams: Record<string, unknown>) =>
+ merge(
+ [
+ layer({ endpoints: { azureOpenAI: { groups: [ownGroup] } } }, '__base__', 0),
+ layer({ endpoints: { azureOpenAI: { groupMap: { west: { addParams } } } } }),
+ ],
+ azureBase(),
+ ).merged.endpoints?.azureOpenAI?.groupMap?.west?.apiKey;
+
+ expect(moved({ configuration: { baseURL: 'https://evil.example/v1' } })).toBe('');
+ expect(moved({ reasoning_effort: 'high' })).toBe('v3:west-admin-key');
+ });
+
+ it('leaves groups that do not resolve unread, and what lies below in place', () => {
+ const { merged } = merge(
+ [
+ layer({
+ endpoints: { azureOpenAI: { groups: [ownGroup, { ...ownGroup, group: 'w2' }] } },
+ }),
+ ],
+ azureBase(),
+ );
+
+ expect(Object.keys(merged.endpoints?.azureOpenAI?.groupMap ?? {})).toEqual(['east']);
+ expect(merged.endpoints?.azureOpenAI?.modelNames).toEqual(['gpt-4o']);
+ });
+ });
+
+ describe('custom endpoints: every setting that picks the destination, under any spelling', () => {
+ const claude = {
+ name: 'Claude',
+ provider: 'anthropic',
+ apiKey: 'yaml-literal-claude-key',
+ baseURL: 'https://gateway.example.com/anthropic',
+ models: { default: ['claude-x'] },
+ };
+ const ollama = {
+ name: 'Ollama',
+ apiKey: 'yaml-literal-ollama-key',
+ baseURL: 'http://ollama.internal:11434/v1',
+ models: { default: ['llama3'] },
+ };
+
+ function endpointsBase(...custom: Record<string, unknown>[]): AppConfig {
+ return {
+ config: { endpoints: { custom } },
+ endpoints: { custom: structuredClone(custom) },
+ } as unknown as AppConfig;
+ }
+
+ function mergeEndpoints(entries: Record<string, unknown>[][], base: AppConfig) {
+ return merge(
+ entries.map((custom, index) =>
+ layer({ endpoints: { custom } }, index === 0 ? '__base__' : `group${index}`, index * 10),
+ ),
+ base,
+ );
+ }
+
+ const attacker = 'https://attacker.example';
+
+ it.each<[string, { name: string } & Record<string, unknown>]>([
+ [
+ 'an anthropicApiUrl the native client sends to',
+ { name: 'Claude', addParams: { anthropicApiUrl: attacker } },
+ ],
+ ['a provider switch', { name: 'Gateway', provider: 'anthropic' }],
+ [
+ 'a provider switch with its own destination option',
+ { name: 'Gateway', provider: 'anthropic', addParams: { anthropicApiUrl: attacker } },
+ ],
+ [
+ 'a nested destination option',
+ { name: 'Gateway', addParams: { configuration: { baseURL: attacker } } },
+ ],
+ [
+ 'a dropParams that removes the destinations the client reads',
+ { name: 'Claude', dropParams: ['anthropicApiUrl', 'clientOptions'] },
+ ],
+ ])('drops an inherited key under %s', (_label, change) => {
+ const { merged, ignored } = mergeEndpoints([[change]], endpointsBase(customEndpoint, claude));
+ const { name } = change;
+ const entry = merged.endpoints?.custom?.find((item) => item.name === name);
+ expect(entry?.apiKey).toBe('');
+ expect(ignored).toEqual([
+ {
+ path: `endpoints.custom[${JSON.stringify(name)}].apiKey`,
+ segments: ['endpoints', 'custom', name, 'apiKey'],
+ reason: 'secret_rebinding',
+ },
+ ]);
+ });
+
+ it('keeps the key through options that only shape requests, or with the key entered again', () => {
+ const shaped = mergeEndpoints(
+ [
+ [
+ {
+ name: 'Claude',
+ addParams: { promptCache: true, web_search: true, firstPartyEndpoint: true },
+ dropParams: ['temperature'],
+ },
+ ],
+ ],
+ endpointsBase(claude),
+ );
+ expect(shaped.merged.endpoints?.custom?.[0]?.apiKey).toBe(claude.apiKey);
+ expect(shaped.rebindings).toEqual([]);
+
+ const entered = mergeEndpoints(
+ [
+ [
+ {
+ name: 'Claude',
+ apiKey: 'v3:own-ciphertext',
+ addParams: { anthropicApiUrl: attacker },
+ },
+ ],
+ ],
+ endpointsBase(claude),
+ );
+ expect(entered.merged.endpoints?.custom?.[0]?.apiKey).toBe('v3:own-ciphertext');
+ expect(entered.rebindings).toEqual([]);
+
+ const yamlOption = {
+ ...claude,
+ addParams: { anthropicApiUrl: 'https://gateway.example.com/a' },
+ };
+ const untouched = mergeEndpoints(
+ [[{ name: 'Claude', models: { default: ['claude-y'] } }]],
+ endpointsBase(yamlOption),
+ );
+ expect(untouched.merged.endpoints?.custom?.[0]?.apiKey).toBe(claude.apiKey);
+ expect(untouched.rebindings).toEqual([]);
+ });
+
+ it("drops a layer's own key when a lower layer moved the native client's destination", () => {
+ const { merged, ignored, rebindings } = mergeEndpoints(
+ [
+ [{ name: 'Claude', addParams: { anthropicApiUrl: attacker } }],
+ [{ name: 'Claude', apiKey: 'v3:group-ciphertext' }],
+ ],
+ endpointsBase(claude),
+ );
+ expect(merged.endpoints?.custom?.[0]?.apiKey).toBe('');
+ expect(rebindings.map(({ layer: { principalId } }) => principalId)).toEqual([
+ '__base__',
+ 'group1',
+ ]);
+ expect(ignored[1].path).toBe('endpoints.custom["Claude"].apiKey');
+ });
+
+ it.each(['ollama', 'OLLAMA'])(
+ 'drops an inherited key a layer moves under the folded spelling %s, named as the merge keeps it',
+ (spelling) => {
+ const { merged, ignored } = mergeEndpoints(
+ [[{ name: spelling, baseURL: `${attacker}/v1` }]],
+ endpointsBase(ollama),
+ );
+ expect(merged.endpoints?.custom).toEqual([
+ { ...ollama, apiKey: '', baseURL: `${attacker}/v1` },
+ ]);
+ expect(ignored).toEqual([
+ {
+ path: 'endpoints.custom["Ollama"].apiKey',
+ segments: ['endpoints', 'custom', 'Ollama', 'apiKey'],
+ reason: 'secret_rebinding',
+ },
+ ]);
+ },
+ );
+
+ it("drops a layer's own key under a folded spelling when a lower layer moved the endpoint", () => {
+ const { merged, rebindings } = mergeEndpoints(
+ [
+ [{ name: 'Ollama', baseURL: `${attacker}/v1` }],
+ [{ name: 'OLLAMA', apiKey: 'v3:group-ciphertext' }],
+ ],
+ endpointsBase(ollama),
+ );
+ expect(merged.endpoints?.custom?.[0]).toMatchObject({ name: 'Ollama', apiKey: '' });
+ expect(rebindings.map(({ layer: { principalId }, path }) => [principalId, path])).toEqual([
+ ['__base__', 'endpoints.custom["Ollama"].apiKey'],
+ ['group1', 'endpoints.custom["Ollama"].apiKey'],
+ ]);
+
+ const kept = mergeEndpoints(
+ [[{ name: 'ollama', models: { default: ['llama3.1'] } }]],
+ endpointsBase(ollama),
+ );
+ expect(kept.merged.endpoints?.custom?.[0]?.apiKey).toBe(ollama.apiKey);
+ expect(kept.rebindings).toEqual([]);
+ });
+
+ it('judges every entry a folded name reaches against the entry it was merged onto', () => {
+ const second = { ...ollama, name: 'ollama', apiKey: 'yaml-literal-second-key' };
+ const { merged, ignored } = mergeEndpoints(
+ [[{ name: 'OLLAMA', baseURL: `${attacker}/v1` }]],
+ endpointsBase(ollama, second),
+ );
+ expect(merged.endpoints?.custom?.map((entry) => entry.apiKey)).toEqual(['', '']);
+ expect(ignored.map(({ path }) => path)).toEqual([
+ 'endpoints.custom["Ollama"].apiKey',
+ 'endpoints.custom["ollama"].apiKey',
+ ]);
+ });
+ });
+
+ describe('web search URLs a layer points at another variable', () => {
+ const proxy = '${OPENAI_REVERSE_PROXY}';
+
+ it('sets the URL back when the layer enters no key for it', () => {
+ for (const firecrawlApiKey of [undefined, '', ' ']) {
+ const { merged, rebindings } = merge([
+ layer({ webSearch: { firecrawlApiUrl: proxy, firecrawlApiKey } }),
+ ]);
+
+ expect(merged.webSearch?.firecrawlApiUrl).toBe('https://api.firecrawl.dev');
+ expect(rebindings.map(({ kind, path }) => [kind, path])).toEqual([
+ ['destination', 'webSearch.firecrawlApiUrl'],
+ ]);
+ }
+ });
+
+ it("keeps the URL with a key the layer enters, a literal URL, or librechat.yaml's own", () => {
+ const restated = merge([
+ layer({ webSearch: { firecrawlApiUrl: proxy, firecrawlApiKey: '${FIRECRAWL_API_KEY}' } }),
+ ]);
+ expect(restated.merged.webSearch?.firecrawlApiUrl).toBe(proxy);
+ expect(restated.rebindings).toEqual([]);
+
+ const literal = merge([layer({ webSearch: { firecrawlApiUrl: 'https://other.example' } })]);
+ expect(literal.merged.webSearch?.firecrawlApiUrl).toBe('https://other.example');
+
+ const base = baseConfig();
+ const yamlReference = {
+ ...base,
+ webSearch: { ...base.webSearch, firecrawlApiUrl: '${FIRECRAWL_API_URL}' },
+ } as unknown as AppConfig;
+ const back = merge(
+ [
+ layer({ webSearch: { firecrawlApiUrl: 'https://lower.example' } }, 'lower', 5),
+ layer({ webSearch: { firecrawlApiUrl: '${FIRECRAWL_API_URL}' } }),
+ ],
+ yamlReference,
+ );
+ expect(back.merged.webSearch?.firecrawlApiUrl).toBe('${FIRECRAWL_API_URL}');
+ });
+ });
+
+ describe('custom endpoints a layer changes without naming them in its overrides', () => {
+ function step(merged: AppConfig, layerOverrides: Record<string, unknown> = {}) {
+ const base = baseConfig();
+ return {
+ layer: layer(layerOverrides),
+ base,
+ below: base,
+ applied: layerOverrides,
+ merged,
+ alone: () => base,
+ };
+ }
+
+ it('drops the inherited key of an entry whose destination changed some other way', () => {
+ const rebindings: SecretRebinding[] = [];
+ const guard = createSecretRebindingGuard((rebinding) => rebindings.push(rebinding));
+ const moved = {
+ ...baseConfig(),
+ endpoints: {
+ custom: [{ name: 'Gateway', apiKey: '${GATEWAY_KEY}', models: customEndpoint.models }],
+ },
+ } as unknown as AppConfig;
+
+ const result = guard(step(moved));
+
+ expect(result.endpoints?.custom?.[0]?.apiKey).toBe('');
+ expect(rebindings.map(({ path }) => path)).toEqual(['endpoints.custom["Gateway"].apiKey']);
+ });
+
+ it('keeps the key of an entry a layer left as it was below', () => {
+ const guard = createSecretRebindingGuard();
+ const copied = {
+ ...baseConfig(),
+ endpoints: { custom: [{ ...customEndpoint }] },
+ } as unknown as AppConfig;
+
+ expect(guard(step(copied)).endpoints?.custom?.[0]?.apiKey).toBe('${GATEWAY_KEY}');
+ });
+
+ it('leaves an endpoint as it was under a tombstone inside the list, which the merge never applies', () => {
+ const tombstoned = {
+ ...layer({}),
+ tombstones: ['endpoints.custom.0.baseURL', 'endpoints.custom.0.addParams'],
+ } as ConfigOverrideLayer;
+ const { merged, rebindings } = merge([tombstoned]);
+
+ expect(merged.endpoints?.custom?.[0]).toMatchObject({
+ apiKey: '${GATEWAY_KEY}',
+ baseURL: customEndpoint.baseURL,
+ });
+ expect(rebindings).toEqual([]);
+ });
+ });
+
+ it('never mutates the base config or the objects a lower layer shares', () => {
+ const base = baseConfig();
+ const snapshot = structuredClone(base);
+ merge(
+ [
+ layer({
+ endpoints: { custom: [{ name: 'Gateway', baseURL: 'https://evil.example/v1' }] },
+ mcpServers: { tools: { url: 'https://evil.example/mcp' } },
+ ocr: { baseURL: 'https://evil.example/v1' },
+ }),
+ ],
+ base,
+ );
+ expect(base).toEqual(snapshot);
+ });
+});
diff --git a/packages/api/src/app/rebinding.ts b/packages/api/src/app/rebinding.ts
new file mode 100644
index 0000000000..9421b745e4
--- /dev/null
+++ b/packages/api/src/app/rebinding.ts
@@ -0,0 +1,1525 @@
+import { createHash } from 'crypto';
+import { EModelEndpoint, envVarRegex } from 'librechat-data-provider';
+import {
+ getAtPath,
+ setAtPath,
+ foldConfigMergeKey,
+ webSearchUrlApiKeys,
+} from '@librechat/data-schemas';
+import type {
+ AppConfig,
+ ConfigMergeStep,
+ ConfigOverrideLayer,
+ AdminConfigIgnoredSecret,
+} from '@librechat/data-schemas';
+import type { CredentialBindingConfig } from '~/mcp/registry/binding';
+import {
+ diffApiKeyBinding,
+ getApiKeyBindingFields,
+ getOAuthSecretBindingFields,
+ getChangedOAuthSecretBindingFields,
+} from '~/mcp/registry/binding';
+import { hasUserCredentialPlaceholder } from '~/utils/oidc';
+import { isUserVariableTemplate } from '~/admin/secrets';
+import { isUserProvided } from '~/utils/common';
+
+type JsonRecord = Record<string, unknown>;
+
+/**
+ * What one override layer's merge left out because it would send a credential somewhere it was not
+ * entered for: a secret it dropped, or a destination it set back (for a credential the reader takes
+ * from the deployment when the config holds none, which dropping cannot stop).
+ */
+export interface SecretRebinding {
+ layer: ConfigOverrideLayer;
+ kind: 'secret' | 'destination';
+ /** Where the value is, in YAML keys; an `endpoints.custom` entry is named by its `name`. */
+ segments: string[];
+ /** The same location as text: `endpoints.custom["Name"].apiKey`, `summarization.parameters.baseURL`. */
+ path: string;
+ /**
+ * For a secret the layer supplies, dropped because a layer below it changed where it is sent:
+ * the fingerprint of the destination the merge sends it to. A write that enters the secret
+ * over that destination stores it beside the secret ({@link getSecretBindingKey}), which binds
+ * the secret to it.
+ */
+ binding?: string;
+}
+
+/**
+ * A secret and the settings beside it that decide where it is sent, in one object of the resolved
+ * config (whose keys match librechat.yaml for these sections).
+ */
+export interface SecretBinding {
+ path: readonly string[];
+ secretKey: string;
+ bindingKeys: readonly string[];
+}
+
+/** The scalar secrets bound to settings beside them: OCR's and each speech service's key. */
+export const SECRET_BINDINGS: readonly SecretBinding[] = [
+ { path: ['ocr'], secretKey: 'apiKey', bindingKeys: ['baseURL'] },
+ { path: ['speech', 'tts', 'openai'], secretKey: 'apiKey', bindingKeys: ['url'] },
+ { path: ['speech', 'tts', 'azureOpenAI'], secretKey: 'apiKey', bindingKeys: ['instanceName'] },
+ {
+ path: ['speech', 'tts', 'elevenlabs'],
+ secretKey: 'apiKey',
+ bindingKeys: ['url', 'websocketUrl'],
+ },
+ { path: ['speech', 'tts', 'localai'], secretKey: 'apiKey', bindingKeys: ['url'] },
+ { path: ['speech', 'stt', 'openai'], secretKey: 'apiKey', bindingKeys: ['url'] },
+ { path: ['speech', 'stt', 'azureOpenAI'], secretKey: 'apiKey', bindingKeys: ['instanceName'] },
+];
+
+/**
+ * The librechat.yaml sections that hold a bound credential or its destination (`mcpConfig` is the
+ * alias of `mcpServers`). Writes anywhere else cannot change where a credential is sent.
+ */
+export const REBINDING_SECTIONS: readonly string[] = [
+ 'mcpServers',
+ 'mcpConfig',
+ 'endpoints',
+ 'ocr',
+ 'speech',
+ 'webSearch',
+ 'summarization',
+];
+
+/**
+ * A key a layer can enter for a destination it chooses, and the client that reads both. A key is
+ * bound to that client as much as to the destination: another client reads other destination
+ * settings, or authenticates some other way.
+ */
+interface DestinationSecret {
+ /** Where the key is in the destination's object. */
+ key: string;
+ /** The setting that picks the client which reads the destination and the key. */
+ client: (config: AppConfig) => unknown;
+ /** Whether that client authenticates with the key, rather than a credential it finds itself. */
+ isUsed: (config: AppConfig) => boolean;
+}
+
+/**
+ * A destination whose credential the reader takes from the deployment when the config holds none,
+ * so dropping a secret cannot keep it home; the destination is set back instead.
+ */
+interface DestinationBinding {
+ /** The object in the resolved config that holds the destination (and the secret, if any). */
+ path: readonly string[];
+ /** Whether a key of that object chooses where requests, and the credential, go. */
+ isDestination: (key: string) => boolean;
+ /**
+ * A key a layer can enter for a destination it chooses. Without one, only the deployment's
+ * credential is ever sent, so only the destination librechat.yaml chose is used.
+ */
+ secret?: DestinationSecret;
+ /**
+ * What picks the deployment credential the reader uses when the config holds no key. A
+ * destination librechat.yaml chose stays only while it picks the credential librechat.yaml's does.
+ */
+ fallback?: (config: AppConfig) => readonly unknown[];
+}
+
+/**
+ * Names of client options that choose where requests, and the credential, go. Summarization's
+ * `parameters` become the summarizer's client options: LibreChat reads `baseURL`, and the
+ * provider clients read their own (`anthropicApiUrl`, `azureOpenAIBasePath`,
+ * `azureOpenAIEndpoint`, `azureOpenAIApiInstanceName`, Google's `baseUrl`, Vertex's `endpoint` and
+ * `location`, Bedrock's `endpointHost` and `region`, Mistral's `serverURL`). A custom endpoint's
+ * `addParams` reach its client the same way: the native Anthropic client (`provider: anthropic`)
+ * sends to an `anthropicApiUrl` there over the endpoint's `baseURL`. The pattern errs strict, so a
+ * name a client adds later is covered before anyone lists it; the options it matches that only
+ * shape requests are named in {@link REQUEST_OPTIONS}.
+ */
+const DESTINATION_OPTION = /(?:url|endpoint|host|path|instancename|proxy|location|region)$/i;
+
+/**
+ * Client options whose names match the destination pattern but which change how requests are
+ * shaped, not where they go: `firstPartyEndpoint` turns on OpenAI's first-party request rules for
+ * the host the client already uses.
+ */
+const REQUEST_OPTIONS: ReadonlySet<string> = new Set(['firstPartyEndpoint']);
+
+function isDestinationOption(key: string): boolean {
+ return DESTINATION_OPTION.test(key) && !REQUEST_OPTIONS.has(key);
+}
+
+function getSummarizationProvider(config: AppConfig): string | undefined {
+ const provider = config.summarization?.provider;
+ return isKeyString(provider) ? provider : undefined;
+}
+
+/**
+ * Whether the summarizer authenticates with `parameters.apiKey`. Without a provider it runs on
+ * each agent's own, which may not; Bedrock never does, and signs with the AWS credentials of the
+ * agent or the environment.
+ */
+function summarizationUsesKey(config: AppConfig): boolean {
+ const provider = getSummarizationProvider(config);
+ return provider != null && provider.trim().toLowerCase() !== EModelEndpoint.bedrock;
+}
+
+/**
+ * The deployment credential a summarizer without a key uses: its provider's, and for an Azure
+ * model (named, or summarized on an Azure agent's own provider) the key of the group it maps to.
+ */
+function getSummarizationFallback(config: AppConfig): readonly unknown[] {
+ const provider = getSummarizationProvider(config);
+ const model = config.summarization?.model;
+ const azure = provider == null || provider === EModelEndpoint.azureOpenAI;
+ const group =
+ azure && typeof model === 'string'
+ ? getAt(config.endpoints?.azureOpenAI?.modelGroupMap, [model, 'group'])
+ : undefined;
+ return [provider, group];
+}
+
+const DESTINATION_BINDINGS: readonly DestinationBinding[] = [
+ /**
+ * Without a key it authenticates with, summarization uses its provider's own credential:
+ * `OPENAI_API_KEY`, the Azure group's key, a custom endpoint's key, the agent's resolved client
+ * options (when it summarizes on the agent's provider) or the provider SDK's env default. Only a
+ * string `parameters.apiKey` replaces it, and only for a named provider other than Bedrock.
+ */
+ {
+ path: ['summarization', 'parameters'],
+ isDestination: isDestinationOption,
+ secret: { key: 'apiKey', client: getSummarizationProvider, isUsed: summarizationUsesKey },
+ fallback: getSummarizationFallback,
+ },
+ /**
+ * `vertexConfig` is what librechat.yaml's `endpoints.anthropic.vertex` resolves to, and an
+ * override can write it directly. Its region is part of the API host, and the credential is
+ * always the deployment's service account.
+ */
+ { path: ['endpoints', 'anthropic', 'vertexConfig'], isDestination: (key) => key === 'region' },
+];
+
+function asRecord(value: unknown): JsonRecord | null {
+ return value != null && typeof value === 'object' && !Array.isArray(value)
+ ? (value as JsonRecord)
+ : null;
+}
+
+function getAt(root: unknown, segments: readonly string[]): unknown {
+ let cursor: unknown = root;
+ for (const segment of segments) {
+ const record = asRecord(cursor);
+ if (record == null) {
+ return undefined;
+ }
+ cursor = record[segment];
+ }
+ return cursor;
+}
+
+/** A non-empty string: the only value a reader sends as a key. */
+function isKeyString(value: unknown): value is string {
+ return typeof value === 'string' && value.trim() !== '';
+}
+
+/** `user_provided` or a whole `{{VAR}}` template: a value each user enters for themselves. */
+function isUserEntered(value: string): boolean {
+ const trimmed = value.trim();
+ return isUserProvided(trimmed) || isUserVariableTemplate(trimmed);
+}
+
+/** A key the deployment or an admin entered, in the form a reader sends it. */
+function isEnteredKey(value: unknown): boolean {
+ return isKeyString(value) && !isUserEntered(value);
+}
+
+/**
+ * Whether a value is a credential the deployment or an admin supplies, which a new destination
+ * must not receive: any set value except `user_provided` and a whole `{{VAR}}` template. Anything
+ * that is not a string counts too, so a value no reader expects is dropped rather than kept.
+ */
+function isBoundSecret(value: unknown): boolean {
+ if (value == null) {
+ return false;
+ }
+ return typeof value !== 'string' || isEnteredKey(value);
+}
+
+/** A URL in canonical form (fragment dropped), so a cosmetic respelling is not a change. */
+function normalizeBindingValue(value: unknown): unknown {
+ if (typeof value !== 'string') {
+ return value;
+ }
+ try {
+ const url = new URL(value);
+ url.hash = '';
+ return url.href;
+ } catch {
+ return value;
+ }
+}
+
+function bindingChanged(
+ reference: JsonRecord | null,
+ merged: JsonRecord,
+ keys: readonly string[],
+): boolean {
+ return keys.some(
+ (key) => normalizeBindingValue(reference?.[key]) !== normalizeBindingValue(merged[key]),
+ );
+}
+
+/**
+ * Which of a scalar secret's binding keys differ between two objects that hold it, compared as
+ * the guard compares them (a URL in canonical form).
+ */
+export function getChangedScalarBindingKeys(
+ binding: SecretBinding,
+ reference: JsonRecord | null,
+ merged: JsonRecord,
+): string[] {
+ return binding.bindingKeys.filter((key) => bindingChanged(reference, merged, [key]));
+}
+
+/**
+ * The key beside a secret a layer supplies that holds the fingerprint of the destination a write
+ * entered it for, when that destination is not the one librechat.yaml and the layer alone define
+ * (`<secret>Binding`, as `<secret>Preview` holds its preview). The admin config API writes it and
+ * never returns it; the merge removes it ({@link withoutSecretBindings}).
+ */
+export function getSecretBindingKey(secretKey: string): string {
+ return `${secretKey}Binding`;
+}
+
+/**
+ * A destination's fingerprint, from what decides where a secret is sent. One-way, so the key it
+ * is stored beside tells nothing of where it points.
+ */
+function toFingerprint(signature: unknown): string {
+ return createHash('sha256').update(JSON.stringify(signature)).digest('hex');
+}
+
+/** Whether the object that holds a layer's secret binds it to the destination `fingerprint` names. */
+function isBoundTo(owner: unknown, secretKey: string, fingerprint: string): boolean {
+ return asRecord(owner)?.[getSecretBindingKey(secretKey)] === fingerprint;
+}
+
+/**
+ * A binding's locations and values in one order, by code unit rather than locale, so equal
+ * bindings serialize alike on every replica. Locations are unique, so none compare equal.
+ */
+function toSortedEntries(binding: Iterable<[string, unknown]>): Array<[string, unknown]> {
+ return [...binding].sort(([left], [right]) => (left < right ? -1 : 1));
+}
+
+function getScalarSignature(bindingKeys: readonly string[], record: JsonRecord): unknown[] {
+ return bindingKeys.map((key) => normalizeBindingValue(record[key]) ?? null);
+}
+
+/** The fingerprint of where a scalar secret in `record` is sent ({@link getSecretBindingKey}). */
+export function getScalarBindingFingerprint(binding: SecretBinding, record: JsonRecord): string {
+ return toFingerprint(getScalarSignature(binding.bindingKeys, record));
+}
+
+/**
+ * Copies `root` along `segments` (array items by index) and sets the last one to `value`, so
+ * objects the merge shares with lower layers and the base config are never mutated.
+ */
+function setAt(root: unknown, segments: readonly (string | number)[], value: unknown): unknown {
+ if (segments.length === 0) {
+ return value;
+ }
+ const [segment, ...rest] = segments;
+ if (Array.isArray(root) && typeof segment === 'number') {
+ const next = [...root];
+ next[segment] = setAt(root[segment], rest, value);
+ return next;
+ }
+ const record = asRecord(root) ?? {};
+ return { ...record, [segment]: setAt(record[segment], rest, value) };
+}
+
+/** An inherited secret to drop: where it is in the merged config, and how a write names it. */
+interface Drop {
+ at: readonly (string | number)[];
+ segments: string[];
+ path: string;
+ /** For the layer's own secret, the fingerprint of the destination it would be sent to. */
+ binding?: string;
+}
+
+/**
+ * Which config a merged secret's destination must match for the secret to stay:
+ * - `below`: the layer inherited the secret, so the destination it inherited with it;
+ * - `alone`: the layer supplied the secret, so the destination librechat.yaml and the layer
+ * itself define, whatever another layer below it changed, or the one a write bound it to
+ * (`<secret>Binding`, {@link getSecretBindingKey});
+ * - `null`: nothing to check (no secret, or a value each user supplies).
+ */
+type BindingReference = 'below' | 'alone' | null;
+
+function getBindingReference(below: unknown, merged: unknown, applied: unknown): BindingReference {
+ if (!isBoundSecret(merged)) {
+ return null;
+ }
+ if (applied === undefined) {
+ return merged === below ? 'below' : null;
+ }
+ return merged === applied ? 'alone' : null;
+}
+
+/**
+ * The fingerprint of where the merge sends a secret the layer supplies, when the layer did not
+ * bind the secret to it (`null` when it did): the drop reports it, so a write that enters the
+ * secret over this destination can bind it there.
+ */
+function getUnboundFingerprint(
+ owner: unknown,
+ secretKey: string,
+ signature: unknown,
+): string | null {
+ const fingerprint = toFingerprint(signature);
+ return isBoundTo(owner, secretKey, fingerprint) ? null : fingerprint;
+}
+
+function findScalarDrops(step: ConfigMergeStep): Drop[] {
+ return SECRET_BINDINGS.flatMap(({ path, secretKey, bindingKeys }) => {
+ const merged = asRecord(getAt(step.merged, path));
+ if (merged == null) {
+ return [];
+ }
+ const below = asRecord(getAt(step.below, path));
+ const applied = asRecord(getAt(step.applied, path));
+ const reference = getBindingReference(
+ below?.[secretKey],
+ merged[secretKey],
+ applied?.[secretKey],
+ );
+ if (reference == null) {
+ return [];
+ }
+ const expected = reference === 'below' ? below : asRecord(getAt(step.alone(), path));
+ if (!bindingChanged(expected, merged, bindingKeys)) {
+ return [];
+ }
+ const binding =
+ reference === 'alone'
+ ? getUnboundFingerprint(applied, secretKey, getScalarSignature(bindingKeys, merged))
+ : undefined;
+ if (binding === null) {
+ return [];
+ }
+ const segments = [...path, secretKey];
+ return [{ at: segments, segments, path: segments.join('.'), binding }];
+ });
+}
+
+const CUSTOM_ENDPOINTS: readonly string[] = ['endpoints', 'custom'];
+const CUSTOM_ENDPOINTS_PATH = CUSTOM_ENDPOINTS.join('.');
+
+/**
+ * Options a custom endpoint's `dropParams` can remove that hold a destination: the native
+ * Anthropic client sends to `anthropicApiUrl`, else to `clientOptions.baseURL`, and without both
+ * to its SDK's default host.
+ */
+const CLIENT_OPTION_GROUPS: ReadonlySet<string> = new Set(['clientOptions', 'configuration']);
+
+/**
+ * The identity a custom endpoint merges on and is served by: its name as the merge folds it
+ * (`foldConfigMergeKey`), so `Ollama` and `ollama` are one endpoint.
+ */
+function getEndpointIdentity(name: string): string {
+ return foldConfigMergeKey(CUSTOM_ENDPOINTS_PATH, name);
+}
+
+/** A custom endpoint list's entries by identity, in list order. */
+function groupByIdentity(value: unknown): Map<string, JsonRecord[]> {
+ const groups = new Map<string, JsonRecord[]>();
+ if (!Array.isArray(value)) {
+ return groups;
+ }
+ for (const item of value) {
+ const entry = asRecord(item);
+ if (entry == null || typeof entry.name !== 'string') {
+ continue;
+ }
+ const identity = getEndpointIdentity(entry.name);
+ const group = groups.get(identity);
+ if (group == null) {
+ groups.set(identity, [entry]);
+ } else {
+ group.push(entry);
+ }
+ }
+ return groups;
+}
+
+/** A destination option's value in the form two spellings of one destination share. */
+function toBindingValue(value: unknown): unknown {
+ return asRecord(value) != null || Array.isArray(value)
+ ? JSON.stringify(value)
+ : normalizeBindingValue(value);
+}
+
+/**
+ * Each option named like a destination in `options`, at any depth (array items included), keyed
+ * by its location.
+ */
+function collectDestinationOptions(
+ options: unknown,
+ segments: readonly string[],
+ into: Map<string, unknown>,
+): void {
+ const record: JsonRecord | null = Array.isArray(options) ? { ...options } : asRecord(options);
+ if (record == null) {
+ return;
+ }
+ for (const [key, value] of Object.entries(record)) {
+ const location = [...segments, key];
+ if (isDestinationOption(key)) {
+ into.set(JSON.stringify(location), toBindingValue(value));
+ } else {
+ collectDestinationOptions(value, location, into);
+ }
+ }
+}
+
+/**
+ * The settings of a custom endpoint that decide where its `apiKey` is sent, keyed by location:
+ * - `baseURL`;
+ * - `provider`, which picks the client that reads the rest;
+ * - each option in `addParams` named like a destination ({@link isDestinationOption}), at any
+ * depth: the native Anthropic client sends to `addParams.anthropicApiUrl` over `baseURL`;
+ * - each name in `dropParams` that removes such an option or the client options holding one
+ * ({@link CLIENT_OPTION_GROUPS}).
+ */
+function getCustomEndpointBinding(entry: JsonRecord | null): Map<string, unknown> {
+ const binding = new Map<string, unknown>([
+ [JSON.stringify(['baseURL']), normalizeBindingValue(entry?.baseURL)],
+ [JSON.stringify(['provider']), entry?.provider],
+ ]);
+ return collectClientOptionBinding(entry, binding);
+}
+
+/**
+ * The destination options of an entry whose `addParams` and `dropParams` reach its client's
+ * options (a custom endpoint, an Azure group), added to `binding` by location: each option in
+ * `addParams` named like a destination, at any depth, and each name in `dropParams` that removes
+ * such an option or the client options holding one ({@link CLIENT_OPTION_GROUPS}).
+ */
+function collectClientOptionBinding(
+ entry: JsonRecord | null,
+ binding: Map<string, unknown>,
+): Map<string, unknown> {
+ collectDestinationOptions(entry?.addParams, ['addParams'], binding);
+ const dropped = entry?.dropParams;
+ if (!Array.isArray(dropped)) {
+ return binding;
+ }
+ for (const name of dropped) {
+ if (typeof name === 'string' && (isDestinationOption(name) || CLIENT_OPTION_GROUPS.has(name))) {
+ binding.set(JSON.stringify(['dropParams', name]), true);
+ }
+ }
+ return binding;
+}
+
+/** Whether two bindings ({@link getCustomEndpointBinding}) differ in any location. */
+function bindingsDiffer(expected: Map<string, unknown>, actual: Map<string, unknown>): boolean {
+ if (expected.size !== actual.size) {
+ return true;
+ }
+ for (const [location, value] of actual) {
+ if (!expected.has(location) || expected.get(location) !== value) {
+ return true;
+ }
+ }
+ return false;
+}
+
+function customEndpointBindingChanged(reference: JsonRecord | null, merged: JsonRecord): boolean {
+ return bindingsDiffer(getCustomEndpointBinding(reference), getCustomEndpointBinding(merged));
+}
+
+/**
+ * The locations of a custom endpoint's binding ({@link getCustomEndpointBinding}) that differ
+ * between two definitions of it, each as segments within the entry (`['baseURL']`,
+ * `['addParams', 'anthropicApiUrl']`, `['dropParams', 'clientOptions']`), in a stable order.
+ */
+export function getChangedCustomEndpointBinding(
+ reference: JsonRecord | null,
+ merged: JsonRecord,
+): string[][] {
+ const expected = getCustomEndpointBinding(reference);
+ const actual = getCustomEndpointBinding(merged);
+ return [...new Set([...expected.keys(), ...actual.keys()])]
+ .filter(
+ (location) =>
+ !expected.has(location) ||
+ !actual.has(location) ||
+ expected.get(location) !== actual.get(location),
+ )
+ .sort()
+ .map((location) => JSON.parse(location) as string[]);
+}
+
+function getCustomEndpointSignature(entry: JsonRecord): unknown {
+ return toSortedEntries(getCustomEndpointBinding(entry));
+}
+
+/** The fingerprint of where a custom endpoint sends its key ({@link getSecretBindingKey}). */
+export function getCustomEndpointFingerprint(entry: JsonRecord): string {
+ return toFingerprint(getCustomEndpointSignature(entry));
+}
+
+/** A merged custom endpoint and the entry below it that the merge kept it from. */
+interface EndpointPair {
+ index: number;
+ entry: JsonRecord;
+ name: string;
+ identity: string;
+ /** Which entry of its identity it is: the merge keeps one merged entry per entry below, in order. */
+ occurrence: number;
+ below: JsonRecord | null;
+}
+
+function pairCustomEndpoints(merged: readonly unknown[], below: unknown): EndpointPair[] {
+ const belowGroups = groupByIdentity(below);
+ const occurrences = new Map<string, number>();
+ const pairs: EndpointPair[] = [];
+ merged.forEach((item, index) => {
+ const entry = asRecord(item);
+ const name = entry?.name;
+ if (entry == null || typeof name !== 'string') {
+ return;
+ }
+ const identity = getEndpointIdentity(name);
+ const occurrence = occurrences.get(identity) ?? 0;
+ occurrences.set(identity, occurrence + 1);
+ const belowEntry = belowGroups.get(identity)?.[occurrence] ?? null;
+ pairs.push({ index, entry, name, identity, occurrence, below: belowEntry });
+ });
+ return pairs;
+}
+
+/**
+ * Custom endpoints merge by name, folded as the merge folds it; each one's `apiKey` is bound to
+ * the settings {@link getCustomEndpointBinding} lists. A merged entry is judged against the
+ * entry of the layer that supplied it (the last of its identity, as the merge applies them) and
+ * the entry it was merged onto: the merge keeps one merged entry per entry below, in order, so
+ * the n-th merged entry of an identity comes from the n-th one below. An entry the layer's
+ * overrides do not name is judged too, as inherited: whatever else changed it (a tombstone, say)
+ * changed it without entering its key. A drop names the entry by the spelling the merge keeps,
+ * the lower layer's. The layer's own key stays where its entry binds it
+ * ({@link getSecretBindingKey}).
+ */
+function findCustomEndpointDrops(step: ConfigMergeStep): Drop[] {
+ const merged = getAt(step.merged, CUSTOM_ENDPOINTS);
+ const below = getAt(step.below, CUSTOM_ENDPOINTS);
+ if (!Array.isArray(merged) || merged === below) {
+ return [];
+ }
+ const appliedGroups = groupByIdentity(getAt(step.applied, CUSTOM_ENDPOINTS));
+ let aloneGroups: Map<string, JsonRecord[]> | undefined;
+ const drops: Drop[] = [];
+ for (const { index, entry, name, identity, occurrence, below: belowEntry } of pairCustomEndpoints(
+ merged,
+ below,
+ )) {
+ const appliedGroup = appliedGroups.get(identity);
+ const appliedEntry = appliedGroup?.[appliedGroup.length - 1];
+ if (appliedEntry == null && entry === belowEntry) {
+ continue;
+ }
+ const reference = getBindingReference(belowEntry?.apiKey, entry.apiKey, appliedEntry?.apiKey);
+ if (reference == null) {
+ continue;
+ }
+ if (reference === 'alone') {
+ aloneGroups ??= groupByIdentity(getAt(step.alone(), CUSTOM_ENDPOINTS));
+ }
+ const expected =
+ reference === 'below' ? belowEntry : (aloneGroups?.get(identity)?.[occurrence] ?? null);
+ if (!customEndpointBindingChanged(expected, entry)) {
+ continue;
+ }
+ const binding =
+ reference === 'alone'
+ ? getUnboundFingerprint(appliedEntry, 'apiKey', getCustomEndpointSignature(entry))
+ : undefined;
+ if (binding === null) {
+ continue;
+ }
+ drops.push({
+ at: [...CUSTOM_ENDPOINTS, index, 'apiKey'],
+ segments: [...CUSTOM_ENDPOINTS, name, 'apiKey'],
+ path: `endpoints.custom[${JSON.stringify(name)}].apiKey`,
+ binding,
+ });
+ }
+ return drops;
+}
+
+/** A secret inside each entry of a record keyed by entry name, and what decides where it goes. */
+interface RecordSecret {
+ /** Where the secret is inside an entry. */
+ segments: readonly string[];
+ /** The fields that decide where the secret is sent and differ between two entries. */
+ changedFields: (reference: JsonRecord, merged: JsonRecord) => string[];
+ /**
+ * What decides where an entry sends the secret, for a secret its own layer supplies: equal for
+ * two entries that send it alike, ignoring what {@link OWN_SECRET_IGNORED_FIELDS} names.
+ */
+ signature: (entry: JsonRecord) => unknown;
+}
+
+/** A record of entries, keyed by name, each with its own bound secrets. */
+interface RecordBinding {
+ /** The record in the resolved config. */
+ path: readonly string[];
+ /** The record as librechat.yaml and the admin API name it. */
+ reportPath: readonly string[];
+ secrets: readonly RecordSecret[];
+}
+
+/** Where an Azure group's key is sent: its own base URL, or its instance's Azure host. */
+const AZURE_GROUP_BINDING_KEYS = ['baseURL', 'instanceName'];
+
+/** The Azure client's base URL template a deployment name fills (`constructAzureURL`). */
+const DEPLOYMENT_NAME_TEMPLATE = '${DEPLOYMENT_NAME}';
+
+/** Whether a base URL's host, rather than its path, is filled from a deployment name. */
+function isHostFromDeployment(baseURL: unknown): boolean {
+ if (typeof baseURL !== 'string') {
+ return false;
+ }
+ const authority = baseURL.replace(/^[a-z][a-z\d+.-]*:\/\//i, '').split(/[/?#]/, 1)[0];
+ return authority.includes(DEPLOYMENT_NAME_TEMPLATE);
+}
+
+/**
+ * An Azure group's destination setting as the client reads it: blank is unset (resolved groups
+ * spell an unset base URL and instance as `''`).
+ */
+function toAzureDestination(value: unknown): unknown {
+ return typeof value === 'string' && value.trim() === ''
+ ? undefined
+ : normalizeBindingValue(value);
+}
+
+/** Every deployment name a group's requests are built with: the group's and each model's. */
+function getDeploymentNames(group: JsonRecord): string {
+ const models = asRecord(group.models) ?? {};
+ return JSON.stringify([
+ group.deploymentName,
+ ...Object.keys(models)
+ .sort()
+ .map((model) => asRecord(models[model])?.deploymentName),
+ ]);
+}
+
+/**
+ * What decides where an Azure group sends its `apiKey` ({@link diffAzureGroupBinding}), equal for
+ * two groups that send it alike.
+ */
+function getAzureGroupSignature(group: JsonRecord): unknown {
+ return [
+ ...AZURE_GROUP_BINDING_KEYS.map((key) => toAzureDestination(group[key]) ?? null),
+ isHostFromDeployment(group.baseURL) ? getDeploymentNames(group) : null,
+ toSortedEntries(collectClientOptionBinding(group, new Map())),
+ ];
+}
+
+/**
+ * The settings of a resolved Azure group (a `groupMap` entry, or a `groups` item) that differ
+ * between two definitions of it and decide where its `apiKey` is sent: `baseURL`, `instanceName`
+ * (the Azure host, and the `${INSTANCE_NAME}` a base URL template holds), the deployment names
+ * when a base URL takes its host from `${DEPLOYMENT_NAME}`, and the destination options of its
+ * `addParams` and `dropParams`, which reach the client's options as a custom endpoint's do.
+ */
+export function diffAzureGroupBinding(reference: JsonRecord, merged: JsonRecord): string[] {
+ const changed = AZURE_GROUP_BINDING_KEYS.filter(
+ (key) => toAzureDestination(reference[key]) !== toAzureDestination(merged[key]),
+ );
+ const deploymentPicksHost =
+ isHostFromDeployment(reference.baseURL) || isHostFromDeployment(merged.baseURL);
+ if (deploymentPicksHost && getDeploymentNames(reference) !== getDeploymentNames(merged)) {
+ changed.push('deploymentName');
+ }
+ const options = (group: JsonRecord) => collectClientOptionBinding(group, new Map());
+ if (bindingsDiffer(options(reference), options(merged))) {
+ changed.push('addParams');
+ }
+ return changed;
+}
+
+/**
+ * Binding fields not compared for a secret the layer supplies: a transport `type` set below it
+ * changes the protocol spoken to the same URL, not the host the secret reaches, so a profile that
+ * sets a key and URL for a server another layer defines need not restate its type.
+ */
+const OWN_SECRET_IGNORED_FIELDS = new Set(['type']);
+
+/** A credential's binding fields without those a secret the layer supplies ignores, in one order. */
+function getOwnSecretSignature(fields: Record<string, string | undefined> | null): unknown {
+ if (fields == null) {
+ return null;
+ }
+ return toSortedEntries(
+ Object.entries(fields).filter(([field]) => !OWN_SECRET_IGNORED_FIELDS.has(field)),
+ );
+}
+
+/** What decides where a server sends `apiKey.key` or `oauth.client_secret`, for its own layer. */
+function getServerSecretSignature(parent: 'apiKey' | 'oauth', server: JsonRecord): unknown {
+ const config = server as CredentialBindingConfig;
+ return getOwnSecretSignature(
+ parent === 'apiKey' ? getApiKeyBindingFields(config) : getOAuthSecretBindingFields(config),
+ );
+}
+
+/**
+ * The fingerprint of where an MCP server sends `apiKey.key` or `oauth.client_secret`
+ * ({@link getSecretBindingKey}).
+ */
+export function getServerSecretFingerprint(parent: 'apiKey' | 'oauth', server: JsonRecord): string {
+ return toFingerprint(getServerSecretSignature(parent, server));
+}
+
+/** The fingerprint of where an Azure group sends its `apiKey` ({@link getSecretBindingKey}). */
+export function getAzureGroupFingerprint(group: JsonRecord): string {
+ return toFingerprint(getAzureGroupSignature(group));
+}
+
+const MCP_SERVERS_REPORT_PATH: readonly string[] = ['mcpServers'];
+const AZURE_GROUP_MAP_PATH: readonly string[] = ['endpoints', 'azureOpenAI', 'groupMap'];
+
+const RECORD_BINDINGS: readonly RecordBinding[] = [
+ /**
+ * MCP servers merge by name. `apiKey.key` and `oauth.client_secret` are bound by the same rules
+ * the user-managed tier enforces when a stored key is kept (`mcp/registry/binding.ts`).
+ */
+ {
+ path: ['mcpConfig'],
+ reportPath: MCP_SERVERS_REPORT_PATH,
+ secrets: [
+ {
+ segments: ['apiKey', 'key'],
+ changedFields: (reference, merged) =>
+ diffApiKeyBinding(
+ reference as CredentialBindingConfig,
+ merged as CredentialBindingConfig,
+ ),
+ signature: (entry) => getServerSecretSignature('apiKey', entry),
+ },
+ {
+ segments: ['oauth', 'client_secret'],
+ changedFields: (reference, merged) =>
+ getChangedOAuthSecretBindingFields(
+ reference as CredentialBindingConfig,
+ merged as CredentialBindingConfig,
+ ),
+ signature: (entry) => getServerSecretSignature('oauth', entry),
+ },
+ ],
+ },
+ /**
+ * `groupMap` is what Azure `groups` resolve to (librechat.yaml's, or a layer's, which the merge
+ * resolves the same way) and what runtime readers use; an override can also write it directly,
+ * so each group's key is bound to its own destination.
+ */
+ {
+ path: AZURE_GROUP_MAP_PATH,
+ reportPath: AZURE_GROUP_MAP_PATH,
+ secrets: [
+ {
+ segments: ['apiKey'],
+ changedFields: diffAzureGroupBinding,
+ signature: getAzureGroupSignature,
+ },
+ ],
+ },
+];
+
+/** Entries the merge left untouched (the same object as below) cannot have moved. */
+function findRecordDrops(step: ConfigMergeStep, binding: RecordBinding): Drop[] {
+ const merged = asRecord(getAt(step.merged, binding.path));
+ const below = asRecord(getAt(step.below, binding.path));
+ if (merged == null || merged === below) {
+ return [];
+ }
+ const applied = asRecord(getAt(step.applied, binding.path));
+ const drops: Drop[] = [];
+ for (const [name, mergedEntry] of Object.entries(merged)) {
+ const entry = asRecord(mergedEntry);
+ const belowEntry = below?.[name];
+ if (entry == null || mergedEntry === belowEntry) {
+ continue;
+ }
+ const appliedEntry = applied?.[name];
+ for (const { segments, changedFields, signature } of binding.secrets) {
+ const reference = getBindingReference(
+ getAt(belowEntry, segments),
+ getAt(entry, segments),
+ getAt(appliedEntry, segments),
+ );
+ if (reference == null) {
+ continue;
+ }
+ const expected =
+ reference === 'below' ? belowEntry : getAt(step.alone(), [...binding.path, name]);
+ const changed = changedFields(asRecord(expected) ?? {}, entry);
+ const moved =
+ reference === 'below'
+ ? changed
+ : changed.filter((field) => !OWN_SECRET_IGNORED_FIELDS.has(field));
+ if (moved.length === 0) {
+ continue;
+ }
+ const owner = getAt(appliedEntry, segments.slice(0, -1));
+ const secretKey = segments[segments.length - 1];
+ const fingerprint =
+ reference === 'alone'
+ ? getUnboundFingerprint(owner, secretKey, signature(entry))
+ : undefined;
+ if (fingerprint === null) {
+ continue;
+ }
+ const reported = [...binding.reportPath, name, ...segments];
+ drops.push({
+ at: [...binding.path, name, ...segments],
+ segments: reported,
+ path: reported.join('.'),
+ binding: fingerprint,
+ });
+ }
+ }
+ return drops;
+}
+
+/** A destination set back to the one its credential belongs with. */
+interface Restore {
+ path: readonly string[];
+ /** The object at `path` with its destination keys set back and its secret, if dropped, removed. */
+ record: JsonRecord;
+ /** The destination keys that changed. */
+ keys: string[];
+ /** The secret removed because the client that reads it is not the one it was entered for. */
+ droppedSecret?: string;
+}
+
+function isSameSelection(a: readonly unknown[], b: readonly unknown[]): boolean {
+ return a.length === b.length && a.every((value, index) => value === b[index]);
+}
+
+/**
+ * The destination the deployment's own credential may keep: librechat.yaml's, while
+ * librechat.yaml sends that same credential there (it sets no key its client uses, and picks the
+ * same fallback); otherwise the reader's default, which holds no destination keys.
+ */
+function getFallbackReference(step: ConfigMergeStep, binding: DestinationBinding): JsonRecord {
+ const base = asRecord(getAt(step.base, binding.path)) ?? {};
+ const { secret, fallback } = binding;
+ const baseKeyed = secret != null && secret.isUsed(step.base) && isKeyString(base[secret.key]);
+ const sameFallback =
+ fallback == null || isSameSelection(fallback(step.base), fallback(step.merged));
+ return !baseKeyed && sameFallback ? base : {};
+}
+
+/** How a merged destination is judged: the object it must match, and whether its secret goes. */
+interface DestinationPlan {
+ reference: JsonRecord;
+ dropSecret: boolean;
+}
+
+/**
+ * - A key the layer entered, which its client authenticates with: the destination librechat.yaml
+ * and the layer itself define (`alone`).
+ * - An inherited key: the destination it was inherited with (`below`).
+ * - Either one, under another client than the one it was entered for: the key is dropped, and
+ * the destination judged as without one.
+ * - A key each user enters (`user_provided`, `{{VAR}}`): nothing to judge.
+ * - No key the client uses (absent, empty, not a string, or a client that ignores it): the
+ * deployment's credential is sent, so {@link getFallbackReference}.
+ */
+function getDestinationPlan(
+ step: ConfigMergeStep,
+ binding: DestinationBinding,
+ merged: JsonRecord,
+): DestinationPlan | null {
+ const { path, secret } = binding;
+ if (secret != null && secret.isUsed(step.merged)) {
+ const value = merged[secret.key];
+ const own = isEnteredKey(getAt(step.applied, [...path, secret.key]));
+ if (own || isEnteredKey(value)) {
+ const keyedWith = own ? step.alone() : step.below;
+ if (secret.client(keyedWith) === secret.client(step.merged)) {
+ return { reference: asRecord(getAt(keyedWith, path)) ?? {}, dropSecret: false };
+ }
+ return { reference: getFallbackReference(step, binding), dropSecret: true };
+ }
+ if (isKeyString(value)) {
+ return null;
+ }
+ }
+ return { reference: getFallbackReference(step, binding), dropSecret: false };
+}
+
+/**
+ * Whether a layer left the destination object, and everything that picks the client and
+ * credential reading it, as it was below.
+ */
+function isUntouched(step: ConfigMergeStep, binding: DestinationBinding, merged: unknown): boolean {
+ if (merged !== getAt(step.below, binding.path)) {
+ return false;
+ }
+ const { secret, fallback } = binding;
+ return (
+ (secret == null || secret.client(step.below) === secret.client(step.merged)) &&
+ (fallback == null || isSameSelection(fallback(step.below), fallback(step.merged)))
+ );
+}
+
+/**
+ * Destinations a layer left somewhere their credential was not entered for. One the merge left
+ * untouched cannot have moved, and one the merge removed sends nothing.
+ */
+function findDestinationRestores(step: ConfigMergeStep): Restore[] {
+ return DESTINATION_BINDINGS.flatMap((binding) => {
+ const merged = asRecord(getAt(step.merged, binding.path));
+ if (merged == null || isUntouched(step, binding, merged)) {
+ return [];
+ }
+ const plan = getDestinationPlan(step, binding, merged);
+ if (plan == null) {
+ return [];
+ }
+ const { reference, dropSecret } = plan;
+ const keys = [...new Set([...Object.keys(merged), ...Object.keys(reference)])].filter(
+ (key) => binding.isDestination(key) && bindingChanged(reference, merged, [key]),
+ );
+ const droppedSecret = dropSecret ? binding.secret?.key : undefined;
+ if (keys.length === 0 && droppedSecret == null) {
+ return [];
+ }
+ const record = { ...merged };
+ if (droppedSecret != null) {
+ delete record[droppedSecret];
+ }
+ for (const key of keys) {
+ if (reference[key] === undefined) {
+ delete record[key];
+ } else {
+ record[key] = reference[key];
+ }
+ }
+ return [{ path: binding.path, record, keys, droppedSecret }];
+ });
+}
+
+/** A web search URL a layer pointed elsewhere, and the one it is set back to. */
+interface WebSearchRestore {
+ url: string;
+ value: unknown;
+}
+
+/** A whole `${VAR}` reference, which web search's runtime treats as the deployment's own. */
+function isEnvReference(value: unknown): value is string {
+ return typeof value === 'string' && envVarRegex.test(value.trim());
+}
+
+function sameReference(a: unknown, b: unknown): boolean {
+ return (typeof a === 'string' ? a.trim() : a) === (typeof b === 'string' ? b.trim() : b);
+}
+
+/**
+ * Web search URLs a layer points at a `${VAR}` reference other than librechat.yaml's without
+ * entering the key sent there. Web search's runtime counts every `${VAR}` URL as the
+ * deployment's own: it sends the deployment's key there, and when the config holds no key (an
+ * unset one, or one the merge withholds, `unbindWebSearchKeys`) the search client falls back to
+ * its own environment default, so dropping a key cannot keep that URL from receiving one. The URL
+ * is set back to the one below instead. A literal URL is left to that runtime, which never sends
+ * an environment key to a URL stored in config.
+ */
+function findWebSearchRestores(step: ConfigMergeStep): WebSearchRestore[] {
+ const applied = asRecord(step.applied.webSearch);
+ if (applied == null) {
+ return [];
+ }
+ const merged = asRecord(step.merged.webSearch) ?? {};
+ const below = asRecord(step.below.webSearch) ?? {};
+ const base = asRecord(step.base.webSearch) ?? {};
+ const restores: WebSearchRestore[] = [];
+ for (const [url, apiKey] of webSearchUrlApiKeys) {
+ if (
+ applied[url] === undefined ||
+ isKeyString(applied[apiKey]) ||
+ !isEnvReference(merged[url]) ||
+ sameReference(merged[url], below[url]) ||
+ sameReference(merged[url], base[url])
+ ) {
+ continue;
+ }
+ restores.push({ url, value: below[url] });
+ }
+ return restores;
+}
+
+function withWebSearchRestores(config: unknown, restores: readonly WebSearchRestore[]): unknown {
+ const webSearch = { ...asRecord(asRecord(config)?.webSearch) };
+ for (const { url, value } of restores) {
+ if (value === undefined) {
+ delete webSearch[url];
+ } else {
+ webSearch[url] = value;
+ }
+ }
+ return { ...asRecord(config), webSearch };
+}
+
+/** A `{{NAME}}` that is none of LibreChat's own placeholders: one of the user's custom variables. */
+const CUSTOM_VARIABLE_PLACEHOLDER = /\{\{(?!LIBRECHAT_)[^{}]+\}\}/;
+
+/**
+ * Whether a value sends a credential each user holds: a `{{...}}` LibreChat fills with their
+ * OpenID or Graph token, or with one of their custom variables. Identity and request placeholders
+ * (`{{LIBRECHAT_USER_ID}}`, `{{LIBRECHAT_BODY_*}}`) are not credentials: whoever chooses the
+ * destination receives the conversation they belong to anyway.
+ */
+function sendsUserCredential(value: unknown): boolean {
+ if (typeof value === 'string') {
+ return hasUserCredentialPlaceholder(value) || CUSTOM_VARIABLE_PLACEHOLDER.test(value);
+ }
+ if (Array.isArray(value)) {
+ return value.some(sendsUserCredential);
+ }
+ const record = asRecord(value);
+ return record != null && Object.values(record).some(sendsUserCredential);
+}
+
+/** Whether an entry declares `customUserVars`, which each user fills in for themselves. */
+function declaresUserVars(entry: JsonRecord): boolean {
+ const customUserVars = asRecord(entry.customUserVars);
+ return customUserVars != null && Object.keys(customUserVars).length > 0;
+}
+
+/**
+ * Whether a custom endpoint sends a credential each user enters or holds: their own key or URL
+ * (`user_provided`, which LibreChat looks up by the endpoint's name alone, wherever it points),
+ * the values of its `customUserVars`, or one {@link sendsUserCredential} finds in its key or
+ * headers.
+ */
+function endpointSendsUserValues(entry: JsonRecord): boolean {
+ const { apiKey, baseURL } = entry;
+ return (
+ (typeof apiKey === 'string' && isUserEntered(apiKey)) ||
+ (typeof baseURL === 'string' && isUserProvided(baseURL.trim())) ||
+ declaresUserVars(entry) ||
+ sendsUserCredential(apiKey) ||
+ sendsUserCredential(entry.headers)
+ );
+}
+
+/**
+ * Whether an MCP server sends a credential each user enters or holds: the values of its
+ * `customUserVars`, a key each user provides (`apiKey.source: user`), or one
+ * {@link sendsUserCredential} finds in its URL, headers or key. LibreChat keeps those per user
+ * and server name, not per destination.
+ */
+function serverSendsUserValues(server: JsonRecord): boolean {
+ const apiKey = asRecord(server.apiKey);
+ return (
+ declaresUserVars(server) ||
+ apiKey?.source === 'user' ||
+ sendsUserCredential(apiKey?.key) ||
+ sendsUserCredential(server.url) ||
+ sendsUserCredential(server.headers)
+ );
+}
+
+/** Copies `root` along `location` and sets `value` there, or removes the key when `undefined`. */
+function restoreAt(root: unknown, location: readonly string[], value: unknown): unknown {
+ const [segment, ...rest] = location;
+ if (Array.isArray(root)) {
+ const index = Number(segment);
+ const next = [...root];
+ next[index] = rest.length === 0 ? value : restoreAt(root[index], rest, value);
+ return next;
+ }
+ const record = { ...(asRecord(root) ?? {}) };
+ if (rest.length > 0) {
+ record[segment] = restoreAt(record[segment], rest, value);
+ } else if (value === undefined) {
+ delete record[segment];
+ } else {
+ record[segment] = value;
+ }
+ return record;
+}
+
+/**
+ * `entry` with the binding locations {@link getChangedCustomEndpointBinding} names set back to
+ * `below`'s: its base URL, provider and destination options, and the names of `dropParams` that
+ * remove a destination, keeping the rest of what the layer set.
+ */
+function restoreEndpointBinding(
+ entry: JsonRecord,
+ below: JsonRecord,
+ locations: readonly string[][],
+): JsonRecord {
+ let restored: unknown = entry;
+ const dropped = new Set<string>();
+ for (const location of locations) {
+ if (location[0] === 'dropParams') {
+ dropped.add(location[1]);
+ continue;
+ }
+ restored = restoreAt(restored, location, getAtPath(below, location));
+ }
+ if (dropped.size === 0) {
+ return restored as JsonRecord;
+ }
+ const names = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);
+ const record = asRecord(restored) ?? {};
+ const dropParams = [
+ ...names(record.dropParams).filter((name) => typeof name !== 'string' || !dropped.has(name)),
+ ...names(below.dropParams).filter((name) => typeof name === 'string' && dropped.has(name)),
+ ];
+ return { ...record, dropParams };
+}
+
+/** A destination a layer moved, set back because what it sends there is each user's own. */
+interface UserValueRestore {
+ segments: string[];
+ path: string;
+}
+
+/**
+ * Custom endpoints whose destination a layer changed while what they send there is each user's
+ * own ({@link endpointSendsUserValues}), below and merged: the binding is set back to the entry
+ * below's. A user's key is stored under the endpoint's name, so the layer could otherwise collect
+ * every key users entered for the destination it inherited, which no one can enter again for it.
+ */
+function restoreUserEndpoints(step: ConfigMergeStep): {
+ merged: AppConfig;
+ restores: UserValueRestore[];
+} {
+ const merged = getAt(step.merged, CUSTOM_ENDPOINTS);
+ const below = getAt(step.below, CUSTOM_ENDPOINTS);
+ if (!Array.isArray(merged) || merged === below) {
+ return { merged: step.merged, restores: [] };
+ }
+ let entries: unknown[] | undefined;
+ const restores: UserValueRestore[] = [];
+ for (const { index, entry, name, below: belowEntry } of pairCustomEndpoints(merged, below)) {
+ if (
+ belowEntry == null ||
+ entry === belowEntry ||
+ !endpointSendsUserValues(belowEntry) ||
+ !endpointSendsUserValues(entry)
+ ) {
+ continue;
+ }
+ const locations = getChangedCustomEndpointBinding(belowEntry, entry);
+ if (locations.length === 0) {
+ continue;
+ }
+ entries ??= [...merged];
+ entries[index] = restoreEndpointBinding(entry, belowEntry, locations);
+ const reported = new Set(
+ locations.map((location) =>
+ JSON.stringify(location[0] === 'dropParams' ? ['dropParams'] : location),
+ ),
+ );
+ for (const location of reported) {
+ const fields = JSON.parse(location) as string[];
+ restores.push({
+ segments: [...CUSTOM_ENDPOINTS, name, ...fields],
+ path: `endpoints.custom[${JSON.stringify(name)}].${fields.join('.')}`,
+ });
+ }
+ }
+ if (entries == null) {
+ return { merged: step.merged, restores };
+ }
+ return { merged: setAt(step.merged, CUSTOM_ENDPOINTS, entries) as AppConfig, restores };
+}
+
+/** The settings of an MCP server that decide where it connects, set back together. */
+const SERVER_DESTINATION_KEYS = ['url', 'type', 'proxy'] as const;
+
+/** Whether a server connects somewhere else: another URL or proxy (a fragment aside). */
+function serverMoved(below: JsonRecord, merged: JsonRecord): boolean {
+ return bindingChanged(below, merged, ['url', 'proxy']);
+}
+
+/**
+ * MCP servers a layer points elsewhere while what they send is each user's own
+ * ({@link serverSendsUserValues}), below and merged: the server's URL, transport and proxy are
+ * set back to the ones below.
+ */
+function restoreUserServers(
+ step: ConfigMergeStep,
+ config: AppConfig,
+): { merged: AppConfig; restores: UserValueRestore[] } {
+ const merged = asRecord(getAt(config, ['mcpConfig']));
+ const below = asRecord(getAt(step.below, ['mcpConfig']));
+ if (merged == null || below == null || merged === below) {
+ return { merged: config, restores: [] };
+ }
+ let result: unknown = config;
+ const restores: UserValueRestore[] = [];
+ for (const [name, value] of Object.entries(merged)) {
+ const server = asRecord(value);
+ const belowServer = asRecord(below[name]);
+ if (
+ server == null ||
+ belowServer == null ||
+ server === belowServer ||
+ !serverSendsUserValues(belowServer) ||
+ !serverSendsUserValues(server) ||
+ !serverMoved(belowServer, server)
+ ) {
+ continue;
+ }
+ const keys = SERVER_DESTINATION_KEYS.filter((key) => server[key] !== belowServer[key]);
+ let restored: unknown = server;
+ for (const key of keys) {
+ restored = restoreAt(restored, [key], belowServer[key]);
+ }
+ result = setAt(result, ['mcpConfig', name], restored);
+ for (const key of keys) {
+ const segments = [...MCP_SERVERS_REPORT_PATH, name, key];
+ restores.push({ segments, path: segments.join('.') });
+ }
+ }
+ return { merged: result as AppConfig, restores };
+}
+
+/** Where a bound secret sits in a config or override document. */
+export interface BoundSecretLocation {
+ /** The object that holds the secret and its {@link getSecretBindingKey} companion; array items by index. */
+ owner: string[];
+ /** The secret's key in it. */
+ key: string;
+ /** The secret's identity, as {@link getRebindingIdentity} names a rebinding of it. */
+ identity: string;
+}
+
+const AZURE_GROUPS_PATH: readonly string[] = ['endpoints', 'azureOpenAI', 'groups'];
+const MCP_SECRET_KEYS: ReadonlyArray<readonly [string, string]> = [
+ ['apiKey', 'key'],
+ ['oauth', 'client_secret'],
+];
+
+/**
+ * A secret's identity by its YAML location (`SecretRebinding.segments`): a custom endpoint is
+ * named by its name as the merge folds it, so every spelling of one endpoint has one identity.
+ */
+export function getRebindingIdentity(segments: readonly string[]): string {
+ const [section, field, name, ...rest] = segments;
+ if (section === CUSTOM_ENDPOINTS[0] && field === CUSTOM_ENDPOINTS[1] && name != null) {
+ return JSON.stringify([section, field, getEndpointIdentity(name), ...rest]);
+ }
+ return JSON.stringify(segments);
+}
+
+/** The entry a YAML location is in: a custom endpoint by its folded name, an MCP server by name. */
+function getEntryKey(segments: readonly string[]): string {
+ const [section, field, name] = segments;
+ if (section === CUSTOM_ENDPOINTS[0] && field === CUSTOM_ENDPOINTS[1] && name != null) {
+ return JSON.stringify([section, field, getEndpointIdentity(name)]);
+ }
+ return JSON.stringify(segments.slice(0, 2));
+}
+
+function collectBoundSecretLocations(
+ root: unknown,
+ mcpSections: readonly string[],
+): BoundSecretLocation[] {
+ const locations: BoundSecretLocation[] = [];
+ const add = (owner: string[], key: string, reported: readonly string[]) =>
+ locations.push({ owner, key, identity: getRebindingIdentity(reported) });
+ for (const { path, secretKey } of SECRET_BINDINGS) {
+ if (asRecord(getAt(root, path)) != null) {
+ add([...path], secretKey, [...path, secretKey]);
+ }
+ }
+ const endpoints = getAt(root, CUSTOM_ENDPOINTS);
+ (Array.isArray(endpoints) ? endpoints : []).forEach((item, index) => {
+ const name = asRecord(item)?.name;
+ if (typeof name === 'string') {
+ add([...CUSTOM_ENDPOINTS, String(index)], 'apiKey', [...CUSTOM_ENDPOINTS, name, 'apiKey']);
+ }
+ });
+ const groups = getAt(root, AZURE_GROUPS_PATH);
+ (Array.isArray(groups) ? groups : []).forEach((item, index) => {
+ if (asRecord(item) != null) {
+ add([...AZURE_GROUPS_PATH, String(index)], 'apiKey', [
+ ...AZURE_GROUPS_PATH,
+ String(index),
+ 'apiKey',
+ ]);
+ }
+ });
+ for (const [group, value] of Object.entries(asRecord(getAt(root, AZURE_GROUP_MAP_PATH)) ?? {})) {
+ if (asRecord(value) != null) {
+ add([...AZURE_GROUP_MAP_PATH, group], 'apiKey', [...AZURE_GROUP_MAP_PATH, group, 'apiKey']);
+ }
+ }
+ for (const section of mcpSections) {
+ for (const [name, server] of Object.entries(asRecord(getAt(root, [section])) ?? {})) {
+ for (const [parent, key] of MCP_SECRET_KEYS) {
+ if (asRecord(asRecord(server)?.[parent]) != null) {
+ add([section, name, parent], key, [...MCP_SERVERS_REPORT_PATH, name, parent, key]);
+ }
+ }
+ }
+ }
+ return locations;
+}
+
+/**
+ * Every place an override document can hold a secret bound to a destination, and so a
+ * {@link getSecretBindingKey} companion: OCR's and each speech service's key, each custom
+ * endpoint's and Azure group's (`groups` and `groupMap`), and each MCP server's credentials
+ * under `mcpServers` and its alias `mcpConfig`.
+ */
+export function getBoundSecretLocations(overrides: unknown): BoundSecretLocation[] {
+ return collectBoundSecretLocations(overrides, ['mcpServers', 'mcpConfig']);
+}
+
+/** `root` without the companions at `locations`; objects are copied only where one is removed. */
+function withoutBindingsAt<T>(root: T, locations: readonly BoundSecretLocation[]): T {
+ let result: unknown = root;
+ for (const { owner, key } of locations) {
+ const companion = getSecretBindingKey(key);
+ const record = asRecord(getAtPath(result, owner));
+ if (record == null || !Object.prototype.hasOwnProperty.call(record, companion)) {
+ continue;
+ }
+ const { [companion]: _removed, ...rest } = record;
+ result = setAtPath(result as JsonRecord, owner, rest);
+ }
+ return result as T;
+}
+
+/**
+ * A merged config without the destination fingerprints layers store beside their secrets
+ * ({@link getSecretBindingKey}): the guard reads them from each layer's own overrides, and no
+ * runtime reader expects them.
+ */
+export function withoutSecretBindings(config: AppConfig): AppConfig {
+ return withoutBindingsAt(config, collectBoundSecretLocations(config, ['mcpConfig']));
+}
+
+/** An override document's overrides without its destination fingerprints, as reads return them. */
+export function withoutStoredSecretBindings<T>(overrides: T): T {
+ return withoutBindingsAt(overrides, getBoundSecretLocations(overrides));
+}
+
+/**
+ * The merge's `afterLayer` policy for credentials bound to a destination. A credential stays
+ * only where it was entered:
+ * - a layer that changes where an entry sends a secret it inherits (from librechat.yaml or a
+ * lower layer), without supplying the secret again, drops it;
+ * - a secret a layer supplies is bound to the destination librechat.yaml and that layer define;
+ * when another layer below it changed that destination, the layer's secret is dropped;
+ * - where a reader falls back to a deployment credential when the config holds no key it uses
+ * (summarization, Vertex AI), the destination is set back instead: it may differ from
+ * librechat.yaml's only together with a key the layer enters and the reader authenticates
+ * with, and stays librechat.yaml's only while it receives the credential librechat.yaml sends
+ * there. A key that another client would read than the one it was entered for is removed.
+ *
+ * Those are all the places a destination in the config meets a credential, apart from web
+ * search: MCP servers (URL, transport, proxy, auth header, OAuth endpoints), custom endpoints
+ * (base URL, `provider`, and the destination options of `addParams` and `dropParams`, matched by
+ * the name the merge folds), OCR, speech, summarization parameters, the resolved Azure groups
+ * (`groupMap`, which a layer's `groups` resolve to, or which it writes directly) and the Vertex AI
+ * settings (`vertexConfig`) an override can write directly. Web
+ * search keys follow the merge's own rule (`unbindWebSearchKeys`, which keeps a key over an
+ * inherited `${VAR}` or default URL), and its drops are reported like these
+ * (`mergeOverrideLayers`); a web search URL a layer points at another `${VAR}` without entering
+ * its key is set back ({@link findWebSearchRestores}). The built-in endpoints, assistants and the memory agent take their
+ * URLs from the environment, and Langfuse only reaches destinations the deployment configures.
+ * Header maps are not covered: their values are not registered secrets.
+ *
+ * A secret a layer supplies whose destination a layer below defines is kept when the layer's
+ * own object binds it to exactly the destination the merge sends it to: the admin config API
+ * stores that fingerprint beside a key it encrypts (`<secret>Binding`, {@link
+ * getSecretBindingKey}) when the destination over the active Base is not the layer's own, which
+ * the drop reports (`SecretRebinding.binding`). A later move below drops the key again.
+ *
+ * A dropped bound secret is set to `''`, which those readers treat as missing. `user_provided`
+ * and `{{VAR}}` name a value each user enters and are never dropped. LibreChat keeps those values
+ * per user and entry name, not per destination, so an inherited custom endpoint or MCP server that
+ * sends them ({@link restoreUserEndpoints}, {@link restoreUserServers}) keeps the destination it
+ * inherited: a layer that moves it has the move set back. Each change is reported to
+ * `onRebinding`.
+ *
+ * A secret a layer writes counts as entered by it, whatever it is. That includes a `${VAR}`
+ * reference, which config reads return as written: restating the reference librechat.yaml or a
+ * lower layer uses, beside a destination of the layer's own, sends that variable there. Which
+ * names a layer may reference is the env allowlist's to decide (`allowlist.ts`), so this guard
+ * binds encrypted admin-entered secrets and literals, and stops a layer from moving a reference
+ * it does not restate.
+ */
+export function createSecretRebindingGuard(
+ onRebinding?: (rebinding: SecretRebinding) => void,
+): (step: ConfigMergeStep) => AppConfig {
+ return (layerStep) => {
+ const endpoints = restoreUserEndpoints(layerStep);
+ const servers = restoreUserServers(layerStep, endpoints.merged);
+ const step =
+ servers.merged === layerStep.merged ? layerStep : { ...layerStep, merged: servers.merged };
+ const userRestores = [...endpoints.restores, ...servers.restores];
+ for (const { segments, path } of userRestores) {
+ onRebinding?.({ layer: step.layer, kind: 'destination', segments, path });
+ }
+ /** A key is never bound to a destination the guard put back over the layer's own. */
+ const restoredEntries = new Set(userRestores.map(({ segments }) => getEntryKey(segments)));
+ const drops = [
+ ...findScalarDrops(step),
+ ...findCustomEndpointDrops(step),
+ ...RECORD_BINDINGS.flatMap((binding) => findRecordDrops(step, binding)),
+ ];
+ const restores = findDestinationRestores(step);
+ const webSearchRestores = findWebSearchRestores(step);
+ let result: unknown = step.merged;
+ for (const { at, segments, path, binding } of drops) {
+ result = setAt(result, at, '');
+ onRebinding?.({
+ layer: step.layer,
+ kind: 'secret',
+ segments,
+ path,
+ ...(binding != null && !restoredEntries.has(getEntryKey(segments)) && { binding }),
+ });
+ }
+ if (webSearchRestores.length > 0) {
+ result = withWebSearchRestores(result, webSearchRestores);
+ for (const { url } of webSearchRestores) {
+ const segments = ['webSearch', url];
+ onRebinding?.({
+ layer: step.layer,
+ kind: 'destination',
+ segments,
+ path: segments.join('.'),
+ });
+ }
+ }
+ for (const { path, record, keys, droppedSecret } of restores) {
+ result = setAt(result, path, record);
+ const changes = [
+ ...(droppedSecret != null ? [{ kind: 'secret' as const, key: droppedSecret }] : []),
+ ...keys.map((key) => ({ kind: 'destination' as const, key })),
+ ];
+ for (const { kind, key } of changes) {
+ const segments = [...path, key];
+ onRebinding?.({ layer: step.layer, kind, segments, path: segments.join('.') });
+ }
+ }
+ return result as AppConfig;
+ };
+}
+
+/** How a write reports a rebinding its own layer causes. */
+export function toIgnoredSecretOverride(rebinding: SecretRebinding): AdminConfigIgnoredSecret {
+ return { path: rebinding.path, segments: rebinding.segments, reason: 'secret_rebinding' };
+}
diff --git a/packages/api/src/app/service.spec.ts b/packages/api/src/app/service.spec.ts
index 303ffaf8c3..1b8728a50a 100644
--- a/packages/api/src/app/service.spec.ts
+++ b/packages/api/src/app/service.spec.ts
@@ -1,5 +1,11 @@
-import { getMaxSubagents, setMaxSubagents } from 'librechat-data-provider';
-import { AppService, getTenantId, tenantStorage, SYSTEM_TENANT_ID } from '@librechat/data-schemas';
+import { PrincipalType, getMaxSubagents, setMaxSubagents } from 'librechat-data-provider';
+import {
+ logger,
+ AppService,
+ getTenantId,
+ tenantStorage,
+ SYSTEM_TENANT_ID,
+} from '@librechat/data-schemas';
import type { AppConfig } from '@librechat/data-schemas';
import {
createAppConfigService,
@@ -505,7 +511,7 @@ describe('createAppConfigService', () => {
isActive: true,
overrides: {
endpoints: {
- custom: [{ name: 'Private Gateway', baseURL: 'https://override.example' }],
+ custom: [{ name: 'Private Gateway', models: { default: ['override-model'] } }],
},
},
},
@@ -516,11 +522,45 @@ describe('createAppConfigService', () => {
expect(owner.endpoints?.custom?.[0]).toMatchObject({
tenantId: 'tenant-a',
apiKey: 'private-gateway-key',
- baseURL: 'https://override.example',
+ baseURL: 'https://private.example',
+ models: { default: ['override-model'] },
});
expect(owner.modelSpecs?.list).toHaveLength(1);
const yaml = await getAppConfig({ tenantId: 'tenant-a', baseOnly: true });
- expect(yaml.config.endpoints?.custom?.[0].baseURL).toBe('https://private.example');
+ expect(yaml.config.endpoints?.custom?.[0].models?.default).toEqual(['private-model']);
+ });
+
+ it('drops the YAML key when a partial admin override points the endpoint elsewhere', async () => {
+ const base = await tenantBase();
+ const deps = createDeps({
+ loadBaseConfig: jest.fn().mockResolvedValue(base),
+ getApplicableConfigs: jest.fn().mockResolvedValue([
+ {
+ principalType: PrincipalType.ROLE,
+ principalId: 'USER',
+ priority: 10,
+ isActive: true,
+ overrides: {
+ endpoints: {
+ custom: [{ name: 'Private Gateway', baseURL: 'https://override.example' }],
+ },
+ },
+ },
+ ]),
+ });
+ const warn = jest.spyOn(logger, 'warn').mockReturnValue(logger);
+ const { getAppConfig } = createAppConfigService(deps);
+ const owner = await getAppConfig({ role: 'USER', tenantId: 'tenant-a' });
+ expect(owner.endpoints?.custom?.[0]).toMatchObject({
+ tenantId: 'tenant-a',
+ apiKey: '',
+ baseURL: 'https://override.example',
+ });
+ expect(JSON.stringify(owner.endpoints)).not.toContain('private-gateway-key');
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('Dropping secret "endpoints.custom["Private Gateway"].apiKey"'),
+ );
+ warn.mockRestore();
});
it('revokes a cached endpoint when a successful YAML reload changes its tenant', async () => {
@@ -779,6 +819,7 @@ describe('createAppConfigService', () => {
custom: [
{
name: 'ollama',
+ apiKey: 'ollama',
baseURL: 'http://override:11434/v1',
modelDisplayLabel: 'Ollama (override)',
},
@@ -809,6 +850,39 @@ describe('createAppConfigService', () => {
expect(config.modelSpecs?.list?.[0]?.preset?.endpoint).toBe('ollama');
expect(config.modelSpecs?.addedEndpoints).toEqual(['ollama']);
});
+
+ it('drops the YAML `Ollama` key an override `ollama` points elsewhere without it', async () => {
+ const deps = createDeps({
+ loadBaseConfig: jest.fn().mockResolvedValue(await ollamaBase()),
+ getApplicableConfigs: jest.fn().mockResolvedValue([
+ {
+ principalType: PrincipalType.ROLE,
+ principalId: 'USER',
+ priority: 10,
+ isActive: true,
+ overrides: {
+ endpoints: { custom: [{ name: 'ollama', baseURL: 'http://override:11434/v1' }] },
+ },
+ },
+ ]),
+ });
+ const warn = jest.spyOn(logger, 'warn').mockReturnValue(logger);
+ const { getAppConfig } = createAppConfigService(deps);
+
+ const config = await getAppConfig({ role: 'USER' });
+
+ expect(config.endpoints?.custom).toEqual([
+ expect.objectContaining({
+ name: 'Ollama',
+ apiKey: '',
+ baseURL: 'http://override:11434/v1',
+ }),
+ ]);
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('Dropping secret "endpoints.custom["Ollama"].apiKey"'),
+ );
+ warn.mockRestore();
+ });
});
/**
diff --git a/packages/api/src/app/service.ts b/packages/api/src/app/service.ts
index 7354a302d2..f845cf5068 100644
--- a/packages/api/src/app/service.ts
+++ b/packages/api/src/app/service.ts
@@ -1,24 +1,28 @@
import { createHash } from 'node:crypto';
-import {
- PrincipalType,
- materializeModelSpecEndpoints,
- getConfigDefaults,
- normalizeEndpointName,
- setMaxSubagents,
-} from 'librechat-data-provider';
import {
logger,
getTenantId,
- mergeConfigOverrides,
loadDefaultInterface,
tenantStorage,
BASE_CONFIG_PRINCIPAL_ID,
SYSTEM_TENANT_ID,
} from '@librechat/data-schemas';
+import {
+ PrincipalType,
+ materializeModelSpecEndpoints,
+ getConfigDefaults,
+ normalizeEndpointName,
+ setMaxSubagents,
+} from 'librechat-data-provider';
import type { AppConfig, ConfigOverrideLayer } from '@librechat/data-schemas';
import type { Types } from 'mongoose';
+import type { EnvReferencePolicy } from './allowlist';
import type { CustomConfigLoadMode } from './loader';
+import type { SecretRebinding } from './rebinding';
+import { createEnvReferencePolicy, parseEnvAllowlist } from './allowlist';
+import { resolveRuntimeConfigSecrets } from '~/admin/secrets';
import { normalizeEndpointReferences } from './references';
+import { mergeOverrideLayers } from './overrides';
import { checkAppConfigTheme } from './theme';
const BASE_CONFIG_KEY = '_BASE_';
@@ -250,6 +254,12 @@ export interface AppConfigServiceDeps {
}) => Promise<AppConfig>;
/** TTL in ms for per-user/role merged config caches. Defaults to 60 000. */
overrideCacheTtl?: number;
+ /**
+ * Extra env names override values may reference (`CONFIG_OVERRIDE_ENV_ALLOWLIST`: names
+ * separated by commas or whitespace), beyond those librechat.yaml references and the built-in
+ * endpoint credentials.
+ */
+ overrideEnvAllowlist?: string;
}
export interface GetAppConfigOptions {
@@ -359,6 +369,38 @@ export function createMessageBudgetReader(): {
};
}
+/** Most distinct rebinding warnings remembered before the record starts over. */
+const MAX_REBINDING_WARNINGS = 1000;
+
+/**
+ * Logs each secret a layer drops for being sent somewhere other than where it was entered, and
+ * each destination it sets back, once per principal and path for the process's lifetime
+ * (bounded), since every uncached merge does it again.
+ */
+function createRebindingWarner(): (rebinding: SecretRebinding) => void {
+ const warned = new Set<string>();
+ return ({ layer, kind, path }) => {
+ const principal = `${layer.principalType}/${layer.principalId?.toString()}`;
+ const key = `${principal}:${path}`;
+ if (warned.has(key)) {
+ return;
+ }
+ if (warned.size >= MAX_REBINDING_WARNINGS) {
+ warned.clear();
+ }
+ warned.add(key);
+ if (kind === 'destination') {
+ logger.warn(
+ `[getAppConfig] Ignoring "${path}" for ${principal}: it would send a credential to a destination that was not chosen for it`,
+ );
+ return;
+ }
+ logger.warn(
+ `[getAppConfig] Dropping secret "${path}" for ${principal}: the merged config sends it somewhere other than the destination it was entered for`,
+ );
+ };
+}
+
// ── Service factory ──────────────────────────────────────────────────
export function createAppConfigService(deps: AppConfigServiceDeps): {
@@ -377,9 +419,55 @@ export function createAppConfigService(deps: AppConfigServiceDeps): {
getUserPrincipals,
augmentConfig,
overrideCacheTtl = DEFAULT_OVERRIDE_CACHE_TTL,
+ overrideEnvAllowlist,
} = deps;
const cache = getCache(cacheKeys.APP_CONFIG);
+ const envAllowlist = parseEnvAllowlist(overrideEnvAllowlist);
+ const envPolicies = new WeakMap<AppConfig, Map<string, EnvReferencePolicy>>();
+ const warnRebinding = createRebindingWarner();
+ const runtimeConfigs = new WeakMap<AppConfig, AppConfig>();
+
+ /**
+ * A merged config with its stored credentials decrypted for runtime readers. The override cache
+ * (shared through Redis when `APP_CONFIG` is not kept in memory) holds the config as merged,
+ * with ciphertext; each read decrypts it, once per cached object.
+ */
+ function withRuntimeSecrets(merged: AppConfig): AppConfig {
+ let resolved = runtimeConfigs.get(merged);
+ if (!resolved) {
+ resolved = resolveRuntimeConfigSecrets(merged);
+ runtimeConfigs.set(merged, resolved);
+ }
+ return resolved;
+ }
+
+ /**
+ * The env reference policy for a tenant, built once per loaded librechat.yaml and tenant from
+ * the YAML that tenant sees, so a name only another tenant's endpoint references is not
+ * allowed in this tenant's overrides.
+ */
+ function getEnvPolicy(
+ baseConfig: AppConfig,
+ scopedBaseConfig: AppConfig,
+ tenantId: string | undefined,
+ ): EnvReferencePolicy {
+ let byTenant = envPolicies.get(baseConfig);
+ if (!byTenant) {
+ byTenant = new Map();
+ envPolicies.set(baseConfig, byTenant);
+ }
+ const key = tenantId ?? '';
+ let policy = byTenant.get(key);
+ if (!policy) {
+ policy = createEnvReferencePolicy({
+ config: scopedBaseConfig.config,
+ allowlist: envAllowlist,
+ });
+ byTenant.set(key, policy);
+ }
+ return policy;
+ }
let lastGoodBaseConfig: AppConfig | undefined;
let baseConfigFlight: { promise: Promise<AppConfig>; generation: number } | undefined;
@@ -662,7 +750,7 @@ export function createAppConfigService(deps: AppConfigServiceDeps): {
if (cacheable && !refresh) {
const cachedMerged = (await cache.get(cacheKey)) as AppConfig | undefined;
if (cachedMerged) {
- return await augment(cachedMerged);
+ return await augment(withRuntimeSecrets(cachedMerged));
}
}
@@ -670,11 +758,12 @@ export function createAppConfigService(deps: AppConfigServiceDeps): {
try {
const configs = await getApplicableConfigs(principals);
if (configs.length > 0) {
+ const layered = mergeOverrideLayers(scopedBaseConfig, configs, {
+ envPolicy: getEnvPolicy(baseConfig, scopedBaseConfig, effectiveTenantId),
+ onRebinding: warnRebinding,
+ });
merged = scopeCustomEndpoints(
- checkOverrideTheme(
- scopedBaseConfig,
- completeEffectiveConfig(mergeConfigOverrides(scopedBaseConfig, configs)),
- ),
+ checkOverrideTheme(scopedBaseConfig, completeEffectiveConfig(layered)),
effectiveTenantId,
hiddenEndpoints,
);
@@ -691,7 +780,7 @@ export function createAppConfigService(deps: AppConfigServiceDeps): {
await cache.delete(cacheKey);
}
}
- return await augment(merged);
+ return await augment(withRuntimeSecrets(merged));
}
/**
diff --git a/packages/api/src/endpoints/config/endpoints.spec.ts b/packages/api/src/endpoints/config/endpoints.spec.ts
index 112823cbaf..843fa09250 100644
--- a/packages/api/src/endpoints/config/endpoints.spec.ts
+++ b/packages/api/src/endpoints/config/endpoints.spec.ts
@@ -486,7 +486,8 @@ describe('createEndpointsConfigService', () => {
});
});
- it('exposes custom endpoints from group-scoped overrides for grouped users', async () => {
+ /** Endpoints a grouped user gets from a group override that references `${FOO_KEY}`/`${FOO_URL}`. */
+ async function getGroupScopedEndpoints(overrideEnvAllowlist?: string) {
const groupId = new Types.ObjectId('6a0aea2172e2d59d4658c9d2');
const getUserPrincipals = jest.fn().mockResolvedValue([
{ principalType: PrincipalType.ROLE, principalId: 'USER' },
@@ -530,6 +531,7 @@ describe('createEndpointsConfigService', () => {
cacheKeys: { APP_CONFIG: 'app_config' },
getApplicableConfigs,
getUserPrincipals,
+ overrideEnvAllowlist,
});
const { getEndpointsConfig } = createEndpointsConfigService({
getAppConfig,
@@ -547,8 +549,18 @@ describe('createEndpointsConfigService', () => {
expect.objectContaining({ principalType: PrincipalType.GROUP, principalId: groupId }),
]),
);
+ return result;
+ }
+
+ it('exposes custom endpoints from group-scoped overrides for grouped users', async () => {
+ const result = await getGroupScopedEndpoints('FOO_KEY,FOO_URL');
expect(result?.FOO).toEqual(expect.objectContaining({ type: EModelEndpoint.custom }));
});
+
+ it('treats env references outside the override allowlist as missing', async () => {
+ const result = await getGroupScopedEndpoints();
+ expect(result?.FOO).toBeUndefined();
+ });
});
describe('checkCapability', () => {
diff --git a/packages/api/src/files/mistral/crud.spec.ts b/packages/api/src/files/mistral/crud.spec.ts
index d482317fb4..4f0dc1ee8c 100644
--- a/packages/api/src/files/mistral/crud.spec.ts
+++ b/packages/api/src/files/mistral/crud.spec.ts
@@ -1263,7 +1263,10 @@ describe('MistralOCR Service', () => {
(isEncryptedSecretPayload as jest.Mock).mockReturnValueOnce(true);
(decryptConfigSecret as jest.Mock).mockReturnValueOnce(undefined);
- mockLoadAuthValues.mockResolvedValue({ OCR_API_KEY: 'env-fallback-key' });
+ mockLoadAuthValues.mockResolvedValue({
+ OCR_API_KEY: 'env-fallback-key',
+ OCR_BASEURL: 'https://api.mistral.ai/v1',
+ });
mockAxios.post!.mockClear();
mockAxios.get!.mockClear();
@@ -1311,7 +1314,7 @@ describe('MistralOCR Service', () => {
config: {
ocr: {
apiKey: corruptedCiphertext,
- baseURL: 'https://api.mistral.ai/v1',
+ baseURL: '${OCR_BASEURL}',
mistralModel: 'mistral-ocr-latest',
},
},
@@ -1336,7 +1339,7 @@ describe('MistralOCR Service', () => {
}),
);
- // Treated as empty, so it fails over to loading OCR_API_KEY from the environment.
+ // Treated as empty; with the deployment's base URL that falls back to OCR_API_KEY.
expect(mockLoadAuthValues).toHaveBeenCalledWith(
expect.objectContaining({ authFields: expect.arrayContaining(['OCR_API_KEY']) }),
);
@@ -1467,6 +1470,128 @@ describe('MistralOCR Service', () => {
expect(result.text).toEqual('Content from default configuration\n\n');
});
+ describe('Default key binding', () => {
+ const mockOCRFlow = () => {
+ mockAxios.post!.mockResolvedValueOnce({
+ data: {
+ id: 'file-789',
+ object: 'file',
+ bytes: 1024,
+ created_at: Date.now(),
+ filename: 'document.pdf',
+ purpose: 'ocr',
+ } as MistralFileUploadResponse,
+ });
+ mockAxios.get!.mockResolvedValueOnce({
+ data: {
+ url: 'https://signed-url.com',
+ expires_at: Date.now() + 86400000,
+ } as MistralSignedUrlResponse,
+ });
+ mockAxios.post!.mockResolvedValueOnce({
+ data: {
+ model: 'mistral-ocr-latest',
+ pages: [
+ {
+ index: 0,
+ markdown: 'Bound key',
+ images: [],
+ dimensions: { dpi: 300, height: 1100, width: 850 },
+ },
+ ],
+ document_annotation: '',
+ usage_info: { pages_processed: 1, doc_size_bytes: 1024 },
+ },
+ });
+ };
+
+ const upload = (ocr: Record<string, string>) =>
+ uploadMistralOCR({
+ req: { user: { id: 'user-bound' }, config: { ocr } } as unknown as ServerRequest,
+ file: {
+ path: '/tmp/upload/file.pdf',
+ originalname: 'document.pdf',
+ mimetype: 'application/pdf',
+ } as Express.Multer.File,
+ loadAuthValues: mockLoadAuthValues,
+ });
+
+ const sentAuthorizations = () =>
+ mockAxios.post!.mock.calls.map(
+ (call) => (call[2] as { headers?: Record<string, string> })?.headers?.Authorization,
+ );
+
+ beforeEach(() => {
+ mockAxios.post!.mockClear();
+ mockAxios.get!.mockClear();
+ mockLoadAuthValues.mockResolvedValue({
+ OCR_API_KEY: 'deployment-ocr-key',
+ OCR_BASEURL: 'https://ocr.deployment.example/v1',
+ });
+ });
+
+ it('never fills an empty key from OCR_API_KEY for a configured base URL', async () => {
+ mockOCRFlow();
+
+ await upload({ apiKey: '', baseURL: 'https://elsewhere.example/v1' });
+
+ expect(mockLoadAuthValues).not.toHaveBeenCalled();
+ expect(mockAxios.post!.mock.calls[0][0]).toBe('https://elsewhere.example/v1/files');
+ expect(sentAuthorizations().join(' ')).not.toContain('deployment-ocr-key');
+ });
+
+ it('fills an empty key from OCR_API_KEY with the deployment base URL', async () => {
+ mockOCRFlow();
+
+ await upload({ apiKey: '', baseURL: '' });
+
+ expect(mockLoadAuthValues).toHaveBeenCalledWith(
+ expect.objectContaining({ authFields: ['OCR_BASEURL', 'OCR_API_KEY'] }),
+ );
+ expect(mockAxios.post!.mock.calls[0][0]).toBe('https://ocr.deployment.example/v1/files');
+ expect(sentAuthorizations()[0]).toBe('Bearer deployment-ocr-key');
+ });
+
+ it('never fills an empty key from OCR_API_KEY for a base URL in another variable', async () => {
+ mockOCRFlow();
+ mockLoadAuthValues.mockResolvedValue({
+ OCR_API_KEY: 'deployment-ocr-key',
+ OPENAI_REVERSE_PROXY: 'https://proxy.elsewhere.example/v1',
+ });
+
+ await upload({ apiKey: '', baseURL: '${OPENAI_REVERSE_PROXY}' });
+
+ expect(mockLoadAuthValues).toHaveBeenCalledWith(
+ expect.objectContaining({ authFields: ['OPENAI_REVERSE_PROXY'] }),
+ );
+ expect(mockAxios.post!.mock.calls[0][0]).toBe('https://proxy.elsewhere.example/v1/files');
+ expect(sentAuthorizations().join(' ')).not.toContain('deployment-ocr-key');
+ });
+
+ it('fills an empty key from OCR_API_KEY with the default base URL variable', async () => {
+ mockOCRFlow();
+
+ await upload({ apiKey: '', baseURL: '${OCR_BASEURL}' });
+
+ expect(mockLoadAuthValues).toHaveBeenCalledWith(
+ expect.objectContaining({ authFields: ['OCR_BASEURL', 'OCR_API_KEY'] }),
+ );
+ expect(mockAxios.post!.mock.calls[0][0]).toBe('https://ocr.deployment.example/v1/files');
+ expect(sentAuthorizations()[0]).toBe('Bearer deployment-ocr-key');
+ });
+
+ it('resolves an explicit key reference with a configured base URL', async () => {
+ mockOCRFlow();
+
+ await upload({ apiKey: '${OCR_API_KEY}', baseURL: 'https://ocr.internal.example/v1' });
+
+ expect(mockLoadAuthValues).toHaveBeenCalledWith(
+ expect.objectContaining({ authFields: ['OCR_API_KEY'] }),
+ );
+ expect(sentAuthorizations()[0]).toBe('Bearer deployment-ocr-key');
+ });
+ });
+
describe('Mixed env var and hardcoded configuration', () => {
beforeEach(() => {
// Clean up any PROXY env var from previous tests
diff --git a/packages/api/src/files/mistral/crud.ts b/packages/api/src/files/mistral/crud.ts
index abe146ffc9..905bce4967 100644
--- a/packages/api/src/files/mistral/crud.ts
+++ b/packages/api/src/files/mistral/crud.ts
@@ -314,6 +314,15 @@ function getEnvVarName(configValue: string, defaultName: string): string {
return extractVariableName(configValue) || defaultName;
}
+/** The variable that names OCR's default destination, the one `OCR_API_KEY` belongs with. */
+const DEFAULT_OCR_BASEURL_VAR = 'OCR_BASEURL';
+
+/** Whether a base URL is OCR's default destination: unset, or `${OCR_BASEURL}`. */
+function isDefaultOCRDestination(baseURL: string): boolean {
+ const trimmed = baseURL.trim();
+ return trimmed === '' || extractVariableName(trimmed) === DEFAULT_OCR_BASEURL_VAR;
+}
+
/**
* Resolves a configuration value from either hardcoded or environment
*/
@@ -334,7 +343,13 @@ async function resolveConfigValue(
}
/**
- * Loads authentication configuration from OCR config
+ * Loads authentication configuration from OCR config.
+ *
+ * An empty API key falls back to the deployment's `OCR_API_KEY` only while the base URL is the
+ * deployment's default OCR destination too: unset, or `${OCR_BASEURL}`. With any other base URL,
+ * a literal or a reference to another variable, an empty key stays empty: the deployment's key is
+ * never sent to a host a config override chose, including when the override's inherited key was
+ * dropped for pointing OCR elsewhere.
*/
async function loadAuthConfig(context: OCRContext): Promise<AuthConfig> {
const appConfig = context.req.config;
@@ -344,34 +359,47 @@ async function loadAuthConfig(context: OCRContext): Promise<AuthConfig> {
? (decryptConfigSecret(rawApiKeyConfig) ?? '')
: rawApiKeyConfig;
const baseURLConfig = ocrConfig?.baseURL || '';
+ const baseURLFromEnv = needsEnvLoad(baseURLConfig);
+ const apiKeyBlank = !apiKeyConfig.trim();
+ const defaultDestination = isDefaultOCRDestination(baseURLConfig);
+ const apiKeyFromEnv = envVarRegex.test(apiKeyConfig) || (apiKeyBlank && defaultDestination);
+ const literalApiKey = apiKeyBlank ? '' : apiKeyConfig;
+
+ if (apiKeyBlank && !defaultDestination) {
+ logger.warn(
+ '[loadAuthConfig] OCR has a configured base URL and no API key; the default OCR_API_KEY is only used with the default OCR base URL',
+ );
+ }
- if (!needsEnvLoad(apiKeyConfig) && !needsEnvLoad(baseURLConfig)) {
+ if (!apiKeyFromEnv && !baseURLFromEnv) {
return {
- apiKey: apiKeyConfig,
+ apiKey: literalApiKey,
baseURL: baseURLConfig,
};
}
const authFields: string[] = [];
- if (needsEnvLoad(baseURLConfig)) {
- authFields.push(getEnvVarName(baseURLConfig, 'OCR_BASEURL'));
+ if (baseURLFromEnv) {
+ authFields.push(getEnvVarName(baseURLConfig, DEFAULT_OCR_BASEURL_VAR));
}
- if (needsEnvLoad(apiKeyConfig)) {
+ if (apiKeyFromEnv) {
authFields.push(getEnvVarName(apiKeyConfig, 'OCR_API_KEY'));
}
const authValues = await context.loadAuthValues({
userId: context.req.user?.id || '',
authFields,
- optional: new Set(['OCR_BASEURL']),
+ optional: new Set([DEFAULT_OCR_BASEURL_VAR]),
});
- const apiKey = await resolveConfigValue(apiKeyConfig, 'OCR_API_KEY', authValues);
+ const apiKey = apiKeyFromEnv
+ ? await resolveConfigValue(apiKeyConfig, 'OCR_API_KEY', authValues)
+ : literalApiKey;
const baseURL = await resolveConfigValue(
baseURLConfig,
- 'OCR_BASEURL',
+ DEFAULT_OCR_BASEURL_VAR,
authValues,
DEFAULT_MISTRAL_BASE_URL,
);
diff --git a/packages/api/src/mcp/__tests__/utils.test.ts b/packages/api/src/mcp/__tests__/utils.test.ts
index 7bc211da20..66762cc34f 100644
--- a/packages/api/src/mcp/__tests__/utils.test.ts
+++ b/packages/api/src/mcp/__tests__/utils.test.ts
@@ -294,6 +294,28 @@ describe('redactServerSecrets', () => {
expect(redacted.oauth?.scope).toBe('read');
});
+ it('never returns the masked previews the admin config API stores beside the secrets', () => {
+ const config: ParsedServerConfig = {
+ type: 'sse',
+ url: 'https://example.com/mcp',
+ apiKey: {
+ source: 'admin',
+ authorization_type: 'bearer',
+ key: 'decrypted-at-runtime',
+ keyPreview: '...time',
+ },
+ oauth: {
+ client_id: 'cid',
+ client_secret: 'decrypted-oauth-secret',
+ client_secretPreview: '...cret',
+ },
+ };
+ const redacted = redactServerSecrets(config);
+ expect(redacted.apiKey).toEqual({ source: 'admin', authorization_type: 'bearer' });
+ expect(redacted.oauth).toEqual({ client_id: 'cid' });
+ expect(JSON.stringify(redacted)).not.toMatch(/time|cret/);
+ });
+
it('should strip both apiKey.key and oauth.client_secret simultaneously', () => {
const config: ParsedServerConfig = {
type: 'sse',
diff --git a/packages/api/src/mcp/registry/MCPServersRegistry.ts b/packages/api/src/mcp/registry/MCPServersRegistry.ts
index 8ba3866531..0699f4be85 100644
--- a/packages/api/src/mcp/registry/MCPServersRegistry.ts
+++ b/packages/api/src/mcp/registry/MCPServersRegistry.ts
@@ -23,7 +23,7 @@ import { normalizeLegacyHeaderMaps, normalizeLegacyHeaderMapsIn } from './compat
import { canBackfillSharedServerInstructions, isUserSourced } from '~/mcp/utils';
import { ReadThroughAllCache } from './cache/ReadThroughAllCache';
import { isPluginSourced, MCP_PLUGIN_SOURCE } from '~/utils/env';
-import { requireApiKeyReentryForRebinding } from './binding';
+import { requireApiKeyReentryForRebinding } from './reentry';
import { ReadThroughCache } from './cache/ReadThroughCache';
import { MCPServerInspector } from './MCPServerInspector';
import { ServerConfigsDB } from './db/ServerConfigsDB';
diff --git a/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts b/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts
index b4f6cfd4a0..8e6ebc1e3e 100644
--- a/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts
+++ b/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts
@@ -313,6 +313,13 @@ describe('ServerConfigsDB', () => {
'url',
(config) => ({ ...updateOAuth(config, {}), url: 'https://attacker.example.com/sse' }),
],
+ [
+ 'proxy',
+ (config) => ({
+ ...updateOAuth(config, {}),
+ proxy: 'http://proxy.attacker.example.com:8080',
+ }),
+ ],
[
'oauth.authorization_url',
(config) =>
diff --git a/packages/api/src/mcp/registry/__tests__/ensureConfigServers.test.ts b/packages/api/src/mcp/registry/__tests__/ensureConfigServers.test.ts
index 7f1c1f12ea..e7925e4246 100644
--- a/packages/api/src/mcp/registry/__tests__/ensureConfigServers.test.ts
+++ b/packages/api/src/mcp/registry/__tests__/ensureConfigServers.test.ts
@@ -1,3 +1,5 @@
+import { PrincipalType } from 'librechat-data-provider';
+import type { AppConfig, ConfigOverrideLayer } from '@librechat/data-schemas';
import type * as t from '~/mcp/types';
import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry';
import { MCPServerInspector } from '~/mcp/registry/MCPServerInspector';
@@ -699,4 +701,73 @@ describe('MCPServersRegistry — ensureConfigServers', () => {
expect(config?.inspectionFailed).toBe(true);
});
});
+
+ describe('credentials an admin config override stores', () => {
+ const CREDS_KEY = 'ab'.repeat(32);
+ let previousKey: string | undefined;
+
+ beforeAll(() => {
+ previousKey = process.env.CREDS_KEY;
+ process.env.CREDS_KEY = CREDS_KEY;
+ });
+
+ afterAll(() => {
+ if (previousKey === undefined) {
+ delete process.env.CREDS_KEY;
+ } else {
+ process.env.CREDS_KEY = previousKey;
+ }
+ });
+
+ it('initializes the server with the decrypted key, never the ciphertext', async () => {
+ /** Loaded under `CREDS_KEY`: the encryption key is read when data-schemas loads. */
+ let encryptV3!: typeof import('@librechat/data-schemas').encryptV3;
+ let resolveConfigOverrides!: typeof import('~/app/overrides').resolveConfigOverrides;
+ let createEnvReferencePolicy!: typeof import('~/app/allowlist').createEnvReferencePolicy;
+ await jest.isolateModulesAsync(async () => {
+ ({ encryptV3 } = await import('@librechat/data-schemas'));
+ ({ resolveConfigOverrides } = await import('~/app/overrides'));
+ ({ createEnvReferencePolicy } = await import('~/app/allowlist'));
+ });
+
+ const ciphertext = encryptV3('sk-admin-stored-key');
+ const layer = {
+ principalType: PrincipalType.ROLE,
+ principalId: 'USER',
+ priority: 10,
+ overrides: {
+ mcpServers: {
+ remote: {
+ type: 'streamable-http',
+ url: 'https://mcp.example.com/mcp',
+ apiKey: {
+ source: 'admin',
+ authorization_type: 'bearer',
+ key: ciphertext,
+ keyPreview: '...-key',
+ },
+ },
+ },
+ },
+ } as unknown as ConfigOverrideLayer;
+ const appConfig = resolveConfigOverrides({ config: {} } as AppConfig, [layer], {
+ envPolicy: createEnvReferencePolicy({}),
+ });
+
+ const result = await registry.ensureConfigServers(
+ appConfig.mcpConfig as Record<string, t.MCPOptions>,
+ );
+
+ expect(result).toHaveProperty('remote');
+ expect(inspectSpy).toHaveBeenCalledTimes(1);
+ const [name, rawConfig] = inspectSpy.mock.calls[0] as [string, t.MCPOptions];
+ expect(name).toBe('remote');
+ expect(rawConfig.apiKey).toMatchObject({
+ source: 'admin',
+ authorization_type: 'bearer',
+ key: 'sk-admin-stored-key',
+ });
+ expect(JSON.stringify(inspectSpy.mock.calls)).not.toContain(ciphertext);
+ });
+ });
});
diff --git a/packages/api/src/mcp/registry/binding.ts b/packages/api/src/mcp/registry/binding.ts
index bc9b2ecf8c..778bedf800 100644
--- a/packages/api/src/mcp/registry/binding.ts
+++ b/packages/api/src/mcp/registry/binding.ts
@@ -1,13 +1,25 @@
import { createHash } from 'crypto';
-import type { MCPOptions } from '~/mcp/types';
+import type { MCPOptions } from 'librechat-data-provider';
import { isGeneratedUserApiKeyVariable } from '~/mcp/headers';
-import { MCPApiKeyReentryRequiredError } from '~/mcp/errors';
-function getUrl(config: MCPOptions): string | undefined {
+/**
+ * The parts of a server config that decide where its credentials are sent. Structural, so the
+ * admin config tier can compare configs as librechat.yaml and overrides spell them, before the
+ * schema fills defaults.
+ */
+export type CredentialBindingConfig = {
+ type?: string;
+ url?: string;
+ proxy?: string;
+ apiKey?: Partial<NonNullable<MCPOptions['apiKey']>>;
+ oauth?: Partial<NonNullable<MCPOptions['oauth']>>;
+};
+
+function getUrl(config: CredentialBindingConfig): string | undefined {
return 'url' in config ? config.url : undefined;
}
-function getProxy(config: MCPOptions): string | undefined {
+function getProxy(config: CredentialBindingConfig): string | undefined {
return 'proxy' in config ? config.proxy : undefined;
}
@@ -27,18 +39,32 @@ function normalizeUrl(value?: string, stripFragment = false): string | undefined
}
}
-function normalizeTransport(type: MCPOptions['type']): string {
+function normalizeTransport(type?: string): string | undefined {
return type === 'http' ? 'streamable-http' : type;
}
-function normalizeCustomHeader(apiKey: MCPOptions['apiKey']): string | undefined {
+function normalizeCustomHeader(apiKey: CredentialBindingConfig['apiKey']): string | undefined {
if (apiKey?.authorization_type !== 'custom') {
return undefined;
}
return (apiKey.custom_header || 'X-Api-Key').toLowerCase();
}
-function apiKeyBinding(config: MCPOptions): Record<string, string | undefined> {
+/** A credential's binding fields, normalized, by name: two configs that send it alike match. */
+export type CredentialBindingFields = Record<string, string | undefined>;
+
+function diffBindingFields(
+ existing: CredentialBindingFields,
+ updated: CredentialBindingFields,
+): string[] {
+ return Object.keys(existing).filter((field) => existing[field] !== updated[field]);
+}
+
+/**
+ * The request-boundary fields (`url`, `type`, `proxy`, `apiKey.authorization_type`,
+ * `apiKey.custom_header`) of a config, normalized: where an `apiKey.key` would be sent.
+ */
+export function getApiKeyBindingFields(config: CredentialBindingConfig): CredentialBindingFields {
return {
url: normalizeUrl(getUrl(config), true),
type: normalizeTransport(config.type),
@@ -48,6 +74,20 @@ function apiKeyBinding(config: MCPOptions): Record<string, string | undefined> {
};
}
+/**
+ * The request-boundary fields (`url`, `type`, `proxy`, `apiKey.authorization_type`,
+ * `apiKey.custom_header`) that differ between two configs: where an `apiKey.key` would be sent.
+ */
+export function diffApiKeyBinding(
+ existingConfig: CredentialBindingConfig,
+ updatedConfig: CredentialBindingConfig,
+): string[] {
+ return diffBindingFields(
+ getApiKeyBindingFields(existingConfig),
+ getApiKeyBindingFields(updatedConfig),
+ );
+}
+
/** Returns fields that would move an omitted, stored admin key to a new request boundary. */
export function getChangedApiKeyBindingFields(
existingConfig: MCPOptions,
@@ -63,14 +103,93 @@ export function getChangedApiKeyBindingFields(
return [];
}
- const existing = apiKeyBinding(existingConfig);
- const updated = apiKeyBinding(updatedConfig);
- return Object.keys(existing).filter((field) => existing[field] !== updated[field]);
+ return diffApiKeyBinding(existingConfig, updatedConfig);
+}
+
+type OAuthOptions = NonNullable<MCPOptions['oauth']>;
+
+function normalizeOAuthMethods(values?: readonly string[]): string | undefined {
+ if (!values?.length) {
+ return undefined;
+ }
+ return JSON.stringify([...new Set(values)].sort());
+}
+
+/**
+ * Keeps the optional OAuth binding fields an update omits (`token_endpoint_auth_methods_supported`
+ * and the revocation settings) at their stored values, so leaving them out reads as unchanged.
+ */
+export function preserveOmittedOAuthBindingFields<T extends Partial<OAuthOptions>>(
+ existingOAuth: Partial<OAuthOptions>,
+ updatedOAuth: T,
+): T {
+ return {
+ ...updatedOAuth,
+ ...(updatedOAuth.token_endpoint_auth_methods_supported === undefined &&
+ existingOAuth.token_endpoint_auth_methods_supported !== undefined && {
+ token_endpoint_auth_methods_supported: existingOAuth.token_endpoint_auth_methods_supported,
+ }),
+ ...(updatedOAuth.revocation_endpoint === undefined &&
+ existingOAuth.revocation_endpoint !== undefined && {
+ revocation_endpoint: existingOAuth.revocation_endpoint,
+ }),
+ ...(updatedOAuth.revocation_endpoint_auth_methods_supported === undefined &&
+ existingOAuth.revocation_endpoint_auth_methods_supported !== undefined && {
+ revocation_endpoint_auth_methods_supported:
+ existingOAuth.revocation_endpoint_auth_methods_supported,
+ }),
+ };
+}
+
+/**
+ * The fields of a config that bind an OAuth client secret to its authorization server and
+ * client, and the access token exchanged for it to the server and proxy it is sent through,
+ * normalized; `null` without an `oauth` block.
+ */
+export function getOAuthSecretBindingFields(
+ config: CredentialBindingConfig,
+): CredentialBindingFields | null {
+ const oauth = config.oauth;
+ if (!oauth) {
+ return null;
+ }
+ return {
+ url: normalizeUrl(getUrl(config)),
+ proxy: normalizeUrl(getProxy(config), true),
+ 'oauth.authorization_url': normalizeUrl(oauth.authorization_url),
+ 'oauth.token_url': normalizeUrl(oauth.token_url),
+ 'oauth.client_id': oauth.client_id,
+ 'oauth.token_exchange_method': oauth.token_exchange_method,
+ 'oauth.token_endpoint_auth_methods_supported': normalizeOAuthMethods(
+ oauth.token_endpoint_auth_methods_supported,
+ ),
+ 'oauth.revocation_endpoint': normalizeUrl(oauth.revocation_endpoint),
+ 'oauth.revocation_endpoint_auth_methods_supported': normalizeOAuthMethods(
+ oauth.revocation_endpoint_auth_methods_supported,
+ ),
+ };
+}
+
+/**
+ * The OAuth binding fields ({@link getOAuthSecretBindingFields}) that differ between two
+ * configs: changing any of them while keeping a stored secret would hand that secret, or the
+ * token it obtains, to a different destination or client.
+ */
+export function getChangedOAuthSecretBindingFields(
+ existingConfig: CredentialBindingConfig,
+ updatedConfig: CredentialBindingConfig,
+): string[] {
+ const existing = getOAuthSecretBindingFields(existingConfig);
+ const updated = getOAuthSecretBindingFields(updatedConfig);
+ if (!existing || !updated) {
+ return [];
+ }
+ return diffBindingFields(existing, updated);
}
function userApiKeyBinding(config: MCPOptions): string {
return JSON.stringify([
- apiKeyBinding(config),
+ getApiKeyBindingFields(config),
normalizeUrl(config.oauth?.authorization_url, true),
normalizeUrl(config.oauth?.token_url, true),
/** redirect_uri is sent as an OAuth parameter, not used as an outbound request URL. */
@@ -95,14 +214,3 @@ export function getUserApiKeyVariable(config: MCPOptions, existingConfig?: MCPOp
}
return `MCP_API_KEY_${createHash('sha256').update(binding).digest('hex')}`;
}
-
-/** Requires a replacement key before a stored admin credential can cross request boundaries. */
-export function requireApiKeyReentryForRebinding(
- existingConfig: MCPOptions,
- updatedConfig: MCPOptions,
-): void {
- const changedFields = getChangedApiKeyBindingFields(existingConfig, updatedConfig);
- if (changedFields.length > 0) {
- throw new MCPApiKeyReentryRequiredError(changedFields);
- }
-}
diff --git a/packages/api/src/mcp/registry/db/ServerConfigsDB.ts b/packages/api/src/mcp/registry/db/ServerConfigsDB.ts
index ae24599b20..395b400db5 100644
--- a/packages/api/src/mcp/registry/db/ServerConfigsDB.ts
+++ b/packages/api/src/mcp/registry/db/ServerConfigsDB.ts
@@ -10,8 +10,13 @@ import type { AllMethods, MCPServerDocument, IAgent } from '@librechat/data-sche
import type { IServerConfigsRepositoryInterface } from '~/mcp/registry/ServerConfigsRepositoryInterface';
import type { ParsedServerConfig, AddServerResult } from '~/mcp/types';
import type { ResolvedPrincipal } from '~/types/principal';
-import { getUserApiKeyVariable, requireApiKeyReentryForRebinding } from '~/mcp/registry/binding';
+import {
+ getUserApiKeyVariable,
+ preserveOmittedOAuthBindingFields,
+ getChangedOAuthSecretBindingFields,
+} from '~/mcp/registry/binding';
import { MCPCommittedWriteError, MCPOAuthSecretReentryRequiredError } from '~/mcp/errors';
+import { requireApiKeyReentryForRebinding } from '~/mcp/registry/reentry';
import { normalizeLegacyHeaderMaps } from '~/mcp/registry/compat';
import { AccessControlService } from '~/acl/accessControlService';
import { isGeneratedUserApiKeyVariable } from '~/mcp/headers';
@@ -33,8 +38,6 @@ const DANGEROUS_CREDENTIAL_PATTERNS = [
const BLOCKED_USER_OAUTH_ENDPOINT_PARAMS = ['audience', 'resource'] as const;
-type OAuthConfig = NonNullable<ParsedServerConfig['oauth']>;
-
/**
* Sanitizes headers by removing dangerous credential placeholders.
* This prevents credential exfiltration when MCP servers are shared between users.
@@ -120,99 +123,6 @@ function sanitizeUserManagedOAuthConfig(config: ParsedServerConfig): ParsedServe
};
}
-function normalizeOAuthUrl(value?: string): string | undefined {
- if (!value) {
- return value;
- }
-
- try {
- return new URL(value).href;
- } catch {
- return value;
- }
-}
-
-function normalizeOAuthMethods(values?: readonly string[]): string | undefined {
- if (!values?.length) {
- return undefined;
- }
- return JSON.stringify([...new Set(values)].sort());
-}
-
-function preserveOmittedOAuthBindingFields(
- existingOAuth: OAuthConfig,
- updatedOAuth: OAuthConfig,
-): OAuthConfig {
- return {
- ...updatedOAuth,
- ...(updatedOAuth.token_endpoint_auth_methods_supported === undefined &&
- existingOAuth.token_endpoint_auth_methods_supported !== undefined && {
- token_endpoint_auth_methods_supported: existingOAuth.token_endpoint_auth_methods_supported,
- }),
- ...(updatedOAuth.revocation_endpoint === undefined &&
- existingOAuth.revocation_endpoint !== undefined && {
- revocation_endpoint: existingOAuth.revocation_endpoint,
- }),
- ...(updatedOAuth.revocation_endpoint_auth_methods_supported === undefined &&
- existingOAuth.revocation_endpoint_auth_methods_supported !== undefined && {
- revocation_endpoint_auth_methods_supported:
- existingOAuth.revocation_endpoint_auth_methods_supported,
- }),
- };
-}
-
-function getChangedOAuthSecretBindingFields(
- existingConfig: MCPServerDocument['config'],
- updatedConfig: ParsedServerConfig,
-): string[] {
- const existingOAuth = existingConfig.oauth;
- const updatedOAuth = updatedConfig.oauth;
- if (!existingOAuth || !updatedOAuth) {
- return [];
- }
-
- const fields = [
- [
- 'url',
- normalizeOAuthUrl('url' in existingConfig ? existingConfig.url : undefined),
- normalizeOAuthUrl(updatedConfig.url),
- ],
- [
- 'oauth.authorization_url',
- normalizeOAuthUrl(existingOAuth.authorization_url),
- normalizeOAuthUrl(updatedOAuth.authorization_url),
- ],
- [
- 'oauth.token_url',
- normalizeOAuthUrl(existingOAuth.token_url),
- normalizeOAuthUrl(updatedOAuth.token_url),
- ],
- ['oauth.client_id', existingOAuth.client_id, updatedOAuth.client_id],
- [
- 'oauth.token_exchange_method',
- existingOAuth.token_exchange_method,
- updatedOAuth.token_exchange_method,
- ],
- [
- 'oauth.token_endpoint_auth_methods_supported',
- normalizeOAuthMethods(existingOAuth.token_endpoint_auth_methods_supported),
- normalizeOAuthMethods(updatedOAuth.token_endpoint_auth_methods_supported),
- ],
- [
- 'oauth.revocation_endpoint',
- normalizeOAuthUrl(existingOAuth.revocation_endpoint),
- normalizeOAuthUrl(updatedOAuth.revocation_endpoint),
- ],
- [
- 'oauth.revocation_endpoint_auth_methods_supported',
- normalizeOAuthMethods(existingOAuth.revocation_endpoint_auth_methods_supported),
- normalizeOAuthMethods(updatedOAuth.revocation_endpoint_auth_methods_supported),
- ],
- ] as const;
-
- return fields.filter(([, existing, updated]) => existing !== updated).map(([field]) => field);
-}
-
/** Unions `mcpServerNames` over the candidate agents the caller can access. */
function unionMCPServerNames(
candidates: Array<Pick<IAgent, '_id' | 'mcpServerNames'>>,
diff --git a/packages/api/src/mcp/registry/reentry.ts b/packages/api/src/mcp/registry/reentry.ts
new file mode 100644
index 0000000000..3c51de02f2
--- /dev/null
+++ b/packages/api/src/mcp/registry/reentry.ts
@@ -0,0 +1,14 @@
+import type { MCPOptions } from 'librechat-data-provider';
+import { MCPApiKeyReentryRequiredError } from '~/mcp/errors';
+import { getChangedApiKeyBindingFields } from './binding';
+
+/** Requires a replacement key before a stored admin credential can cross request boundaries. */
+export function requireApiKeyReentryForRebinding(
+ existingConfig: MCPOptions,
+ updatedConfig: MCPOptions,
+): void {
+ const changedFields = getChangedApiKeyBindingFields(existingConfig, updatedConfig);
+ if (changedFields.length > 0) {
+ throw new MCPApiKeyReentryRequiredError(changedFields);
+ }
+}
diff --git a/packages/api/src/mcp/utils.ts b/packages/api/src/mcp/utils.ts
index 5ce89efe0f..845f6a0096 100644
--- a/packages/api/src/mcp/utils.ts
+++ b/packages/api/src/mcp/utils.ts
@@ -768,7 +768,11 @@ export function redactServerSecrets(
}
if (config.oauth) {
- const { client_secret: _secret, ...safeOAuth } = config.oauth;
+ const {
+ client_secret: _secret,
+ client_secretPreview: _secretPreview,
+ ...safeOAuth
+ } = config.oauth;
safe.oauth = safeOAuth;
}
diff --git a/packages/api/src/schedules/authorization/configuration.spec.ts b/packages/api/src/schedules/authorization/configuration.spec.ts
index 758eb71dfd..ca73288ba8 100644
--- a/packages/api/src/schedules/authorization/configuration.spec.ts
+++ b/packages/api/src/schedules/authorization/configuration.spec.ts
@@ -1,7 +1,14 @@
import type { ScheduledMCPResourceBinding } from 'librechat-data-provider';
import type { ParsedServerConfig } from '~/mcp/types';
+import { encryptConfigSecrets, resolveRuntimeConfigSecrets } from '~/admin/secrets';
import { getScheduledMCPConfigurationRevision } from './configuration';
+/** Encryption reads `CREDS_KEY` when data-schemas loads, before any spec code runs. */
+jest.mock('@librechat/data-schemas', () => {
+ process.env.CREDS_KEY ??= '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
+ return jest.requireActual('@librechat/data-schemas');
+});
+
const binding: ScheduledMCPResourceBinding = {
url: 'https://warehouse.example/mcp',
credentialMode: 'resource_bearer',
@@ -95,6 +102,37 @@ it('excludes rotating client/API secrets and display/inspection bookkeeping', ()
).toBe(getScheduledMCPConfigurationRevision(config, binding));
});
+/** The server as the admin config API stores it, read back by the MCP runtime (decrypted). */
+function storedByAdmin(key: string, clientSecret: string): ParsedServerConfig {
+ const { mcpServers } = encryptConfigSecrets({
+ mcpServers: {
+ warehouse: {
+ ...config,
+ apiKey: { ...config.apiKey!, key },
+ oauth: { ...config.oauth, client_secret: clientSecret },
+ },
+ },
+ });
+ return resolveRuntimeConfigSecrets({ mcpConfig: mcpServers }).mcpConfig.warehouse;
+}
+
+it('keeps the fence when an admin rotates a stored client/API secret in place', () => {
+ const before = storedByAdmin('fixture-api-key-0001', 'fixture-client-secret-0001');
+ const rotated = storedByAdmin('fixture-api-key-0002', 'fixture-client-secret-0002');
+ /** The runtime reads the new secrets, with the masked previews stored beside them. */
+ expect(rotated.apiKey).toMatchObject({ key: 'fixture-api-key-0002', keyPreview: '...0002' });
+ expect(rotated.oauth).toMatchObject({
+ client_secret: 'fixture-client-secret-0002',
+ client_secretPreview: '...0002',
+ });
+ expect(getScheduledMCPConfigurationRevision(rotated, binding)).toBe(
+ getScheduledMCPConfigurationRevision(before, binding),
+ );
+ expect(getScheduledMCPConfigurationRevision(rotated, binding)).toBe(
+ getScheduledMCPConfigurationRevision(config, binding),
+ );
+});
+
it('fences effective operator routing across environment changes', () => {
const variable = 'LC_SCHEDULE_CONSENT_ROUTE_FIXTURE';
const previous = process.env[variable];
diff --git a/packages/api/src/schedules/authorization/configuration.ts b/packages/api/src/schedules/authorization/configuration.ts
index cc6474d1c7..109b41ce53 100644
--- a/packages/api/src/schedules/authorization/configuration.ts
+++ b/packages/api/src/schedules/authorization/configuration.ts
@@ -43,7 +43,11 @@ function hasRoutingTemplate(headers?: Record<string, string>): boolean {
});
}
-/** Binds effective routing and trust without retaining tokens or rotating client/API secrets. */
+/**
+ * Binds effective routing and trust without retaining tokens or rotating client/API secrets, nor
+ * the masked previews the admin config API stores beside them (`keyPreview`,
+ * `client_secretPreview`), which change whenever an admin rotates the secret in place.
+ */
export function getScheduledMCPConfigurationRevision(
config: ParsedServerConfig,
binding: ScheduledMCPResourceBinding,
@@ -59,10 +63,14 @@ export function getScheduledMCPConfigurationRevision(
requestHeaders: config.requestHeaders,
proxy: config.proxy,
requiresOAuth: config.requiresOAuth,
- oauth: config.oauth && { ...config.oauth, client_secret: undefined },
+ oauth: config.oauth && {
+ ...config.oauth,
+ client_secret: undefined,
+ client_secretPreview: undefined,
+ },
oauth_headers: config.oauth_headers,
obo: config.obo,
- apiKey: config.apiKey && { ...config.apiKey, key: undefined },
+ apiKey: config.apiKey && { ...config.apiKey, key: undefined, keyPreview: undefined },
};
const runtime = processMCPEnv({ options: declared });
if (runtime.type !== 'sse' && runtime.type !== 'http' && runtime.type !== 'streamable-http')
diff --git a/packages/api/src/utils/env.ts b/packages/api/src/utils/env.ts
index a58d6949bd..950d578c14 100644
--- a/packages/api/src/utils/env.ts
+++ b/packages/api/src/utils/env.ts
@@ -5,6 +5,7 @@ import type { IUser } from '@librechat/data-schemas';
import type { RequestBody } from '~/types';
import {
OPENID_TOKEN_FIELDS,
+ OPENID_CREDENTIAL_PLACEHOLDER_PATTERN,
isOpenIDTokenValid,
extractOpenIDTokenInfo,
processOpenIDPlaceholders,
@@ -170,17 +171,6 @@ const RESOLVABLE_PLACEHOLDER_PATTERN = new RegExp(
'g',
);
-/**
- * The subset of OpenID placeholders that cannot resolve without a usable token
- * set. Identity metadata (`USER_ID`, `USER_EMAIL`, `USER_NAME`) comes from the
- * user document and `EXPIRES_AT` is only ever a hint, so those must keep their
- * pre-existing literal-then-strip behaviour when the token set is invalid
- * rather than raising re-auth. Non-global so `exec` stays stateless, and
- * unknown names are excluded so a typo stays literal and diagnosable.
- */
-const OPENID_CREDENTIAL_PLACEHOLDER_PATTERN =
- /\{\{LIBRECHAT_OPENID_(?:ACCESS_TOKEN|ID_TOKEN|TOKEN)\}\}/;
-
/**
* The credential placeholders that specifically need a usable *access* token, which is all
* `isOpenIDTokenValid` reports on. `ID_TOKEN` is absent because `processOpenIDPlaceholders`
diff --git a/packages/api/src/utils/oidc.ts b/packages/api/src/utils/oidc.ts
index 04b19f752f..a6822825c6 100644
--- a/packages/api/src/utils/oidc.ts
+++ b/packages/api/src/utils/oidc.ts
@@ -38,6 +38,27 @@ export type OpenIDTokenField = (typeof OPENID_TOKEN_FIELDS)[number];
*/
export const GRAPH_TOKEN_PLACEHOLDER = '{{LIBRECHAT_GRAPH_ACCESS_TOKEN}}';
+/**
+ * The subset of OpenID placeholders that cannot resolve without a usable token
+ * set. Identity metadata (`USER_ID`, `USER_EMAIL`, `USER_NAME`) comes from the
+ * user document and `EXPIRES_AT` is only ever a hint, so those must keep their
+ * pre-existing literal-then-strip behaviour when the token set is invalid
+ * rather than raising re-auth. Non-global so `exec` stays stateless, and
+ * unknown names are excluded so a typo stays literal and diagnosable.
+ */
+export const OPENID_CREDENTIAL_PLACEHOLDER_PATTERN: RegExp =
+ /\{\{LIBRECHAT_OPENID_(?:ACCESS_TOKEN|ID_TOKEN|TOKEN)\}\}/;
+
+/**
+ * Whether a value names a credential LibreChat fills in for each user: an OpenID token, or the
+ * Microsoft Graph token the OBO flow obtains. Identity and request placeholders are not.
+ */
+export function hasUserCredentialPlaceholder(value: string): boolean {
+ return (
+ OPENID_CREDENTIAL_PLACEHOLDER_PATTERN.test(value) || value.includes(GRAPH_TOKEN_PLACEHOLDER)
+ );
+}
+
/**
* Default Microsoft Graph API scopes for OBO token exchange.
* Can be overridden via GRAPH_API_SCOPES environment variable.
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 5921139122..cbf47e0daa 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -713,6 +713,13 @@ export const azureGroupSchema = z
models: z.record(z.string(), modelConfigSchema),
})
.required()
+ .extend({
+ /**
+ * Masked preview of the group's `apiKey`, set by the admin config API when it stores the key
+ * encrypted. Read-only: writes to it are rejected.
+ */
+ apiKeyPreview: z.string().optional(),
+ })
.and(azureBaseSchema);
export const azureGroupConfigsSchema = z.array(azureGroupSchema).min(1);
diff --git a/packages/data-provider/src/mcp.ts b/packages/data-provider/src/mcp.ts
index 01c09d730a..0e2f6aa1b9 100644
--- a/packages/data-provider/src/mcp.ts
+++ b/packages/data-provider/src/mcp.ts
@@ -55,6 +55,11 @@ const OAuthOptionsBaseSchema = z.object({
client_id: z.string().optional(),
/** OAuth client secret (requires explicit authorization and token endpoints) */
client_secret: z.string().optional(),
+ /**
+ * Masked preview of `client_secret`, set by the admin config API when it stores the secret
+ * encrypted. Read-only: writes to it are rejected, and it never reaches end users.
+ */
+ client_secretPreview: z.string().optional(),
/** OAuth scopes to request */
scope: z.string().optional(),
/** OAuth redirect URI (defaults to /api/mcp/{serverName}/oauth/callback) */
@@ -170,6 +175,7 @@ const UserOAuthOptionsSchema = OAuthOptionsBaseSchema.omit({
audience: true,
forward_audience_on_refresh: true,
send_resource_parameter: true,
+ client_secretPreview: true,
})
.extend({
authorization_url: userOAuthEndpointUrlSchema.optional(),
@@ -334,6 +340,11 @@ const BaseOptionsSchema = z.object({
.object({
/** API key value (only for admin-provided mode, stored encrypted) */
key: z.string().optional(),
+ /**
+ * Masked preview of `key`, set by the admin config API when it stores the key encrypted.
+ * Read-only: writes to it are rejected, and it never reaches end users.
+ */
+ keyPreview: z.string().optional(),
/** Whether key is provided by admin or each user */
source: z.enum(['admin', 'user']),
/** How to format the authorization header */
diff --git a/packages/data-schemas/src/app/azure.ts b/packages/data-schemas/src/app/azure.ts
index 35d855ba43..7dd2d15c5f 100644
--- a/packages/data-schemas/src/app/azure.ts
+++ b/packages/data-schemas/src/app/azure.ts
@@ -1,10 +1,164 @@
-import logger from '~/config/winston';
import {
EModelEndpoint,
validateAzureGroups,
mapModelToAzureConfig,
} from 'librechat-data-provider';
-import type { TCustomConfig, TAzureConfig } from 'librechat-data-provider';
+import type {
+ TAzureConfig,
+ TCustomConfig,
+ TValidatedAzureConfig,
+ TAzureConfigValidationResult,
+} from 'librechat-data-provider';
+import logger from '~/config/winston';
+
+/** What Azure `groups` resolve to: the fields the Azure clients read instead of the groups. */
+export type ResolvedAzureGroups = TAzureConfigValidationResult & {
+ assistantModels: string[];
+ assistantGroups: string[];
+};
+
+/** A field of the resolved Azure config that its `groups` decide. */
+export type AzureResolvedGroupField =
+ | 'groupMap'
+ | 'modelGroupMap'
+ | 'modelNames'
+ | 'assistantModels'
+ | 'assistantGroups';
+
+/**
+ * The fields of the resolved Azure config that its `groups` decide, which the Azure clients,
+ * model lists and assistants read. A config override's `groups` resolve to them as
+ * librechat.yaml's do ({@link resolveAzureGroups}).
+ */
+export const AZURE_RESOLVED_GROUP_FIELDS: readonly AzureResolvedGroupField[] = [
+ 'groupMap',
+ 'modelGroupMap',
+ 'modelNames',
+ 'assistantModels',
+ 'assistantGroups',
+];
+
+/**
+ * Whether an Azure config turns `assistants` on without a model that supports them, which
+ * `azureConfigSetup` refuses: the Azure Assistants client would have no model to default to.
+ */
+export function lacksAzureAssistantModels(config: {
+ assistants?: unknown;
+ assistantModels?: unknown;
+}): boolean {
+ const { assistants, assistantModels } = config;
+ return Boolean(assistants) && !(Array.isArray(assistantModels) && assistantModels.length > 0);
+}
+
+/** The maps of a resolved Azure config that say which group serves a model. */
+type AzureModelMaps = Partial<Pick<TValidatedAzureConfig, 'groupMap' | 'modelGroupMap'>>;
+
+/**
+ * The name of the group that serves `modelName`: the one `modelGroupMap` maps it to, when
+ * `groupMap` holds that group and the group lists the model. Values an override wrote in any
+ * shape are read defensively.
+ */
+function getServingGroupName(maps: AzureModelMaps, modelName: unknown): string | undefined {
+ if (typeof modelName !== 'string' || maps.modelGroupMap == null) {
+ return undefined;
+ }
+ const groupName = maps.modelGroupMap[modelName]?.group;
+ const group = typeof groupName === 'string' ? maps.groupMap?.[groupName] : undefined;
+ const models = group?.models;
+ return models != null &&
+ typeof models === 'object' &&
+ Object.prototype.hasOwnProperty.call(models, modelName)
+ ? groupName
+ : undefined;
+}
+
+/**
+ * Whether the group `modelGroupMap` maps `modelName` to serves it with assistants, as
+ * `azureConfigSetup` has always judged it: the group's `assistants`, or an `assistants` flag on
+ * an entry the group holds under the model's name.
+ */
+function supportsAzureAssistants(maps: AzureModelMaps, modelName: string): boolean {
+ const groupName = maps.modelGroupMap?.[modelName]?.group;
+ const group = groupName != null ? maps.groupMap?.[groupName] : undefined;
+ if (group == null) {
+ return false;
+ }
+ if (group.assistants) {
+ return true;
+ }
+ const named: unknown = Object.getOwnPropertyDescriptor(group, modelName)?.value;
+ return (
+ named != null && typeof named === 'object' && 'assistants' in named && Boolean(named.assistants)
+ );
+}
+
+/**
+ * Resolves Azure `groups` into the maps the Azure clients read (`groupMap`, `modelGroupMap`), the
+ * models they serve and the assistants among them. The groups are validated here, so any value
+ * is accepted: a malformed list, or a structural problem (a duplicate group or model, a group
+ * without an instance, a serverless one without a base URL), is reported in `errors` with
+ * `isValid: false`. The per-model settings each request resolves are not checked.
+ */
+export function resolveAzureGroups(groups: unknown): ResolvedAzureGroups {
+ const validation = validateAzureGroups(groups);
+ const { isValid, modelNames, modelGroupMap } = validation;
+ const assistantModels: string[] = [];
+ const assistantGroups = new Set<string>();
+ for (const modelName of isValid ? modelNames : []) {
+ const groupName = modelGroupMap[modelName]?.group;
+ if (groupName != null && supportsAzureAssistants(validation, modelName)) {
+ assistantModels.push(modelName);
+ assistantGroups.add(groupName);
+ }
+ }
+ return { ...validation, assistantModels, assistantGroups: Array.from(assistantGroups) };
+}
+
+/** The lists of a resolved Azure config that name models or groups its maps must serve. */
+type AzureServedList = Extract<
+ AzureResolvedGroupField,
+ 'modelNames' | 'assistantModels' | 'assistantGroups'
+>;
+
+/** A resolved Azure config as the served lists are judged on. */
+type AzureServedConfig = AzureModelMaps & Partial<Pick<TValidatedAzureConfig, AzureServedList>>;
+
+/**
+ * A resolved Azure config whose lists name only what its maps serve: `modelNames` the models
+ * `modelGroupMap` maps to a `groupMap` group that lists them, `assistantModels` those among them
+ * that support assistants, and `assistantGroups` the groups serving those. Groups resolve to
+ * consistent lists on their own (`resolveAzureGroups`); a list a config override writes
+ * directly, or one whose maps a later override replaced or removed, can name a model no group
+ * serves, which the Azure clients cannot map (`mapModelToAzureConfig`) and the Azure Assistants
+ * client would default to. `narrowed` names the lists that changed; `config` is returned itself
+ * when none did.
+ */
+export function narrowAzureServedModels<T extends AzureServedConfig>(
+ config: T,
+): { config: T; narrowed: AzureServedList[] } {
+ const next: T = { ...config };
+ const narrowed: AzureServedList[] = [];
+ const narrow = (field: AzureServedList, keep: (value: unknown) => boolean) => {
+ const list: unknown = config[field];
+ if (list === undefined) {
+ return;
+ }
+ const kept = Array.isArray(list) ? list.filter(keep) : [];
+ if (Array.isArray(list) && kept.length === list.length) {
+ return;
+ }
+ next[field] = kept;
+ narrowed.push(field);
+ };
+ const isServed = (model: unknown): model is string => getServingGroupName(config, model) != null;
+ narrow('modelNames', isServed);
+ narrow('assistantModels', (model) => isServed(model) && supportsAzureAssistants(config, model));
+ const assistantGroups = new Set(
+ (next.assistantModels ?? []).map((model) => getServingGroupName(config, model)),
+ );
+ narrow('assistantGroups', (group) => typeof group === 'string' && assistantGroups.has(group));
+ return { config: narrowed.length === 0 ? config : next, narrowed };
+}
/**
* Sets up the Azure OpenAI configuration from the config (`librechat.yaml`) file.
@@ -17,7 +171,8 @@ export function azureConfigSetup(config: Partial<TCustomConfig>): TAzureConfig {
throw new Error('Azure OpenAI configuration is missing.');
}
const { groups, ...azureConfiguration } = azureConfig;
- const { isValid, modelNames, modelGroupMap, groupMap, errors } = validateAzureGroups(groups);
+ const resolved = resolveAzureGroups(groups);
+ const { isValid, modelNames, modelGroupMap, groupMap, errors } = resolved;
if (!isValid) {
const errorString = errors.join('\n');
@@ -26,22 +181,16 @@ export function azureConfigSetup(config: Partial<TCustomConfig>): TAzureConfig {
throw new Error(errorMessage);
}
- const assistantModels: string[] = [];
- const assistantGroups = new Set<string>();
for (const modelName of modelNames) {
mapModelToAzureConfig({ modelName, modelGroupMap, groupMap });
- const groupName = modelGroupMap?.[modelName]?.group;
- const modelGroup = groupMap?.[groupName];
- const supportsAssistants = modelGroup?.assistants || modelGroup?.[modelName]?.assistants;
- if (supportsAssistants) {
- assistantModels.push(modelName);
- if (!assistantGroups.has(groupName)) {
- assistantGroups.add(groupName);
- }
- }
}
- if (azureConfiguration.assistants && assistantModels.length === 0) {
+ if (
+ lacksAzureAssistantModels({
+ assistants: azureConfiguration.assistants,
+ assistantModels: resolved.assistantModels,
+ })
+ ) {
throw new Error(
'No Azure models are configured to support assistants. Please remove the `assistants` field or configure at least one model to support assistants.',
);
@@ -64,8 +213,8 @@ export function azureConfigSetup(config: Partial<TCustomConfig>): TAzureConfig {
groupMap,
modelNames,
modelGroupMap,
- assistantModels,
- assistantGroups: Array.from(assistantGroups),
+ assistantModels: resolved.assistantModels,
+ assistantGroups: resolved.assistantGroups,
...azureConfiguration,
};
}
diff --git a/packages/data-schemas/src/app/changes.spec.ts b/packages/data-schemas/src/app/changes.spec.ts
index b422500cdc..5d40414cff 100644
--- a/packages/data-schemas/src/app/changes.spec.ts
+++ b/packages/data-schemas/src/app/changes.spec.ts
@@ -5,6 +5,9 @@ import {
isConfigEntryError,
applyConfigChanges,
isSameConfigValue,
+ toConfigIdentityPath,
+ renameConfigIdentityPath,
+ resolveConfigIdentityPath,
getConfigBatchWrittenPaths,
getConfigChangeWrittenPaths,
} from './changes';
@@ -643,6 +646,55 @@ describe('getConfigBatchWrittenPaths', () => {
});
});
+describe('config identity paths', () => {
+ const doc = {
+ endpoints: { custom: [{ name: 'Good' }, { name: 'Ollama', headers: { K: 'v' } }, { x: 1 }] },
+ mcpServers: { draft: { url: 'u' } },
+ };
+
+ it('names an entry of a merged-by-key array by its key, anything else by segment', () => {
+ expect(toConfigIdentityPath(doc, ['endpoints', 'custom', '1', 'headers', 'K'])).toEqual([
+ 'endpoints',
+ 'custom',
+ { entry: 'Ollama' },
+ 'headers',
+ 'K',
+ ]);
+ expect(toConfigIdentityPath(doc, ['endpoints', 'custom', '2', 'x'])).toEqual(
+ at('endpoints.custom.2.x'),
+ );
+ });
+
+ it('finds an entry where another document holds it, under a folded spelling too', () => {
+ const path = toConfigIdentityPath(doc, ['endpoints', 'custom', '1', 'headers', 'K']);
+
+ expect(
+ resolveConfigIdentityPath({ endpoints: { custom: [{ name: 'ollama' }] } }, path),
+ ).toEqual(at('endpoints.custom.0.headers.K'));
+ expect(resolveConfigIdentityPath({ endpoints: { custom: [{ name: 'Good' }] } }, path)).toBe(
+ null,
+ );
+ });
+
+ it('follows a rename of the record key or entry the path passes through, and nothing else', () => {
+ const server = toConfigIdentityPath(doc, at('mcpServers.draft.url'));
+ const entry = toConfigIdentityPath(doc, at('endpoints.custom.1.headers.K'));
+
+ expect(renameConfigIdentityPath(server, ['mcpServers'], 'draft', 'tools')).toEqual(
+ at('mcpServers.tools.url'),
+ );
+ expect(renameConfigIdentityPath(server, ['mcpServers'], 'other', 'tools')).toEqual(server);
+ expect(renameConfigIdentityPath(entry, CUSTOM, 'OLLAMA', 'Renamed')).toEqual([
+ ...CUSTOM,
+ { entry: 'Renamed' },
+ 'headers',
+ 'K',
+ ]);
+ expect(renameConfigIdentityPath(entry, CUSTOM, 'Good', 'x')).toEqual(entry);
+ expect(renameConfigIdentityPath(entry, ['mcpServers'], 'Ollama', 'x')).toEqual(entry);
+ });
+});
+
describe('isSameConfigValue', () => {
it('compares JSON structurally, ignoring object key order but not array order', () => {
expect(isSameConfigValue({ a: 1, b: [1, { c: 2 }] }, { b: [1, { c: 2 }], a: 1 })).toBe(true);
diff --git a/packages/data-schemas/src/app/changes.ts b/packages/data-schemas/src/app/changes.ts
index e7d2575680..0f22a82f06 100644
--- a/packages/data-schemas/src/app/changes.ts
+++ b/packages/data-schemas/src/app/changes.ts
@@ -407,6 +407,88 @@ export function applyConfigChanges(
return { state: current, changed };
}
+/**
+ * A step of a location named by identity rather than position: a key (or a position in an array
+ * that is not merged by key), or an entry of a merged-by-key array by its merge key.
+ */
+export type ConfigIdentityStep = string | { readonly entry: string };
+
+/**
+ * `segments` as `root` holds them, by identity: a position in a merged-by-key array becomes the
+ * key of the entry there, so the location still names that entry once other entries come and go.
+ * A position whose item has no key stays a position.
+ */
+export function toConfigIdentityPath(
+ root: unknown,
+ segments: ConfigPathSegments,
+): ConfigIdentityStep[] {
+ return segments.map((segment, index): ConfigIdentityStep => {
+ const parent = segments.slice(0, index);
+ const keyField = getConfigArrayMergeKey(parent);
+ const items = keyField ? getAtPath(root, parent) : undefined;
+ const key =
+ keyField && Array.isArray(items)
+ ? getConfigEntryKey(items[Number(segment)], keyField)
+ : undefined;
+ return key !== undefined ? { entry: key } : segment;
+ });
+}
+
+/**
+ * Where an identity path ({@link toConfigIdentityPath}) is in `root`: each entry of a
+ * merged-by-key array by its position there. `null` when an entry it passes through is gone.
+ */
+export function resolveConfigIdentityPath(
+ root: unknown,
+ path: readonly ConfigIdentityStep[],
+): string[] | null {
+ const segments: string[] = [];
+ for (const step of path) {
+ if (typeof step === 'string') {
+ segments.push(step);
+ continue;
+ }
+ const keyField = getConfigArrayMergeKey(segments);
+ const items = getAtPath(root, segments);
+ const index =
+ keyField && Array.isArray(items)
+ ? items.findIndex(getConfigEntryMatcher(segments, keyField, step.entry))
+ : -1;
+ if (index === -1) {
+ return null;
+ }
+ segments.push(String(index));
+ }
+ return segments;
+}
+
+/**
+ * An identity path once a `rename` of the collection at `collection` has moved the record key, or
+ * renamed the merged-by-key entry, the path passes through from `from` to `to`.
+ */
+export function renameConfigIdentityPath(
+ path: readonly ConfigIdentityStep[],
+ collection: ConfigPathSegments,
+ from: string,
+ to: string,
+): ConfigIdentityStep[] {
+ const step = path[collection.length];
+ if (step === undefined || !collection.every((segment, index) => path[index] === segment)) {
+ return [...path];
+ }
+ const keyed = getConfigArrayMergeKey(collection) !== undefined;
+ const renamed = keyed
+ ? typeof step !== 'string' &&
+ getConfigEntryIdentity(collection, step.entry) === getConfigEntryIdentity(collection, from)
+ : step === from;
+ if (!renamed) {
+ return [...path];
+ }
+ const next = [...path];
+ next[collection.length] = keyed ? { entry: to } : to;
+ return next;
+}
+
/**
* The paths a change writes, for attributing validation issues to it: the path itself, or for
* an entry change, the entry by its index in `result`'s own array. A removed entry is gone, so
diff --git a/packages/data-schemas/src/app/index.ts b/packages/data-schemas/src/app/index.ts
index 6306eb188b..c13ed9efd2 100644
--- a/packages/data-schemas/src/app/index.ts
+++ b/packages/data-schemas/src/app/index.ts
@@ -1,6 +1,8 @@
export * from './agents';
+export * from './azure';
export * from './interface';
export * from './memory';
+export * from './ocr';
export * from './service';
export * from './specs';
export * from './turnstile';
diff --git a/packages/data-schemas/src/app/ocr.spec.ts b/packages/data-schemas/src/app/ocr.spec.ts
index 7c4cccaeb3..8130fdfae1 100644
--- a/packages/data-schemas/src/app/ocr.spec.ts
+++ b/packages/data-schemas/src/app/ocr.spec.ts
@@ -24,4 +24,25 @@ describe('loadOCRConfig', () => {
});
expect(loaded?.allowedAddresses).toBeUndefined();
});
+
+ it('spells out the default OCR_API_KEY reference when librechat.yaml sets no key', () => {
+ for (const apiKey of [undefined, '', ' ']) {
+ const loaded = loadOCRConfig({
+ apiKey,
+ baseURL: 'https://ocr.internal/v1',
+ strategy: OCRStrategy.MISTRAL_OCR,
+ } as Parameters<typeof loadOCRConfig>[0]);
+ expect(loaded?.apiKey).toBe('${OCR_API_KEY}');
+ expect(loaded?.baseURL).toBe('https://ocr.internal/v1');
+ }
+ });
+
+ it('keeps a key librechat.yaml sets', () => {
+ const loaded = loadOCRConfig({
+ apiKey: '${AZURE_OCR_KEY}',
+ strategy: OCRStrategy.AZURE_MISTRAL_OCR,
+ } as Parameters<typeof loadOCRConfig>[0]);
+ expect(loaded?.apiKey).toBe('${AZURE_OCR_KEY}');
+ expect(loaded?.baseURL).toBe('');
+ });
});
diff --git a/packages/data-schemas/src/app/ocr.ts b/packages/data-schemas/src/app/ocr.ts
index b60719d675..7d5f99cb5e 100644
--- a/packages/data-schemas/src/app/ocr.ts
+++ b/packages/data-schemas/src/app/ocr.ts
@@ -1,10 +1,18 @@
import { OCRStrategy } from 'librechat-data-provider';
import type { TCustomConfig } from 'librechat-data-provider';
+/**
+ * The key OCR uses when librechat.yaml sets none. Spelled out as a reference so it stays bound to
+ * the YAML's own base URL: the OCR runtime fills an empty key from `OCR_API_KEY` only while the
+ * base URL is the deployment's default, so a config override that points OCR elsewhere never
+ * inherits it implicitly.
+ */
+const DEFAULT_OCR_API_KEY = '${OCR_API_KEY}';
+
export function loadOCRConfig(config?: TCustomConfig['ocr']): TCustomConfig['ocr'] | undefined {
if (!config) return;
const baseURL = config?.baseURL ?? '';
- const apiKey = config?.apiKey ?? '';
+ const apiKey = config?.apiKey?.trim() ? config.apiKey : DEFAULT_OCR_API_KEY;
const mistralModel = config?.mistralModel ?? '';
return {
apiKey,
diff --git a/packages/data-schemas/src/app/resolution.spec.ts b/packages/data-schemas/src/app/resolution.spec.ts
index 5a8e991283..74e783b2e3 100644
--- a/packages/data-schemas/src/app/resolution.spec.ts
+++ b/packages/data-schemas/src/app/resolution.spec.ts
@@ -2447,6 +2447,438 @@ describe('getConfigFieldIssues', () => {
});
});
+describe('mergeConfigOverrides: afterLayer', () => {
+ const base = {
+ config: { ocr: { baseURL: 'https://yaml.example' } },
+ ocr: { baseURL: 'https://yaml.example', mistralModel: 'base' },
+ mcpConfig: { tools: { url: 'https://tools.example/mcp' } },
+ } as unknown as AppConfig;
+
+ it('sees each layer in precedence order: what it inherited, contributed and produced', () => {
+ const steps: Array<{ principalId: string; below: unknown; applied: unknown; merged: unknown }> =
+ [];
+ mergeConfigOverrides(
+ base,
+ [
+ fakeConfig({ ocr: { mistralModel: 'role' } }, 20, undefined, 'role'),
+ fakeConfig({ mcpServers: { tools: { title: 'Tools' } } }, 0, undefined, 'base'),
+ ],
+ {
+ afterLayer: ({ layer, below, applied, merged }) => {
+ steps.push({
+ principalId: layer.principalId.toString(),
+ below: below.ocr,
+ applied,
+ merged: merged.ocr,
+ });
+ return merged;
+ },
+ },
+ );
+
+ expect(steps).toEqual([
+ {
+ principalId: 'base',
+ below: base.ocr,
+ /** Under the AppConfig section name the merge applies it to. */
+ applied: { mcpConfig: { tools: { title: 'Tools' } } },
+ merged: base.ocr,
+ },
+ {
+ principalId: 'role',
+ below: base.ocr,
+ applied: { ocr: { mistralModel: 'role' } },
+ merged: { baseURL: 'https://yaml.example', mistralModel: 'role' },
+ },
+ ]);
+ });
+
+ it('merges the next layer onto the config the hook returns', () => {
+ const merged = mergeConfigOverrides(
+ base,
+ [
+ fakeConfig({ ocr: { mistralModel: 'low' } }, 10, undefined, 'low'),
+ fakeConfig({ ocr: { strategy: 'mistral_ocr' } }, 20, undefined, 'high'),
+ ],
+ {
+ afterLayer: ({ layer, merged: next }) =>
+ layer.principalId.toString() === 'low'
+ ? ({ ...next, ocr: { ...next.ocr, baseURL: '' } } as AppConfig)
+ : next,
+ },
+ );
+
+ expect(merged.ocr).toEqual({ baseURL: '', mistralModel: 'low', strategy: 'mistral_ocr' });
+ });
+
+ it('shows each layer alone over the base config, after its own tombstones only', () => {
+ const alone: Record<string, unknown> = {};
+ let calls = 0;
+ mergeConfigOverrides(
+ base,
+ [
+ fakeConfig({ ocr: { mistralModel: 'low' } }, 10, ['ocr.mistralModel'], 'low'),
+ fakeConfig(
+ { ocr: { apiKey: 'own' }, mcpServers: { tools: { title: 'Tools' } } },
+ 20,
+ ['ocr.baseURL'],
+ 'high',
+ ),
+ ],
+ {
+ afterLayer: (step) => {
+ if (step.layer.principalId.toString() === 'high') {
+ calls++;
+ const first = step.alone();
+ expect(step.alone()).toBe(first);
+ alone.ocr = first.ocr;
+ alone.mcpConfig = first.mcpConfig;
+ }
+ return step.merged;
+ },
+ },
+ );
+
+ expect(calls).toBe(1);
+ /** Not the lower layer's model, and without the base URL this layer tombstones. */
+ expect(alone.ocr).toEqual({ mistralModel: 'base', apiKey: 'own' });
+ expect(alone.mcpConfig).toEqual({
+ tools: { url: 'https://tools.example/mcp', title: 'Tools' },
+ });
+ expect(base.ocr).toEqual({ baseURL: 'https://yaml.example', mistralModel: 'base' });
+ });
+
+ it('shows every layer the base config the merge started from', () => {
+ const bases: unknown[] = [];
+ mergeConfigOverrides(
+ base,
+ [
+ fakeConfig({ ocr: { mistralModel: 'low' } }, 10, undefined, 'low'),
+ fakeConfig({ ocr: { mistralModel: 'high' } }, 20, undefined, 'high'),
+ ],
+ {
+ afterLayer: (step) => {
+ bases.push(step.base);
+ return step.merged;
+ },
+ },
+ );
+
+ expect(bases).toEqual([base, base]);
+ expect(bases[1]).toBe(base);
+ });
+
+ it('runs for a layer that only tombstones, with nothing applied', () => {
+ const applied: unknown[] = [];
+ const merged = mergeConfigOverrides(base, [fakeConfig({}, 10, ['ocr.baseURL'])], {
+ afterLayer: (step) => {
+ applied.push(step.applied);
+ return step.merged;
+ },
+ });
+
+ expect(applied).toEqual([{}]);
+ expect(merged.ocr).toEqual({ mistralModel: 'base' });
+ });
+});
+
+describe('mergeConfigOverrides: Azure groups an override writes', () => {
+ const yamlGroup = {
+ group: 'east',
+ apiKey: '${AZURE_EAST_KEY}',
+ instanceName: 'east',
+ version: '2024-10-21',
+ deploymentName: 'gpt-4o',
+ models: { 'gpt-4o': true },
+ };
+ const base = {
+ config: { endpoints: { azureOpenAI: { groups: [yamlGroup] } } },
+ endpoints: {
+ azureOpenAI: {
+ titleModel: 'gpt-4o',
+ groupMap: { east: { ...yamlGroup } },
+ modelGroupMap: { 'gpt-4o': { group: 'east' } },
+ modelNames: ['gpt-4o'],
+ assistantModels: [],
+ assistantGroups: [],
+ },
+ },
+ } as unknown as AppConfig;
+ const west = {
+ group: 'west',
+ apiKey: 'v3:stored-west-key',
+ instanceName: 'west',
+ version: '2024-10-21',
+ deploymentName: 'gpt-5',
+ assistants: true,
+ models: { 'gpt-5': true, 'o3-mini': { deploymentName: 'o3' } },
+ };
+
+ it('resolves them into the fields the Azure clients read, replacing what lay below', () => {
+ const merged = mergeConfigOverrides(base, [
+ fakeConfig({ endpoints: { azureOpenAI: { groups: [west] } } }, 10),
+ ]);
+
+ const azure = merged.endpoints?.azureOpenAI;
+ expect(azure?.groupMap).toEqual({
+ west: expect.objectContaining({ apiKey: 'v3:stored-west-key', instanceName: 'west' }),
+ });
+ expect(azure?.modelGroupMap).toEqual({
+ 'gpt-5': { group: 'west' },
+ 'o3-mini': { group: 'west' },
+ });
+ expect(azure?.modelNames).toEqual(['gpt-5', 'o3-mini']);
+ expect(azure?.assistantModels).toEqual(['gpt-5', 'o3-mini']);
+ expect(azure?.assistantGroups).toEqual(['west']);
+ expect(azure?.titleModel).toBe('gpt-4o');
+ expect(base.endpoints?.azureOpenAI?.modelNames).toEqual(['gpt-4o']);
+ });
+
+ it("merges a groupMap the same layer writes over its own groups', and a later layer's over them", () => {
+ const merged = mergeConfigOverrides(base, [
+ fakeConfig(
+ { endpoints: { azureOpenAI: { groups: [west], groupMap: { west: { version: 'v2' } } } } },
+ 10,
+ ),
+ fakeConfig({ endpoints: { azureOpenAI: { groupMap: { west: { baseURL: 'b' } } } } }, 20),
+ ]);
+
+ expect(merged.endpoints?.azureOpenAI?.groupMap?.west).toMatchObject({
+ apiKey: 'v3:stored-west-key',
+ version: 'v2',
+ baseURL: 'b',
+ });
+ });
+
+ it("shows the layer alone with its groups in place of librechat.yaml's", () => {
+ let aloneGroups: unknown;
+ mergeConfigOverrides(
+ base,
+ [fakeConfig({ endpoints: { azureOpenAI: { groups: [west] } } }, 10)],
+ {
+ afterLayer: (step) => {
+ aloneGroups = Object.keys(step.alone().endpoints?.azureOpenAI?.groupMap ?? {});
+ return step.merged;
+ },
+ },
+ );
+
+ expect(aloneGroups).toEqual(['west']);
+ });
+
+ describe('a tombstone of the groups', () => {
+ const tombstone = (priority = 10) =>
+ fakeConfig({}, priority, ['endpoints.azureOpenAI.groups'], `t${priority}`);
+
+ it('resolves the groups to none, so no Azure model or group is served', () => {
+ const merged = mergeConfigOverrides(base, [tombstone()]);
+
+ expect(merged.endpoints?.azureOpenAI).toEqual({
+ titleModel: 'gpt-4o',
+ groupMap: {},
+ modelGroupMap: {},
+ modelNames: [],
+ assistantModels: [],
+ assistantGroups: [],
+ });
+ expect(base.endpoints?.azureOpenAI?.groupMap).toHaveProperty('east');
+ });
+
+ it('creates no Azure endpoint where none is configured', () => {
+ const merged = mergeConfigOverrides({ config: {}, endpoints: {} } as AppConfig, [
+ tombstone(),
+ ]);
+
+ expect(merged.endpoints).toEqual({});
+ });
+
+ it("lets the same layer's groups, or a later layer's, resolve in their place", () => {
+ const same = mergeConfigOverrides(base, [
+ fakeConfig({ endpoints: { azureOpenAI: { groups: [west] } } }, 10, [
+ 'endpoints.azureOpenAI.groups',
+ ]),
+ ]);
+ const later = mergeConfigOverrides(base, [
+ tombstone(10),
+ fakeConfig({ endpoints: { azureOpenAI: { groups: [west] } } }, 20),
+ ]);
+
+ for (const merged of [same, later]) {
+ expect(Object.keys(merged.endpoints?.azureOpenAI?.groupMap ?? {})).toEqual(['west']);
+ expect(merged.endpoints?.azureOpenAI?.modelNames).toEqual(['gpt-5', 'o3-mini']);
+ }
+ });
+
+ it('shows the layer alone without the groups, and removes them from the YAML floor', () => {
+ let alone: unknown;
+ mergeConfigOverrides(base, [tombstone()], {
+ afterLayer: (step) => {
+ alone = step.alone().endpoints?.azureOpenAI;
+ return step.merged;
+ },
+ });
+
+ expect(alone).toEqual({ titleModel: 'gpt-4o' });
+ expect(
+ applyConfigTombstones(
+ {
+ endpoints: { azureOpenAI: { groups: [yamlGroup], groupMap: { east: yamlGroup } } },
+ } as Partial<TCustomConfig>,
+ ['endpoints.azureOpenAI.groups'],
+ ),
+ ).toEqual({ endpoints: { azureOpenAI: {} } });
+ });
+ });
+
+ it('leaves groups that do not resolve unread, with a warning', () => {
+ const warn = jest.spyOn(logger, 'warn').mockImplementation(() => logger);
+ const merged = mergeConfigOverrides(base, [
+ fakeConfig({ endpoints: { azureOpenAI: { groups: [west, { ...west, group: 'w2' }] } } }, 10),
+ ]);
+
+ expect(merged.endpoints?.azureOpenAI?.groupMap).toEqual(base.endpoints?.azureOpenAI?.groupMap);
+ expect(merged.endpoints?.azureOpenAI?.modelNames).toEqual(['gpt-4o']);
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('endpoints.azureOpenAI.groups'));
+ warn.mockRestore();
+ });
+
+ describe('with Azure assistants on', () => {
+ /** As AppService resolves librechat.yaml's `assistants: true` over a group that serves them. */
+ const assistantsBase = {
+ ...base,
+ endpoints: {
+ azureOpenAI: {
+ ...base.endpoints?.azureOpenAI,
+ groupMap: { east: { ...yamlGroup, assistants: true } },
+ assistants: true,
+ assistantModels: ['gpt-4o'],
+ assistantGroups: ['east'],
+ },
+ },
+ } as unknown as AppConfig;
+ const plain = {
+ group: 'plain',
+ apiKey: 'v3:stored-plain-key',
+ instanceName: 'plain',
+ version: '2024-10-21',
+ deploymentName: 'gpt-5-mini',
+ models: { 'gpt-5-mini': true },
+ };
+
+ it('turns them off for groups none of whose models supports them, with a warning', () => {
+ const warn = jest.spyOn(logger, 'warn').mockImplementation(() => logger);
+ const merged = mergeConfigOverrides(assistantsBase, [
+ fakeConfig({ endpoints: { azureOpenAI: { groups: [plain] } } }, 10),
+ ]);
+
+ const azure = merged.endpoints?.azureOpenAI;
+ expect(azure?.modelNames).toEqual(['gpt-5-mini']);
+ expect(azure?.assistantModels).toEqual([]);
+ expect(azure?.assistants).toBe(false);
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('Turning off endpoints.azureOpenAI.assistants for role/'),
+ );
+ expect(assistantsBase.endpoints?.azureOpenAI?.assistants).toBe(true);
+ warn.mockRestore();
+ });
+
+ it("keeps them on when the groups serve them, or a later layer's groups serve them again", () => {
+ const own = mergeConfigOverrides(assistantsBase, [
+ fakeConfig({ endpoints: { azureOpenAI: { groups: [west] } } }, 10),
+ ]);
+ const later = mergeConfigOverrides(assistantsBase, [
+ fakeConfig({ endpoints: { azureOpenAI: { groups: [plain] } } }, 10),
+ fakeConfig({ endpoints: { azureOpenAI: { groups: [west] } } }, 20),
+ ]);
+
+ for (const merged of [own, later]) {
+ expect(merged.endpoints?.azureOpenAI?.assistants).toBe(true);
+ expect(merged.endpoints?.azureOpenAI?.assistantModels).toEqual(['gpt-5', 'o3-mini']);
+ }
+ });
+
+ it('turns off a layer that turns them on over models none of which supports them', () => {
+ const warn = jest.spyOn(logger, 'warn').mockImplementation(() => logger);
+ const merged = mergeConfigOverrides(base, [
+ fakeConfig({ endpoints: { azureOpenAI: { assistants: true } } }, 10),
+ ]);
+
+ expect(merged.endpoints?.azureOpenAI?.assistants).toBe(false);
+ expect(merged.endpoints?.azureOpenAI?.modelNames).toEqual(['gpt-4o']);
+ warn.mockRestore();
+ });
+
+ it('turns them off when the groups are tombstoned', () => {
+ const warn = jest.spyOn(logger, 'warn').mockImplementation(() => logger);
+ const merged = mergeConfigOverrides(assistantsBase, [
+ fakeConfig({}, 10, ['endpoints.azureOpenAI.groups']),
+ ]);
+
+ expect(merged.endpoints?.azureOpenAI?.assistants).toBe(false);
+ expect(merged.endpoints?.azureOpenAI?.assistantModels).toEqual([]);
+ warn.mockRestore();
+ });
+
+ it('keeps only the assistant models an override names that a merged group serves them with', () => {
+ const warn = jest.spyOn(logger, 'warn').mockImplementation(() => logger);
+ const missing = mergeConfigOverrides(assistantsBase, [
+ fakeConfig({ endpoints: { azureOpenAI: { assistantModels: ['missing'] } } }, 10),
+ ]);
+ const mixed = mergeConfigOverrides(assistantsBase, [
+ fakeConfig(
+ {
+ endpoints: {
+ azureOpenAI: {
+ assistantModels: ['missing', 'gpt-4o'],
+ assistantGroups: ['nowhere', 'east'],
+ },
+ },
+ },
+ 10,
+ ),
+ ]);
+
+ expect(missing.endpoints?.azureOpenAI).toMatchObject({
+ assistants: false,
+ assistantModels: [],
+ assistantGroups: [],
+ });
+ expect(mixed.endpoints?.azureOpenAI).toMatchObject({
+ assistants: true,
+ assistantModels: ['gpt-4o'],
+ assistantGroups: ['east'],
+ });
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining(
+ 'Leaving out of endpoints.azureOpenAI.assistantModels, endpoints.azureOpenAI.assistantGroups for role/',
+ ),
+ );
+ warn.mockRestore();
+ });
+ });
+
+ it('lists only the models a merged group serves, whatever an override writes to the lists', () => {
+ const warn = jest.spyOn(logger, 'warn').mockImplementation(() => logger);
+ const listed = mergeConfigOverrides(base, [
+ fakeConfig({ endpoints: { azureOpenAI: { modelNames: ['missing', 'gpt-4o'] } } }, 10),
+ ]);
+ const unmapped = mergeConfigOverrides(base, [
+ fakeConfig(
+ { endpoints: { azureOpenAI: { modelGroupMap: { 'gpt-4o': { group: 'nowhere' } } } } },
+ 10,
+ ),
+ ]);
+ const untouched = mergeConfigOverrides(base, [
+ fakeConfig({ interface: { customWelcome: 'hi' } }, 10),
+ ]);
+
+ expect(listed.endpoints?.azureOpenAI?.modelNames).toEqual(['gpt-4o']);
+ expect(unmapped.endpoints?.azureOpenAI?.modelNames).toEqual([]);
+ expect(untouched.endpoints?.azureOpenAI).toEqual(base.endpoints?.azureOpenAI);
+ warn.mockRestore();
+ });
+});
+
describe('merge precedence', () => {
function layer(
principalType: 'role' | 'group' | 'user',
diff --git a/packages/data-schemas/src/app/resolution.ts b/packages/data-schemas/src/app/resolution.ts
index 4177543f04..1a4306ab11 100644
--- a/packages/data-schemas/src/app/resolution.ts
+++ b/packages/data-schemas/src/app/resolution.ts
@@ -7,11 +7,19 @@ import {
PERMISSION_SUB_KEYS,
isProcessMCPServerConfig,
normalizeEndpointName,
+ EModelEndpoint,
configSchema,
} from 'librechat-data-provider';
import type { TCustomConfig } from 'librechat-data-provider';
import type { AdminConfigMergeRules, AppConfig, Config, TWebSearchKeys } from '~/types';
+import type { AzureResolvedGroupField } from './azure';
import type { ConfigFieldWrite } from './mutations';
+import {
+ AZURE_RESOLVED_GROUP_FIELDS,
+ lacksAzureAssistantModels,
+ narrowAzureServedModels,
+ resolveAzureGroups,
+} from './azure';
import { isBaseConfigPrincipal, sortByConfigPrecedence } from './precedence';
import { setConfigFields, toConfigOverrideState } from './mutations';
import { webSearchPairedFields, unbindWebSearchKeys } from './web';
@@ -38,6 +46,48 @@ const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
const BASE_ONLY_OVERRIDE_SECTIONS = new Set<string>(['filters', ...BASE_ONLY_CONFIG_SECTIONS]);
const BASE_PRINCIPAL_OVERRIDE_SECTIONS = new Set<string>(BASE_PRINCIPAL_CONFIG_SECTIONS);
+/** Where the resolved Azure config sits in an AppConfig. */
+const AZURE_CONFIG_PATH = `endpoints.${EModelEndpoint.azureOpenAI}`;
+
+/** The resolved Azure fields a layer's `groups` replace, as AppConfig paths. */
+const AZURE_RESOLVED_PATHS: readonly string[] = AZURE_RESOLVED_GROUP_FIELDS.map(
+ (field) => `${AZURE_CONFIG_PATH}.${field}`,
+);
+
+/** Azure `groups`, as a librechat.yaml path (the same in an AppConfig). */
+const AZURE_GROUPS_PATH = `${AZURE_CONFIG_PATH}.groups`;
+
+/**
+ * The paths a tombstone removes: its own, and for Azure `groups` every field they resolve to
+ * (`AZURE_RESOLVED_PATHS`), which the Azure clients and model lists read in their place. A
+ * tombstone removes the groups whole, as a layer's own `groups` replace them.
+ */
+function getTombstoneRemovals(path: string): readonly string[] {
+ return path === AZURE_GROUPS_PATH ? [path, ...AZURE_RESOLVED_PATHS] : [path];
+}
+
+/**
+ * `merged` with its Azure groups resolved to none, when it has an Azure endpoint: every field the
+ * groups resolve to stays, empty, so the Azure clients and model lists serve no group. Their
+ * absence would read differently: the model lists fall back to the environment's default Azure
+ * models, which the Azure client, configured by librechat.yaml, cannot map to a group.
+ */
+function withoutAzureGroups<T extends AnyObject>(merged: T): T {
+ const segments = AZURE_CONFIG_PATH.split('.');
+ const azure = getPath(merged, segments);
+ if (!isPlainObject(azure)) {
+ return merged;
+ }
+ const empty: Record<AzureResolvedGroupField, object> = {
+ groupMap: {},
+ modelGroupMap: {},
+ modelNames: [],
+ assistantModels: [],
+ assistantGroups: [],
+ };
+ return setPath(merged, segments, { ...azure, ...empty }) as T;
+}
+
/**
* Paths within the config tree where arrays of objects should be merged by
* a key field rather than replaced wholesale. `deepMerge` matches items by
@@ -975,6 +1025,7 @@ export function applyConfigTombstones(
): Partial<TCustomConfig> {
return (tombstones ?? [])
.filter((path): path is string => typeof path === 'string' && !cleared.has(path))
+ .flatMap(getTombstoneRemovals)
.reduce((current, path) => deletePath(current, path), base as AnyObject);
}
@@ -1233,6 +1284,64 @@ function filterMCPServerOverrides(value: unknown, current: unknown): AnyObject {
return filtered;
}
+/** One layer's step through {@link mergeConfigOverrides}, as `afterLayer` sees it. */
+export interface ConfigMergeStep {
+ layer: ConfigOverrideLayer;
+ /** The base config the merge started from, before any layer. */
+ base: AppConfig;
+ /** The merged config before this layer applied its tombstones and overrides. */
+ below: AppConfig;
+ /**
+ * What the layer's overrides contributed, under AppConfig section names (`mcpConfig`,
+ * `interfaceConfig`, ...), after invalid, base-only and filtered values were removed.
+ */
+ applied: Readonly<Record<string, unknown>>;
+ /** The merged config with this layer applied. */
+ merged: AppConfig;
+ /**
+ * The base config with only this layer applied (its tombstones, then its overrides; its Azure
+ * `groups` replacing what librechat.yaml's resolved to), as if no other layer were below it.
+ * Computed on first call.
+ */
+ alone: () => AppConfig;
+}
+
+export interface MergeConfigOverridesOptions {
+ /**
+ * Runs after each layer merges; the config it returns is what the next layer merges onto. A
+ * caller uses it to apply a policy that depends on what a layer inherited and what it changed,
+ * such as dropping an inherited credential the layer sends somewhere new.
+ */
+ afterLayer?: (step: ConfigMergeStep) => AppConfig;
+ /**
+ * Told about each stored web search key the merge withholds from the URL it was not entered
+ * for, with the layer whose write moved it: the URL's writer when it is the later layer, and
+ * otherwise the key's own. When given, it reports these instead of the merge's own warning.
+ */
+ onWebSearchKeyUnbound?: (unbound: WebSearchKeyUnbound) => void;
+}
+
+/** A stored web search key the merge withholds, and the layer whose write caused it. */
+export interface WebSearchKeyUnbound {
+ layer: ConfigOverrideLayer;
+ url: TWebSearchKeys;
+ apiKey: TWebSearchKeys;
+}
+
+/** One layer's step through {@link foldConfigLayers}, from which `ConfigMergeStep` is built. */
+interface FoldStep<T> {
+ layer: ConfigOverrideLayer;
+ below: T;
+ /** What the layer's overrides contributed, under AppConfig section names. */
+ applied: AnyObject;
+ merged: T;
+ /**
+ * What the layer removed before its overrides landed, as AppConfig paths: its tombstones that
+ * applied, and the resolved Azure fields its `groups` replace.
+ */
+ removed: readonly string[];
+}
+
/** The override document that last set or removed a paired web search field, and its merge position. */
interface WebSearchWriter {
config: ConfigOverrideLayer;
@@ -1291,7 +1400,11 @@ function describeLayer(writer?: WebSearchWriter): string {
* never sends on a key it cannot read. `writers` lists the override document
* behind each field; unlisted fields come from the base config.
*/
-function bindWebSearchKeys(merged: AppConfig, writers: WebSearchWriters): AppConfig {
+function bindWebSearchKeys(
+ merged: AppConfig,
+ writers: WebSearchWriters,
+ onUnbound?: MergeConfigOverridesOptions['onWebSearchKeyUnbound'],
+): AppConfig {
const { webSearch, unbound } = unbindWebSearchKeys(
merged.webSearch,
(field) => writers.get(field)?.order,
@@ -1301,8 +1414,16 @@ function bindWebSearchKeys(merged: AppConfig, writers: WebSearchWriters): AppCon
}
for (const { url, apiKey } of unbound) {
const urlWriter = writers.get(url);
+ const keyWriter = writers.get(apiKey);
+ if (onUnbound) {
+ const cause = (urlWriter?.order ?? -1) > (keyWriter?.order ?? -1) ? urlWriter : keyWriter;
+ if (cause) {
+ onUnbound({ layer: cause.config, url, apiKey });
+ }
+ continue;
+ }
logger.warn(
- `[mergeConfigOverrides] Ignoring webSearch.${apiKey} from ${describeLayer(writers.get(apiKey))}: ` +
+ `[mergeConfigOverrides] Ignoring webSearch.${apiKey} from ${describeLayer(keyWriter)}: ` +
`webSearch.${url} is ${urlWriter?.removed ? 'removed' : 'set'} by ${describeLayer(urlWriter)}. ` +
'Store the key in the same config as the URL.',
);
@@ -1310,6 +1431,10 @@ function bindWebSearchKeys(merged: AppConfig, writers: WebSearchWriters): AppCon
return { ...merged, webSearch };
}
+function describePrincipal(config: ConfigOverrideLayer): string {
+ return `${config.principalType}/${config.principalId}`;
+}
+
/**
* 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
@@ -1348,23 +1473,107 @@ function withAcceptedSections(config: ConfigOverrideLayer): ConfigOverrideLayer
return config;
}
logger.warn(
- `[mergeConfigOverrides] Ignoring unknown config sections ${[...ignored].join(', ')} for ${config.principalType}/${config.principalId}`,
+ `[mergeConfigOverrides] Ignoring unknown config sections ${[...ignored].join(', ')} for ${describePrincipal(config)}`,
);
return { ...config, overrides, tombstones };
}
+/**
+ * A layer's `endpoints` override with its Azure `groups` resolved as AppService resolves
+ * librechat.yaml's (`resolveAzureGroups`): the Azure clients read `groupMap`, `modelGroupMap` and
+ * the model lists resolved with them, never `groups`. The layer's groups replace the groups below
+ * whole, as its `groups` array does in the YAML-shaped config, so what they resolve to replaces
+ * what those resolved to (the caller removes that first); a resolved field the same layer also
+ * writes directly merges over its own groups' (objects) or replaces it. `null` when the layer
+ * writes no groups, or groups that do not resolve, which then stay unread, with a warning.
+ */
+function resolveLayerAzureGroups(
+ endpoints: unknown,
+ config: ConfigOverrideLayer,
+): AnyObject | null {
+ if (!isPlainObject(endpoints)) {
+ return null;
+ }
+ const azure = endpoints[EModelEndpoint.azureOpenAI];
+ if (!isPlainObject(azure) || !Array.isArray(azure.groups)) {
+ return null;
+ }
+ const resolved = resolveAzureGroups(azure.groups);
+ if (!resolved.isValid) {
+ logger.warn(
+ `[mergeConfigOverrides] Ignoring ${AZURE_CONFIG_PATH}.groups for ${describePrincipal(config)}: ${resolved.errors.join('; ')}`,
+ );
+ return null;
+ }
+ const next: AnyObject = { ...azure };
+ for (const field of AZURE_RESOLVED_GROUP_FIELDS) {
+ const own = azure[field];
+ const derived: unknown = resolved[field];
+ next[field] =
+ isPlainObject(own) && isPlainObject(derived) ? deepMerge(derived, own) : (own ?? derived);
+ }
+ return { ...endpoints, [EModelEndpoint.azureOpenAI]: next };
+}
+
+/**
+ * `merged` with the Azure model lists narrowed to what its groups serve
+ * (`narrowAzureServedModels`), and Azure assistants turned off when none of the models it serves
+ * supports them (`lacksAzureAssistantModels`), a combination `azureConfigSetup` refuses in
+ * librechat.yaml. A list an override writes directly, or one whose groups a later layer replaced
+ * or tombstoned, could otherwise name a model no group serves, and groups without an assistant
+ * model under an inherited `assistants: true` would leave the Azure Assistants client no model to
+ * default to. Judged on the merged result, so a later layer whose groups serve assistants keeps
+ * them on.
+ */
+function withServedAzureModels<T extends AppConfig>(
+ merged: T,
+ configs: readonly ConfigOverrideLayer[],
+): T {
+ const endpoints = merged.endpoints;
+ const azure = endpoints?.[EModelEndpoint.azureOpenAI];
+ if (!endpoints || !azure) {
+ return merged;
+ }
+ const principals = configs.map(describePrincipal).join(', ');
+ const { config: served, narrowed } = narrowAzureServedModels(azure);
+ if (narrowed.length > 0) {
+ logger.warn(
+ `[mergeConfigOverrides] Leaving out of ${narrowed.map((field) => `${AZURE_CONFIG_PATH}.${field}`).join(', ')} for ${principals} the Azure models and groups no merged group serves`,
+ );
+ }
+ const assistantsOff = lacksAzureAssistantModels(served);
+ if (assistantsOff) {
+ logger.warn(
+ `[mergeConfigOverrides] Turning off ${AZURE_CONFIG_PATH}.assistants for ${principals}: none of the Azure models they serve supports assistants`,
+ );
+ }
+ if (narrowed.length === 0 && !assistantsOff) {
+ return merged;
+ }
+ return {
+ ...merged,
+ endpoints: {
+ ...endpoints,
+ [EModelEndpoint.azureOpenAI]: assistantsOff ? { ...served, assistants: false } : served,
+ },
+ };
+}
+
/**
* Folds override layers, in merge precedence order (`compareConfigPrecedence`), into
* `merged`, the served config, and `raw`, the YAML-shaped config each layer is validated on
* before it lands (`stripInvalidOverrides`). `merged` starts as any object whose `mcpConfig`
- * is the MCP servers config of `raw`, because the process-MCP filter reads it.
+ * is the MCP servers config of `raw`, because the process-MCP filter reads it. A layer's Azure
+ * `groups` resolve into the fields the Azure clients read (`resolveLayerAzureGroups`).
* `webSearchWriters` names the layer behind each paired web search field, by its position in
- * that order.
+ * that order. `afterLayer` runs after each layer lands, and the next layer folds onto what it
+ * returns.
*/
function foldConfigLayers<T extends AnyObject>(
initial: T,
initialRaw: Partial<TCustomConfig>,
configs: readonly ConfigOverrideLayer[],
+ afterLayer?: (step: FoldStep<T>) => T,
): { merged: T; raw: Partial<TCustomConfig>; webSearchWriters: WebSearchWriters } {
const sorted = sortByConfigPrecedence(configs);
let merged = initial;
@@ -1372,6 +1581,9 @@ function foldConfigLayers<T extends AnyObject>(
const webSearchWriters: WebSearchWriters = new Map();
for (let order = 0; order < sorted.length; order++) {
const config = withAcceptedSections(sorted[order]);
+ const below = merged;
+ let contributed: AnyObject = {};
+ const removed: string[] = [];
const isBasePrincipal = isBaseConfigPrincipal(config);
if (Array.isArray(config.tombstones)) {
const removal: WebSearchWriter = { config, order, removed: true };
@@ -1381,8 +1593,15 @@ function foldConfigLayers<T extends AnyObject>(
!isBaseOnlyOverridePath(path) &&
(isBasePrincipal || !BASE_PRINCIPAL_OVERRIDE_SECTIONS.has(path.split('.')[0]))
) {
- merged = deleteConfigPath(merged, remapOverridePath(path));
- raw = deletePath(raw as AnyObject, path) as Partial<TCustomConfig>;
+ for (const removedPath of getTombstoneRemovals(path)) {
+ const mappedPath = remapOverridePath(removedPath);
+ removed.push(mappedPath);
+ merged = deleteConfigPath(merged, mappedPath);
+ raw = deletePath(raw as AnyObject, removedPath) as Partial<TCustomConfig>;
+ }
+ if (path === AZURE_GROUPS_PATH) {
+ merged = withoutAzureGroups(merged);
+ }
recordWebSearchTombstone(webSearchWriters, path, removal);
}
}
@@ -1391,6 +1610,7 @@ function foldConfigLayers<T extends AnyObject>(
if (config.overrides && typeof config.overrides === 'object') {
const remapped: AnyObject = {};
const applied: AnyObject = {};
+ let replacesAzureGroups = false;
for (const [key, value] of Object.entries(stripInvalidOverrides(config, raw))) {
if (
BASE_ONLY_OVERRIDE_SECTIONS.has(key) ||
@@ -1440,10 +1660,20 @@ function foldConfigLayers<T extends AnyObject>(
if (Object.keys(filtered).length > 0) {
remapped[mappedKey] = filtered;
}
+ } else if (key === 'endpoints') {
+ const resolved = resolveLayerAzureGroups(value, config);
+ remapped[mappedKey] = resolved ?? value;
+ replacesAzureGroups = resolved != null;
} else {
remapped[mappedKey] = value;
}
}
+ if (replacesAzureGroups) {
+ for (const path of AZURE_RESOLVED_PATHS) {
+ merged = deletePath(merged, path);
+ removed.push(path);
+ }
+ }
merged = deepMerge(merged, remapped);
raw = deepMerge(raw as AnyObject, applied) as Partial<TCustomConfig>;
recordWebSearchWrites(webSearchWriters, applied.webSearch, {
@@ -1451,6 +1681,11 @@ function foldConfigLayers<T extends AnyObject>(
order,
removed: false,
});
+ contributed = remapped;
+ }
+
+ if (afterLayer) {
+ merged = afterLayer({ layer: config, below, applied: contributed, merged, removed });
}
}
return { merged, raw, webSearchWriters };
@@ -1462,17 +1697,47 @@ function foldConfigLayers<T extends AnyObject>(
* Configs merge in precedence order (`compareConfigPrecedence`): Base first, then ascending
* priority, then role < group < user, then document identity; the last layer wins. Each
* config's `overrides` is deep-merged into the base config in that order. A stored web search
- * key is dropped when a layer other than its own decides the URL it is sent to.
+ * key is dropped when a layer other than its own decides the URL it is sent to, the Azure model
+ * lists name only models the merged groups serve, and Azure assistants none of those supports
+ * are turned off (`withServedAzureModels`).
*/
export function mergeConfigOverrides(
baseConfig: AppConfig,
configs: readonly ConfigOverrideLayer[],
+ options: MergeConfigOverridesOptions = {},
): AppConfig {
if (!configs || configs.length === 0) {
return baseConfig;
}
- const folded = foldConfigLayers({ ...baseConfig }, baseConfig.config ?? {}, configs);
- const merged = bindWebSearchKeys(folded.merged, folded.webSearchWriters);
+ const { afterLayer } = options;
+ const folded = foldConfigLayers(
+ { ...baseConfig },
+ baseConfig.config ?? {},
+ configs,
+ afterLayer &&
+ (({ layer, below, applied, merged, removed }) => {
+ let alone: AppConfig | undefined;
+ return afterLayer({
+ layer,
+ base: baseConfig,
+ below,
+ applied,
+ merged,
+ alone: () => {
+ alone ??= deepMerge(
+ removed.reduce((current, path) => deleteConfigPath(current, path), { ...baseConfig }),
+ applied,
+ );
+ return alone;
+ },
+ });
+ }),
+ );
+ const merged = bindWebSearchKeys(
+ withServedAzureModels(folded.merged, configs),
+ folded.webSearchWriters,
+ options.onWebSearchKeyUnbound,
+ );
return preserveBaseOnlyPaths(baseConfig, preserveRuntimeStops(baseConfig, merged));
}
diff --git a/packages/data-schemas/src/types/admin.ts b/packages/data-schemas/src/types/admin.ts
index 5d46ab74dc..9cae7e8175 100644
--- a/packages/data-schemas/src/types/admin.ts
+++ b/packages/data-schemas/src/types/admin.ts
@@ -178,6 +178,21 @@ export type AdminConfigSkipReason =
*/
export type AdminConfigIgnoreReason = 'process_mcp_server' | 'base_only_path';
+/**
+ * A credential the runtime merge leaves out of a document's layer, or a destination it sets back,
+ * because the document would send a credential somewhere it was not entered for
+ * (`secret_rebinding`): an inherited secret whose destination the document changes without
+ * entering the secret again, or its own secret whose destination a layer below changed. PUT,
+ * PATCH, field deletes, tombstones and `POST …/changes` list these in `ignored`, judged on the
+ * document as written over `librechat.yaml` and the Base profile. Each describes the stored
+ * document rather than one change, so it names a location, not an op.
+ */
+export type AdminConfigIgnoredSecret = {
+ path: string;
+ segments: string[];
+ reason: 'secret_rebinding';
+};
+
/** A change of the batch, by position, with the location it addressed. */
export type AdminConfigChangeRef = {
/** Index of the change in the request's `ops`. */
@@ -207,8 +222,15 @@ export type AdminConfigChangesResponse = {
applied: AdminConfigChangeRef[];
/** Changes, or parts of a `set` value (at their own `segments`), that were not stored. */
skipped: Array<AdminConfigChangeRef & { reason: AdminConfigSkipReason }>;
- /** Applied changes, or parts of one (at their own `segments`), the runtime merge does not use. */
- ignored: Array<AdminConfigChangeRef & { reason: AdminConfigIgnoreReason }>;
+ /**
+ * Applied changes, or parts of one (at their own `segments`), the runtime merge does not use,
+ * then the credentials it leaves out of the document as written (`secret_rebinding`, also on a
+ * dry run, for the planned document), in the sections the caller can read (on a dry run, the
+ * sections the batch writes).
+ */
+ ignored: Array<
+ (AdminConfigChangeRef & { reason: AdminConfigIgnoreReason }) | AdminConfigIgnoredSecret
+ >;
/**
* Valid changes that left the document as it was: it was already in that state, or the
* batch's changes cancel out (a `set`, then an `unset` of its parent), in which case every
@@ -254,9 +276,12 @@ export type AdminConfigChangeErrorResponse = {
* or a `librechat.yaml` literal) at runtime, not only a `${VAR}` reference, and stores
* `webSearch.keenableApiKey` encrypted like the other web search keys. A stored key reaches a
* URL stored in config only when the same layer set both; it is kept over an inherited
- * `${VAR}` or default URL. A later layer that changes, blanks or removes the paired URL drops
+ * `${VAR}` or default URL (a layer that points a URL at a `${VAR}` other than librechat.yaml's
+ * without a key of its own is set back, `secretRebinding`). A later layer that changes, blanks
+ * or removes the paired URL drops
* the key, and a write that changes or removes the URL beside a stored key must enter the key
- * again (400 `CONFIG_SECRET_REENTRY_REQUIRED`).
+ * again (400 `CONFIG_SECRET_REENTRY_REQUIRED`); the key counts as entered only when the written
+ * document holds the value the request entered.
* - `expectedRevision`: every config document a response returns carries `revision`
* (`<id>:<configVersion>`), and a write with nothing to apply answers `{ message, revision }`.
* PUT, PATCH `/fields`, POST `/fields/tombstone` and PATCH `/active` take `expectedRevision` in
@@ -308,6 +333,94 @@ export type AdminConfigChangeErrorResponse = {
* rename changed, so a grant revoked or a member reassigned meanwhile stays that way. A profile already held by the new
* name answers 409 `ROLE_CONFIG_CONFLICT`, and the Base principal id is a reserved role name
* (400 `ROLE_NAME_RESERVED`).
+ * - `recordSecrets`: each MCP server's `apiKey.key` and `oauth.client_secret`
+ * (`rules.recordSecretFields`, which also lists Azure `groupMap`) is stored encrypted with a masked preview beside it
+ * (`keyPreview`, `client_secretPreview`), left out of every read (GET `/base` included, and
+ * the end-user MCP server list never carries a preview), kept when a write omits it, and
+ * decrypted for the MCP runtime. A `${VAR}` or `{{VAR}}` reference stays readable. A `renames`
+ * hint (`[{ path: 'mcpServers', previousName, name }]`) on PUT and PATCH, or a `rename` op in
+ * a change batch, carries the stored credentials to the new name. A write that keeps a stored
+ * credential while changing where the server sends it (URL, transport, proxy, auth header,
+ * OAuth endpoints and client; the proxy binds the OAuth client secret too, since the access
+ * token it obtains travels through it) answers 400 `MCP_API_KEY_REENTRY_REQUIRED` or
+ * `MCP_OAUTH_SECRET_REENTRY_REQUIRED` with `server` and `fields`: on PUT, PATCH, field
+ * deletes, tombstones and change batches. A credential counts as entered again only when the
+ * written document holds the value the request entered, whatever order its writes came in;
+ * one a rename, a copy or a chain of renames carried is compared with the server it came from,
+ * so a name swap that moves each key with its own server is accepted. The rule covers MCP
+ * credentials, web search keys (`webSearchStoredKeys`) and Azure group keys
+ * (`azureGroupSecrets`) only: a custom endpoint, OCR or speech key a document stores stays with
+ * that document when the same document changes its destination; only the merge's cross-layer
+ * rule (`secretRebinding`) applies to those.
+ * - `azureGroupSecrets`: `endpoints.azureOpenAI.groups[].apiKey` is stored encrypted with
+ * `apiKeyPreview`, matched across writes by `group` (omit it to keep it), left out of reads
+ * and decrypted for the Azure clients, which use it: the merge resolves a profile's `groups`
+ * as AppService resolves librechat.yaml's, into the `groupMap`, `modelGroupMap`, model list
+ * and assistant models the clients read. A profile's `groups` replace the groups below whole,
+ * as its array does, and a tombstone of `groups` removes everything they resolve to; groups
+ * that do not resolve (a duplicate group or model, a model without a deployment or version)
+ * stay unread, with a warning. The merged model lists name only models a merged group serves:
+ * a `modelNames`, `assistantModels` or `assistantGroups` an override writes directly is
+ * narrowed to them, with a warning. When none of the models the merge leaves supports
+ * assistants, `assistants` is off for that profile, with a warning, rather than on without a
+ * model (librechat.yaml refuses that combination at startup). An override that writes
+ * `endpoints.azureOpenAI.groupMap.<group>.apiKey` directly (a record secret,
+ * `rules.recordSecretFields`) gets the same treatment: encrypted with `apiKeyPreview`, kept
+ * when a write of its group omits it, left out of every read (GET `/base` included, where a
+ * librechat.yaml literal shows the fixed mask) and decrypted for the Azure clients; a `groupMap`
+ * entry merges over the resolved group of its name. A write that keeps a stored group key
+ * (in `groups` or `groupMap`) while changing where the group sends it (`baseURL`,
+ * `instanceName`, a deployment name its base URL takes its host from, a destination option in
+ * `addParams` or `dropParams`), judged as the document resolves over librechat.yaml, answers
+ * 400 `CONFIG_SECRET_REENTRY_REQUIRED` with `issues` naming the changed field and `secretPath`:
+ * on PUT, PATCH, field deletes, tombstones and change batches.
+ * - `yamlSecretPreview`: a read of a secret with no stored preview (a librechat.yaml literal,
+ * or ciphertext stored without one) shows the fixed mask `********` in its preview field
+ * instead of nothing, so it reads as set; nothing about the value is revealed. A `${VAR}`
+ * reference, where the field allows one, stays readable.
+ * - `envAllowlist`: a `${NAME}` reference in a value written through the admin config API is
+ * refused unless `NAME` is referenced in librechat.yaml, is a built-in endpoint credential
+ * (`OPENAI_API_KEY`, ...) or is listed in `CONFIG_OVERRIDE_ENV_ALLOWLIST`, or the value is
+ * where loading librechat.yaml puts that same reference (the `${OCR_API_KEY}` of an `ocr`
+ * section without a key, and the web search defaults such as `${SEARXNG_INSTANCE_URL}`,
+ * which GET `/base` returns, so a section read there is accepted written back): 400
+ * `CONFIG_OVERRIDE_INVALID` with issue `env_reference_not_allowed`, on PUT, PATCH and change
+ * batches. A batch is judged on the document it leaves: a reference counts when that document
+ * still holds it where the batch changed something, named there (an entry of a merged-by-key
+ * list, set alone or within its collection, by its index in the collection the batch leaves;
+ * a value under a renamed key or entry by its new name), so one a later change of the batch
+ * removes or replaces is not refused. Text no reader expands
+ * (`interface`, `modelSpecs`, prompt fields) is exempt, and so are the `${INSTANCE_NAME}` and
+ * `${DEPLOYMENT_NAME}` templates the Azure client fills in a group's `baseURL` (`groups` or
+ * `groupMap`), which are not env references, and opaque credentials: the OCR, speech, web
+ * search and Langfuse keys, which are stored encrypted and sent as entered, so a `${...}`
+ * inside one is part of the key (a whole `${VAR}` reference there is still checked). Custom
+ * endpoint, Azure group and MCP credentials are expanded by their clients once decrypted and
+ * stay checked. At runtime an unlisted reference in a stored override resolves to nothing. The
+ * allowlist decides which names a value may reference, not where the value is sent: an allowed
+ * name may appear in any value, a URL, a header or a key beside a host of the writer's
+ * choosing.
+ * - `secretRebinding`: the merge drops a credential a layer would send somewhere it was not
+ * entered for: an inherited one whose destination the layer changes without entering it again,
+ * or the layer's own one whose destination a layer below changed (MCP servers, custom
+ * endpoints, OCR, speech, web search, Azure `groupMap`, including the groups a profile's
+ * `groups` resolve to); for summarization and Vertex AI, which fall back to a deployment
+ * credential, it sets the destination back instead, and so for a web search URL a layer points
+ * at a `${VAR}` reference other than librechat.yaml's without entering the key sent there
+ * (web search sends the deployment's key to any `${VAR}` URL). The OCR client fills an empty
+ * key from `OCR_API_KEY` only for its default destination (no base URL, or `${OCR_BASEURL}`),
+ * so a dropped OCR key is not replaced by the deployment's. A custom
+ * endpoint's destination is its `baseURL`, its `provider` (the client that reads the rest) and
+ * the options in `addParams` and `dropParams` named like a destination, such as the
+ * `anthropicApiUrl` the native Anthropic client sends to; an entry is matched under any
+ * spelling the merge folds (`ollama` is `Ollama`) and reported by the name the merge keeps. Write
+ * responses list each in `ignored` with reason `secret_rebinding` (`AdminConfigIgnoredSecret`),
+ * in the sections the response shows (`readFilteredWriteResponses`; a dry run shows the ones it
+ * writes).
+ * A secret the layer writes counts as entered, a `${VAR}` reference included: restating the
+ * reference librechat.yaml uses beside a new destination keeps it, so for allowlisted names
+ * (`envAllowlist`) the rule stops a destination change that leaves the reference out, not one
+ * that restates it. Header maps are not covered.
*/
export type AdminConfigFeatureFlag =
| 'dottedKeys'
@@ -323,7 +436,12 @@ export type AdminConfigFeatureFlag =
| 'deterministicPrecedence'
| 'priorityRoute'
| 'principalCheck'
- | 'roleRenameMovesProfile';
+ | 'roleRenameMovesProfile'
+ | 'recordSecrets'
+ | 'azureGroupSecrets'
+ | 'yamlSecretPreview'
+ | 'envAllowlist'
+ | 'secretRebinding';
export type AdminConfigFeatures = Record<AdminConfigFeatureFlag, boolean>;
@@ -344,6 +462,16 @@ export type AdminConfigArraySecretFieldRule = {
identityKey: string;
};
+/** A secret every entry of a record keyed by entry name holds, such as each MCP server's. */
+export type AdminConfigRecordSecretFieldRule = {
+ /** The record's dot-path (`mcpServers`, `endpoints.azureOpenAI.groupMap`). */
+ recordPath: string;
+ /** The secret's location inside each entry, as a dot-path. */
+ secretPath: string;
+ /** Its masked-preview companion inside each entry; never writable. */
+ previewPath: string;
+};
+
/** How overrides merge, in override (`librechat.yaml`) key names. */
export type AdminConfigMergeRules = {
/** Arrays merged item by item on a key field instead of replaced. */
@@ -365,6 +493,8 @@ export type AdminConfigRules = AdminConfigMergeRules & {
baseOnlyPaths: string[];
secretFields: AdminConfigSecretFieldRule[];
arraySecretFields: AdminConfigArraySecretFieldRule[];
+ /** Secrets of record entries, kept and encrypted per entry like array secrets. */
+ recordSecretFields: AdminConfigRecordSecretFieldRule[];
/** Maps of credentials admin writes are refused for; reads mask their values. */
refusedMaps: string[];
/** MCP server fields that make a server process-backed; only `librechat.yaml` sets them. */