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

[Security Solution][Endpoint] New route for create an exception list and return the existing one if it already exists #139618

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
Expand Up @@ -40,3 +40,6 @@ export * from './update_exception_list_item_validation';
export * from './update_exception_list_schema';
export * from './update_list_item_schema';
export * from './update_list_schema';

// Internal routes
export * from './internal/create_exception_list_schema';
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { left } from 'fp-ts/lib/Either';
import { pipe } from 'fp-ts/lib/pipeable';

import { ExceptionListTypeEnum } from '../../../common/exception_list';
import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils';

import { internalCreateExceptionListSchema } from '.';
import { getCreateExceptionListSchemaMock } from '../../create_exception_list_schema/index.mock';

describe('create_exception_list_schema', () => {
test('it should accept artifact list_id', () => {
const payload = {
...getCreateExceptionListSchemaMock(),
list_id: ExceptionListTypeEnum.ENDPOINT_BLOCKLISTS,
};
const decoded = internalCreateExceptionListSchema.decode(payload);
const checked = exactCheck(payload, decoded);
const message = pipe(checked, foldLeftRight);
expect(getPaths(left(message.errors))).toEqual([]);
expect(message.schema).toEqual(payload);
});
test('it should fail when invalid list_id', () => {
const payload = {
...getCreateExceptionListSchemaMock(),
list_id: ExceptionListTypeEnum.DETECTION,
};
const decoded = internalCreateExceptionListSchema.decode(payload);
const checked = exactCheck(payload, decoded);
const message = pipe(checked, foldLeftRight);
expect(getPaths(left(message.errors))).toEqual([
'Invalid value "detection" supplied to "list_id"',
]);
expect(message.schema).toEqual({});
});
test('it should accept artifact type', () => {
const payload = {
...getCreateExceptionListSchemaMock(),
list_id: ExceptionListTypeEnum.ENDPOINT_BLOCKLISTS,
type: ExceptionListTypeEnum.ENDPOINT_BLOCKLISTS,
};
const decoded = internalCreateExceptionListSchema.decode(payload);
const checked = exactCheck(payload, decoded);
const message = pipe(checked, foldLeftRight);
expect(getPaths(left(message.errors))).toEqual([]);
expect(message.schema).toEqual(payload);
});
test('it should fail when invalid type', () => {
const payload = {
...getCreateExceptionListSchemaMock(),
list_id: ExceptionListTypeEnum.ENDPOINT_BLOCKLISTS,
type: ExceptionListTypeEnum.DETECTION,
};
const decoded = internalCreateExceptionListSchema.decode(payload);
const checked = exactCheck(payload, decoded);
const message = pipe(checked, foldLeftRight);
expect(getPaths(left(message.errors))).toEqual([
'Invalid value "detection" supplied to "type"',
]);
expect(message.schema).toEqual({});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import {
ENDPOINT_BLOCKLISTS_LIST_ID,
ENDPOINT_EVENT_FILTERS_LIST_ID,
ENDPOINT_HOST_ISOLATION_EXCEPTIONS_LIST_ID,
ENDPOINT_TRUSTED_APPS_LIST_ID,
} from '@kbn/securitysolution-list-constants';
import * as t from 'io-ts';

import {
createExceptionListSchema,
CreateExceptionListSchemaDecoded,
} from '../../create_exception_list_schema';

export const internalCreateExceptionListSchema = t.intersection([
t.exact(
t.type({
Copy link
Contributor

Choose a reason for hiding this comment

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

Nice - thanks for these updates!

type: t.keyof({
endpoint: null,
endpoint_events: null,
endpoint_host_isolation_exceptions: null,
endpoint_blocklists: null,
}),
})
),
t.exact(
t.partial({
// TODO: Move the ALL_ENDPOINT_ARTIFACT_LIST_IDS inside the package and use it here instead
list_id: t.keyof({
[ENDPOINT_TRUSTED_APPS_LIST_ID]: null,
[ENDPOINT_EVENT_FILTERS_LIST_ID]: null,
[ENDPOINT_HOST_ISOLATION_EXCEPTIONS_LIST_ID]: null,
[ENDPOINT_BLOCKLISTS_LIST_ID]: null,
}),
})
),
createExceptionListSchema,
]);

export type InternalCreateExceptionListSchema = t.OutputOf<
typeof internalCreateExceptionListSchema
>;

// This type is used after a decode since some things are defaults after a decode.
export type InternalCreateExceptionListSchemaDecoded = CreateExceptionListSchemaDecoded;
6 changes: 6 additions & 0 deletions packages/kbn-securitysolution-list-constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ export const LIST_PRIVILEGES_URL = `${LIST_URL}/privileges`;
export const EXCEPTION_LIST_URL = '/api/exception_lists';
export const EXCEPTION_LIST_ITEM_URL = '/api/exception_lists/items';

/**
* Internal exception list routes
*/
export const INTERNAL_EXCEPTION_LIST_URL = `/internal${EXCEPTION_LIST_URL}`;
export const INTERNAL_EXCEPTIONS_LIST_ENSURE_CREATED_URL = `${INTERNAL_EXCEPTION_LIST_URL}/_create`;

/**
* Exception list spaces
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* 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 { validate } from '@kbn/securitysolution-io-ts-utils';
import {
CreateExceptionListSchemaDecoded,
exceptionListSchema,
} from '@kbn/securitysolution-io-ts-list-types';
import { IKibanaResponse, KibanaRequest, KibanaResponseFactory } from '@kbn/core-http-server';

import { SiemResponseFactory, getExceptionListClient } from '../routes';
import { ListsRequestHandlerContext } from '../types';

export const createExceptionListHandler = async (
context: ListsRequestHandlerContext,
request: KibanaRequest<unknown, unknown, CreateExceptionListSchemaDecoded, 'post'>,
response: KibanaResponseFactory,
siemResponse: SiemResponseFactory,
options: { ignoreExisting: boolean } = { ignoreExisting: false }
): Promise<IKibanaResponse> => {
const {
name,
tags,
meta,
namespace_type: namespaceType,
description,
list_id: listId,
type,
version,
} = request.body;
const exceptionLists = await getExceptionListClient(context);
Copy link
Member

Choose a reason for hiding this comment

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

nit: Better to name this exceptionListsClient.

const exceptionList = await exceptionLists.getExceptionList({
id: undefined,
listId,
namespaceType,
});

if (exceptionList != null) {
if (options.ignoreExisting) {
return response.ok({ body: exceptionList });
}
return siemResponse.error({
body: `exception list id: "${listId}" already exists`,
statusCode: 409,
});
} else {
const createdList = await exceptionLists.createExceptionList({
description,
immutable: false,
listId,
meta,
name,
namespaceType,
tags,
type,
version,
});
const [validated, errors] = validate(createdList, exceptionListSchema);
if (errors != null) {
return siemResponse.error({ body: errors, statusCode: 500 });
} else {
return response.ok({ body: validated ?? {} });
}
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,17 @@
* 2.0.
*/

import { validate } from '@kbn/securitysolution-io-ts-utils';
import { transformError } from '@kbn/securitysolution-es-utils';
import {
CreateExceptionListSchemaDecoded,
createExceptionListSchema,
exceptionListSchema,
} from '@kbn/securitysolution-io-ts-list-types';
import { EXCEPTION_LIST_URL } from '@kbn/securitysolution-list-constants';

import type { ListsPluginRouter } from '../types';
import { createExceptionListHandler } from '../handlers/create_exception_list_handler';

import { buildRouteValidation, buildSiemResponse } from './utils';
import { getExceptionListClient } from './utils/get_exception_list_client';

export const createExceptionListRoute = (router: ListsPluginRouter): void => {
router.post(
Expand All @@ -36,46 +34,7 @@ export const createExceptionListRoute = (router: ListsPluginRouter): void => {
async (context, request, response) => {
const siemResponse = buildSiemResponse(response);
try {
const {
name,
tags,
meta,
namespace_type: namespaceType,
description,
list_id: listId,
type,
version,
} = request.body;
const exceptionLists = await getExceptionListClient(context);
const exceptionList = await exceptionLists.getExceptionList({
id: undefined,
listId,
namespaceType,
});
if (exceptionList != null) {
return siemResponse.error({
body: `exception list id: "${listId}" already exists`,
statusCode: 409,
});
} else {
const createdList = await exceptionLists.createExceptionList({
description,
immutable: false,
listId,
meta,
name,
namespaceType,
tags,
type,
version,
});
const [validated, errors] = validate(createdList, exceptionListSchema);
if (errors != null) {
return siemResponse.error({ body: errors, statusCode: 500 });
} else {
return response.ok({ body: validated ?? {} });
}
}
return await createExceptionListHandler(context, request, response, siemResponse);
} catch (err) {
const error = transformError(err);
return siemResponse.error({
Expand Down
3 changes: 3 additions & 0 deletions x-pack/plugins/lists/server/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,6 @@ export * from './update_exception_list_route';
export * from './update_list_item_route';
export * from './update_list_route';
export * from './utils';

// internal
export * from './internal/create_exceptions_list_route';
yctercero marked this conversation as resolved.
Show resolved Hide resolved
4 changes: 4 additions & 0 deletions x-pack/plugins/lists/server/routes/init_routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
findListRoute,
importExceptionsRoute,
importListItemRoute,
internalCreateExceptionListRoute,
patchListItemRoute,
patchListRoute,
readEndpointListItemRoute,
Expand Down Expand Up @@ -103,4 +104,7 @@ export const initRoutes = (router: ListsPluginRouter, config: ConfigType): void

// exception list items summary
summaryExceptionListRoute(router);

// internal routes
internalCreateExceptionListRoute(router);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* 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 { transformError } from '@kbn/securitysolution-es-utils';
import {
InternalCreateExceptionListSchemaDecoded,
internalCreateExceptionListSchema,
} from '@kbn/securitysolution-io-ts-list-types';
import { INTERNAL_EXCEPTIONS_LIST_ENSURE_CREATED_URL } from '@kbn/securitysolution-list-constants';

import { createExceptionListHandler } from '../../handlers/create_exception_list_handler';
import type { ListsPluginRouter } from '../../types';
import { buildRouteValidation, buildSiemResponse } from '../utils';

export const internalCreateExceptionListRoute = (router: ListsPluginRouter): void => {
router.post(
{
options: {
tags: ['access:lists-all'],
},
path: INTERNAL_EXCEPTIONS_LIST_ENSURE_CREATED_URL,
validate: {
body: buildRouteValidation<
typeof internalCreateExceptionListSchema,
InternalCreateExceptionListSchemaDecoded
>(internalCreateExceptionListSchema),
},
},
async (context, request, response) => {
const siemResponse = buildSiemResponse(response);
try {
return await createExceptionListHandler(context, request, response, siemResponse, {
ignoreExisting: true,
});
} catch (err) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Do you need the try {} catch ()?
createExceptionListHandler() seems to already do all fo this.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah, it will catch all errors inside the handler and will return a proper http error if something throws.

const error = transformError(err);
return siemResponse.error({
body: error.message,
statusCode: error.statusCode,
});
}
}
);
};
Loading