Protect Asset Inventory API with UI setting check (#212266)

## Summary

Closes https://github.com/elastic/security-team/issues/12021.

Protect all Asset Inventory server endpoints so that they return 403 if
`securitysolution:enableAssetInventory` advanced setting is off.

### Screenshots

<details><summary>Error returned by /status endpoint check</summary>
<img width="2267" alt="Screenshot 2025-04-02 at 13 14 52"
src="https://github.com/user-attachments/assets/24892c90-3c59-4615-9523-e8df5c52ee71"
/>

</details>

<details><summary>Surfaced error after clicking on "enable"
button</summary>
<img width="2270" alt="Screenshot 2025-04-02 at 13 14 28"
src="https://github.com/user-attachments/assets/7c6b5aa2-e62f-4045-8d6d-a9b7cbde0dc4"
/>

</details>

### Checklist

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/src/platform/packages/shared/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [x] This was checked for breaking HTTP API changes, and any breaking
changes have been approved by the breaking-change committee. The
`release_note:breaking` label should be applied in these situations.
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [x] The PR description includes the appropriate Release Notes section,
and the correct `release_note:*` label is applied per the
[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

### Identify risks

We will expose the server endpoints if they're not gated correctly.
This commit is contained in:
Alberto Blázquez 2025-04-03 18:34:26 +02:00 committed by GitHub
parent 8db71f1feb
commit 5402d2b90e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 140 additions and 42 deletions

View file

@ -10,6 +10,7 @@ import type { EntityAnalyticsPrivileges } from '../entity_analytics';
import type { InitEntityStoreResponse } from '../entity_analytics/entity_store/enable.gen';
export type AssetInventoryStatus =
| 'inactive_feature'
| 'disabled'
| 'initializing'
| 'empty'

View file

@ -30,6 +30,7 @@ export const AssetInventoryOnboarding: FC<PropsWithChildren> = ({ children }) =>
// Render different screens based on the onboarding status.
switch (status) {
case 'inactive_feature':
case 'disabled': // The user has not yet started the onboarding process.
return <GetStarted />;
case 'initializing': // The onboarding process is currently initializing.

View file

@ -4,10 +4,15 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { AssetInventoryDataClient } from './asset_inventory_data_client';
import {
loggingSystemMock,
elasticsearchServiceMock,
uiSettingsServiceMock,
} from '@kbn/core/server/mocks';
import type { InitEntityStoreRequestBody } from '../../../common/api/entity_analytics/entity_store/enable.gen';
import type { SecuritySolutionApiRequestHandlerContext } from '../..';
import { loggingSystemMock, elasticsearchServiceMock } from '@kbn/core/server/mocks';
import { mockGlobalState } from '../../../public/common/mock';
import { AssetInventoryDataClient } from './asset_inventory_data_client';
const mockSecSolutionContext = {
getEntityStoreDataClient: jest.fn(),
@ -26,16 +31,26 @@ const mockEntityStorePrivileges = {
describe('AssetInventoryDataClient', () => {
const loggerMock = loggingSystemMock.createLogger();
const clusterClientMock = elasticsearchServiceMock.createScopedClusterClient();
const uiSettingsClientMock = uiSettingsServiceMock.createClient();
const client: AssetInventoryDataClient = new AssetInventoryDataClient({
logger: loggerMock,
clusterClient: clusterClientMock,
experimentalFeatures: mockGlobalState.app.enableExperimental,
uiSettingsClient: uiSettingsClientMock,
});
describe('status function', () => {
beforeEach(() => {
jest.clearAllMocks();
uiSettingsClientMock.get.mockResolvedValue(true);
});
it('returns INACTIVE_FEATURE when uisetting is disabled', async () => {
uiSettingsClientMock.get.mockResolvedValue(false);
const result = await client.status(mockSecSolutionContext, mockEntityStorePrivileges);
expect(result).toEqual({ status: 'inactive_feature' });
});
it('returns INSUFFICIENT_PRIVILEGES with missing privileges when user lacks required privileges', async () => {
@ -151,4 +166,32 @@ describe('AssetInventoryDataClient', () => {
expect(result).toEqual({ status: 'initializing' });
});
});
describe('enable function', () => {
beforeEach(() => {
jest.clearAllMocks();
uiSettingsClientMock.get.mockResolvedValue(true);
});
it('throws error when uisetting is disabled', async () => {
uiSettingsClientMock.get.mockResolvedValue(false);
await expect(
client.enable(mockSecSolutionContext, {} as InitEntityStoreRequestBody)
).rejects.toThrowError('uiSetting');
});
});
describe('delete function', () => {
beforeEach(() => {
jest.clearAllMocks();
uiSettingsClientMock.get.mockResolvedValue(true);
});
it('throws error when uisetting is disabled', async () => {
uiSettingsClientMock.get.mockResolvedValue(false);
await expect(client.delete()).rejects.toThrowError('uiSetting');
});
});
});

View file

@ -6,17 +6,18 @@
*/
import type { Logger, IScopedClusterClient } from '@kbn/core/server';
import type { IUiSettingsClient } from '@kbn/core-ui-settings-server';
import { SECURITY_SOLUTION_ENABLE_ASSET_INVENTORY_SETTING } from '@kbn/management-settings-ids';
import type { EntityAnalyticsPrivileges } from '../../../common/api/entity_analytics';
import type { GetEntityStoreStatusResponse } from '../../../common/api/entity_analytics/entity_store/status.gen';
import type { InitEntityStoreRequestBody } from '../../../common/api/entity_analytics/entity_store/enable.gen';
import type { ExperimentalFeatures } from '../../../common';
import type { SecuritySolutionApiRequestHandlerContext } from '../..';
interface AssetInventoryClientOpts {
logger: Logger;
clusterClient: IScopedClusterClient;
experimentalFeatures: ExperimentalFeatures;
uiSettingsClient: IUiSettingsClient;
}
type EntityStoreEngineStatus = GetEntityStoreStatusResponse['engines'][number];
@ -30,7 +31,8 @@ interface TransformMetadata {
trigger_count: number;
}
const ASSET_INVENTORY_STATUS: Record<string, string> = {
export const ASSET_INVENTORY_STATUS: Record<string, string> = {
INACTIVE_FEATURE: 'inactive_feature',
DISABLED: 'disabled',
INITIALIZING: 'initializing',
INSUFFICIENT_PRIVILEGES: 'insufficient_privileges',
@ -43,29 +45,6 @@ const ASSET_INVENTORY_STATUS: Record<string, string> = {
export class AssetInventoryDataClient {
constructor(private readonly options: AssetInventoryClientOpts) {}
// Enables the asset inventory by deferring the initialization to avoid blocking the main thread.
public async enable(
secSolutionContext: SecuritySolutionApiRequestHandlerContext,
requestBodyOverrides: InitEntityStoreRequestBody
) {
const { logger } = this.options;
try {
logger.debug(`Enabling asset inventory`);
const entityStoreEnableResponse = await secSolutionContext
.getEntityStoreDataClient()
.enable(requestBodyOverrides);
logger.debug(`Enabled asset inventory`);
return entityStoreEnableResponse;
} catch (err) {
logger.error(`Error enabling asset inventory: ${err.message}`);
throw err;
}
}
// Initializes the asset inventory by validating experimental feature flags and triggering asynchronous setup.
public async init() {
const { logger } = this.options;
@ -88,6 +67,33 @@ export class AssetInventoryDataClient {
}
}
// Enables the asset inventory by deferring the initialization to avoid blocking the main thread.
public async enable(
secSolutionContext: SecuritySolutionApiRequestHandlerContext,
requestBodyOverrides: InitEntityStoreRequestBody
) {
const { logger } = this.options;
logger.debug(`Enabling asset inventory`);
try {
if (!(await this.checkUISettingEnabled())) {
throw new Error('uiSetting');
}
const entityStoreEnableResponse = await secSolutionContext
.getEntityStoreDataClient()
.enable(requestBodyOverrides);
logger.debug(`Enabled asset inventory`);
return entityStoreEnableResponse;
} catch (err) {
logger.error(`Error enabling asset inventory: ${err.message}`);
throw err;
}
}
// Cleans up the resources associated with the asset inventory, such as removing the ingest pipeline.
public async delete() {
const { logger } = this.options;
@ -95,6 +101,10 @@ export class AssetInventoryDataClient {
logger.debug(`Deleting asset inventory`);
try {
if (!(await this.checkUISettingEnabled())) {
throw new Error('uiSetting');
}
logger.debug(`Deleted asset inventory`);
return { deleted: true };
} catch (err) {
@ -107,6 +117,10 @@ export class AssetInventoryDataClient {
secSolutionContext: SecuritySolutionApiRequestHandlerContext,
entityStorePrivileges: EntityAnalyticsPrivileges
) {
if (!(await this.checkUISettingEnabled())) {
return { status: ASSET_INVENTORY_STATUS.INACTIVE_FEATURE };
}
// Check if the user has the required privileges to access the entity store.
if (!entityStorePrivileges.has_all_required) {
return {
@ -149,6 +163,22 @@ export class AssetInventoryDataClient {
return { status: ASSET_INVENTORY_STATUS.INITIALIZING };
}
private async checkUISettingEnabled() {
const { uiSettingsClient, logger } = this.options;
const isAssetInventoryEnabled = await uiSettingsClient.get<boolean>(
SECURITY_SOLUTION_ENABLE_ASSET_INVENTORY_SETTING
);
if (!isAssetInventoryEnabled) {
logger.debug(
`${SECURITY_SOLUTION_ENABLE_ASSET_INVENTORY_SETTING} advanced setting is disabled`
);
}
return isAssetInventoryEnabled;
}
// Type guard to check if an entity engine is a host entity engine
// Todo: Change to the new 'generic' entity engine once it's ready
private isHostEntityEngine(engine: EntityStoreEngineStatus): engine is HostEntityEngineStatus {

View file

@ -0,0 +1,14 @@
/*
* 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 { SECURITY_SOLUTION_ENABLE_ASSET_INVENTORY_SETTING } from '@kbn/management-settings-ids';
import type { KibanaResponseFactory } from '@kbn/core-http-server';
export const errorInactiveFeature = (response: KibanaResponseFactory) =>
response.forbidden({
body: `${SECURITY_SOLUTION_ENABLE_ASSET_INVENTORY_SETTING} feature must be activated first`,
});

View file

@ -11,6 +11,7 @@ import { transformError } from '@kbn/securitysolution-es-utils';
import { ASSET_INVENTORY_DELETE_API_PATH } from '../../../../common/api/asset_inventory/constants';
import { API_VERSIONS } from '../../../../common/constants';
import type { AssetInventoryRoutesDeps } from '../types';
import { errorInactiveFeature } from '../errors';
export const deleteAssetInventoryRoute = (
router: AssetInventoryRoutesDeps['router'],
@ -33,7 +34,7 @@ export const deleteAssetInventoryRoute = (
validate: false,
},
async (context, request, response) => {
async (context, _request, response) => {
const siemResponse = buildSiemResponse(response);
try {
@ -42,6 +43,10 @@ export const deleteAssetInventoryRoute = (
return response.ok({ body });
} catch (e) {
if (e instanceof Error && e.message === 'uiSetting') {
return errorInactiveFeature(response);
}
logger.error('Error in DeleteEntityEngine:', e);
const error = transformError(e);
return siemResponse.error({

View file

@ -10,11 +10,11 @@ import { transformError } from '@kbn/securitysolution-es-utils';
import type { Logger } from '@kbn/core/server';
import { buildRouteValidationWithZod } from '@kbn/zod-helpers';
import { API_VERSIONS } from '../../../../common/constants';
import type { AssetInventoryRoutesDeps } from '../types';
import { InitEntityStoreRequestBody } from '../../../../common/api/entity_analytics/entity_store/enable.gen';
import { ASSET_INVENTORY_ENABLE_API_PATH } from '../../../../common/api/asset_inventory/constants';
import { checkAndInitAssetCriticalityResources } from '../../entity_analytics/asset_criticality/check_and_init_asset_criticality_resources';
import { errorInactiveFeature } from '../errors';
export const enableAssetInventoryRoute = (
router: AssetInventoryRoutesDeps['router'],
@ -42,16 +42,20 @@ export const enableAssetInventoryRoute = (
async (context, request, response) => {
const siemResponse = buildSiemResponse(response);
const secSol = await context.securitySolution;
try {
// Criticality resources are required by the Entity Store transforms
await checkAndInitAssetCriticalityResources(context, logger);
const secSol = await context.securitySolution;
const body = await secSol.getAssetInventoryClient().enable(secSol, request.body);
return response.ok({ body });
} catch (e) {
if (e instanceof Error && e.message === 'uiSetting') {
return errorInactiveFeature(response);
}
const error = transformError(e);
logger.error(`Error initializing asset inventory: ${error.message}`);
return siemResponse.error({

View file

@ -275,15 +275,14 @@ export class RequestContextFactory implements IRequestContextFactory {
request,
});
}),
getAssetInventoryClient: memoize(() => {
const clusterClient = coreContext.elasticsearch.client;
const logger = options.logger;
return new AssetInventoryDataClient({
clusterClient,
logger,
experimentalFeatures: config.experimentalFeatures,
});
}),
getAssetInventoryClient: memoize(
() =>
new AssetInventoryDataClient({
logger: options.logger,
clusterClient: coreContext.elasticsearch.client,
uiSettingsClient: coreContext.uiSettings.client,
})
),
};
}
}

View file

@ -241,5 +241,6 @@
"@kbn/security-ai-prompts",
"@kbn/scout-security",
"@kbn/custom-icons",
"@kbn/management-settings-ids"
]
}