Skip to content

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

🖇️ fix: Bind Model-Spec Authorization to the Loaded Agent (#15256)

Danny Avila62a55213f0c0
diff --git a/CONTEXT.md b/CONTEXT.md
index 9764a82526..78d4cd7ccf 100644
--- a/CONTEXT.md
+++ b/CONTEXT.md
@@ -1,6 +1,7 @@
# Domain language
- **Agent run envelope**: the versioned, JSON-safe request contract created after ingress authentication and protocol validation but before agent, provider, tool, or MCP initialization. It carries only the validated protocol payload and the minimum trusted principal identifiers. The execution host rehydrates all runtime state from those identifiers.
+- **Effective agent selection**: the resolved endpoint and agent identity after an enforced model spec is applied. Authorization and agent loading must consume this same identity before the Agent run envelope is initialized.
- **MCP runtime request body**: trusted chat identifiers supplied only while an MCP server handles an agent request. It enables request-scoped header placeholders without retaining user-specific request data on a shared server definition.
- **Caller Capability Projection**: the versioned, SDK-owned classification of currently active tools by direct and programmatic callers. Event-driven execution transports this projection as data; LibreChat intersects it with its trusted registry and never recomputes deferred-tool discovery policy or treats the projection as authorization.
- **Subagent thread**: a durable, view-only child conversation owned by one parent conversation and subagent identity. A parent agent may continue it by stable `threadId`; each continuation uses a fresh execution lease restored from the canonical child transcript. It is not an ordinary human-writable chat.
diff --git a/api/server/middleware/accessResources/canAccessAgentFromBody.js b/api/server/middleware/accessResources/canAccessAgentFromBody.js
index 5ade76bb77..913f6c3521 100644
--- a/api/server/middleware/accessResources/canAccessAgentFromBody.js
+++ b/api/server/middleware/accessResources/canAccessAgentFromBody.js
@@ -8,12 +8,28 @@ const {
isAgentsEndpoint,
isEphemeralAgentId,
} = require('librechat-data-provider');
+const { resolveModelSpecForEndpoint } = require('@librechat/api');
const { checkPermission } = require('~/server/services/PermissionService');
const { canAccessResource } = require('./canAccessResource');
const db = require('~/models');
const { getRoleByName, getAgent } = db;
+const resolveEnforcedAgentId = (req, endpoint) => {
+ const modelSpecs = req.config?.modelSpecs;
+ const spec = req.body?.spec;
+ if (!modelSpecs?.enforce || typeof spec !== 'string') {
+ return undefined;
+ }
+
+ const resolution = resolveModelSpecForEndpoint({ modelSpecs, spec, endpoint });
+ if (!('modelSpec' in resolution)) {
+ return undefined;
+ }
+
+ return resolution.modelSpec.preset.agent_id;
+};
+
/**
* Resolves custom agent ID (e.g., "agent_abc123") to a MongoDB document.
* @param {string} agentCustomId - Custom agent ID from request body
@@ -158,7 +174,7 @@ const canAccessAgentFromBody = (options) => {
return async (req, res, next) => {
try {
const { endpoint, agent_id } = req.body;
- let agentId = agent_id;
+ let agentId = resolveEnforcedAgentId(req, endpoint) ?? agent_id;
if (!isAgentsEndpoint(endpoint)) {
agentId = Constants.EPHEMERAL_AGENT_ID;
diff --git a/api/server/middleware/accessResources/canAccessAgentFromBody.spec.js b/api/server/middleware/accessResources/canAccessAgentFromBody.spec.js
index 9e5e0b093a..0cbd5bd770 100644
--- a/api/server/middleware/accessResources/canAccessAgentFromBody.spec.js
+++ b/api/server/middleware/accessResources/canAccessAgentFromBody.spec.js
@@ -129,6 +129,83 @@ describe('canAccessAgentFromBody middleware', () => {
expect(next).toHaveBeenCalled();
});
+
+ test.each([
+ {
+ label: 'inferred agents endpoint',
+ preset: { agent_id: 'agent_restricted' },
+ },
+ {
+ label: 'explicit agents endpoint',
+ preset: { endpoint: 'agents', agent_id: 'agent_restricted' },
+ },
+ ])('checks the enforced model spec agent for an $label', async ({ preset }) => {
+ const restrictedAgent = await createAgent({
+ id: preset.agent_id,
+ name: 'Restricted Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: otherUser._id,
+ });
+
+ await AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalId: otherUser._id,
+ principalModel: PrincipalModel.USER,
+ resourceType: ResourceType.AGENT,
+ resourceId: restrictedAgent._id,
+ permBits: 15,
+ grantedBy: otherUser._id,
+ });
+
+ req.body.spec = 'restricted-agent';
+ req.config = {
+ modelSpecs: {
+ enforce: true,
+ list: [{ name: 'restricted-agent', preset }],
+ },
+ };
+
+ const middleware = canAccessAgentFromBody({ requiredPermission: 1 });
+ await middleware(req, res, next);
+
+ expect(next).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(403);
+ });
+
+ test('permits an enforced model spec agent when the requester has access', async () => {
+ const restrictedAgent = await createAgent({
+ id: 'agent_shared',
+ name: 'Shared Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: otherUser._id,
+ });
+
+ await AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalId: testUser._id,
+ principalModel: PrincipalModel.USER,
+ resourceType: ResourceType.AGENT,
+ resourceId: restrictedAgent._id,
+ permBits: 1,
+ grantedBy: otherUser._id,
+ });
+
+ req.body.spec = 'shared-agent';
+ req.config = {
+ modelSpecs: {
+ enforce: true,
+ list: [{ name: 'shared-agent', preset: { agent_id: restrictedAgent.id } }],
+ },
+ };
+
+ const middleware = canAccessAgentFromBody({ requiredPermission: 1 });
+ await middleware(req, res, next);
+
+ expect(next).toHaveBeenCalled();
+ expect(res.status).not.toHaveBeenCalled();
+ });
});
describe('addedConvo — absent or invalid shape', () => {
diff --git a/api/server/middleware/buildEndpointOption.js b/api/server/middleware/buildEndpointOption.js
index b6e6bfafe3..58154adedc 100644
--- a/api/server/middleware/buildEndpointOption.js
+++ b/api/server/middleware/buildEndpointOption.js
@@ -1,8 +1,7 @@
const {
handleError,
applyModelSpecPreset,
- findModelSpecByName,
- isModelSpecEndpointMatch,
+ resolveModelSpecForEndpoint,
resolveModelSpecPromptPrefixVariables,
inspectContent,
extractChatContent,
@@ -101,14 +100,20 @@ async function buildEndpointOption(req, res, next) {
return handleError(res, { text: 'No model spec selected' });
}
- const currentModelSpec = findModelSpecByName({ list }, spec);
- if (!currentModelSpec) {
- return handleError(res, { text: 'Invalid model spec' });
- }
-
- if (!isModelSpecEndpointMatch(currentModelSpec, endpoint)) {
- return handleError(res, { text: 'Model spec mismatch' });
+ const modelSpecResolution = resolveModelSpecForEndpoint({
+ modelSpecs: { list },
+ spec,
+ endpoint,
+ });
+ if ('error' in modelSpecResolution) {
+ return handleError(res, {
+ text:
+ modelSpecResolution.error === 'invalid-model-spec'
+ ? 'Invalid model spec'
+ : 'Model spec mismatch',
+ });
}
+ const { modelSpec: currentModelSpec } = modelSpecResolution;
try {
const result = applyModelSpecPreset({
@@ -126,11 +131,13 @@ async function buildEndpointOption(req, res, next) {
return handleError(res, { text: 'Error parsing model spec' });
}
} else if (parsedBody.spec && appConfig.modelSpecs?.list) {
- const modelSpec = findModelSpecByName(appConfig.modelSpecs, parsedBody.spec);
- if (modelSpec) {
- if (!isModelSpecEndpointMatch(modelSpec, endpoint)) {
- return handleError(res, { text: 'Model spec mismatch' });
- }
+ const modelSpecResolution = resolveModelSpecForEndpoint({
+ modelSpecs: appConfig.modelSpecs,
+ spec: parsedBody.spec,
+ endpoint,
+ });
+ if ('modelSpec' in modelSpecResolution) {
+ const { modelSpec } = modelSpecResolution;
try {
const result = applyModelSpecPreset({
@@ -146,6 +153,8 @@ async function buildEndpointOption(req, res, next) {
logger.error('Error parsing model spec', error);
return handleError(res, { text: 'Error parsing model spec' });
}
+ } else if (modelSpecResolution.error === 'model-spec-mismatch') {
+ return handleError(res, { text: 'Model spec mismatch' });
}
}
diff --git a/packages/api/src/modelSpecs/index.ts b/packages/api/src/modelSpecs/index.ts
index e22c94f9f1..72c4f28ef8 100644
--- a/packages/api/src/modelSpecs/index.ts
+++ b/packages/api/src/modelSpecs/index.ts
@@ -134,6 +134,36 @@ export function isModelSpecEndpointMatch(
return Boolean(modelSpec && endpoint === resolveModelSpecEndpoint(modelSpec));
}
+export type ModelSpecEndpointResolution =
+ | { modelSpec: TModelSpec }
+ | { error: 'invalid-model-spec' | 'model-spec-mismatch' };
+
+/**
+ * Resolves the selected spec only when it serves the requested endpoint.
+ * Authorization and endpoint construction use this same result so a preset
+ * cannot change the resource identity after its access check has completed.
+ */
+export function resolveModelSpecForEndpoint({
+ modelSpecs,
+ spec,
+ endpoint,
+}: {
+ modelSpecs: Pick<TSpecsConfig, 'list'> | undefined;
+ spec: string;
+ endpoint: string | null | undefined;
+}): ModelSpecEndpointResolution {
+ const modelSpec = findModelSpecByName(modelSpecs, spec);
+ if (!modelSpec) {
+ return { error: 'invalid-model-spec' };
+ }
+
+ if (!isModelSpecEndpointMatch(modelSpec, endpoint)) {
+ return { error: 'model-spec-mismatch' };
+ }
+
+ return { modelSpec };
+}
+
export function applyModelSpecPreset({
modelSpec,
parsedBody,
diff --git a/packages/api/src/modelSpecs/modelSpecs.test.ts b/packages/api/src/modelSpecs/modelSpecs.test.ts
index 220c344aab..359ff23b8a 100644
--- a/packages/api/src/modelSpecs/modelSpecs.test.ts
+++ b/packages/api/src/modelSpecs/modelSpecs.test.ts
@@ -4,6 +4,7 @@ import {
applyModelSpecPreset,
findModelSpecByName,
isModelSpecEndpointMatch,
+ resolveModelSpecForEndpoint,
resolveModelSpecPromptPrefixVariables,
sanitizeModelSpecs,
} from './index';
@@ -183,6 +184,37 @@ describe('modelSpecs helpers', () => {
expect(isModelSpecEndpointMatch(modelSpec, EModelEndpoint.google)).toBe(false);
});
+ it('should resolve a model spec only for its selected endpoint', () => {
+ const modelSpec: TModelSpec = {
+ name: 'restricted-agent',
+ label: 'Restricted Agent',
+ preset: { agent_id: 'agent_restricted' },
+ } as TModelSpec;
+ const modelSpecs = { list: [modelSpec] };
+
+ expect(
+ resolveModelSpecForEndpoint({
+ modelSpecs,
+ spec: 'restricted-agent',
+ endpoint: EModelEndpoint.agents,
+ }),
+ ).toEqual({ modelSpec });
+ expect(
+ resolveModelSpecForEndpoint({
+ modelSpecs,
+ spec: 'missing-agent',
+ endpoint: EModelEndpoint.agents,
+ }),
+ ).toEqual({ error: 'invalid-model-spec' });
+ expect(
+ resolveModelSpecForEndpoint({
+ modelSpecs,
+ spec: 'restricted-agent',
+ endpoint: EModelEndpoint.openAI,
+ }),
+ ).toEqual({ error: 'model-spec-mismatch' });
+ });
+
/**
* A preset naming an `agent_id` can only be served by the agents endpoint, so
* omitting `endpoint` previously left the spec matching nothing at all.