diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/components/agent_policy_advanced_fields/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/components/agent_policy_advanced_fields/index.tsx index 6b0a7c512d197..0277184acabf2 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/components/agent_policy_advanced_fields/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/components/agent_policy_advanced_fields/index.tsx @@ -328,7 +328,7 @@ export const AgentPolicyAdvancedOptionsContent: React.FunctionComponent = } > { ); }); + it('throw when trying to change a managed policies space', async () => { + jest.mocked(agentPolicyService.get).mockResolvedValue({ + id: 'policy1', + space_ids: ['default'], + is_managed: true, + } as any); + jest.mocked(packagePolicyService.findAllForAgentPolicy).mockResolvedValue([] as any); + await expect( + updateAgentPolicySpaces({ + agentPolicyId: 'policy1', + currentSpaceId: 'default', + newSpaceIds: ['test'], + authorizedSpaces: ['test', 'default'], + }) + ).rejects.toThrowError(/Cannot update hosted agent policy policy1 space/); + }); + it('throw when trying to add a space with missing permissions', async () => { await expect( updateAgentPolicySpaces({ diff --git a/x-pack/plugins/fleet/server/services/spaces/agent_policy.ts b/x-pack/plugins/fleet/server/services/spaces/agent_policy.ts index 905f7980af994..14d7f45f2c47c 100644 --- a/x-pack/plugins/fleet/server/services/spaces/agent_policy.ts +++ b/x-pack/plugins/fleet/server/services/spaces/agent_policy.ts @@ -19,7 +19,7 @@ import { appContextService } from '../app_context'; import { agentPolicyService } from '../agent_policy'; import { ENROLLMENT_API_KEYS_INDEX } from '../../constants'; import { packagePolicyService } from '../package_policy'; -import { FleetError } from '../../errors'; +import { FleetError, HostedAgentPolicyRestrictionRelatedError } from '../../errors'; import { isSpaceAwarenessEnabled } from './helpers'; @@ -28,11 +28,13 @@ export async function updateAgentPolicySpaces({ currentSpaceId, newSpaceIds, authorizedSpaces, + options, }: { agentPolicyId: string; currentSpaceId: string; newSpaceIds: string[]; authorizedSpaces: string[]; + options?: { force?: boolean }; }) { const useSpaceAwareness = await isSpaceAwarenessEnabled(); if (!useSpaceAwareness || !newSpaceIds || newSpaceIds.length === 0) { @@ -50,6 +52,16 @@ export async function updateAgentPolicySpaces({ agentPolicyId ); + if (!existingPolicy) { + return; + } + + if (existingPolicy.is_managed && !options?.force) { + throw new HostedAgentPolicyRestrictionRelatedError( + `Cannot update hosted agent policy ${existingPolicy.id} space ` + ); + } + if (deepEqual(existingPolicy?.space_ids?.sort() ?? [DEFAULT_SPACE_ID], newSpaceIds.sort())) { return; }