Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[EDR Workflows] The host isolation exception tab is hidden on the basic license if no artifacts #192562

Merged
merged 14 commits into from
Sep 23, 2024
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import { useHostIsolationExceptionsAccess } from './use_host_isolation_exceptions_access';
import { checkArtifactHasData } from '../../services/exceptions_list/check_artifact_has_data';

jest.mock('../../services/exceptions_list/check_artifact_has_data', () => ({
checkArtifactHasData: jest.fn(),
}));

const mockArtifactHasData = (hasData = true) => {
(checkArtifactHasData as jest.Mock).mockResolvedValueOnce(hasData);
};

describe('useHostIsolationExceptionsAccess', () => {
const mockApiClient = jest.fn();

beforeEach(() => {
jest.clearAllMocks();
});

const setupHook = (canAccess: boolean, canRead: boolean) => {
return renderHook(() => useHostIsolationExceptionsAccess(canAccess, canRead, mockApiClient));
};

test('should set access to true if canAccessHostIsolationExceptions is true', async () => {
const { result, waitFor } = setupHook(true, false);

await waitFor(() => expect(result.current.hasAccessToHostIsolationExceptions).toBe(true));
});

test('should check for artifact data if canReadHostIsolationExceptions is true and canAccessHostIsolationExceptions is false', async () => {
mockArtifactHasData();

const { result, waitFor } = setupHook(false, true);

await waitFor(() => {
expect(checkArtifactHasData).toHaveBeenCalledWith(mockApiClient());
expect(result.current.hasAccessToHostIsolationExceptions).toBe(true);
});
});

test('should set access to false if canReadHostIsolationExceptions is true but no artifact data exists', async () => {
mockArtifactHasData(false);

const { result, waitFor } = setupHook(false, true);

await waitFor(() => {
expect(checkArtifactHasData).toHaveBeenCalledWith(mockApiClient());
expect(result.current.hasAccessToHostIsolationExceptions).toBe(false);
});
});

test('should set access to false if neither canAccessHostIsolationExceptions nor canReadHostIsolationExceptions is true', async () => {
const { result, waitFor } = setupHook(false, false);
await waitFor(() => {
expect(result.current.hasAccessToHostIsolationExceptions).toBe(false);
});
});

test('should not call checkArtifactHasData if canAccessHostIsolationExceptions is true', async () => {
const { result, waitFor } = setupHook(true, true);

await waitFor(() => {
expect(checkArtifactHasData).not.toHaveBeenCalled();
expect(result.current.hasAccessToHostIsolationExceptions).toBe(true);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think a test case for isHostIsolationExceptionsAccessLoading: true would be useful, both here and in policy_details.test.tsx

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree!

});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { useEffect, useState } from 'react';
import { checkArtifactHasData } from '../../services/exceptions_list/check_artifact_has_data';
import type { ExceptionsListApiClient } from '../../services/exceptions_list/exceptions_list_api_client';

export const useHostIsolationExceptionsAccess = (
canAccessHostIsolationExceptions: boolean,
canReadHostIsolationExceptions: boolean,
getApiClient: () => ExceptionsListApiClient
): {
hasAccessToHostIsolationExceptions: boolean;
isHostIsolationExceptionsAccessLoading: boolean;
} => {
const [hasAccess, setHasAccess] = useState<boolean | null>(null);

useEffect(() => {
(async () => {
// Host isolation exceptions is a paid feature and therefore:
// canAccessHostIsolationExceptions signifies if the user has required license to access the feature.
// canReadHostIsolationExceptions, however, is a privilege that allows the user to read and delete the data even if the license is not sufficient (downgrade scenario).
// In such cases, the tab should be visible only if there is existing data.
if (canAccessHostIsolationExceptions) {
setHasAccess(true);
} else if (canReadHostIsolationExceptions) {
const result = await checkArtifactHasData(getApiClient());
setHasAccess(result);
} else {
setHasAccess(false);
}
})();
}, [canAccessHostIsolationExceptions, canReadHostIsolationExceptions, getApiClient]);

return {
hasAccessToHostIsolationExceptions: !!hasAccess,
isHostIsolationExceptionsAccessLoading: hasAccess === null,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import type {
ExceptionListItemSchema,
UpdateExceptionListItemSchema,
} from '@kbn/securitysolution-io-ts-list-types';
import { ENDPOINT_BLOCKLISTS_LIST_ID } from '@kbn/securitysolution-list-constants';
import { ENDPOINT_ARTIFACT_LISTS } from '@kbn/securitysolution-list-constants';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for cleaning up the deprecations 🥇


import type { HttpStart } from '@kbn/core/public';
import type { ConditionEntry } from '../../../../../common/endpoint/types';
Expand Down Expand Up @@ -46,7 +46,7 @@ export class BlocklistsApiClient extends ExceptionsListApiClient {
constructor(http: HttpStart) {
super(
http,
ENDPOINT_BLOCKLISTS_LIST_ID,
ENDPOINT_ARTIFACT_LISTS.blocklists.id,
BLOCKLISTS_LIST_DEFINITION,
readTransform,
writeTransform
Expand All @@ -56,7 +56,7 @@ export class BlocklistsApiClient extends ExceptionsListApiClient {
public static getInstance(http: HttpStart): ExceptionsListApiClient {
return super.getInstance(
http,
ENDPOINT_BLOCKLISTS_LIST_ID,
ENDPOINT_ARTIFACT_LISTS.blocklists.id,
BLOCKLISTS_LIST_DEFINITION,
readTransform,
writeTransform
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { ENDPOINT_EVENT_FILTERS_LIST_ID } from '@kbn/securitysolution-list-constants';
import { ENDPOINT_ARTIFACT_LISTS } from '@kbn/securitysolution-list-constants';
import type { HttpStart } from '@kbn/core/public';
import type {
CreateExceptionListItemSchema,
Expand Down Expand Up @@ -33,7 +33,7 @@ export class EventFiltersApiClient extends ExceptionsListApiClient {
constructor(http: HttpStart) {
super(
http,
ENDPOINT_EVENT_FILTERS_LIST_ID,
ENDPOINT_ARTIFACT_LISTS.eventFilters.id,
EVENT_FILTER_LIST_DEFINITION,
undefined,
writeTransform
Expand All @@ -43,7 +43,7 @@ export class EventFiltersApiClient extends ExceptionsListApiClient {
public static getInstance(http: HttpStart): ExceptionsListApiClient {
return super.getInstance(
http,
ENDPOINT_EVENT_FILTERS_LIST_ID,
ENDPOINT_ARTIFACT_LISTS.eventFilters.id,
EVENT_FILTER_LIST_DEFINITION,
undefined,
writeTransform
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { ENDPOINT_HOST_ISOLATION_EXCEPTIONS_LIST_ID } from '@kbn/securitysolution-list-constants';
import { ENDPOINT_ARTIFACT_LISTS } from '@kbn/securitysolution-list-constants';
import type { HttpStart } from '@kbn/core/public';
import { ExceptionsListApiClient } from '../../services/exceptions_list/exceptions_list_api_client';
import { HOST_ISOLATION_EXCEPTIONS_LIST_DEFINITION } from './constants';
Expand All @@ -19,15 +19,15 @@ export class HostIsolationExceptionsApiClient extends ExceptionsListApiClient {
constructor(http: HttpStart) {
super(
http,
ENDPOINT_HOST_ISOLATION_EXCEPTIONS_LIST_ID,
ENDPOINT_ARTIFACT_LISTS.hostIsolationExceptions.id,
HOST_ISOLATION_EXCEPTIONS_LIST_DEFINITION
);
}

public static getInstance(http: HttpStart): ExceptionsListApiClient {
return super.getInstance(
http,
ENDPOINT_HOST_ISOLATION_EXCEPTIONS_LIST_ID,
ENDPOINT_ARTIFACT_LISTS.hostIsolationExceptions.id,
HOST_ISOLATION_EXCEPTIONS_LIST_DEFINITION
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,15 @@ import { PolicyDetails } from './policy_details';
import { APP_UI_ID } from '../../../../../common/constants';
import { createLicenseServiceMock } from '../../../../../common/license/mocks';
import { licenseService as licenseServiceMocked } from '../../../../common/hooks/__mocks__/use_license';
import { useHostIsolationExceptionsAccess } from '../../../hooks/artifacts/use_host_isolation_exceptions_access';

jest.mock('../../../../common/components/user_privileges');
jest.mock('../../../../common/hooks/use_license');
jest.mock('../../../hooks/artifacts/use_host_isolation_exceptions_access');

const useUserPrivilegesMock = useUserPrivileges as jest.Mock;
const useLicenseMock = _useLicense as jest.Mock;
const useHostIsolationExceptionsAccessMock = useHostIsolationExceptionsAccess as jest.Mock;

describe('Policy Details', () => {
const policyDetailsPathUrl = getPolicyDetailPath('1');
Expand Down Expand Up @@ -100,11 +103,15 @@ describe('Policy Details', () => {
policyPackagePolicy.policy_id = policyPackagePolicy.policy_ids[0];

const policyListApiHandlers = policyListApiPathHandlers();
useHostIsolationExceptionsAccessMock.mockReturnValue({
hasAccessToHostIsolationExceptions: true,
isHostIsolationExceptionsAccessLoading: false,
});

http.get.mockImplementation((...args) => {
const [path] = args;
if (typeof path === 'string') {
// GET datasouce
// GET datasource
if (path === `${PACKAGE_POLICY_API_ROOT}/1`) {
asyncActions = asyncActions.then<unknown>(async (): Promise<unknown> => sleep());
return Promise.resolve({
Expand Down Expand Up @@ -210,13 +217,24 @@ describe('Policy Details', () => {
expect(eventFiltersTab.text()).toBe('Event filters');
});

it('should display the host isolation exceptions tab', async () => {
it('should display the host isolation exceptions tab if user have access', async () => {
policyView = render();
await asyncActions;
policyView.update();
const tab = policyView.find('button#hostIsolationExceptions');
const tab = policyView.find('button[data-test-subj="policyHostIsolationExceptionsTab"]');
expect(tab).toHaveLength(1);
expect(tab.text()).toBe('Host isolation exceptions');
});

it("shouldn't display when user doesn't have access", async () => {
szwarckonrad marked this conversation as resolved.
Show resolved Hide resolved
useHostIsolationExceptionsAccessMock.mockReturnValue({
hasAccessToHostIsolationExceptions: false,
isHostIsolationExceptionsAccessLoading: false,
});
policyView = render();
await asyncActions;
policyView.update();
const tab = policyView.find('button[data-test-subj="policyHostIsolationExceptionsTab"]');
expect(tab).toHaveLength(0);
});

it('should display the protection updates tab', async () => {
Expand All @@ -234,6 +252,10 @@ describe('Policy Details', () => {
licenseServiceMock.isEnterprise.mockReturnValue(false);

useLicenseMock.mockReturnValue(licenseServiceMock);
useHostIsolationExceptionsAccessMock.mockReturnValue({
hasAccessToHostIsolationExceptions: false,
isHostIsolationExceptionsAccessLoading: false,
});
});

afterEach(() => {
Expand All @@ -247,55 +269,55 @@ describe('Policy Details', () => {
const tab = policyView.find('button#protectionUpdates');
expect(tab).toHaveLength(0);
});
});

describe('without required permissions', () => {
const renderWithPrivilege = async (privilege: string) => {
useUserPrivilegesMock.mockReturnValue({
endpointPrivileges: {
loading: false,
[privilege]: false,
},
});
policyView = render();
await asyncActions;
policyView.update();
};

it.each([
['trusted apps', 'canReadTrustedApplications', 'trustedApps'],
['event filters', 'canReadEventFilters', 'eventFilters'],
['host isolation exeptions', 'canReadHostIsolationExceptions', 'hostIsolationExceptions'],
['blocklist', 'canReadBlocklist', 'blocklists'],
])(
'should not display the %s tab with no privileges',
async (_: string, privilege: string, selector: string) => {
await renderWithPrivilege(privilege);
expect(policyView.find(`button#${selector}`)).toHaveLength(0);
}
);

it.each([
['trusted apps', 'canReadTrustedApplications', getPolicyTrustedAppsPath('1')],
['event filters', 'canReadEventFilters', getPolicyEventFiltersPath('1')],
[
'host isolation exeptions',
'canReadHostIsolationExceptions',
getPolicyHostIsolationExceptionsPath('1'),
],
['blocklist', 'canReadBlocklist', getPolicyBlocklistsPath('1')],
])(
'should redirect to policy details when no %s required privileges',
async (_: string, privilege: string, path: string) => {
history.push(path);
await renderWithPrivilege(privilege);
expect(history.location.pathname).toBe(policyDetailsPathUrl);
expect(coreStart.notifications.toasts.addDanger).toHaveBeenCalledTimes(1);
expect(coreStart.notifications.toasts.addDanger).toHaveBeenCalledWith(
'You do not have the required Kibana permissions to use the given artifact.'
);
}
);
describe('without required permissions', () => {
const renderWithoutPrivilege = async (privilege: string) => {
useUserPrivilegesMock.mockReturnValue({
endpointPrivileges: {
loading: false,
[privilege]: false,
},
});
policyView = render();
await asyncActions;
policyView.update();
};

it.each([
['trusted apps', 'canReadTrustedApplications', 'trustedApps'],
['event filters', 'canReadEventFilters', 'eventFilters'],
['host isolation exeptions', 'canReadHostIsolationExceptions', 'hostIsolationExceptions'],
['blocklist', 'canReadBlocklist', 'blocklists'],
])(
'should not display the %s tab with no privileges',
async (_: string, privilege: string, selector: string) => {
await renderWithoutPrivilege(privilege);
expect(policyView.find(`button#${selector}`)).toHaveLength(0);
}
);

it.each([
['trusted apps', 'canReadTrustedApplications', getPolicyTrustedAppsPath('1')],
['event filters', 'canReadEventFilters', getPolicyEventFiltersPath('1')],
[
'host isolation exeptions',
'canReadHostIsolationExceptions',
getPolicyHostIsolationExceptionsPath('1'),
],
['blocklist', 'canReadBlocklist', getPolicyBlocklistsPath('1')],
])(
'should redirect to policy details when no %s required privileges',
async (_: string, privilege: string, path: string) => {
history.push(path);
await renderWithoutPrivilege(privilege);
expect(history.location.pathname).toBe(policyDetailsPathUrl);
expect(coreStart.notifications.toasts.addDanger).toHaveBeenCalledTimes(1);
expect(coreStart.notifications.toasts.addDanger).toHaveBeenCalledWith(
'You do not have the required Kibana permissions to use the given artifact.'
);
}
);
});
});
});
});
Loading