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: Scope People Picker Searches to Permitted Types (#15878)

Danny Avila424d559b5ed1
diff --git a/api/server/controllers/PermissionsController.js b/api/server/controllers/PermissionsController.js
index 6bfe9028f9..fabc561093 100644
--- a/api/server/controllers/PermissionsController.js
+++ b/api/server/controllers/PermissionsController.js
@@ -7,6 +7,7 @@ const { logger, getTenantId, SYSTEM_TENANT_ID } = require('@librechat/data-schem
const { ResourceType, PrincipalType, PermissionBits } = require('librechat-data-provider');
const {
enrichRemoteAgentPrincipals,
+ createPrincipalSearch,
backfillRemoteAgentPermissions,
auditInsightsPermissionChanges,
getInsightsPrincipalState,
@@ -471,120 +472,13 @@ const getUserEffectivePermissions = async (req, res) => {
* Supports hybrid local database + Entra ID search when configured
* @route GET /api/permissions/search-principals
*/
-const searchPrincipals = async (req, res) => {
- try {
- const { q: rawQuery, limit = 20, types } = req.query;
-
- if (typeof rawQuery !== 'string' || rawQuery.trim().length === 0) {
- return res.status(400).json({
- error: 'Query parameter "q" is required and must not be empty',
- });
- }
-
- const query = rawQuery.trim();
-
- if (query.length < 2) {
- return res.status(400).json({
- error: 'Query must be at least 2 characters long',
- });
- }
-
- const searchLimit = Math.min(Math.max(1, parseInt(limit) || 10), 50);
-
- let typeFilters = null;
- if (types) {
- const typesArray = Array.isArray(types) ? types : types.split(',');
- const validTypes = typesArray.filter((t) =>
- [PrincipalType.USER, PrincipalType.GROUP, PrincipalType.ROLE].includes(t),
- );
- typeFilters = validTypes.length > 0 ? validTypes : null;
- }
-
- const localResults = await db.searchPrincipals(query, searchLimit, typeFilters);
- let allPrincipals = [...localResults];
-
- const useEntraId = entraIdPrincipalFeatureEnabled(req.user);
-
- if (useEntraId && localResults.length < searchLimit) {
- try {
- let graphType = 'all';
- if (typeFilters && typeFilters.length === 1) {
- const graphTypeMap = {
- [PrincipalType.USER]: 'users',
- [PrincipalType.GROUP]: 'groups',
- };
- const mappedType = graphTypeMap[typeFilters[0]];
- if (mappedType) {
- graphType = mappedType;
- }
- }
-
- const authHeader = req.headers.authorization;
- const accessToken =
- authHeader && authHeader.startsWith('Bearer ') ? authHeader.substring(7) : null;
-
- if (accessToken) {
- const graphResults = await searchEntraIdPrincipals(
- accessToken,
- req.user.openidId,
- query,
- graphType,
- searchLimit - localResults.length,
- );
-
- const localEmails = new Set(
- localResults.map((p) => p.email?.toLowerCase()).filter(Boolean),
- );
- const localGroupSourceIds = new Set(
- localResults.map((p) => p.idOnTheSource).filter(Boolean),
- );
-
- for (const principal of graphResults) {
- const isDuplicateByEmail =
- principal.email && localEmails.has(principal.email.toLowerCase());
- const isDuplicateBySourceId =
- principal.idOnTheSource && localGroupSourceIds.has(principal.idOnTheSource);
-
- if (!isDuplicateByEmail && !isDuplicateBySourceId) {
- allPrincipals.push(principal);
- }
- }
- }
- } catch (graphError) {
- logger.warn('Graph API search failed, falling back to local results:', graphError.message);
- }
- }
- const scoredResults = allPrincipals.map((item) => ({
- ...item,
- _searchScore: db.calculateRelevanceScore(item, query),
- }));
-
- const finalResults = db
- .sortPrincipalsByRelevance(scoredResults)
- .slice(0, searchLimit)
- .map((result) => {
- const { _searchScore, ...resultWithoutScore } = result;
- return resultWithoutScore;
- });
-
- res.status(200).json({
- query,
- limit: searchLimit,
- types: typeFilters,
- results: finalResults,
- count: finalResults.length,
- sources: {
- local: finalResults.filter((r) => r.source === 'local').length,
- entra: finalResults.filter((r) => r.source === 'entra').length,
- },
- });
- } catch (error) {
- logger.error('Error searching principals:', error);
- res.status(500).json({
- error: 'Failed to search principals',
- });
- }
-};
+const searchPrincipals = createPrincipalSearch({
+ searchPrincipals: db.searchPrincipals,
+ calculateRelevanceScore: db.calculateRelevanceScore,
+ sortPrincipalsByRelevance: db.sortPrincipalsByRelevance,
+ entraIdPrincipalFeatureEnabled,
+ searchEntraIdPrincipals,
+});
/**
* Get user's effective permissions for all accessible resources of a type
diff --git a/api/server/controllers/__tests__/PermissionsController.spec.js b/api/server/controllers/__tests__/PermissionsController.spec.js
index 2a578b75e7..0b83041a56 100644
--- a/api/server/controllers/__tests__/PermissionsController.spec.js
+++ b/api/server/controllers/__tests__/PermissionsController.spec.js
@@ -9,8 +9,9 @@ jest.mock('@librechat/data-schemas', () => ({
SYSTEM_TENANT_ID: '__SYSTEM__',
}));
-const { AccessRoleIds, ResourceType, PrincipalType, SystemRoles } =
+const { AccessRoleIds, ResourceType, PrincipalType, SystemRoles, PermissionTypes, Permissions } =
jest.requireActual('librechat-data-provider');
+const { createPeoplePickerAccess } = jest.requireActual('@librechat/api');
jest.mock('librechat-data-provider', () => ({
...jest.requireActual('librechat-data-provider'),
@@ -100,68 +101,32 @@ describe('PermissionsController', () => {
db.sortPrincipalsByRelevance.mockImplementation((results) => results);
});
- it('rejects non-string query parameters', async () => {
- const req = createMockReq({
- query: { q: ['alice'] },
- });
- const res = createMockRes();
-
- await searchPrincipals(req, res);
-
- expect(res.status).toHaveBeenCalledWith(400);
- expect(res.json).toHaveBeenCalledWith({
- error: 'Query parameter "q" is required and must not be empty',
- });
- expect(db.searchPrincipals).not.toHaveBeenCalled();
- });
-
- it('searches with the trimmed literal query', async () => {
- db.searchPrincipals.mockResolvedValue([
- {
- id: 'user-1',
- type: PrincipalType.USER,
- name: 'Regex [invalid User',
- source: 'local',
- },
- ]);
-
- const req = createMockReq({
- query: { q: ' [invalid ', limit: '5', types: PrincipalType.USER },
- });
- const res = createMockRes();
-
- await searchPrincipals(req, res);
-
- expect(db.searchPrincipals).toHaveBeenCalledWith('[invalid', 5, [PrincipalType.USER]);
- expect(db.calculateRelevanceScore).toHaveBeenCalledWith(
- expect.objectContaining({ name: 'Regex [invalid User' }),
- '[invalid',
- );
- expect(res.status).toHaveBeenCalledWith(200);
- expect(res.json).toHaveBeenCalledWith(
- expect.objectContaining({
- query: '[invalid',
- limit: 5,
- count: 1,
- }),
- );
- });
-
- it('does not expose internal error details on search failures', async () => {
- db.searchPrincipals.mockRejectedValue(new Error('database failure with internal detail'));
-
- const req = createMockReq({
- query: { q: 'alice' },
- });
- const res = createMockRes();
-
- await searchPrincipals(req, res);
-
- expect(res.status).toHaveBeenCalledWith(500);
- expect(res.json).toHaveBeenCalledWith({
- error: 'Failed to search principals',
- });
- });
+ it.each([{ q: 'al', type: PrincipalType.GROUP }, { q: 'al', types: 'foobar' }, { q: 'al' }])(
+ 'searches only the types the people picker check resolved for %j',
+ async (query) => {
+ const checkAccess = createPeoplePickerAccess({
+ getRoleByName: async () => ({
+ permissions: {
+ [PermissionTypes.PEOPLE_PICKER]: {
+ [Permissions.VIEW_USERS]: false,
+ [Permissions.VIEW_GROUPS]: true,
+ [Permissions.VIEW_ROLES]: false,
+ },
+ },
+ }),
+ });
+ const req = createMockReq({ query });
+ const res = createMockRes();
+
+ await checkAccess(req, res, () => searchPrincipals(req, res));
+
+ expect(db.searchPrincipals).toHaveBeenCalledWith('al', 20, [PrincipalType.GROUP]);
+ expect(res.status).toHaveBeenCalledWith(200);
+ expect(res.json).toHaveBeenCalledWith(
+ expect.objectContaining({ types: [PrincipalType.GROUP] }),
+ );
+ },
+ );
});
describe('getResourcePermissions — principal details', () => {
diff --git a/api/server/middleware/checkPeoplePickerAccess.js b/api/server/middleware/checkPeoplePickerAccess.js
index 83329f56a3..016c35f082 100644
--- a/api/server/middleware/checkPeoplePickerAccess.js
+++ b/api/server/middleware/checkPeoplePickerAccess.js
@@ -1,114 +1,7 @@
-const { logger } = require('@librechat/data-schemas');
-const {
- PrincipalType,
- PermissionTypes,
- Permissions,
- SystemRoles,
-} = require('librechat-data-provider');
+const { createPeoplePickerAccess } = require('@librechat/api');
const { getRoleByName } = require('~/models');
-const VALID_PRINCIPAL_TYPES = new Set([
- PrincipalType.USER,
- PrincipalType.GROUP,
- PrincipalType.ROLE,
-]);
-
-/**
- * Middleware to check if user has permission to access people picker functionality.
- * Validates requested principal types via `type` (singular) and `types` (comma-separated or array)
- * query parameters against the caller's role permissions:
- * - user: requires VIEW_USERS permission
- * - group: requires VIEW_GROUPS permission
- * - role: requires VIEW_ROLES permission
- * - no type filter (mixed search): requires at least one of the above
- */
-const checkPeoplePickerAccess = async (req, res, next) => {
- try {
- const user = req.user;
- if (!user || !user.role) {
- return res.status(401).json({
- error: 'Unauthorized',
- message: 'Authentication required',
- });
- }
-
- if (user.role === SystemRoles.ADMIN) {
- return next();
- }
-
- const role = await getRoleByName(user.role);
- if (!role || !role.permissions) {
- return res.status(403).json({
- error: 'Forbidden',
- message: 'No permissions configured for user role',
- });
- }
-
- const { type, types } = req.query;
- const peoplePickerPerms = role.permissions[PermissionTypes.PEOPLE_PICKER] || {};
- const canViewUsers = peoplePickerPerms[Permissions.VIEW_USERS] === true;
- const canViewGroups = peoplePickerPerms[Permissions.VIEW_GROUPS] === true;
- const canViewRoles = peoplePickerPerms[Permissions.VIEW_ROLES] === true;
-
- const permissionChecks = {
- [PrincipalType.USER]: {
- hasPermission: canViewUsers,
- message: 'Insufficient permissions to search for users',
- },
- [PrincipalType.GROUP]: {
- hasPermission: canViewGroups,
- message: 'Insufficient permissions to search for groups',
- },
- [PrincipalType.ROLE]: {
- hasPermission: canViewRoles,
- message: 'Insufficient permissions to search for roles',
- },
- };
-
- const requestedTypes = new Set();
-
- if (type && VALID_PRINCIPAL_TYPES.has(type)) {
- requestedTypes.add(type);
- }
-
- if (types) {
- const typesArray = Array.isArray(types) ? types : types.split(',');
- for (const t of typesArray) {
- if (VALID_PRINCIPAL_TYPES.has(t)) {
- requestedTypes.add(t);
- }
- }
- }
-
- for (const requested of requestedTypes) {
- const check = permissionChecks[requested];
- if (!check.hasPermission) {
- return res.status(403).json({
- error: 'Forbidden',
- message: check.message,
- });
- }
- }
-
- if (requestedTypes.size === 0 && !canViewUsers && !canViewGroups && !canViewRoles) {
- return res.status(403).json({
- error: 'Forbidden',
- message: 'Insufficient permissions to search for users, groups, or roles',
- });
- }
-
- next();
- } catch (error) {
- logger.error(
- `[checkPeoplePickerAccess][${req.user?.id}] error for type=${req.query.type}, types=${req.query.types}`,
- error,
- );
- return res.status(500).json({
- error: 'Internal Server Error',
- message: 'Failed to check permissions',
- });
- }
-};
+const checkPeoplePickerAccess = createPeoplePickerAccess({ getRoleByName });
module.exports = {
checkPeoplePickerAccess,
diff --git a/api/server/middleware/checkPeoplePickerAccess.spec.js b/api/server/middleware/checkPeoplePickerAccess.spec.js
deleted file mode 100644
index 45097ef290..0000000000
--- a/api/server/middleware/checkPeoplePickerAccess.spec.js
+++ /dev/null
@@ -1,431 +0,0 @@
-const { logger } = require('@librechat/data-schemas');
-const {
- PrincipalType,
- PermissionTypes,
- Permissions,
- SystemRoles,
-} = require('librechat-data-provider');
-const { checkPeoplePickerAccess } = require('./checkPeoplePickerAccess');
-const { getRoleByName } = require('~/models');
-
-jest.mock('~/models');
-jest.mock('@librechat/data-schemas', () => ({
- ...jest.requireActual('@librechat/data-schemas'),
- logger: {
- error: jest.fn(),
- },
-}));
-
-describe('checkPeoplePickerAccess', () => {
- let req, res, next;
-
- beforeEach(() => {
- req = {
- user: { id: 'user123', role: 'USER' },
- query: {},
- };
- res = {
- status: jest.fn().mockReturnThis(),
- json: jest.fn(),
- };
- next = jest.fn();
- jest.clearAllMocks();
- });
-
- it('should return 401 if user is not authenticated', async () => {
- req.user = null;
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(res.status).toHaveBeenCalledWith(401);
- expect(res.json).toHaveBeenCalledWith({
- error: 'Unauthorized',
- message: 'Authentication required',
- });
- expect(next).not.toHaveBeenCalled();
- });
-
- it('should return 403 if role has no permissions', async () => {
- getRoleByName.mockResolvedValue(null);
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(res.status).toHaveBeenCalledWith(403);
- expect(res.json).toHaveBeenCalledWith({
- error: 'Forbidden',
- message: 'No permissions configured for user role',
- });
- expect(next).not.toHaveBeenCalled();
- });
-
- it('allows a literal admin regardless of configured people picker permissions', async () => {
- req.user.role = SystemRoles.ADMIN;
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(next).toHaveBeenCalled();
- expect(getRoleByName).not.toHaveBeenCalled();
- expect(res.status).not.toHaveBeenCalled();
- });
-
- it('should allow access when searching for users with VIEW_USERS permission', async () => {
- req.query.type = PrincipalType.USER;
- getRoleByName.mockResolvedValue({
- permissions: {
- [PermissionTypes.PEOPLE_PICKER]: {
- [Permissions.VIEW_USERS]: true,
- [Permissions.VIEW_GROUPS]: false,
- [Permissions.VIEW_ROLES]: false,
- },
- },
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(next).toHaveBeenCalled();
- expect(res.status).not.toHaveBeenCalled();
- });
-
- it('should deny access when searching for users without VIEW_USERS permission', async () => {
- req.query.type = PrincipalType.USER;
- getRoleByName.mockResolvedValue({
- permissions: {
- [PermissionTypes.PEOPLE_PICKER]: {
- [Permissions.VIEW_USERS]: false,
- [Permissions.VIEW_GROUPS]: true,
- [Permissions.VIEW_ROLES]: true,
- },
- },
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(res.status).toHaveBeenCalledWith(403);
- expect(res.json).toHaveBeenCalledWith({
- error: 'Forbidden',
- message: 'Insufficient permissions to search for users',
- });
- expect(next).not.toHaveBeenCalled();
- });
-
- it('should allow access when searching for groups with VIEW_GROUPS permission', async () => {
- req.query.type = PrincipalType.GROUP;
- getRoleByName.mockResolvedValue({
- permissions: {
- [PermissionTypes.PEOPLE_PICKER]: {
- [Permissions.VIEW_USERS]: false,
- [Permissions.VIEW_GROUPS]: true,
- [Permissions.VIEW_ROLES]: false,
- },
- },
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(next).toHaveBeenCalled();
- expect(res.status).not.toHaveBeenCalled();
- });
-
- it('should deny access when searching for groups without VIEW_GROUPS permission', async () => {
- req.query.type = PrincipalType.GROUP;
- getRoleByName.mockResolvedValue({
- permissions: {
- [PermissionTypes.PEOPLE_PICKER]: {
- [Permissions.VIEW_USERS]: true,
- [Permissions.VIEW_GROUPS]: false,
- [Permissions.VIEW_ROLES]: true,
- },
- },
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(res.status).toHaveBeenCalledWith(403);
- expect(res.json).toHaveBeenCalledWith({
- error: 'Forbidden',
- message: 'Insufficient permissions to search for groups',
- });
- expect(next).not.toHaveBeenCalled();
- });
-
- it('should allow access when searching for roles with VIEW_ROLES permission', async () => {
- req.query.type = PrincipalType.ROLE;
- getRoleByName.mockResolvedValue({
- permissions: {
- [PermissionTypes.PEOPLE_PICKER]: {
- [Permissions.VIEW_USERS]: false,
- [Permissions.VIEW_GROUPS]: false,
- [Permissions.VIEW_ROLES]: true,
- },
- },
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(next).toHaveBeenCalled();
- expect(res.status).not.toHaveBeenCalled();
- });
-
- it('should deny access when searching for roles without VIEW_ROLES permission', async () => {
- req.query.type = PrincipalType.ROLE;
- getRoleByName.mockResolvedValue({
- permissions: {
- [PermissionTypes.PEOPLE_PICKER]: {
- [Permissions.VIEW_USERS]: true,
- [Permissions.VIEW_GROUPS]: true,
- [Permissions.VIEW_ROLES]: false,
- },
- },
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(res.status).toHaveBeenCalledWith(403);
- expect(res.json).toHaveBeenCalledWith({
- error: 'Forbidden',
- message: 'Insufficient permissions to search for roles',
- });
- expect(next).not.toHaveBeenCalled();
- });
-
- it('should deny access when using types param to bypass type-specific check', async () => {
- req.query.types = PrincipalType.GROUP;
- getRoleByName.mockResolvedValue({
- permissions: {
- [PermissionTypes.PEOPLE_PICKER]: {
- [Permissions.VIEW_USERS]: true,
- [Permissions.VIEW_GROUPS]: false,
- [Permissions.VIEW_ROLES]: false,
- },
- },
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(res.status).toHaveBeenCalledWith(403);
- expect(res.json).toHaveBeenCalledWith({
- error: 'Forbidden',
- message: 'Insufficient permissions to search for groups',
- });
- expect(next).not.toHaveBeenCalled();
- });
-
- it('should deny access when types contains any unpermitted type', async () => {
- req.query.types = `${PrincipalType.USER},${PrincipalType.ROLE}`;
- getRoleByName.mockResolvedValue({
- permissions: {
- [PermissionTypes.PEOPLE_PICKER]: {
- [Permissions.VIEW_USERS]: true,
- [Permissions.VIEW_GROUPS]: false,
- [Permissions.VIEW_ROLES]: false,
- },
- },
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(res.status).toHaveBeenCalledWith(403);
- expect(res.json).toHaveBeenCalledWith({
- error: 'Forbidden',
- message: 'Insufficient permissions to search for roles',
- });
- expect(next).not.toHaveBeenCalled();
- });
-
- it('should allow access when all requested types are permitted', async () => {
- req.query.types = `${PrincipalType.USER},${PrincipalType.GROUP}`;
- getRoleByName.mockResolvedValue({
- permissions: {
- [PermissionTypes.PEOPLE_PICKER]: {
- [Permissions.VIEW_USERS]: true,
- [Permissions.VIEW_GROUPS]: true,
- [Permissions.VIEW_ROLES]: false,
- },
- },
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(next).toHaveBeenCalled();
- expect(res.status).not.toHaveBeenCalled();
- });
-
- it('should validate types when provided as array (Express qs parsing)', async () => {
- req.query.types = [PrincipalType.GROUP, PrincipalType.ROLE];
- getRoleByName.mockResolvedValue({
- permissions: {
- [PermissionTypes.PEOPLE_PICKER]: {
- [Permissions.VIEW_USERS]: true,
- [Permissions.VIEW_GROUPS]: false,
- [Permissions.VIEW_ROLES]: true,
- },
- },
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(res.status).toHaveBeenCalledWith(403);
- expect(res.json).toHaveBeenCalledWith({
- error: 'Forbidden',
- message: 'Insufficient permissions to search for groups',
- });
- expect(next).not.toHaveBeenCalled();
- });
-
- it('should enforce permissions for combined type and types params', async () => {
- req.query.type = PrincipalType.USER;
- req.query.types = PrincipalType.GROUP;
- getRoleByName.mockResolvedValue({
- permissions: {
- [PermissionTypes.PEOPLE_PICKER]: {
- [Permissions.VIEW_USERS]: true,
- [Permissions.VIEW_GROUPS]: false,
- [Permissions.VIEW_ROLES]: false,
- },
- },
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(res.status).toHaveBeenCalledWith(403);
- expect(res.json).toHaveBeenCalledWith({
- error: 'Forbidden',
- message: 'Insufficient permissions to search for groups',
- });
- expect(next).not.toHaveBeenCalled();
- });
-
- it('should treat all-invalid types values as mixed search', async () => {
- req.query.types = 'foobar';
- getRoleByName.mockResolvedValue({
- permissions: {
- [PermissionTypes.PEOPLE_PICKER]: {
- [Permissions.VIEW_USERS]: true,
- [Permissions.VIEW_GROUPS]: false,
- [Permissions.VIEW_ROLES]: false,
- },
- },
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(next).toHaveBeenCalled();
- expect(res.status).not.toHaveBeenCalled();
- });
-
- it('should deny when types is empty string and user has no permissions', async () => {
- req.query.types = '';
- getRoleByName.mockResolvedValue({
- permissions: {
- [PermissionTypes.PEOPLE_PICKER]: {
- [Permissions.VIEW_USERS]: false,
- [Permissions.VIEW_GROUPS]: false,
- [Permissions.VIEW_ROLES]: false,
- },
- },
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(res.status).toHaveBeenCalledWith(403);
- expect(res.json).toHaveBeenCalledWith({
- error: 'Forbidden',
- message: 'Insufficient permissions to search for users, groups, or roles',
- });
- expect(next).not.toHaveBeenCalled();
- });
-
- it('should treat types=public as mixed search since PUBLIC is not a searchable principal type', async () => {
- req.query.types = PrincipalType.PUBLIC;
- getRoleByName.mockResolvedValue({
- permissions: {
- [PermissionTypes.PEOPLE_PICKER]: {
- [Permissions.VIEW_USERS]: true,
- [Permissions.VIEW_GROUPS]: false,
- [Permissions.VIEW_ROLES]: false,
- },
- },
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(next).toHaveBeenCalled();
- expect(res.status).not.toHaveBeenCalled();
- });
-
- it('should allow mixed search when user has at least one permission', async () => {
- // No type specified = mixed search
- req.query.type = undefined;
- getRoleByName.mockResolvedValue({
- permissions: {
- [PermissionTypes.PEOPLE_PICKER]: {
- [Permissions.VIEW_USERS]: false,
- [Permissions.VIEW_GROUPS]: false,
- [Permissions.VIEW_ROLES]: true,
- },
- },
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(next).toHaveBeenCalled();
- expect(res.status).not.toHaveBeenCalled();
- });
-
- it('should deny mixed search when user has no permissions', async () => {
- // No type specified = mixed search
- req.query.type = undefined;
- getRoleByName.mockResolvedValue({
- permissions: {
- [PermissionTypes.PEOPLE_PICKER]: {
- [Permissions.VIEW_USERS]: false,
- [Permissions.VIEW_GROUPS]: false,
- [Permissions.VIEW_ROLES]: false,
- },
- },
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(res.status).toHaveBeenCalledWith(403);
- expect(res.json).toHaveBeenCalledWith({
- error: 'Forbidden',
- message: 'Insufficient permissions to search for users, groups, or roles',
- });
- expect(next).not.toHaveBeenCalled();
- });
-
- it('should handle errors gracefully', async () => {
- const error = new Error('Database error');
- getRoleByName.mockRejectedValue(error);
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(logger.error).toHaveBeenCalledWith(
- '[checkPeoplePickerAccess][user123] error for type=undefined, types=undefined',
- error,
- );
- expect(res.status).toHaveBeenCalledWith(500);
- expect(res.json).toHaveBeenCalledWith({
- error: 'Internal Server Error',
- message: 'Failed to check permissions',
- });
- expect(next).not.toHaveBeenCalled();
- });
-
- it('should handle missing permissions object gracefully', async () => {
- req.query.type = PrincipalType.USER;
- getRoleByName.mockResolvedValue({
- permissions: {}, // No PEOPLE_PICKER permissions
- });
-
- await checkPeoplePickerAccess(req, res, next);
-
- expect(res.status).toHaveBeenCalledWith(403);
- expect(res.json).toHaveBeenCalledWith({
- error: 'Forbidden',
- message: 'Insufficient permissions to search for users',
- });
- expect(next).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/api/src/acl/search.spec.ts b/packages/api/src/acl/search.spec.ts
new file mode 100644
index 0000000000..65541c3bf3
--- /dev/null
+++ b/packages/api/src/acl/search.spec.ts
@@ -0,0 +1,461 @@
+import { logger } from '@librechat/data-schemas';
+import { Permissions, SystemRoles, PrincipalType, PermissionTypes } from 'librechat-data-provider';
+import type { TPrincipalSearchResult } from 'librechat-data-provider';
+import type { Response } from 'express';
+import type {
+ PrincipalSearchDeps,
+ PrincipalSearchRequest,
+ SearchablePrincipalType,
+} from './search';
+import {
+ createPrincipalSearch,
+ createPeoplePickerAccess,
+ getRequestedPrincipalTypes,
+ getEntraPrincipalSearchType,
+} from './search';
+
+type PickerPermissions = {
+ [Permissions.VIEW_USERS]?: boolean;
+ [Permissions.VIEW_GROUPS]?: boolean;
+ [Permissions.VIEW_ROLES]?: boolean;
+};
+
+type Query = PrincipalSearchRequest['query'];
+
+const { USER, GROUP, ROLE } = PrincipalType;
+
+const permissionsFor = (types: SearchablePrincipalType[]): PickerPermissions => ({
+ [Permissions.VIEW_USERS]: types.includes(USER),
+ [Permissions.VIEW_GROUPS]: types.includes(GROUP),
+ [Permissions.VIEW_ROLES]: types.includes(ROLE),
+});
+
+const setup = ({
+ query = {},
+ role = SystemRoles.USER,
+ picker,
+ getRoleByName = jest.fn(async () => ({
+ permissions: picker ? { [PermissionTypes.PEOPLE_PICKER]: picker } : {},
+ })),
+}: {
+ query?: Query;
+ role?: string | null;
+ picker?: PickerPermissions;
+ getRoleByName?: jest.Mock;
+}) => {
+ const req = { user: role ? { id: 'user123', role } : undefined, query } as PrincipalSearchRequest;
+ const res = { status: jest.fn().mockReturnThis(), json: jest.fn() };
+ const next = jest.fn();
+ const middleware = createPeoplePickerAccess({ getRoleByName });
+ return {
+ req,
+ res,
+ next,
+ getRoleByName,
+ run: () => middleware(req, res as unknown as Response, next),
+ };
+};
+
+const outcomeOf = ({ req, res, next }: ReturnType<typeof setup>) => ({
+ status: res.status.mock.calls[0]?.[0],
+ body: res.json.mock.calls[0]?.[0],
+ nextCalls: next.mock.calls.length,
+ types: req.principalSearchTypes,
+});
+
+const forbidden = (message: string) => ({
+ status: 403,
+ body: { error: 'Forbidden', message },
+ nextCalls: 0,
+ types: undefined,
+});
+
+const allowed = (types: SearchablePrincipalType[]) => ({
+ status: undefined,
+ body: undefined,
+ nextCalls: 1,
+ types,
+});
+
+describe('getRequestedPrincipalTypes', () => {
+ it.each([
+ [{}, []],
+ [{ type: GROUP }, [GROUP]],
+ [{ types: `${USER},${ROLE}` }, [USER, ROLE]],
+ [{ types: [GROUP, `${ROLE},${USER}`] }, [GROUP, ROLE, USER]],
+ [{ type: USER, types: `${GROUP},${USER}` }, [USER, GROUP]],
+ [{ types: `${PrincipalType.PUBLIC},foobar,` }, []],
+ [{ types: { nested: USER } }, []],
+ [{ type: [{ nested: USER }] }, []],
+ ])('reads %j as %j', (query, expected) => {
+ expect(getRequestedPrincipalTypes(query)).toEqual(expected);
+ });
+});
+
+describe('getEntraPrincipalSearchType', () => {
+ it.each([
+ [[USER, GROUP, ROLE], 'all'],
+ [[USER, GROUP], 'all'],
+ [[USER, ROLE], 'users'],
+ [[USER], 'users'],
+ [[GROUP, ROLE], 'groups'],
+ [[GROUP], 'groups'],
+ [[ROLE], null],
+ [[], null],
+ ])('maps %j to %s', (types, expected) => {
+ expect(getEntraPrincipalSearchType(types as SearchablePrincipalType[])).toBe(expected);
+ });
+});
+
+describe('createPeoplePickerAccess', () => {
+ it('returns 401 if user is not authenticated', async () => {
+ const test = setup({ role: null });
+ await test.run();
+
+ expect(test.res.status).toHaveBeenCalledWith(401);
+ expect(test.res.json).toHaveBeenCalledWith({
+ error: 'Unauthorized',
+ message: 'Authentication required',
+ });
+ expect(test.next).not.toHaveBeenCalled();
+ });
+
+ it('returns 403 if role has no permissions', async () => {
+ const test = setup({ getRoleByName: jest.fn(async () => null) });
+ await test.run();
+
+ expect(outcomeOf(test)).toEqual(forbidden('No permissions configured for user role'));
+ });
+
+ it('allows a literal admin every type without loading the role', async () => {
+ const test = setup({ role: SystemRoles.ADMIN });
+ await test.run();
+
+ expect(outcomeOf(test)).toEqual(allowed([USER, GROUP, ROLE]));
+ expect(test.getRoleByName).not.toHaveBeenCalled();
+ });
+
+ it('narrows a literal admin search to the requested types', async () => {
+ const test = setup({ role: SystemRoles.ADMIN, query: { type: GROUP } });
+ await test.run();
+
+ expect(outcomeOf(test)).toEqual(allowed([GROUP]));
+ });
+
+ it.each<[Query, SearchablePrincipalType[], SearchablePrincipalType[]]>([
+ [{ type: USER }, [USER], [USER]],
+ [{ type: GROUP }, [GROUP], [GROUP]],
+ [{ type: ROLE }, [ROLE], [ROLE]],
+ [{ types: `${USER},${GROUP}` }, [USER, GROUP], [USER, GROUP]],
+ [{ types: GROUP }, [GROUP, ROLE], [GROUP]],
+ ])('allows %j for a role permitting %j', async (query, permitted, expected) => {
+ const test = setup({ query, picker: permissionsFor(permitted) });
+ await test.run();
+
+ expect(outcomeOf(test)).toEqual(allowed(expected));
+ });
+
+ it.each<[Query, SearchablePrincipalType[], string]>([
+ [{ type: USER }, [GROUP, ROLE], 'users'],
+ [{ type: GROUP }, [USER, ROLE], 'groups'],
+ [{ type: ROLE }, [USER, GROUP], 'roles'],
+ [{ types: GROUP }, [USER], 'groups'],
+ [{ types: `${USER},${ROLE}` }, [USER], 'roles'],
+ [{ types: [GROUP, ROLE] }, [USER, ROLE], 'groups'],
+ [{ type: USER, types: GROUP }, [USER], 'groups'],
+ [{ type: USER }, [], 'users'],
+ ])('denies %j for a role permitting %j', async (query, permitted, label) => {
+ const test = setup({ query, picker: permissionsFor(permitted) });
+ await test.run();
+
+ expect(outcomeOf(test)).toEqual(forbidden(`Insufficient permissions to search for ${label}`));
+ });
+
+ it.each<[Query, SearchablePrincipalType[]]>([
+ [{}, [GROUP]],
+ [{}, [ROLE]],
+ [{}, [USER, ROLE]],
+ [{}, [USER, GROUP, ROLE]],
+ [{ types: '' }, [GROUP]],
+ [{ types: 'foobar' }, [USER]],
+ [{ types: PrincipalType.PUBLIC }, [GROUP, ROLE]],
+ [{ types: { nested: USER } }, [GROUP]],
+ ])(
+ 'limits an unfiltered search %j to the %j types the role permits',
+ async (query, permitted) => {
+ const test = setup({ query, picker: permissionsFor(permitted) });
+ await test.run();
+
+ expect(outcomeOf(test)).toEqual(allowed(permitted));
+ },
+ );
+
+ it.each([{}, { types: '' }, { types: 'foobar' }])(
+ 'denies an unfiltered search %j when the role permits no types',
+ async (query) => {
+ const test = setup({ query, picker: permissionsFor([]) });
+ await test.run();
+
+ expect(outcomeOf(test)).toEqual(
+ forbidden('Insufficient permissions to search for users, groups, or roles'),
+ );
+ },
+ );
+
+ it('denies a requested type when the role has no people picker permissions', async () => {
+ const test = setup({ query: { type: USER } });
+ await test.run();
+
+ expect(outcomeOf(test)).toEqual(forbidden('Insufficient permissions to search for users'));
+ });
+
+ it('handles errors gracefully', async () => {
+ const error = new Error('Database error');
+ const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => logger);
+ const test = setup({ getRoleByName: jest.fn().mockRejectedValue(error) });
+ await test.run();
+
+ expect(errorSpy).toHaveBeenCalledWith(
+ '[checkPeoplePickerAccess][user123] error for type=undefined, types=undefined',
+ error,
+ );
+ expect(test.res.status).toHaveBeenCalledWith(500);
+ expect(test.res.json).toHaveBeenCalledWith({
+ error: 'Internal Server Error',
+ message: 'Failed to check permissions',
+ });
+ expect(test.next).not.toHaveBeenCalled();
+ errorSpy.mockRestore();
+ });
+});
+
+describe('createPrincipalSearch', () => {
+ type ScoredResults = Parameters<PrincipalSearchDeps['sortPrincipalsByRelevance']>[0];
+
+ const principal = (overrides: Partial<TPrincipalSearchResult>): TPrincipalSearchResult => ({
+ type: USER,
+ name: 'Principal',
+ source: 'local',
+ ...overrides,
+ });
+
+ const setupSearch = ({
+ query = { q: 'alice' },
+ types,
+ entraEnabled = false,
+ authorization = 'Bearer token',
+ localResults = [],
+ entraResults = [],
+ }: {
+ query?: Query;
+ types?: SearchablePrincipalType[];
+ entraEnabled?: boolean;
+ authorization?: string;
+ localResults?: TPrincipalSearchResult[];
+ entraResults?: TPrincipalSearchResult[];
+ }) => {
+ const deps = {
+ searchPrincipals: jest.fn(async () => localResults),
+ calculateRelevanceScore: jest.fn((item: TPrincipalSearchResult) => item.name.length),
+ sortPrincipalsByRelevance: jest.fn((results: ScoredResults) =>
+ [...results].sort((a, b) => b._searchScore - a._searchScore),
+ ),
+ entraIdPrincipalFeatureEnabled: jest.fn(() => entraEnabled),
+ searchEntraIdPrincipals: jest.fn(async () => entraResults),
+ };
+ const req = {
+ query,
+ headers: { authorization },
+ user: { id: 'user123', role: SystemRoles.USER, openidId: 'oid-1' },
+ principalSearchTypes: types,
+ } as PrincipalSearchRequest;
+ const res = { status: jest.fn().mockReturnThis(), json: jest.fn() };
+ const search = createPrincipalSearch(deps);
+ return { deps, req, res, run: () => search(req, res as unknown as Response) };
+ };
+
+ it.each([{}, { q: ['alice'] }, { q: ' ' }])('rejects the query %j', async (query) => {
+ const test = setupSearch({ query, types: [USER] });
+ await test.run();
+
+ expect(test.res.status).toHaveBeenCalledWith(400);
+ expect(test.res.json).toHaveBeenCalledWith({
+ error: 'Query parameter "q" is required and must not be empty',
+ });
+ expect(test.deps.searchPrincipals).not.toHaveBeenCalled();
+ });
+
+ it('rejects a one-character query', async () => {
+ const test = setupSearch({ query: { q: ' a ' }, types: [USER] });
+ await test.run();
+
+ expect(test.res.status).toHaveBeenCalledWith(400);
+ expect(test.res.json).toHaveBeenCalledWith({
+ error: 'Query must be at least 2 characters long',
+ });
+ expect(test.deps.searchPrincipals).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [undefined, 20],
+ ['5', 5],
+ ['500', 50],
+ ['0', 10],
+ ['-3', 1],
+ ['abc', 10],
+ ])('searches the trimmed literal query with limit %s as %d', async (limit, expected) => {
+ const test = setupSearch({ query: { q: ' [invalid ', limit }, types: [USER] });
+ await test.run();
+
+ expect(test.deps.searchPrincipals).toHaveBeenCalledWith('[invalid', expected, [USER]);
+ expect(test.res.status).toHaveBeenCalledWith(200);
+ expect(test.res.json).toHaveBeenCalledWith(
+ expect.objectContaining({ query: '[invalid', limit: expected }),
+ );
+ });
+
+ it('searches only the resolved types, ignoring the query filter', async () => {
+ const test = setupSearch({ query: { q: 'alice', type: USER, types: USER }, types: [GROUP] });
+ await test.run();
+
+ expect(test.deps.searchPrincipals).toHaveBeenCalledWith('alice', 20, [GROUP]);
+ expect(test.res.json).toHaveBeenCalledWith(expect.objectContaining({ types: [GROUP] }));
+ });
+
+ it('searches no types when the access check did not run', async () => {
+ const test = setupSearch({ query: { q: 'alice', types: USER }, entraEnabled: true });
+ await test.run();
+
+ expect(test.deps.searchPrincipals).toHaveBeenCalledWith('alice', 20, []);
+ expect(test.deps.searchEntraIdPrincipals).not.toHaveBeenCalled();
+ expect(test.res.status).toHaveBeenCalledWith(200);
+ });
+
+ it.each<[SearchablePrincipalType[], string | null]>([
+ [[USER, GROUP, ROLE], 'all'],
+ [[USER, ROLE], 'users'],
+ [[GROUP, ROLE], 'groups'],
+ [[ROLE], null],
+ ])('scopes the Entra ID search for %j to %s', async (types, graphType) => {
+ const test = setupSearch({
+ types,
+ entraEnabled: true,
+ localResults: [principal({ name: 'Alice Local', email: '[email protected]' })],
+ });
+ await test.run();
+
+ if (graphType) {
+ expect(test.deps.searchEntraIdPrincipals).toHaveBeenCalledWith(
+ 'token',
+ 'oid-1',
+ 'alice',
+ graphType,
+ 19,
+ );
+ } else {
+ expect(test.deps.searchEntraIdPrincipals).not.toHaveBeenCalled();
+ }
+ expect(test.res.status).toHaveBeenCalledWith(200);
+ });
+
+ it.each([
+ ['Entra ID search is disabled', { entraEnabled: false }],
+ ['there is no bearer token', { authorization: 'Basic token' }],
+ [
+ 'local results fill the limit',
+ { query: { q: 'alice', limit: '1' }, localResults: [principal({ name: 'Alice' })] },
+ ],
+ ])('skips Entra ID search when %s', async (_case, overrides) => {
+ const test = setupSearch({ types: [USER, GROUP], entraEnabled: true, ...overrides });
+ await test.run();
+
+ expect(test.deps.searchEntraIdPrincipals).not.toHaveBeenCalled();
+ expect(test.res.status).toHaveBeenCalledWith(200);
+ });
+
+ it('merges new Entra ID principals, ranks them, and counts sources', async () => {
+ const test = setupSearch({
+ types: [USER, GROUP],
+ entraEnabled: true,
+ localResults: [
+ principal({ name: 'Alice', email: '[email protected]' }),
+ principal({ type: GROUP, name: 'Admins', idOnTheSource: 'group-1' }),
+ ],
+ entraResults: [
+ principal({ name: 'Alice Entra', email: '[email protected]', source: 'entra' }),
+ principal({ type: GROUP, name: 'Admins Entra', idOnTheSource: 'group-1', source: 'entra' }),
+ principal({ name: 'Alexandra', email: '[email protected]', source: 'entra' }),
+ ],
+ });
+ await test.run();
+
+ expect(test.res.json).toHaveBeenCalledWith({
+ query: 'alice',
+ limit: 20,
+ types: [USER, GROUP],
+ results: [
+ principal({ name: 'Alexandra', email: '[email protected]', source: 'entra' }),
+ principal({ type: GROUP, name: 'Admins', idOnTheSource: 'group-1' }),
+ principal({ name: 'Alice', email: '[email protected]' }),
+ ],
+ count: 3,
+ sources: { local: 2, entra: 1 },
+ });
+ });
+
+ it('falls back to local results when Entra ID search fails', async () => {
+ const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => logger);
+ const local = principal({ name: 'Alice' });
+ const test = setupSearch({ types: [USER], entraEnabled: true, localResults: [local] });
+ test.deps.searchEntraIdPrincipals.mockRejectedValue(new Error('graph unavailable'));
+ await test.run();
+
+ expect(warnSpy).toHaveBeenCalledWith(
+ 'Graph API search failed, falling back to local results:',
+ 'graph unavailable',
+ );
+ expect(test.res.status).toHaveBeenCalledWith(200);
+ expect(test.res.json).toHaveBeenCalledWith(
+ expect.objectContaining({ results: [local], sources: { local: 1, entra: 0 } }),
+ );
+ warnSpy.mockRestore();
+ });
+
+ it('does not expose internal error details on search failures', async () => {
+ const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => logger);
+ const test = setupSearch({ types: [USER] });
+ const error = new Error('database failure with internal detail');
+ test.deps.searchPrincipals.mockRejectedValue(error);
+ await test.run();
+
+ expect(errorSpy).toHaveBeenCalledWith('Error searching principals:', error);
+ expect(test.res.status).toHaveBeenCalledWith(500);
+ expect(test.res.json).toHaveBeenCalledWith({ error: 'Failed to search principals' });
+ errorSpy.mockRestore();
+ });
+
+ it.each<Query>([{ q: 'alice', type: GROUP }, { q: 'alice', types: 'foobar' }, { q: 'alice' }])(
+ 'searches local and Entra ID groups only for a groups-only role requesting %j',
+ async (query) => {
+ const test = setupSearch({ query, entraEnabled: true });
+ const search = createPrincipalSearch(test.deps);
+ const checkAccess = createPeoplePickerAccess({
+ getRoleByName: async () => ({
+ permissions: { [PermissionTypes.PEOPLE_PICKER]: permissionsFor([GROUP]) },
+ }),
+ });
+ await checkAccess(test.req, test.res as unknown as Response, () =>
+ search(test.req, test.res as unknown as Response),
+ );
+
+ expect(test.deps.searchPrincipals).toHaveBeenCalledWith('alice', 20, [GROUP]);
+ expect(test.deps.searchEntraIdPrincipals).toHaveBeenCalledWith(
+ 'token',
+ 'oid-1',
+ 'alice',
+ 'groups',
+ 20,
+ );
+ },
+ );
+});
diff --git a/packages/api/src/acl/search.ts b/packages/api/src/acl/search.ts
new file mode 100644
index 0000000000..48ad57ba6e
--- /dev/null
+++ b/packages/api/src/acl/search.ts
@@ -0,0 +1,313 @@
+import { logger } from '@librechat/data-schemas';
+import { Permissions, SystemRoles, PrincipalType, PermissionTypes } from 'librechat-data-provider';
+import type {
+ TUser,
+ TPeoplePickerPermissions,
+ TPrincipalSearchResponse,
+ TPrincipalSearchResult,
+} from 'librechat-data-provider';
+import type { NextFunction, Request, Response } from 'express';
+
+export type SearchablePrincipalType = PrincipalType.USER | PrincipalType.GROUP | PrincipalType.ROLE;
+
+export type EntraPrincipalSearchType = 'all' | 'users' | 'groups';
+
+export type PrincipalSearchUser = Partial<Pick<TUser, 'id' | 'role' | 'provider'>> & {
+ openidId?: string;
+};
+
+export type PrincipalSearchRequest = Pick<Request, 'query' | 'headers'> & {
+ user?: PrincipalSearchUser;
+ /** Principal types the caller may search, resolved by the people picker access check. */
+ principalSearchTypes?: SearchablePrincipalType[];
+};
+
+export type PeoplePickerAccess = (
+ req: PrincipalSearchRequest,
+ res: Response,
+ next: NextFunction,
+) => Promise<Response | void>;
+
+export type PeoplePickerRole = {
+ permissions?: { [PermissionTypes.PEOPLE_PICKER]?: Partial<TPeoplePickerPermissions> };
+};
+
+export type PrincipalSearch = (req: PrincipalSearchRequest, res: Response) => Promise<void>;
+
+type ScoredPrincipal = TPrincipalSearchResult & { _searchScore: number };
+
+export interface PrincipalSearchDeps {
+ searchPrincipals: (
+ query: string,
+ limitPerType: number,
+ types: SearchablePrincipalType[],
+ ) => Promise<TPrincipalSearchResult[]>;
+ calculateRelevanceScore: (item: TPrincipalSearchResult, query: string) => number;
+ sortPrincipalsByRelevance: (results: ScoredPrincipal[]) => ScoredPrincipal[];
+ entraIdPrincipalFeatureEnabled: (user?: PrincipalSearchUser) => boolean;
+ searchEntraIdPrincipals: (
+ accessToken: string,
+ sub: string | undefined,
+ query: string,
+ type: EntraPrincipalSearchType,
+ limit: number,
+ ) => Promise<TPrincipalSearchResult[]>;
+}
+
+const SEARCHABLE_PRINCIPAL_TYPES: readonly SearchablePrincipalType[] = [
+ PrincipalType.USER,
+ PrincipalType.GROUP,
+ PrincipalType.ROLE,
+];
+
+const PRINCIPAL_SEARCH_PERMISSIONS: Record<
+ SearchablePrincipalType,
+ {
+ permission: Permissions.VIEW_USERS | Permissions.VIEW_GROUPS | Permissions.VIEW_ROLES;
+ label: string;
+ }
+> = {
+ [PrincipalType.USER]: { permission: Permissions.VIEW_USERS, label: 'users' },
+ [PrincipalType.GROUP]: { permission: Permissions.VIEW_GROUPS, label: 'groups' },
+ [PrincipalType.ROLE]: { permission: Permissions.VIEW_ROLES, label: 'roles' },
+};
+
+const isSearchablePrincipalType = (value: string): value is SearchablePrincipalType =>
+ (SEARCHABLE_PRINCIPAL_TYPES as readonly string[]).includes(value);
+
+/**
+ * Collects the principal types named by the `type` and `types` query parameters, in request order.
+ * Each value may be a single type, a comma-separated list, or a repeated parameter.
+ */
+export function getRequestedPrincipalTypes(
+ query: PrincipalSearchRequest['query'],
+): SearchablePrincipalType[] {
+ const requested = new Set<SearchablePrincipalType>();
+ for (const value of [query.type, query.types].flat()) {
+ if (typeof value !== 'string') {
+ continue;
+ }
+ for (const name of value.split(',')) {
+ if (isSearchablePrincipalType(name)) {
+ requested.add(name);
+ }
+ }
+ }
+ return [...requested];
+}
+
+/** Maps resolved principal types to the Microsoft Graph search scope, or `null` when none apply. */
+export function getEntraPrincipalSearchType(
+ types: readonly SearchablePrincipalType[],
+): EntraPrincipalSearchType | null {
+ const users = types.includes(PrincipalType.USER);
+ const groups = types.includes(PrincipalType.GROUP);
+ if (users && groups) {
+ return 'all';
+ }
+ if (users) {
+ return 'users';
+ }
+ return groups ? 'groups' : null;
+}
+
+/**
+ * Creates the people picker access check. It resolves the principal types the caller may search —
+ * the requested types when every one is permitted, otherwise every permitted type — and stores
+ * them on `req.principalSearchTypes` for the search handler.
+ */
+export function createPeoplePickerAccess({
+ getRoleByName,
+}: {
+ getRoleByName: (roleName: string) => Promise<PeoplePickerRole | null>;
+}): PeoplePickerAccess {
+ return async (req, res, next) => {
+ try {
+ const user = req.user;
+ if (!user || !user.role) {
+ return res.status(401).json({
+ error: 'Unauthorized',
+ message: 'Authentication required',
+ });
+ }
+
+ const requested = getRequestedPrincipalTypes(req.query);
+
+ if (user.role === SystemRoles.ADMIN) {
+ req.principalSearchTypes =
+ requested.length > 0 ? requested : [...SEARCHABLE_PRINCIPAL_TYPES];
+ return next();
+ }
+
+ const role = await getRoleByName(user.role);
+ if (!role || !role.permissions) {
+ return res.status(403).json({
+ error: 'Forbidden',
+ message: 'No permissions configured for user role',
+ });
+ }
+
+ const peoplePickerPerms = role.permissions[PermissionTypes.PEOPLE_PICKER] ?? {};
+ const canSearch = (type: SearchablePrincipalType) =>
+ peoplePickerPerms[PRINCIPAL_SEARCH_PERMISSIONS[type].permission] === true;
+
+ const denied = requested.find((type) => !canSearch(type));
+ if (denied) {
+ return res.status(403).json({
+ error: 'Forbidden',
+ message: `Insufficient permissions to search for ${PRINCIPAL_SEARCH_PERMISSIONS[denied].label}`,
+ });
+ }
+
+ const types = requested.length > 0 ? requested : SEARCHABLE_PRINCIPAL_TYPES.filter(canSearch);
+ if (types.length === 0) {
+ return res.status(403).json({
+ error: 'Forbidden',
+ message: 'Insufficient permissions to search for users, groups, or roles',
+ });
+ }
+
+ req.principalSearchTypes = types;
+ return next();
+ } catch (error) {
+ logger.error(
+ `[checkPeoplePickerAccess][${req.user?.id}] error for type=${req.query.type}, types=${req.query.types}`,
+ error,
+ );
+ return res.status(500).json({
+ error: 'Internal Server Error',
+ message: 'Failed to check permissions',
+ });
+ }
+ };
+}
+
+/** Entra ID principals for the resolved types that the local results do not already hold. */
+async function findEntraPrincipals({
+ req,
+ query,
+ types,
+ remaining,
+ localResults,
+ deps,
+}: {
+ req: PrincipalSearchRequest;
+ query: string;
+ types: SearchablePrincipalType[];
+ remaining: number;
+ localResults: TPrincipalSearchResult[];
+ deps: Pick<PrincipalSearchDeps, 'entraIdPrincipalFeatureEnabled' | 'searchEntraIdPrincipals'>;
+}): Promise<TPrincipalSearchResult[]> {
+ const graphType = getEntraPrincipalSearchType(types);
+ if (remaining <= 0 || !graphType || !deps.entraIdPrincipalFeatureEnabled(req.user)) {
+ return [];
+ }
+
+ const authHeader = req.headers.authorization;
+ if (!authHeader?.startsWith('Bearer ')) {
+ return [];
+ }
+
+ try {
+ const graphResults = await deps.searchEntraIdPrincipals(
+ authHeader.substring(7),
+ req.user?.openidId,
+ query,
+ graphType,
+ remaining,
+ );
+
+ const localEmails = new Set<string>();
+ const localSourceIds = new Set<string>();
+ for (const principal of localResults) {
+ if (principal.email) {
+ localEmails.add(principal.email.toLowerCase());
+ }
+ if (principal.idOnTheSource) {
+ localSourceIds.add(principal.idOnTheSource);
+ }
+ }
+
+ return graphResults.filter(
+ (principal) =>
+ !(principal.email && localEmails.has(principal.email.toLowerCase())) &&
+ !(principal.idOnTheSource && localSourceIds.has(principal.idOnTheSource)),
+ );
+ } catch (error) {
+ logger.warn(
+ 'Graph API search failed, falling back to local results:',
+ error instanceof Error ? error.message : error,
+ );
+ return [];
+ }
+}
+
+/**
+ * Creates the principal search handler. It searches only `req.principalSearchTypes`, as resolved by
+ * the people picker access check, so a request that skipped the check searches no types.
+ */
+export function createPrincipalSearch(deps: PrincipalSearchDeps): PrincipalSearch {
+ return async (req, res) => {
+ try {
+ const { q: rawQuery, limit = 20 } = req.query;
+
+ if (typeof rawQuery !== 'string' || rawQuery.trim().length === 0) {
+ res.status(400).json({
+ error: 'Query parameter "q" is required and must not be empty',
+ });
+ return;
+ }
+
+ const query = rawQuery.trim();
+
+ if (query.length < 2) {
+ res.status(400).json({
+ error: 'Query must be at least 2 characters long',
+ });
+ return;
+ }
+
+ const searchLimit = Math.min(Math.max(1, parseInt(String(limit)) || 10), 50);
+ const types = req.principalSearchTypes ?? [];
+
+ const localResults = await deps.searchPrincipals(query, searchLimit, types);
+ const entraResults = await findEntraPrincipals({
+ req,
+ query,
+ types,
+ remaining: searchLimit - localResults.length,
+ localResults,
+ deps,
+ });
+
+ const scoredResults = [...localResults, ...entraResults].map((item) => ({
+ ...item,
+ _searchScore: deps.calculateRelevanceScore(item, query),
+ }));
+
+ const sources = { local: 0, entra: 0 };
+ const results = deps
+ .sortPrincipalsByRelevance(scoredResults)
+ .slice(0, searchLimit)
+ .map(({ _searchScore, ...result }) => {
+ sources[result.source] += 1;
+ return result;
+ });
+
+ const response: TPrincipalSearchResponse = {
+ query,
+ limit: searchLimit,
+ types,
+ results,
+ count: results.length,
+ sources,
+ };
+ res.status(200).json(response);
+ } catch (error) {
+ logger.error('Error searching principals:', error);
+ res.status(500).json({
+ error: 'Failed to search principals',
+ });
+ }
+ };
+}
diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts
index 76d96b77e0..aefdd8e179 100644
--- a/packages/api/src/index.ts
+++ b/packages/api/src/index.ts
@@ -3,6 +3,7 @@ export * from './acl/accessControlService';
export * from './acl/insightsPermissions';
export * from './acl/middleware';
export * from './acl/principals';
+export * from './acl/search';
export * from './credentials';
/* Artifacts */
export * from './artifacts';
diff --git a/packages/data-schemas/src/methods/userGroup.spec.ts b/packages/data-schemas/src/methods/userGroup.spec.ts
index 69d47126e2..46ba4cdc7d 100644
--- a/packages/data-schemas/src/methods/userGroup.spec.ts
+++ b/packages/data-schemas/src/methods/userGroup.spec.ts
@@ -1612,6 +1612,21 @@ describe('userGroup methods', () => {
expect(results.length).toBeGreaterThanOrEqual(1);
});
+ it('excludes users from a GROUP and ROLE filter', async () => {
+ const results = await methods.searchPrincipals('a', 10, [
+ PrincipalType.GROUP,
+ PrincipalType.ROLE,
+ ]);
+ expect(new Set(results.map((r) => r.type))).toEqual(
+ new Set([PrincipalType.GROUP, PrincipalType.ROLE]),
+ );
+ });
+
+ it('returns no principals for an empty type filter', async () => {
+ const results = await methods.searchPrincipals('a', 10, []);
+ expect(results).toEqual([]);
+ });
+
it('respects limitPerType', async () => {
const results = await methods.searchPrincipals('a', 1);
const userResults = results.filter((r) => r.type === PrincipalType.USER);