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

[Alerting] fixes to allow pre-configured actions to be executed #63432

Merged
merged 2 commits into from
Apr 14, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
67 changes: 67 additions & 0 deletions x-pack/plugins/actions/server/create_execute_function.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ describe('execute()', () => {
actionTypeRegistry: actionTypeRegistryMock.create(),
getScopedSavedObjectsClient: jest.fn().mockReturnValueOnce(savedObjectsClient),
isESOUsingEphemeralEncryptionKey: false,
preconfiguredActions: [],
});
savedObjectsClient.get.mockResolvedValueOnce({
id: '123',
Expand Down Expand Up @@ -68,6 +69,68 @@ describe('execute()', () => {
});
});

test('schedules the action with all given parameters with a preconfigured action', async () => {
Copy link
Member Author

Choose a reason for hiding this comment

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

This is a copy of the test above it, only changing to use a preconfigured action.

const executeFn = createExecuteFunction({
getBasePath,
taskManager: mockTaskManager,
actionTypeRegistry: actionTypeRegistryMock.create(),
getScopedSavedObjectsClient: jest.fn().mockReturnValueOnce(savedObjectsClient),
isESOUsingEphemeralEncryptionKey: false,
preconfiguredActions: [
{
id: '123',
actionTypeId: 'mock-action-preconfigured',
config: {},
isPreconfigured: true,
name: 'x',
secrets: {},
},
],
});
savedObjectsClient.get.mockResolvedValueOnce({
id: '123',
type: 'action',
attributes: {
actionTypeId: 'mock-action',
},
references: [],
});
savedObjectsClient.create.mockResolvedValueOnce({
id: '234',
type: 'action_task_params',
attributes: {},
references: [],
});
await executeFn({
id: '123',
params: { baz: false },
spaceId: 'default',
apiKey: Buffer.from('123:abc').toString('base64'),
});
expect(mockTaskManager.schedule).toHaveBeenCalledTimes(1);
expect(mockTaskManager.schedule.mock.calls[0]).toMatchInlineSnapshot(`
Array [
Object {
"params": Object {
"actionTaskParamsId": "234",
"spaceId": "default",
},
"scope": Array [
"actions",
],
"state": Object {},
"taskType": "actions:mock-action-preconfigured",
},
]
`);
expect(savedObjectsClient.get).not.toHaveBeenCalled();
expect(savedObjectsClient.create).toHaveBeenCalledWith('action_task_params', {
actionId: '123',
params: { baz: false },
apiKey: Buffer.from('123:abc').toString('base64'),
});
});

