🔎 fix: Enforce WEB_SEARCH Role Permission on Agents (#15875)

* 🔎 fix: Enforce WEB_SEARCH Role Permission on Agents

Squash of #15822 onto dev, preserving authorship:

- 🔎 fix: Enforce WEB_SEARCH Role Permission on Agents
- 🧪 test: Cover the Runtime Tool Loader's Web Search Gate
- 🔒 fix: Gate Web Search on the OpenAI-Compatible Embedder Surface
- 🩹 fix: Authorize Web Search by the Execution Context's User
- 📝 docs: Note the Grant Memo's One-Subject-Per-Request Assumption
- 🧹 fix: Deny Web Search Before an Endpoint Default Can Grant It
- 🙈 fix: Withhold the Web Search Model Parameter From a Denied Role
- 🧱 fix: Strip Provider-Native Search an Endpoint Re-Enables After Denial
- 🔌 fix: Close the OpenRouter Plugin Path and Stop Pruning Hidden Parameters

* 🧭 fix: Gate Provider-Native Web Search on the Built Config

The web search role gate ran before the provider builder and only when the
agent's stored `web_search` was not `false`, so an endpoint's `addParams`
re-enabled native search for a denied role, and every OpenAI-compatible and
Responses request read the role whether or not search was in play.

The gate now reads the builder's output: when it carries a native search tool
or OpenRouter's `web` plugin, the `WEB_SEARCH` grant is resolved and the search
stripped on denial. The routes that reach `initializeAgent` with `runtime` and
no `req` pass a lazy `resolveWebSearchGrant` that joins their request-memoized
grants, forwarded through agent discovery to handoffs and subagents. The
embedder surface wires it whenever `getRoleByName` is supplied, independent of
`appConfig`.

---------

Co-authored-by: TomasPalsson <tomas2212042710@gmail.com>
This commit is contained in:
Danny Avila 2026-09-12 23:00:10 -04:00 • committed by GitHub
parent 2e1ccbb0fd
commit 74fa60cee1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
26 changed files with 898 additions and 38 deletions

View file

@ -178,7 +178,11 @@ jest.mock('@librechat/api', () => ({
createProvisionFilesCallback: () => async () => {},
createAgentExecutionContext: (context) => context,
/** Grants both by default; the capability set is what these specs vary. */
resolveToolRoleGrants: jest.fn(async () => ({ runCode: true, fileSearch: true })),
resolveToolRoleGrants: jest.fn(async () => ({
runCode: true,
fileSearch: true,
webSearch: true,
})),
collectReachableAgents: (roots) => {
const agents = [];
const pending = [...roots];
@ -1853,4 +1857,43 @@ describe('OpenAIChatCompletionController', () => {
);
});
});
describe('web search role gating', () => {
const setCapabilities = (capabilities) => {
req.config.endpoints.agents.capabilities = capabilities;
};
const passedResolver = () => {
const { initializeAgent } = require('@librechat/api');
return initializeAgent.mock.calls[0][0].resolveWebSearchGrant;
};
/** Provider-native search is a model parameter with no capability of its own,
* so the resolver is handed over whatever the capabilities — but it reads
* nothing until the initializer finds native search in the built config. */
it('hands initializeAgent a grant resolver without reading the role', async () => {
const { resolveToolRoleGrants } = require('@librechat/api');
setCapabilities([]);
await OpenAIChatCompletionController(req, res);
expect(passedResolver()).toEqual(expect.any(Function));
expect(resolveToolRoleGrants).not.toHaveBeenCalled();
});
it('resolves the WEB_SEARCH grant against this request when called', async () => {
const { resolveToolRoleGrants } = require('@librechat/api');
resolveToolRoleGrants.mockResolvedValueOnce({
runCode: true,
fileSearch: true,
webSearch: false,
});
setCapabilities([]);
await OpenAIChatCompletionController(req, res);
await expect(passedResolver()()).resolves.toBe(false);
expect(resolveToolRoleGrants).toHaveBeenCalledWith(expect.objectContaining({ req }));
});
});
});

View file

@ -201,7 +201,11 @@ jest.mock('@librechat/api', () => ({
createProvisionFilesCallback: () => async () => {},
createAgentExecutionContext: (context) => context,
/** Grants both by default; the capability set is what these specs vary. */
resolveToolRoleGrants: jest.fn(async () => ({ runCode: true, fileSearch: true })),
resolveToolRoleGrants: jest.fn(async () => ({
runCode: true,
fileSearch: true,
webSearch: true,
})),
SAFE_CONVERSATION_TITLE: 'New Chat',
resolveConversationTitle: (...args) => mockResolveConversationTitle(...args),
/** Pass-through: the controller strips UI-only activity-label parts
@ -2442,4 +2446,43 @@ describe('createResponse controller', () => {
);
});
});
describe('web search role gating', () => {
const setCapabilities = (capabilities) => {
req.config.endpoints.agents.capabilities = capabilities;
};
const passedResolver = () => {
const { initializeAgent } = require('@librechat/api');
return initializeAgent.mock.calls[0][0].resolveWebSearchGrant;
};
/** Provider-native search is a model parameter with no capability of its own,
* so the resolver is handed over whatever the capabilities — but it reads
* nothing until the initializer finds native search in the built config. */
it('hands initializeAgent a grant resolver without reading the role', async () => {
const { resolveToolRoleGrants } = require('@librechat/api');
setCapabilities([]);
await createResponse(req, res);
expect(passedResolver()).toEqual(expect.any(Function));
expect(resolveToolRoleGrants).not.toHaveBeenCalled();
});
it('resolves the WEB_SEARCH grant against this request when called', async () => {
const { resolveToolRoleGrants } = require('@librechat/api');
resolveToolRoleGrants.mockResolvedValueOnce({
runCode: true,
fileSearch: true,
webSearch: false,
});
setCapabilities([]);
await createResponse(req, res);
await expect(passedResolver()()).resolves.toBe(false);
expect(resolveToolRoleGrants).toHaveBeenCalledWith(expect.objectContaining({ req }));
});
});
});

View file

@ -3323,6 +3323,7 @@ class AgentClient extends BaseClient {
getToolFilesByIds: db.getToolFilesByIds,
getCodeGeneratedFiles: db.getCodeGeneratedFiles,
filterFilesByAgentAccess,
getRoleByName: db.getRoleByName,
},
);

View file

