diff --git a/x-pack/plugins/observability_solution/observability_ai_assistant/server/service/util/get_access_query.ts b/x-pack/plugins/observability_solution/observability_ai_assistant/server/service/util/get_access_query.ts index 6b654731a264..b517273630f5 100644 --- a/x-pack/plugins/observability_solution/observability_ai_assistant/server/service/util/get_access_query.ts +++ b/x-pack/plugins/observability_solution/observability_ai_assistant/server/service/util/get_access_query.ts @@ -17,12 +17,7 @@ export function getAccessQuery({ filter: [ { bool: { - should: [ - { term: { public: true } }, - ...(user - ? [{ term: user.id ? { 'user.id': user.id } : { 'user.name': user.name } }] - : []), - ], + should: [{ term: { public: true } }, ...getUserAccessFilters(user)], minimum_should_match: 1, }, }, @@ -51,3 +46,23 @@ export function getAccessQuery({ }, ]; } + +function getUserAccessFilters(user?: { name: string; id?: string }) { + if (!user) { + return []; + } + + if (user.id) { + return [ + { term: { 'user.id': user.id } }, + { + bool: { + must_not: { exists: { field: 'user.id' } }, + must: { term: { 'user.name': user.name } }, + }, + }, + ]; + } + + return [{ term: { 'user.name': user.name } }]; +}