test('uses API key when provided', async () => {
const getScopedSavedObjectsClient = jest.fn().mockReturnValueOnce(savedObjectsClient);
const executeFn = createExecuteFunction({
Expand All @@ -76,6 +139,7 @@ describe('execute()', () => {
getScopedSavedObjectsClient,
isESOUsingEphemeralEncryptionKey: false,
actionTypeRegistry: actionTypeRegistryMock.create(),
preconfiguredActions: [],
});
savedObjectsClient.get.mockResolvedValueOnce({
id: '123',
Expand Down Expand Up @@ -125,6 +189,7 @@ describe('execute()', () => {
getScopedSavedObjectsClient,
isESOUsingEphemeralEncryptionKey: false,
actionTypeRegistry: actionTypeRegistryMock.create(),
preconfiguredActions: [],
});
savedObjectsClient.get.mockResolvedValueOnce({
id: '123',
Expand Down Expand Up @@ -171,6 +236,7 @@ describe('execute()', () => {
getScopedSavedObjectsClient,
isESOUsingEphemeralEncryptionKey: true,
actionTypeRegistry: actionTypeRegistryMock.create(),
preconfiguredActions: [],
});
await expect(
executeFn({
Expand All @@ -193,6 +259,7 @@ describe('execute()', () => {
getScopedSavedObjectsClient,
isESOUsingEphemeralEncryptionKey: false,
actionTypeRegistry: mockedActionTypeRegistry,
preconfiguredActions: [],
});
mockedActionTypeRegistry.ensureActionTypeEnabled.mockImplementation(() => {
throw new Error('Fail');
Expand Down
25 changes: 21 additions & 4 deletions x-pack/plugins/actions/server/create_execute_function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,20 @@

import { SavedObjectsClientContract } from '../../../../src/core/server';
import { TaskManagerStartContract } from '../../task_manager/server';
import { GetBasePathFunction, RawAction, ActionTypeRegistryContract } from './types';
import {
GetBasePathFunction,
RawAction,
ActionTypeRegistryContract,
PreConfiguredAction,
} from './types';

interface CreateExecuteFunctionOptions {
taskManager: TaskManagerStartContract;
getScopedSavedObjectsClient: (request: any) => SavedObjectsClientContract;
getBasePath: GetBasePathFunction;
isESOUsingEphemeralEncryptionKey: boolean;
actionTypeRegistry: ActionTypeRegistryContract;
preconfiguredActions: PreConfiguredAction[];
}

export interface ExecuteOptions {
Expand All @@ -29,6 +35,7 @@ export function createExecuteFunction({
actionTypeRegistry,
getScopedSavedObjectsClient,
isESOUsingEphemeralEncryptionKey,
preconfiguredActions,
}: CreateExecuteFunctionOptions) {
return async function execute({ id, params, spaceId, apiKey }: ExecuteOptions) {
if (isESOUsingEphemeralEncryptionKey === true) {
Expand Down Expand Up @@ -61,9 +68,9 @@ export function createExecuteFunction({
};

const savedObjectsClient = getScopedSavedObjectsClient(fakeRequest);
const actionSavedObject = await savedObjectsClient.get<RawAction>('action', id);
const actionTypeId = await getActionTypeId(id);

actionTypeRegistry.ensureActionTypeEnabled(actionSavedObject.attributes.actionTypeId);
actionTypeRegistry.ensureActionTypeEnabled(actionTypeId);

const actionTaskParamsRecord = await savedObjectsClient.create('action_task_params', {
actionId: id,
Expand All @@ -72,13 +79,23 @@ export function createExecuteFunction({
});

await taskManager.schedule({
taskType: `actions:${actionSavedObject.attributes.actionTypeId}`,
taskType: `actions:${actionTypeId}`,
params: {
spaceId,
actionTaskParamsId: actionTaskParamsRecord.id,
},
state: {},
scope: ['actions'],
});

async function getActionTypeId(actionId: string): Promise<string> {
Copy link
Member Author

Choose a reason for hiding this comment

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

As a side note, we might want to look at denormalizing the action type along side action id, where appropriate, to avoid this SO lookup just to get the action type. OTOH, it's only when actions are executed, so ... it's not on every turn of an alert ...

Copy link
Contributor

@mikecote mikecote Apr 14, 2020

Choose a reason for hiding this comment

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

(Moment not writing a comment haunts me): I think the lookup is also there to ensure the user has access to read that action, otherwise it would fail the attempt to create a task executing that action.

Sigh note, this would also mean pre-configured actions don't work with feature controls at this time. I will open a separate issue for that, to test and validate that theory but the implementation below looks good.

Copy link
Contributor

Choose a reason for hiding this comment

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

Created issue here: #63496.

const pcAction = preconfiguredActions.find(action => action.id === actionId);
if (pcAction) {
return pcAction.actionTypeId;
}

const actionSO = await savedObjectsClient.get<RawAction>('action', actionId);
return actionSO.attributes.actionTypeId;
}
};
}
2 changes: 2 additions & 0 deletions x-pack/plugins/actions/server/lib/action_executor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ actionExecutor.initialize({
actionTypeRegistry,
encryptedSavedObjectsPlugin,
eventLogger: eventLoggerMock.create(),
preconfiguredActions: [],
});

beforeEach(() => {
Expand Down Expand Up @@ -232,6 +233,7 @@ test('throws an error when passing isESOUsingEphemeralEncryptionKey with value o
actionTypeRegistry,
encryptedSavedObjectsPlugin,
eventLogger: eventLoggerMock.create(),
preconfiguredActions: [],
});
await expect(
customActionExecutor.execute(executeParams)
Expand Down
70 changes: 57 additions & 13 deletions x-pack/plugins/actions/server/lib/action_executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import {
ActionTypeRegistryContract,
GetServicesFunction,
RawAction,
PreConfiguredAction,
Services,
} from '../types';
import { EncryptedSavedObjectsPluginStart } from '../../../encrypted_saved_objects/server';
import { SpacesServiceSetup } from '../../../spaces/server';
Expand All @@ -24,6 +26,7 @@ export interface ActionExecutorContext {
encryptedSavedObjectsPlugin: EncryptedSavedObjectsPluginStart;
actionTypeRegistry: ActionTypeRegistryContract;
eventLogger: IEventLogger;
preconfiguredActions: PreConfiguredAction[];
}

export interface ExecuteOptions {
Expand Down Expand Up @@ -72,28 +75,22 @@ export class ActionExecutor {
encryptedSavedObjectsPlugin,
actionTypeRegistry,
eventLogger,
preconfiguredActions,
} = this.actionExecutorContext!;

const services = getServices(request);
const spaceId = spaces && spaces.getSpaceId(request);
const namespace = spaceId && spaceId !== 'default' ? { namespace: spaceId } : {};

// Ensure user can read the action before processing
const {
attributes: { actionTypeId, config, name },
} = await services.savedObjectsClient.get<RawAction>('action', actionId);

actionTypeRegistry.ensureActionTypeEnabled(actionTypeId);

// Only get encrypted attributes here, the remaining attributes can be fetched in
// the savedObjectsClient call
const {
attributes: { secrets },
} = await encryptedSavedObjectsPlugin.getDecryptedAsInternalUser<RawAction>(
'action',
const { actionTypeId, name, config, secrets } = await getActionInfo(
services,
encryptedSavedObjectsPlugin,
preconfiguredActions,
actionId,
namespace
);

actionTypeRegistry.ensureActionTypeEnabled(actionTypeId);
const actionType = actionTypeRegistry.get(actionTypeId);

let validatedParams: Record<string, any>;
Expand Down Expand Up @@ -173,3 +170,50 @@ function actionErrorToMessage(result: ActionTypeExecutorResult): string {

return message;
}

interface ActionInfo {
actionTypeId: string;
name: string;
config: any;
secrets: any;
}

async function getActionInfo(
services: Services,
encryptedSavedObjectsPlugin: EncryptedSavedObjectsPluginStart,
preconfiguredActions: PreConfiguredAction[],
actionId: string,
namespace: string | undefined
): Promise<ActionInfo> {
// check to see if it's a pre-configured action first
const pcAction = preconfiguredActions.find(
preconfiguredAction => preconfiguredAction.id === actionId
);
if (pcAction) {
return {
actionTypeId: pcAction.actionTypeId,
name: pcAction.name,
config: pcAction.config,
secrets: pcAction.secrets,
};
}

// if not pre-configured action, should be a saved object
// ensure user can read the action before processing
const {
attributes: { actionTypeId, config, name },
} = await services.savedObjectsClient.get<RawAction>('action', actionId);

const {
attributes: { secrets },
} = await encryptedSavedObjectsPlugin.getDecryptedAsInternalUser<RawAction>('action', actionId, {
namespace: namespace === 'default' ? undefined : namespace,
});

return {
actionTypeId,
name,
config,
secrets,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ const actionExecutorInitializerParams = {
actionTypeRegistry,
encryptedSavedObjectsPlugin: mockedEncryptedSavedObjectsPlugin,
eventLogger: eventLoggerMock.create(),
preconfiguredActions: [],
};
const taskRunnerFactoryInitializerParams = {
spaceIdToNamespace,
Expand Down
2 changes: 2 additions & 0 deletions x-pack/plugins/actions/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,7 @@ export class ActionsPlugin implements Plugin<Promise<PluginSetupContract>, Plugi
getServices: this.getServicesFactory(core.savedObjects),
encryptedSavedObjectsPlugin: plugins.encryptedSavedObjects,
actionTypeRegistry: actionTypeRegistry!,
preconfiguredActions,
});

taskRunnerFactory!.initialize({
Expand All @@ -265,6 +266,7 @@ export class ActionsPlugin implements Plugin<Promise<PluginSetupContract>, Plugi
getScopedSavedObjectsClient: core.savedObjects.getScopedClient,
getBasePath: this.getBasePath,
isESOUsingEphemeralEncryptionKey: isESOUsingEphemeralEncryptionKey!,
preconfiguredActions,
}),
isActionTypeEnabled: id => {
return this.actionTypeRegistry!.isActionTypeEnabled(id);
Expand Down
21 changes: 21 additions & 0 deletions x-pack/test/alerting_api_integration/common/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,27 @@ export function createTestConfig(name: string, options: CreateTestConfigOptions)
xyzSecret2: 'credential2',
},
},
{
Copy link
Member Author

Choose a reason for hiding this comment

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

More pre-configured actions, used in the tests below. Show up in the various getAll() tests as well ...

id: 'preconfigured-es-index-action',
actionTypeId: '.index',
name: 'preconfigured_es_index_action',
config: {
index: 'functional-test-actions-index-preconfigured',
refresh: true,
executionTimeField: 'timestamp',
},
},
{
id: 'preconfigured.test.index-record',
actionTypeId: 'test.index-record',
name: 'Test:_Preconfigured_Index_Record',
config: {
unencrypted: 'ignored-but-required',
},
secrets: {
encrypted: 'this-is-also-ignored-and-also-required',
},
},
])}`,
...disabledPlugins.map(key => `--xpack.${key}.enabled=false`),
`--plugin-path=${path.join(__dirname, 'fixtures', 'plugins', 'alerts')}`,
Expand Down
Loading