@ -514,6 +514,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {
listSkillsByAccess: skillDbMethods.listSkillsByAccess,
listAlwaysApplySkills: skillDbMethods.listAlwaysApplySkills,
getSkillByName: skillDbMethods.getSkillByName,
getRoleByName: db.getRoleByName,
};
const enabledCapabilities = new Set(agentsEConfig?.capabilities);
@ -543,6 +544,12 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {
* a tool the loader is about to drop. */
const fileSearchAvailable =
fileSearchCapabilityEnabled && (await toolRoleGrants)?.fileSearch === true;
/** Called by `initializeAgent` only when an agent's built provider config
* turns native web search on. It reaches the initializer with `runtime`
* and no `req`, so this is what lets it join the grants memoized on this
* request instead of issuing its own read. */
const resolveWebSearchGrant = async () =>
(await resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName })).webSearch;
const skillsCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.skills);
const ephemeralSkillsToggle = request.ephemeralAgent?.skills === true;
const accessibleSkillIds = skillsCapabilityEnabled
@ -609,6 +616,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {
}),
codeEnvAvailable,
fileSearchAvailable,
resolveWebSearchGrant,
backgroundToolsAvailable: enabledCapabilities.has(AgentCapabilities.run_in_background),
toolIntentsAvailable: enabledCapabilities.has(AgentCapabilities.tool_intents),
statefulSessionsAvailable: enabledCapabilities.has(
@ -689,6 +697,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {
defaultActiveOnShare,
codeEnvAvailable,
fileSearchAvailable,
resolveWebSearchGrant,
backgroundToolsAvailable: enabledCapabilities.has(AgentCapabilities.run_in_background),
toolIntentsAvailable: enabledCapabilities.has(AgentCapabilities.tool_intents),
statefulSessionsAvailable: enabledCapabilities.has(

View file

@ -771,6 +771,7 @@ const executeResponse = async (envelope, { req, res }) => {
listSkillsByAccess: skillDbMethods.listSkillsByAccess,
listAlwaysApplySkills: skillDbMethods.listAlwaysApplySkills,
getSkillByName: skillDbMethods.getSkillByName,
getRoleByName: db.getRoleByName,
};
const enabledCapabilities = new Set(agentsEConfig?.capabilities);
@ -800,6 +801,12 @@ const executeResponse = async (envelope, { req, res }) => {
* a tool the loader is about to drop. */
const fileSearchAvailable =
fileSearchCapabilityEnabled && (await toolRoleGrants)?.fileSearch === true;
/** Called by `initializeAgent` only when an agent's built provider config
* turns native web search on. It reaches the initializer with `runtime`
* and no `req`, so this is what lets it join the grants memoized on this
* request instead of issuing its own read. */
const resolveWebSearchGrant = async () =>
(await resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName })).webSearch;
const skillsCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.skills);
const ephemeralSkillsToggle = request.ephemeralAgent?.skills === true;
const accessibleSkillIds = skillsCapabilityEnabled
@ -866,6 +873,7 @@ const executeResponse = async (envelope, { req, res }) => {
}),
codeEnvAvailable,
fileSearchAvailable,
resolveWebSearchGrant,
backgroundToolsAvailable: enabledCapabilities.has(AgentCapabilities.run_in_background),
toolIntentsAvailable: enabledCapabilities.has(AgentCapabilities.tool_intents),
statefulSessionsAvailable: enabledCapabilities.has(
@ -946,6 +954,7 @@ const executeResponse = async (envelope, { req, res }) => {
defaultActiveOnShare,
codeEnvAvailable,
fileSearchAvailable,
resolveWebSearchGrant,
backgroundToolsAvailable: enabledCapabilities.has(AgentCapabilities.run_in_background),
toolIntentsAvailable: enabledCapabilities.has(AgentCapabilities.tool_intents),
statefulSessionsAvailable: enabledCapabilities.has(

View file

@ -216,6 +216,7 @@ const processAddedConvo = async ({
listSkillsByAccess: skillDbMethods.listSkillsByAccess,
listAlwaysApplySkills: skillDbMethods.listAlwaysApplySkills,
getSkillByName: skillDbMethods.getSkillByName,
getRoleByName: db.getRoleByName,
},
);

View file

@ -734,6 +734,7 @@ const initializeClient = async ({
checkSessionsAlive,
loadCodeApiKey,
updateFile: db.updateFile,
getRoleByName: db.getRoleByName,
},
);
@ -824,6 +825,7 @@ const initializeClient = async ({
checkSessionsAlive,
loadCodeApiKey,
updateFile: db.updateFile,
getRoleByName: db.getRoleByName,
},
// The callback fires during BFS, before the helper prunes agents
// whose edges end up filtered. Don't populate `agentConfigs` here —
@ -1297,6 +1299,7 @@ const initializeClient = async ({
checkSessionsAlive,
loadCodeApiKey,
updateFile: db.updateFile,
getRoleByName: db.getRoleByName,
},
),
context.signal,

View file

@ -151,6 +151,7 @@ const getActiveToolResources = (toolResources, tools) => {
const toolCapabilityGates = {
[Tools.file_search]: AgentCapabilities.file_search,
[Tools.execute_code]: AgentCapabilities.execute_code,
[Tools.web_search]: AgentCapabilities.web_search,
};
/**
@ -865,7 +866,7 @@ async function loadToolDefinitionsWrapper({
return checkCapability(AgentCapabilities.execute_code) && canUseTool(tool);
}
if (tool === Tools.web_search) {
return checkCapability(AgentCapabilities.web_search);
return checkCapability(AgentCapabilities.web_search) && canUseTool(tool);
}
if (tool === Tools.memory) {
return checkCapability(AgentCapabilities.memory);
@ -1651,7 +1652,7 @@ async function loadAgentTools({
} else if (tool === Tools.execute_code) {
return checkCapability(AgentCapabilities.execute_code) && canUseTool(tool);
} else if (tool === Tools.web_search) {
includesWebSearch = checkCapability(AgentCapabilities.web_search);
includesWebSearch = checkCapability(AgentCapabilities.web_search) && canUseTool(tool);
return includesWebSearch;
} else if (tool === Tools.memory) {
return checkCapability(AgentCapabilities.memory);

View file

@ -202,13 +202,14 @@ const { createOnSearchResults } = require('~/server/services/Tools/search');
const { reinitMCPServer } = require('~/server/services/Tools/mcp');
const { ContentFilterError, PENDING_STALE_MS } = require('@librechat/api');
/** Role document shape `checkAccess` reads; both role-gated tools granted. */
/** Role document shape `checkAccess` reads; all three role-gated tools granted. */
function buildRole(overrides = {}) {
return {
name: 'USER',
permissions: {
[PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: true },
[PermissionTypes.RUN_CODE]: { [Permissions.USE]: true },
[PermissionTypes.WEB_SEARCH]: { [Permissions.USE]: true },
...overrides,
},
};
@ -3873,6 +3874,7 @@ describe('ToolService - Action Capability Gating', () => {
AgentCapabilities.tools,
AgentCapabilities.file_search,
AgentCapabilities.execute_code,
AgentCapabilities.web_search,
];
const denyPermission = (deniedType) =>
@ -3980,6 +3982,61 @@ describe('ToolService - Action Capability Gating', () => {
expect(callArgs.codeExecutionEnabled).toBe(true);
});
it('omits web_search from definitions when WEB_SEARCH.USE is denied', async () => {
denyPermission(PermissionTypes.WEB_SEARCH);
await loadAgentTools({
req: createMockReq(capabilities),
res: {},
agent: { id: 'agent_123', tools: [Tools.web_search, Tools.execute_code] },
definitionsOnly: true,
});
const [callArgs] = mockLoadToolDefinitions.mock.calls[0];
expect(callArgs.tools).not.toContain(Tools.web_search);
expect(callArgs.tools).toContain(Tools.execute_code);
});
it('omits web_search from the runtime loader when WEB_SEARCH.USE is denied', async () => {
denyPermission(PermissionTypes.WEB_SEARCH);
await loadAgentTools({
req: createMockReq(capabilities),
res: {},
agent: { id: 'agent_123', tools: [Tools.web_search, Tools.execute_code] },
definitionsOnly: false,
});
expect(mockLoadToolsUtil).toHaveBeenCalledTimes(1);
const [callArgs] = mockLoadToolsUtil.mock.calls[0];
expect(callArgs.tools).not.toContain(Tools.web_search);
expect(callArgs.tools).toContain(Tools.execute_code);
});
it('keeps web_search when the role grants it', async () => {
await loadAgentTools({
req: createMockReq(capabilities),
res: {},
agent: { id: 'agent_123', tools: [Tools.web_search] },
definitionsOnly: true,
});
const [callArgs] = mockLoadToolDefinitions.mock.calls[0];
expect(callArgs.tools).toContain(Tools.web_search);
});
it('keeps web_search in the runtime loader when the role grants it', async () => {
await loadAgentTools({
req: createMockReq(capabilities),
res: {},
agent: { id: 'agent_123', tools: [Tools.web_search] },
definitionsOnly: false,
});
const [callArgs] = mockLoadToolsUtil.mock.calls[0];
expect(callArgs.tools).toContain(Tools.web_search);
});
it('fails closed when the role lookup throws', async () => {
mockGetRoleByName.mockRejectedValue(new Error('role lookup failed'));

View file

@ -118,8 +118,17 @@ export function composeAgentUpdatePayload(
const model = _model ?? '';
const provider =
(typeof _provider === 'string' ? _provider : (_provider as StringOption).value) ?? '';
/** Pruning reads the complete schema, not the rendered subset, so a role-gated
* parameter is preserved rather than deleted when someone without the
* permission saves an unrelated edit. `webSearchAllowed` narrows only
* `visibleParameters`, which this path does not use. */
const modelParameterSettings = parameterConfig
? resolveAgentParameterSettings({ ...parameterConfig, model, provider })
? resolveAgentParameterSettings({
...parameterConfig,
model,
provider,
webSearchAllowed: true,
})
: undefined;
const model_parameters = modelParameterSettings
? pruneAgentModelParameters(currentModelParameters, modelParameterSettings)

View file

@ -72,6 +72,7 @@ jest.mock('~/Providers', () => ({
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
useHasAccess: () => true,
}));
jest.mock('~/utils', () => ({

View file

@ -2,14 +2,20 @@ import React, { useMemo, useEffect } from 'react';
import { ChevronLeft, RotateCcw } from 'lucide-react';
import { Alert, Button, ControlCombobox } from '@librechat/client';
import { useFormContext, useWatch, Controller } from 'react-hook-form';
import { alternateName, LocalStorageKeys, resolveModelCatalogKey } from 'librechat-data-provider';
import {
Permissions,
alternateName,
PermissionTypes,
LocalStorageKeys,
resolveModelCatalogKey,
} from 'librechat-data-provider';
import type * as t from 'librechat-data-provider';
import type { AgentForm, AgentModelPanelProps, StringOption } from '~/common';
import { pruneAgentModelParameters, resolveAgentParameterSettings } from './parameters';
import { componentMapping } from '~/components/SidePanel/Parameters/components';
import { useGetEndpointsQuery, useGetStartupConfig } from '~/data-provider';
import { useLocalize, useHasAccess } from '~/hooks';
import { useLiveAnnouncer } from '~/Providers';
import { useLocalize } from '~/hooks';
import { Panel } from '~/common';
import { cn } from '~/utils';
@ -63,6 +69,11 @@ export default function ModelPanel({
return endpointsConfig?.[provider]?.availableRegions ?? [];
}, [endpointsConfig, provider]);
const webSearchAllowed = useHasAccess({
permissionType: PermissionTypes.WEB_SEARCH,
permission: Permissions.USE,
});
const parameterSettings = useMemo(
() =>
resolveAgentParameterSettings({
@ -70,10 +81,13 @@ export default function ModelPanel({
model: model ?? '',
provider,
startupConfig,
webSearchAllowed,
}),
[endpointsConfig, model, provider, startupConfig],
[endpointsConfig, model, provider, startupConfig, webSearchAllowed],
);
const { parameters } = parameterSettings;
/** The rendered set omits role-gated controls; `parameterSettings.parameters`
* stays complete so the pruning effect below still recognises them. */
const { visibleParameters: parameters } = parameterSettings;
/**
* Prunes `model_parameters` entries that no longer have a visible control (e.g. a

View file

@ -97,7 +97,7 @@ jest.mock('../hooks', () => {
mcpServersMap: mcpServersMap ?? new Map(),
skills: [],
actions: agentActions,
permissions: { mcp: true, skills: false },
permissions: { mcp: true, skills: false, webSearch: true, runCode: true, fileSearch: true },
});
const selected = deriveSelectedItems(
{

View file

@ -163,6 +163,18 @@ export function useAgentItems({
permissionType: PermissionTypes.MCP_SERVERS,
permission: Permissions.USE,
});
const hasWebSearchAccess = useHasAccess({
permissionType: PermissionTypes.WEB_SEARCH,
permission: Permissions.USE,
});
const hasRunCodeAccess = useHasAccess({
permissionType: PermissionTypes.RUN_CODE,
permission: Permissions.USE,
});
const hasFileSearchAccess = useHasAccess({
permissionType: PermissionTypes.FILE_SEARCH,
permission: Permissions.USE,
});
const showMemory = useShowMemory();
const webSearchUserProvided = useWebSearchUserProvided();
const builtinAuthMap = useBuiltinAuthMap();
@ -191,7 +203,13 @@ export function useAgentItems({
mcpServersMap: mcpServersMap ?? new Map(),
skills,
actions: agentActions,
permissions: { mcp: hasMcpAccess, skills: skillsPermission },
permissions: {
mcp: hasMcpAccess,
skills: skillsPermission,
webSearch: hasWebSearchAccess,
runCode: hasRunCodeAccess,
fileSearch: hasFileSearchAccess,
},
showMemory,
webSearchUserProvided,
builtinAuthMap,
@ -203,6 +221,9 @@ export function useAgentItems({
skills,
agentActions,
hasMcpAccess,
hasWebSearchAccess,
hasRunCodeAccess,
hasFileSearchAccess,
skillsPermission,
showMemory,
webSearchUserProvided,

View file

@ -9,7 +9,7 @@ const emptyInputs: BuildCatalogInputs = {
mcpServersMap: new Map(),
skills: [],
actions: [],
permissions: { mcp: true, skills: true },
permissions: { mcp: true, skills: true, webSearch: true, runCode: true, fileSearch: true },
};
const toolInputs: BuildCatalogInputs = {
@ -92,7 +92,7 @@ describe('buildCatalog', () => {
const items = buildCatalog({
...emptyInputs,
mcpServersMap: map,
permissions: { mcp: false, skills: true },
permissions: { ...emptyInputs.permissions, mcp: false },
});
expect(items.find((i) => i.kind === 'mcp')).toBeUndefined();
});
@ -248,6 +248,42 @@ describe('buildCatalog', () => {
}
});
describe.each([
{ cap: AgentCapabilities.web_search, field: 'webSearch' as const },
{ cap: AgentCapabilities.execute_code, field: 'runCode' as const },
{ cap: AgentCapabilities.file_search, field: 'fileSearch' as const },
])('gates the $cap builtin on its role permission', ({ cap, field }) => {
const findBuiltin = (items: ReturnType<typeof buildCatalog>) =>
items.find((i) => i.kind === 'builtin' && i.id === cap);
test('absent when the role permission is false and the capability is enabled', () => {
const items = buildCatalog({
...emptyInputs,
agentsConfig: { capabilities: [cap] },
permissions: { ...emptyInputs.permissions, [field]: false },
});
expect(findBuiltin(items)).toBeUndefined();
});
test('present when both the role permission and the capability are true', () => {
const items = buildCatalog({
...emptyInputs,
agentsConfig: { capabilities: [cap] },
permissions: { ...emptyInputs.permissions, [field]: true },
});
expect(findBuiltin(items)).toBeDefined();
});
test('absent when the capability is off regardless of the role grant', () => {
const items = buildCatalog({
...emptyInputs,
agentsConfig: { capabilities: [] },
permissions: { ...emptyInputs.permissions, [field]: true },
});
expect(findBuiltin(items)).toBeUndefined();
});
});
test('returns items in stable order: builtin -> mcp -> tool -> skill -> action', () => {
const map = new Map();
map.set('srv', { serverName: 'srv', isConfigured: true, tools: [] });

View file

@ -23,7 +23,18 @@ export interface BuildCatalogInputs {
mcpServersMap: Map<string, MCPServerInfo>;
skills: TSkillSummary[];
actions: Action[];
permissions: { mcp: boolean; skills: boolean };
/**
* Role grants gating catalog inclusion. `mcp` and `skills` gate their own item
* kinds; the rest gate the matching builtin (see `BUILTIN_ROLE_PERMISSIONS`) on
* top of its admin-enabled capability, so a builtin has to clear both.
*/
permissions: {
mcp: boolean;
skills: boolean;
webSearch: boolean;
runCode: boolean;
fileSearch: boolean;
};
/**
* Id of the signed-in user. When provided, skills authored by this user are
* flagged `ownedByUser` so the "Made by you" view can surface them. Optional
@ -87,6 +98,15 @@ const BUILTIN_DEFINITIONS: BuiltinDef[] = [
},
];
/** Role grant each builtin needs on top of its capability. A builtin absent here
* (`artifacts`) carries no role permission and passes on the capability alone. */
const BUILTIN_ROLE_PERMISSIONS: Partial<Record<BuiltinId, 'webSearch' | 'runCode' | 'fileSearch'>> =
{
[AgentCapabilities.execute_code]: 'runCode',
[AgentCapabilities.web_search]: 'webSearch',
[AgentCapabilities.file_search]: 'fileSearch',
};
function countEndpoints(settings: Action['settings']): number {
if (settings == null) {
return 0;
@ -106,6 +126,10 @@ export function buildCatalog(inputs: BuildCatalogInputs): AgentItem[] {
if (!enabled.has(def.id)) {
continue;
}
const roleGrant = BUILTIN_ROLE_PERMISSIONS[def.id];
if (roleGrant != null && !inputs.permissions[roleGrant]) {
continue;
}
items.push({
kind: 'builtin',
id: def.id,

View file

@ -0,0 +1,77 @@
import { pruneAgentModelParameters, resolveAgentParameterSettings } from '../parameters';
/**
* `web_search` is a default model parameter for the OpenAI, Anthropic and Google
* column sets, so the builder offers its switch to every agent editor unless the
* role grant is consulted here — the model-parameters twin of the Web Search
* capability toggle.
*/
describe('resolveAgentParameterSettings — web_search role gating', () => {
const settings = (webSearchAllowed: boolean, provider = 'openAI', model = 'gpt-4o') =>
resolveAgentParameterSettings({
endpointsConfig: {},
startupConfig: undefined,
model,
provider,
webSearchAllowed,
});
const resolve = (webSearchAllowed: boolean, provider = 'openAI', model = 'gpt-4o') =>
settings(webSearchAllowed, provider, model).visibleParameters.map((param) => param.key);
it.each([
['openAI', 'gpt-4o'],
['anthropic', 'claude-3-5-sonnet'],
['google', 'gemini-1.5-pro'],
])('offers web_search on %s when the role grants it', (provider, model) => {
expect(resolve(true, provider, model)).toContain('web_search');
});
it.each([
['openAI', 'gpt-4o'],
['anthropic', 'claude-3-5-sonnet'],
['google', 'gemini-1.5-pro'],
])('withholds web_search on %s when the role denies it', (provider, model) => {
expect(resolve(false, provider, model)).not.toContain('web_search');
});
it('withholds only web_search, leaving the rest of the set intact', () => {
const granted = resolve(true);
const denied = resolve(false);
expect(granted.length - denied.length).toBe(1);
expect(denied).toEqual(granted.filter((key) => key !== 'web_search'));
});
});
/**
* A parameter the role may not see is still part of the endpoint schema. Pruning
* has to keep recognising it, or a user without the permission opening someone
* else's agent silently drops that agent's configuration on the next save.
*/
describe('resolveAgentParameterSettings — denied parameters survive pruning', () => {
const resolved = (webSearchAllowed: boolean) =>
resolveAgentParameterSettings({
endpointsConfig: {},
startupConfig: undefined,
model: 'gpt-4o',
provider: 'openAI',
webSearchAllowed,
});
it('keeps web_search in the full parameter set even when the role denies it', () => {
const keys = resolved(false).parameters.map((param) => param.key);
expect(keys).toContain('web_search');
});
it("preserves a stored web_search value through a denied editor's save", () => {
const denied = resolved(false);
const stored = { model: 'gpt-4o', web_search: true, temperature: 0.5 } as never;
expect(pruneAgentModelParameters(stored, denied)).toEqual(stored);
});
it('still prunes a parameter the schema genuinely does not define', () => {
const denied = resolved(false);
const stored = { model: 'gpt-4o', not_a_real_param: true } as never;
expect(pruneAgentModelParameters(stored, denied)).not.toHaveProperty('not_a_real_param');
});
});

View file

@ -20,7 +20,15 @@ export type AgentParameterConfig = {
};
export type ResolvedAgentParameterSettings = {
/**
* Every parameter the endpoint schema defines for this model. Pruning reads
* this, so a value the role may not *see* is still recognised and preserved:
* dropping it here would delete another user's configuration on an unrelated
* save by someone without the permission.
*/
parameters: SettingDefinition[];
/** The subset that gets a control. Role-gated parameters are absent. */
visibleParameters: SettingDefinition[];
schemaResolved: boolean;
};
@ -31,9 +39,14 @@ export function resolveAgentParameterSettings({
model,
provider,
startupConfig,
webSearchAllowed,
}: AgentParameterConfig & {
model: string;
provider: string;
/** `WEB_SEARCH.USE`. `web_search` is a default model parameter for the OpenAI,
* Anthropic and Google column sets, so without this the builder offers a
* switch the server will refuse. Narrows `visibleParameters` only. */
webSearchAllowed: boolean;
}): ResolvedAgentParameterSettings {
const resolvedEndpointsConfig = endpointsConfig ?? {};
const endpointType = getEndpointField(resolvedEndpointsConfig, provider, 'type');
@ -59,12 +72,14 @@ export function resolveAgentParameterSettings({
overriddenEndpointKey,
model,
);
const parameters = modelAwareParams.map(
(param) => (overriddenParamsMap[param.key] as SettingDefinition) ?? param,
);
return {
schemaResolved: defaultParams != null || overriddenParams != null,
parameters: modelAwareParams.map(
(param) => (overriddenParamsMap[param.key] as SettingDefinition) ?? param,
),
parameters,
visibleParameters: parameters.filter((param) => param.key !== 'web_search' || webSearchAllowed),
};
}

View file

@ -34,15 +34,17 @@ jest.mock('@librechat/agents', () => ({
import { Providers } from '@librechat/agents';
import {
Tools,
Constants,
ErrorTypes,
Permissions,
EModelEndpoint,
EToolResources,
FileContext,
FileSources,
PermissionTypes,
AgentCapabilities,
configSchema,
Tools,
} from 'librechat-data-provider';
import type { IMongoFile } from '@librechat/data-schemas';
import type { Agent, TFile } from 'librechat-data-provider';
@ -4211,3 +4213,200 @@ describe('initializeAgent — authorized run file snapshots', () => {
expect(result.currentRequestAttachments[0].user).toBe('user-1');
});
});
/**
* Provider-native web search is gated on what the provider builder produced, not
* on `model_parameters.web_search`: an endpoint's `defaultParams`, `customParams`
* defaults and `addParams` reach the same switch, and `addParams` is applied last.
*/
describe('initializeAgent — provider-native web search role gate', () => {
const OPENAI_SEARCH = { type: 'web_search' };
const roleWithWebSearch = (use: boolean) =>
jest.fn().mockResolvedValue({
name: 'USER',
permissions: { [PermissionTypes.WEB_SEARCH]: { [Permissions.USE]: use } },
});
const roleGatedReq = () =>
({ user: { id: 'user-1', role: 'USER' }, config: {} }) as unknown as ServerRequest;
const run = async ({
provider = Providers.OPENAI,
providerTools = [OPENAI_SEARCH],
getRoleByName,
params = {},
}: {
provider?: Providers;
providerTools?: unknown[];
getRoleByName?: jest.Mock;
params?: Partial<Parameters<typeof initializeAgent>[0]>;
}) => {
const { agent, res, loadTools, db } = createMocks({ provider, providerTools });
return initializeAgent(
{
req: roleGatedReq(),
res,
agent,
loadTools,
endpointOption: { endpoint: EModelEndpoint.agents },
allowedProviders: new Set([provider]),
isInitialAgent: true,
...params,
},
{ ...db, getRoleByName },
);
};
it.each([
['OpenAI', Providers.OPENAI, OPENAI_SEARCH],
['Anthropic', Providers.ANTHROPIC, { type: 'web_search_20250305', name: 'web_search' }],
['Google', Providers.GOOGLE, { googleSearch: {} }],
])(
'strips the %s native search tool when the role denies WEB_SEARCH',
async (_label, provider, nativeTool) => {
const result = await run({
provider: provider as Providers,
providerTools: [nativeTool],
getRoleByName: roleWithWebSearch(false),
});
expect(result.tools).not.toContainEqual(nativeTool);
},
);
it.each([
['OpenAI', Providers.OPENAI, OPENAI_SEARCH],
['Anthropic', Providers.ANTHROPIC, { type: 'web_search_20250305', name: 'web_search' }],
['Google', Providers.GOOGLE, { googleSearch: {} }],
])(
'keeps the %s native search tool when the role grants WEB_SEARCH',
async (_label, provider, nativeTool) => {
const result = await run({
provider: provider as Providers,
providerTools: [nativeTool],
getRoleByName: roleWithWebSearch(true),
});
expect(result.tools).toContainEqual(nativeTool);
},
);
/** An agent that stores `web_search: false` still gets native search when its
* endpoint's `addParams` turns it on, so the stored value cannot short-circuit
* the gate. */
it('strips endpoint-enabled search for a denied role even when the agent stores false', async () => {
mockExtractLibreChatParams.mockReturnValueOnce({
resendFiles: false,
maxContextTokens: undefined,
modelOptions: { model: 'test-model', web_search: false },
});
const result = await run({ getRoleByName: roleWithWebSearch(false) });
expect(result.tools).not.toContainEqual(OPENAI_SEARCH);
});
it('reads no role when the built config turns no native search on', async () => {
const getRoleByName = roleWithWebSearch(false);
const resolveWebSearchGrant = jest.fn().mockResolvedValue(false);
mockExtractLibreChatParams.mockReturnValueOnce({
resendFiles: false,
maxContextTokens: undefined,
modelOptions: { model: 'test-model', web_search: true },
});
await run({ providerTools: [], getRoleByName, params: { resolveWebSearchGrant } });
expect(getRoleByName).not.toHaveBeenCalled();
expect(resolveWebSearchGrant).not.toHaveBeenCalled();
});
/** OpenRouter receives web search as `modelKwargs.plugins`, not as a tool, so
* the plugin alone has to trigger the gate. */
it('strips the OpenRouter web search plugin when the role denies WEB_SEARCH', async () => {
const { agent, res, loadTools, db } = createMocks({ provider: Providers.OPENAI });
const llmConfig = {
model: agent.model,
modelKwargs: { plugins: [{ id: 'web' }, { id: 'file-parser' }] },
};
mockGetProviderConfig.mockReturnValue({
getOptions: jest.fn().mockResolvedValue({ llmConfig }),
overrideProvider: Providers.OPENAI,
});
const getRoleByName = roleWithWebSearch(false);
await initializeAgent(
{
req: roleGatedReq(),
res,
agent,
loadTools,
endpointOption: { endpoint: EModelEndpoint.agents },
allowedProviders: new Set([Providers.OPENAI]),
isInitialAgent: true,
},
{ ...db, getRoleByName },
);
expect(getRoleByName).toHaveBeenCalledTimes(1);
expect(llmConfig.modelKwargs.plugins).toEqual([{ id: 'file-parser' }]);
});
/** The OpenAI-compatible and Responses routes reach the initializer with
* `runtime` and no `req`; their resolver joins the grants memoized on their
* own request, so the initializer must not read the role itself. */
it('uses the caller resolver instead of reading the role', async () => {
const getRoleByName = roleWithWebSearch(true);
const resolveWebSearchGrant = jest.fn().mockResolvedValue(false);
const result = await run({ getRoleByName, params: { resolveWebSearchGrant } });
expect(resolveWebSearchGrant).toHaveBeenCalledTimes(1);
expect(getRoleByName).not.toHaveBeenCalled();
expect(result.tools).not.toContainEqual(OPENAI_SEARCH);
});
it('keeps native search when the caller resolver grants it', async () => {
const resolveWebSearchGrant = jest.fn().mockResolvedValue(true);
const result = await run({ params: { resolveWebSearchGrant } });
expect(result.tools).toContainEqual(OPENAI_SEARCH);
});
it('denies native search when the caller resolver throws', async () => {
const resolveWebSearchGrant = jest.fn().mockRejectedValue(new Error('role store down'));
const result = await run({ params: { resolveWebSearchGrant } });
expect(result.tools).not.toContainEqual(OPENAI_SEARCH);
});
it('authorizes the runtime user when the caller passes runtime and no req', async () => {
const getRoleByName = roleWithWebSearch(false);
const result = await run({
getRoleByName,
params: {
req: undefined,
runtime: {
user: { id: 'user-1', role: 'USER' } as never,
appConfig: {} as never,
requestBody: {},
turnStartedAt: 1000,
},
},
});
expect(getRoleByName).toHaveBeenCalledWith('USER', undefined);
/** One read, not one per grant: without a `req` there is no per-request
* cache to dedupe the three permission checks. */
expect(getRoleByName).toHaveBeenCalledTimes(1);
expect(result.tools).not.toContainEqual(OPENAI_SEARCH);
});
it('applies no role gate when neither a resolver nor a role lookup is wired', async () => {
const result = await run({});
expect(result.tools).toContainEqual(OPENAI_SEARCH);
});
});

View file

@ -308,6 +308,37 @@ describe('discoverConnectedAgents', () => {
},
);
/** A handoff agent's provider config can turn native web search on as well, so
* dropping the resolver here would leave it ungated one hop later. */
it('forwards resolveWebSearchGrant to every handoff initializeAgent call', async () => {
const primaryConfig = makeConfig('A', [{ from: 'A', to: 'B', edgeType: 'handoff' }]);
const getAgent = jest.fn(async () => makeAgent('B', []));
const resolveWebSearchGrant = jest.fn().mockResolvedValue(false);
await discoverConnectedAgents(
{
req: makeReq(),
res: makeRes(),
primaryConfig,
allowedProviders: new Set(),
modelsConfig: { openai: ['gpt-4o'] },
loadTools: jest.fn(),
resolveWebSearchGrant,
},
{
getAgent,
checkPermission: jest.fn().mockResolvedValue(true),
logViolation: jest.fn(),
db: {} as never,
},
);
expect(mockInitializeAgent).toHaveBeenCalledWith(
expect.objectContaining({ resolveWebSearchGrant }),
expect.anything(),
);
});
it('forwards normalized request metadata to every handoff initializeAgent call', async () => {
const primaryConfig = makeConfig('A', [{ from: 'A', to: 'B', edgeType: 'handoff' }]);
const getAgent = jest.fn(async () => makeAgent('B', []));

View file

@ -112,6 +112,12 @@ export interface DiscoverConnectedAgentsParams {
* the terms its parent did.
*/
fileSearchAvailable?: InitializeAgentParams['fileSearchAvailable'];
/**
* The caller's `WEB_SEARCH` grant resolver, forwarded so a handoff or subagent
* whose provider config turns native web search on is authorized by the same
* request-memoized read as its parent.
*/
resolveWebSearchGrant?: InitializeAgentParams['resolveWebSearchGrant'];
/** Sibling of `codeEnvAvailable` — the `stateful_code_sessions` capability flag, forwarded to every handoff `initializeAgent`. */
statefulSessionsAvailable?: InitializeAgentParams['statefulSessionsAvailable'];
/** Deployment policy for stateful workspace scopes, forwarded unchanged to every referenced agent. */
@ -251,6 +257,7 @@ async function initializeReferencedAgent(
defaultActiveOnShare: params.defaultActiveOnShare,
codeEnvAvailable: params.codeEnvAvailable,
fileSearchAvailable: params.fileSearchAvailable,
resolveWebSearchGrant: params.resolveWebSearchGrant,
backgroundToolsAvailable: params.backgroundToolsAvailable,
toolIntentsAvailable: params.toolIntentsAvailable,
statefulSessionsAvailable: params.statefulSessionsAvailable,

View file

@ -28,7 +28,7 @@ import type {
} from 'librechat-data-provider';
import type { GenericTool, LCToolRegistry, ToolMap, LCTool } from '@librechat/agents';
import type { IMongoFile, FileOwnerScope } from '@librechat/data-schemas';
import type { Response as ServerResponse } from 'express';
import type { Request, Response as ServerResponse } from 'express';
import type {
TFileUpdate,
ProvisionState,
@ -56,6 +56,7 @@ import type { LCAvailableTools, RequestScopedMCPConnectionStore } from '../mcp/t
import type { ContentTraversalLimitError } from '../protection/adapters/nested';
import type { SkillContentInput } from '../protection/adapters/submissions';
import type { TextContentFragment } from '../protection/types';
import type { CheckAccessParams } from '../middleware/access';
import type { MCPToolAlias } from '~/tools/classification';
import type { AgentExecutionContext } from './runtime';
import {
@ -110,6 +111,7 @@ import { isImplicitStatefulCodeRouteAvailable } from '../code/config';
import { registerMemoryTools, memoryToolUsageGuard } from './memory';
import { applyIntentLabels, sanitizeIntentLabels } from './intent';
import { ContentFilterError } from '../middleware/contentFilter';
import { resolveToolRoleGrants } from '~/tools/rolePermissions';
import { createRequestAgentExecutionContext } from './runtime';
import { filterFilesByEndpointRuntimeConfig } from '~/files';
import { hasActiveFileFieldPolicy } from '~/protection';
@ -358,6 +360,123 @@ function hasGoogleSearchTool(tool: unknown): boolean {
return 'googleSearch' in tool || 'googleSearchRetrieval' in tool;
}
/**
* Whether a provider-built tool is that provider's own web search.
*
* Each provider spells it differently — OpenAI `{ type: 'web_search' }`, Anthropic
* `{ type: 'web_search_20250305', name: 'web_search' }`, Google `{ googleSearch: {} }` —
* and the tool is already built by the time it reaches here, so the shape is what
* identifies it rather than the parameter that asked for it.
*/
function isProviderWebSearchTool(tool: unknown): boolean {
if (tool == null || typeof tool !== 'object') {
return false;
}
if (hasGoogleSearchTool(tool)) {
return true;
}
if (getToolName(tool) === Tools.web_search) {
return true;
}
const { type } = tool as { type?: unknown };
return typeof type === 'string' && type.startsWith(Tools.web_search);
}
/**
* Removes OpenRouter's web-search plugin from a built LLM config.
*
* OpenRouter does not receive web search as a tool — `getOpenAIConfig` encodes it
* as `modelKwargs.plugins: [{ id: 'web' }]` and pushes no tool at all — so the
* provider-tool filter has nothing to strip on that path and the plugin would
* still reach the provider for a role that was denied.
*/
function stripWebSearchPlugin(llmConfig: Record<string, unknown>): number {
const modelKwargs = llmConfig.modelKwargs as { plugins?: unknown } | undefined;
if (modelKwargs == null || !Array.isArray(modelKwargs.plugins)) {
return 0;
}
const plugins = modelKwargs.plugins as Array<{ id?: unknown }>;
const remaining = plugins.filter((plugin) => !isWebSearchPlugin(plugin));
const removed = plugins.length - remaining.length;
if (removed === 0) {
return 0;
}
if (remaining.length > 0) {
modelKwargs.plugins = remaining;
} else {
delete modelKwargs.plugins;
}
return removed;
}
function isWebSearchPlugin(plugin: unknown): boolean {
return (plugin as { id?: unknown } | null)?.id === 'web';
}
/**
* Whether a built provider config turns native web search on, as a tool or as
* OpenRouter's plugin.
*
* Read from the builder's output rather than from `model_parameters.web_search`:
* the parameter is one of several inputs — an endpoint's `defaultParams`,
* `customParams` defaults and `addParams` all reach the same switch, and
* `addParams` is applied last — so the output is the only place every route
* has already converged.
*/
function hasProviderWebSearch(
tools: unknown[] | undefined,
llmConfig: Record<string, unknown>,
): boolean {
if (tools?.some(isProviderWebSearchTool) === true) {
return true;
}
const plugins = (llmConfig.modelKwargs as { plugins?: unknown } | undefined)?.plugins;
return Array.isArray(plugins) && plugins.some(isWebSearchPlugin);
}
/**
* Resolves the `WEB_SEARCH` grant for provider-native search.
*
* A caller-supplied resolver wins, so a route that memoizes grants on its own
* request — and reaches here with `runtime` and no `req` — joins that read
* instead of issuing another. Without one, the grant is resolved for `user`
* through `db.getRoleByName`; with neither there is no role to consult.
*
* Fails closed: a resolver that throws denies.
*/
async function resolveWebSearchGrant({
req,
user,
resolve,
getRoleByName,
}: {
req?: Request;
user?: CheckAccessParams['user'] | null;
resolve?: () => Promise<boolean>;
getRoleByName?: CheckAccessParams['getRoleByName'];
}): Promise<boolean> {
try {
if (resolve != null) {
return await resolve();
}
if (getRoleByName == null) {
return true;
}
const grants = await resolveToolRoleGrants({
req,
user,
getRoleByName,
context: 'initializeAgent',
});
return grants.webSearch;
} catch {
logger.error(
`[initializeAgent][User: ${user?.id}] Failed to resolve the WEB_SEARCH grant; denying provider-native web search`,
);
return false;
}
}
function normalizeGoogleModelName(model: string): string {
const normalized = model.trim().toLowerCase();
return normalized.split('/').pop() ?? normalized;
@ -429,20 +548,30 @@ function resolveProviderToolConflicts({
provider,
tools,
toolDefinitions,
webSearchDenied = false,
}: {
provider?: string;
tools?: unknown[];
toolDefinitions?: LCTool[];
/**
* Whether the build turned native web search on for a role that denies
* `WEB_SEARCH.USE`. The built tool is stripped, which holds however the build
* was asked for it.
*/
webSearchDenied?: boolean;
}): unknown[] | undefined {
if (!tools?.length) {
return tools;
}
if (!hasToolDefinition(toolDefinitions, Tools.web_search)) {
if (!webSearchDenied && !hasToolDefinition(toolDefinitions, Tools.web_search)) {
return tools;
}
const shouldRemoveTool = (tool: unknown): boolean => {
if (webSearchDenied) {
return isProviderWebSearchTool(tool);
}
if (provider === Providers.ANTHROPIC) {
return getToolName(tool) === Tools.web_search;
}
@ -463,7 +592,9 @@ function resolveProviderToolConflicts({
if (removed > 0) {
logger.debug(
`[initializeAgent] Removed ${removed} ${provider} native web search tool(s); LibreChat web_search is enabled.`,
webSearchDenied
? `[initializeAgent] Removed ${removed} ${provider} native web search tool(s); role denies WEB_SEARCH.`
: `[initializeAgent] Removed ${removed} ${provider} native web search tool(s); LibreChat web_search is enabled.`,
);
}
@ -739,6 +870,16 @@ export interface InitializeAgentParams {
* resolved the grant keeps its current behavior.
*/
fileSearchAvailable?: boolean;
/**
* Resolves this caller's `WEB_SEARCH` role grant for provider-native web search.
* Called only when the built provider config turns native search on, so an
* agent without it costs no role read. Callers that reach `initializeAgent`
* with `runtime` and no `req` — the OpenAI-compatible and Responses routes,
* and the embedder surface in `agents/openai/service.ts` — pass one that joins
* the grants their request already memoizes. Absent, the grant is resolved
* from `db.getRoleByName`.
*/
resolveWebSearchGrant?: () => Promise<boolean>;
/**
* Whether the `run_in_background` capability is enabled for this run. When
* true, tools the agent opted in via `tool_options[name].run_in_background`
@ -876,6 +1017,9 @@ export interface InitializeAgentDbMethods extends EndpointDbMethods {
loadCodeApiKey?: TLoadCodeApiKey;
/** Optional: persist file metadata updates after provisioning */
updateFile?: (data: TFileUpdate) => Promise<unknown>;
/** Resolves a role by name for the tool role-permission grants. Optional: when
* absent the role half of the web-search gate is not applied. */
getRoleByName?: CheckAccessParams['getRoleByName'];
}
/**
@ -1789,6 +1933,19 @@ export async function initializeAgent(
});
const llmConfig = options.llmConfig as Record<string, unknown>;
const webSearchDenied =
hasProviderWebSearch(options.tools, llmConfig) &&
!(await resolveWebSearchGrant({
req: params.req as Request | undefined,
user,
resolve: params.resolveWebSearchGrant,
getRoleByName: db.getRoleByName,
}));
if (webSearchDenied && stripWebSearchPlugin(llmConfig) > 0) {
logger.debug(
`[initializeAgent] Removed the OpenRouter web search plugin; role denies WEB_SEARCH.`,
);
}
const tokensModel =
agent.provider === EModelEndpoint.azureOpenAI ? agent.model : (llmConfig?.model as string);
const maxOutputTokens = optionalChainWithEmptyCheck(
@ -2006,6 +2163,7 @@ export async function initializeAgent(
provider: agent.provider,
tools: options.tools,
toolDefinitions,
webSearchDenied,
});
const hasProviderTools = (providerTools?.length ?? 0) > 0;

View file

@ -432,6 +432,35 @@ describe('createAgentChatCompletion - MCP permission user propagation', () => {
);
});
/** Provider-native search is a model parameter with no capability of its own,
* so an embedder that omits `appConfig` still gets the role gate. */
it('wires the web search grant from the role lookup without appConfig', async () => {
const getRoleByName = jest.fn().mockResolvedValue({
name: 'USER',
permissions: { [PermissionTypes.WEB_SEARCH]: { [Permissions.USE]: false } },
});
deps.getRoleByName = getRoleByName as never;
await createAgentChatCompletion(
createMockReq({ id: 'user-123', role: 'USER' }),
createMockRes(),
deps,
);
expect(getRoleByName).not.toHaveBeenCalled();
const [[{ resolveWebSearchGrant }]] = (deps.initializeAgent as jest.Mock).mock.calls;
await expect(resolveWebSearchGrant()).resolves.toBe(false);
expect(getRoleByName).toHaveBeenCalledTimes(1);
});
it('wires no web search grant when the embedder supplies no role lookup', async () => {
await createAgentChatCompletion(createMockReq({ id: 'user-123' }), createMockRes(), deps);
expect(deps.initializeAgent).toHaveBeenCalledWith(
expect.objectContaining({ resolveWebSearchGrant: undefined }),
);
});
it('preserves stateful scope policy status and code in an initialization error response', async () => {
const policyError = Object.assign(
new Error('Stateful code environment is not allowed by this deployment: conversation'),

View file

@ -212,6 +212,12 @@ interface InitializeAgentParams {
* that priming unconditional.
*/
fileSearchAvailable?: boolean;
/**
* Resolves the `WEB_SEARCH` role grant. `initializeAgent` calls it only when an
* agent's built provider config turns native web search on, and strips that
* search when it resolves `false`.
*/
resolveWebSearchGrant?: () => Promise<boolean>;
/**
* Whether the admin-level `stateful_code_sessions` capability is enabled.
* Threaded to `initializeAgent` alongside `codeEnvAvailable` so this
@ -709,6 +715,14 @@ export async function createAgentChatCompletion(
capabilityAllowsFileSearch === true && deps.getRoleByName != null
? (await resolveToolRoleGrants({ req, getRoleByName: deps.getRoleByName })).fileSearch
: capabilityAllowsFileSearch;
/** Wired whenever the embedder supplies `getRoleByName`, independent of
* `appConfig`: provider-native web search is a model parameter with no
* capability of its own, so the role grant is its only gate. */
const { getRoleByName } = deps;
const resolveWebSearchGrant =
getRoleByName != null
? async () => (await resolveToolRoleGrants({ req, getRoleByName })).webSearch
: undefined;
/** Mirror `codeEnvAvailable` for the stateful-session gate so this route
* also carries each agent's trusted stateful endpoint/profile selection
* into tool loading and prewarming. */
@ -758,6 +772,7 @@ export async function createAgentChatCompletion(
isInitialAgent: true,
codeEnvAvailable,
fileSearchAvailable,
resolveWebSearchGrant,
statefulSessionsAvailable,
allowedStatefulCodeEnvironments,
backgroundToolsAvailable,

View file

@ -18,6 +18,7 @@ const buildRole = (overrides: Record<string, unknown> = {}) =>
permissions: {
[PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: true },
[PermissionTypes.RUN_CODE]: { [Permissions.USE]: true },
[PermissionTypes.WEB_SEARCH]: { [Permissions.USE]: true },
...overrides,
},
}) as unknown as IRole;
@ -25,9 +26,10 @@ const buildRole = (overrides: Record<string, unknown> = {}) =>
const buildReq = () => ({ user: { id: 'user_1', role: 'USER' } }) as unknown as ServerRequest;
describe('tool role permission maps', () => {
it('covers both role-gated agent tools', () => {
it('covers every role-gated agent tool', () => {
expect(toolRolePermissions[Tools.file_search]).toBe(PermissionTypes.FILE_SEARCH);
expect(toolRolePermissions[Tools.execute_code]).toBe(PermissionTypes.RUN_CODE);
expect(toolRolePermissions[Tools.web_search]).toBe(PermissionTypes.WEB_SEARCH);
});
/** The Assistants builder uploads under `code_interpreter`, not `execute_code`,
@ -295,12 +297,13 @@ describe('resolveAssistantToolPermissions', () => {
});
describe('resolveToolRoleGrants', () => {
it('reports both grants from one role read', async () => {
it('reports all three grants from one role read', async () => {
const getRoleByName = jest.fn().mockResolvedValue(buildRole());
await expect(resolveToolRoleGrants({ req: buildReq(), getRoleByName })).resolves.toEqual({
runCode: true,
fileSearch: true,
webSearch: true,
});
expect(getRoleByName).toHaveBeenCalledTimes(1);
});
@ -313,6 +316,19 @@ describe('resolveToolRoleGrants', () => {
await expect(resolveToolRoleGrants({ req: buildReq(), getRoleByName })).resolves.toEqual({
runCode: false,
fileSearch: true,
webSearch: true,
});
});
it('denies web search independently of the other two grants', async () => {
const getRoleByName = jest
.fn()
.mockResolvedValue(buildRole({ [PermissionTypes.WEB_SEARCH]: { [Permissions.USE]: false } }));
await expect(resolveToolRoleGrants({ req: buildReq(), getRoleByName })).resolves.toEqual({
runCode: true,
fileSearch: true,
webSearch: false,
});
});
@ -332,12 +348,13 @@ describe('resolveToolRoleGrants', () => {
expect(getRoleByName).toHaveBeenCalledTimes(1);
});
it('fails both grants closed when the role lookup throws', async () => {
it('fails all three grants closed when the role lookup throws', async () => {
const getRoleByName = jest.fn().mockRejectedValue(new Error('unreachable'));
await expect(resolveToolRoleGrants({ req: buildReq(), getRoleByName })).resolves.toEqual({
runCode: false,
fileSearch: false,
webSearch: false,
});
});
});

View file

@ -18,6 +18,7 @@ import { checkAccessWithRequestCache } from '../middleware/access';
export const toolRolePermissions: Partial<Record<string, PermissionTypes>> = {
[Tools.file_search]: PermissionTypes.FILE_SEARCH,
[Tools.execute_code]: PermissionTypes.RUN_CODE,
[Tools.web_search]: PermissionTypes.WEB_SEARCH,
};
/**
@ -252,34 +253,66 @@ export interface ToolRoleGrants {
runCode: boolean;
/** `FILE_SEARCH.USE` — the search tool and its uploads. */
fileSearch: boolean;
/** `WEB_SEARCH.USE` — the `web_search` tool and provider-native web search. */
webSearch: boolean;
}
export interface ResolveToolRoleGrantsParams {
req?: ServerRequest;
/**
* Whose grants to resolve. Defaults to `req.user`, which is all a route-backed
* caller needs. Callers that carry the user outside the request — the agent
* execution context, whose `runtime` is the canonical source and whose `req` is
* a compatibility adapter some routes no longer pass — supply it here, or the
* absent `req.user` would read as a denial.
*/
user?: CheckAccessParams['user'] | null;
getRoleByName: CheckAccessParams['getRoleByName'];
context?: string;
}
/**
* Resolves both tool grants for a request, once.
* Resolves all three tool grants for a request, once.
*
* Every gate on `AgentCapabilities.execute_code` / `file_search` reads its role
* half from here, so a boundary is authorized by pairing the capability with a
* field of this object rather than by repeating a permission check. The two
* lookups run together and the result is memoized on the request, so a startup
* that consults several gates — the tool loader, the agent initializer, an
* upload handler — pays one role read between them.
* Every gate on `AgentCapabilities.execute_code` / `file_search` / `web_search`
* reads its role half from here, so a boundary is authorized by pairing the
* capability with a field of this object rather than by repeating a permission
* check. The three lookups run together and the result is memoized on the
* request, so a startup that consults several gates — the tool loader, the
* agent initializer, an upload handler — pays one role read between them.
*
* Callers that want the read off their critical path can start it early without
* awaiting; the memoized promise is what later callers join.
*
* Fails closed: a missing user or a check that throws denies both.
* Fails closed: a missing user or a check that throws denies all three.
*/
export function resolveToolRoleGrants({
req,
user,
getRoleByName,
context = 'toolRoleGrants',
}: ResolveToolRoleGrantsParams): Promise<ToolRoleGrants> {
const subject = (user ?? req?.user) as CheckAccessParams['user'];
/** The three checks below read the same role. A request-backed call dedupes
* them in `checkAccess`'s per-request cache, but a caller with no `req` — the
* OpenAI-compatible and Responses routes, which carry the user on `runtime` —
* has no such cache and would issue three identical reads. Sharing one
* in-flight promise per role name makes it one read either way. */
const roleReads = new Map<string, ReturnType<typeof getRoleByName>>();
const getRoleOnce: typeof getRoleByName = (roleName, fieldsToSelect) => {
let pending = roleReads.get(roleName);
if (!pending) {
pending = Promise.resolve(getRoleByName(roleName, fieldsToSelect)).catch((error) => {
roleReads.delete(roleName);
throw error;
});
roleReads.set(roleName, pending);
}
return pending;
};
/** Keyed on the request alone, so it assumes one subject per request — true of
* every caller, since a request authorizes the user who made it. Pass no `req`
* to resolve a different subject without reading another's cached grants. */
const cache = req as
| (ServerRequest & { [toolRoleGrantsKey]?: Promise<ToolRoleGrants> })
| undefined;
@ -291,19 +324,26 @@ export function resolveToolRoleGrants({
const pending = Promise.all([
checkToolRolePermission({
req,
user: req?.user as CheckAccessParams['user'],
user: subject,
permissionType: PermissionTypes.RUN_CODE,
getRoleByName,
getRoleByName: getRoleOnce,
context,
}),
checkToolRolePermission({
req,
user: req?.user as CheckAccessParams['user'],
user: subject,
permissionType: PermissionTypes.FILE_SEARCH,
getRoleByName,
getRoleByName: getRoleOnce,
context,
}),
]).then(([runCode, fileSearch]) => ({ runCode, fileSearch }));
checkToolRolePermission({
req,
user: subject,
permissionType: PermissionTypes.WEB_SEARCH,
getRoleByName: getRoleOnce,
context,
}),
]).then(([runCode, fileSearch, webSearch]) => ({ runCode, fileSearch, webSearch }));
if (cache) {
Object.defineProperty(cache, toolRoleGrantsKey, { value: pending, enumerable: false });