- {item.label}
+ {item.labelFormatted ? labelDateFormatter(item.labelFormatted) : item.label}
|
diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.test.js b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.test.js
index 4dcc67dc4697..ceae784cf74a 100644
--- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.test.js
+++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.test.js
@@ -16,6 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
+import { from } from 'rxjs';
import { AbstractSearchStrategy } from './abstract_search_strategy';
describe('AbstractSearchStrategy', () => {
@@ -55,7 +56,7 @@ describe('AbstractSearchStrategy', () => {
test('should return response', async () => {
const searches = [{ body: 'body', index: 'index' }];
- const searchFn = jest.fn().mockReturnValue(Promise.resolve({}));
+ const searchFn = jest.fn().mockReturnValue(from(Promise.resolve({})));
const responses = await abstractSearchStrategy.search(
{
@@ -82,7 +83,6 @@ describe('AbstractSearchStrategy', () => {
expect(responses).toEqual([{}]);
expect(searchFn).toHaveBeenCalledWith(
- {},
{
params: {
body: 'body',
@@ -92,7 +92,8 @@ describe('AbstractSearchStrategy', () => {
},
{
strategy: 'es',
- }
+ },
+ {}
);
});
});
diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts
index 2eb92b2b777e..7b62ad310a35 100644
--- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts
+++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts
@@ -60,20 +60,22 @@ export class AbstractSearchStrategy {
const requests: any[] = [];
bodies.forEach((body) => {
requests.push(
- deps.data.search.search(
- req.requestContext,
- {
- params: {
- ...body,
- ...this.additionalParams,
+ deps.data.search
+ .search(
+ {
+ params: {
+ ...body,
+ ...this.additionalParams,
+ },
+ indexType: this.indexType,
},
- indexType: this.indexType,
- },
- {
- ...options,
- strategy: this.searchStrategyName,
- }
- )
+ {
+ ...options,
+ strategy: this.searchStrategyName,
+ },
+ req.requestContext
+ )
+ .toPromise()
);
});
return Promise.all(requests);
diff --git a/src/plugins/vis_type_timeseries/server/validation_telemetry/validation_telemetry_service.ts b/src/plugins/vis_type_timeseries/server/validation_telemetry/validation_telemetry_service.ts
index a5f095a4c4f3..0969174c7143 100644
--- a/src/plugins/vis_type_timeseries/server/validation_telemetry/validation_telemetry_service.ts
+++ b/src/plugins/vis_type_timeseries/server/validation_telemetry/validation_telemetry_service.ts
@@ -17,7 +17,7 @@
* under the License.
*/
-import { LegacyAPICaller, CoreSetup, Plugin, PluginInitializerContext } from 'kibana/server';
+import { CoreSetup, Plugin, PluginInitializerContext } from 'kibana/server';
import { UsageCollectionSetup } from '../../../usage_collection/server';
import { tsvbTelemetrySavedObjectType } from '../saved_objects';
@@ -49,7 +49,7 @@ export class ValidationTelemetryService implements Plugin ({
type: 'tsvb-validation',
isReady: () => this.kibanaIndex !== '',
- fetch: async (callCluster: LegacyAPICaller) => {
+ fetch: async ({ callCluster }) => {
try {
const response = await callCluster('get', {
index: this.kibanaIndex,
diff --git a/src/plugins/vis_type_vega/server/usage_collector/get_usage_collector.test.ts b/src/plugins/vis_type_vega/server/usage_collector/get_usage_collector.test.ts
index 891ebf658267..6f17703bc9de 100644
--- a/src/plugins/vis_type_vega/server/usage_collector/get_usage_collector.test.ts
+++ b/src/plugins/vis_type_vega/server/usage_collector/get_usage_collector.test.ts
@@ -17,9 +17,9 @@
* under the License.
*/
-import { LegacyAPICaller } from 'src/core/server';
import { getStats } from './get_usage_collector';
import { HomeServerPluginSetup } from '../../../home/server';
+import { createCollectorFetchContextMock } from 'src/plugins/usage_collection/server/mocks';
const mockedSavedObjects = [
// vega-lite lib spec
@@ -70,8 +70,11 @@ const mockedSavedObjects = [
},
];
-const getMockCallCluster = (hits?: unknown[]) =>
- jest.fn().mockReturnValue(Promise.resolve({ hits: { hits } }) as unknown) as LegacyAPICaller;
+const getMockCollectorFetchContext = (hits?: unknown[]) => {
+ const fetchParamsMock = createCollectorFetchContextMock();
+ fetchParamsMock.callCluster.mockResolvedValue({ hits: { hits } });
+ return fetchParamsMock;
+};
describe('Vega visualization usage collector', () => {
const mockIndex = 'mock_index';
@@ -101,19 +104,23 @@ describe('Vega visualization usage collector', () => {
};
test('Returns undefined when no results found (undefined)', async () => {
- const result = await getStats(getMockCallCluster(), mockIndex, mockDeps);
+ const result = await getStats(getMockCollectorFetchContext().callCluster, mockIndex, mockDeps);
expect(result).toBeUndefined();
});
test('Returns undefined when no results found (0 results)', async () => {
- const result = await getStats(getMockCallCluster([]), mockIndex, mockDeps);
+ const result = await getStats(
+ getMockCollectorFetchContext([]).callCluster,
+ mockIndex,
+ mockDeps
+ );
expect(result).toBeUndefined();
});
test('Returns undefined when no vega saved objects found', async () => {
- const mockCallCluster = getMockCallCluster([
+ const mockCollectorFetchContext = getMockCollectorFetchContext([
{
_id: 'visualization:myvis-123',
_source: {
@@ -122,13 +129,13 @@ describe('Vega visualization usage collector', () => {
},
},
]);
- const result = await getStats(mockCallCluster, mockIndex, mockDeps);
+ const result = await getStats(mockCollectorFetchContext.callCluster, mockIndex, mockDeps);
expect(result).toBeUndefined();
});
test('Should ingnore sample data visualizations', async () => {
- const mockCallCluster = getMockCallCluster([
+ const mockCollectorFetchContext = getMockCollectorFetchContext([
{
_id: 'visualization:sampledata-123',
_source: {
@@ -146,14 +153,14 @@ describe('Vega visualization usage collector', () => {
},
]);
- const result = await getStats(mockCallCluster, mockIndex, mockDeps);
+ const result = await getStats(mockCollectorFetchContext.callCluster, mockIndex, mockDeps);
expect(result).toBeUndefined();
});
test('Summarizes visualizations response data', async () => {
- const mockCallCluster = getMockCallCluster(mockedSavedObjects);
- const result = await getStats(mockCallCluster, mockIndex, mockDeps);
+ const mockCollectorFetchContext = getMockCollectorFetchContext(mockedSavedObjects);
+ const result = await getStats(mockCollectorFetchContext.callCluster, mockIndex, mockDeps);
expect(result).toMatchObject({
vega_lib_specs_total: 2,
diff --git a/src/plugins/vis_type_vega/server/usage_collector/register_vega_collector.test.ts b/src/plugins/vis_type_vega/server/usage_collector/register_vega_collector.test.ts
index 433b786ed46a..e092fc8acfd7 100644
--- a/src/plugins/vis_type_vega/server/usage_collector/register_vega_collector.test.ts
+++ b/src/plugins/vis_type_vega/server/usage_collector/register_vega_collector.test.ts
@@ -20,6 +20,7 @@
import { of } from 'rxjs';
import { mockStats, mockGetStats } from './get_usage_collector.mock';
import { createUsageCollectionSetupMock } from 'src/plugins/usage_collection/server/usage_collection.mock';
+import { createCollectorFetchContextMock } from 'src/plugins/usage_collection/server/mocks';
import { HomeServerPluginSetup } from '../../../home/server';
import { registerVegaUsageCollector } from './register_vega_collector';
@@ -59,10 +60,14 @@ describe('registerVegaUsageCollector', () => {
const mockCollectorSet = createUsageCollectionSetupMock();
registerVegaUsageCollector(mockCollectorSet, mockConfig, mockDeps);
const usageCollectorConfig = mockCollectorSet.makeUsageCollector.mock.calls[0][0];
- const mockCallCluster = jest.fn();
- const fetchResult = await usageCollectorConfig.fetch(mockCallCluster);
+ const mockedCollectorFetchContext = createCollectorFetchContextMock();
+ const fetchResult = await usageCollectorConfig.fetch(mockedCollectorFetchContext);
expect(mockGetStats).toBeCalledTimes(1);
- expect(mockGetStats).toBeCalledWith(mockCallCluster, mockIndex, mockDeps);
+ expect(mockGetStats).toBeCalledWith(
+ mockedCollectorFetchContext.callCluster,
+ mockIndex,
+ mockDeps
+ );
expect(fetchResult).toBe(mockStats);
});
});
diff --git a/src/plugins/vis_type_vega/server/usage_collector/register_vega_collector.ts b/src/plugins/vis_type_vega/server/usage_collector/register_vega_collector.ts
index af62821f7cdc..e4772dad99d4 100644
--- a/src/plugins/vis_type_vega/server/usage_collector/register_vega_collector.ts
+++ b/src/plugins/vis_type_vega/server/usage_collector/register_vega_collector.ts
@@ -35,7 +35,7 @@ export function registerVegaUsageCollector(
vega_lite_lib_specs_total: { type: 'long' },
vega_use_map_total: { type: 'long' },
},
- fetch: async (callCluster) => {
+ fetch: async ({ callCluster }) => {
const { index } = (await config.pipe(first()).toPromise()).kibana;
return await getStats(callCluster, index, dependencies);
diff --git a/src/plugins/visualizations/kibana.json b/src/plugins/visualizations/kibana.json
index 688987b1104a..0ced74e2733d 100644
--- a/src/plugins/visualizations/kibana.json
+++ b/src/plugins/visualizations/kibana.json
@@ -3,7 +3,14 @@
"version": "kibana",
"server": true,
"ui": true,
- "requiredPlugins": ["data", "expressions", "uiActions", "embeddable", "inspector" ],
+ "requiredPlugins": [
+ "data",
+ "expressions",
+ "uiActions",
+ "embeddable",
+ "inspector",
+ "savedObjects"
+ ],
"optionalPlugins": ["usageCollection"],
- "requiredBundles": ["kibanaUtils", "discover", "savedObjects"]
+ "requiredBundles": ["kibanaUtils", "discover"]
}
diff --git a/src/plugins/visualizations/public/mocks.ts b/src/plugins/visualizations/public/mocks.ts
index 90e4936a58b4..f20e87dbd3b6 100644
--- a/src/plugins/visualizations/public/mocks.ts
+++ b/src/plugins/visualizations/public/mocks.ts
@@ -28,6 +28,7 @@ import { usageCollectionPluginMock } from '../../../plugins/usage_collection/pub
import { uiActionsPluginMock } from '../../../plugins/ui_actions/public/mocks';
import { inspectorPluginMock } from '../../../plugins/inspector/public/mocks';
import { dashboardPluginMock } from '../../../plugins/dashboard/public/mocks';
+import { savedObjectsPluginMock } from '../../../plugins/saved_objects/public/mocks';
const createSetupContract = (): VisualizationsSetup => ({
createBaseVisualization: jest.fn(),
@@ -73,6 +74,7 @@ const createInstance = async () => {
dashboard: dashboardPluginMock.createStartContract(),
getAttributeService: jest.fn(),
savedObjectsClient: coreMock.createStart().savedObjects.client,
+ savedObjects: savedObjectsPluginMock.createStartContract(),
});
return {
diff --git a/src/plugins/visualizations/public/plugin.ts b/src/plugins/visualizations/public/plugin.ts
index be7629ef4114..c1dbe39def64 100644
--- a/src/plugins/visualizations/public/plugin.ts
+++ b/src/plugins/visualizations/public/plugin.ts
@@ -78,6 +78,7 @@ import {
} from './saved_visualizations/_saved_vis';
import { createSavedSearchesLoader } from '../../discover/public';
import { DashboardStart } from '../../dashboard/public';
+import { SavedObjectsStart } from '../../saved_objects/public';
/**
* Interface for this plugin's returned setup/start contracts.
@@ -113,6 +114,7 @@ export interface VisualizationsStartDeps {
application: ApplicationStart;
dashboard: DashboardStart;
getAttributeService: EmbeddableStart['getAttributeService'];
+ savedObjects: SavedObjectsStart;
savedObjectsClient: SavedObjectsClientContract;
}
@@ -160,7 +162,7 @@ export class VisualizationsPlugin
public start(
core: CoreStart,
- { data, expressions, uiActions, embeddable, dashboard }: VisualizationsStartDeps
+ { data, expressions, uiActions, embeddable, dashboard, savedObjects }: VisualizationsStartDeps
): VisualizationsStart {
const types = this.types.start();
setI18n(core.i18n);
@@ -182,18 +184,13 @@ export class VisualizationsPlugin
const savedVisualizationsLoader = createSavedVisLoader({
savedObjectsClient: core.savedObjects.client,
indexPatterns: data.indexPatterns,
- search: data.search,
- chrome: core.chrome,
- overlays: core.overlays,
+ savedObjects,
visualizationTypes: types,
});
setSavedVisualizationsLoader(savedVisualizationsLoader);
const savedSearchLoader = createSavedSearchesLoader({
savedObjectsClient: core.savedObjects.client,
- indexPatterns: data.indexPatterns,
- search: data.search,
- chrome: core.chrome,
- overlays: core.overlays,
+ savedObjects,
});
setSavedSearchLoader(savedSearchLoader);
return {
diff --git a/src/plugins/visualizations/public/saved_visualizations/_saved_vis.ts b/src/plugins/visualizations/public/saved_visualizations/_saved_vis.ts
index 8edf494ddc0e..59359fb00cc9 100644
--- a/src/plugins/visualizations/public/saved_visualizations/_saved_vis.ts
+++ b/src/plugins/visualizations/public/saved_visualizations/_saved_vis.ts
@@ -24,17 +24,20 @@
*
* NOTE: It's a type of SavedObject, but specific to visualizations.
*/
-import {
- createSavedObjectClass,
- SavedObject,
- SavedObjectKibanaServices,
-} from '../../../../plugins/saved_objects/public';
+import { SavedObjectsStart, SavedObject } from '../../../../plugins/saved_objects/public';
// @ts-ignore
import { updateOldState } from '../legacy/vis_update_state';
import { extractReferences, injectReferences } from './saved_visualization_references';
-import { IIndexPattern } from '../../../../plugins/data/public';
+import { IIndexPattern, IndexPatternsContract } from '../../../../plugins/data/public';
import { ISavedVis, SerializedVis } from '../types';
import { createSavedSearchesLoader } from '../../../discover/public';
+import { SavedObjectsClientContract } from '../../../../core/public';
+
+export interface SavedVisServices {
+ savedObjectsClient: SavedObjectsClientContract;
+ savedObjects: SavedObjectsStart;
+ indexPatterns: IndexPatternsContract;
+}
export const convertToSerializedVis = (savedVis: ISavedVis): SerializedVis => {
const { id, title, description, visState, uiStateJSON, searchSourceFields } = savedVis;
@@ -73,11 +76,10 @@ export const convertFromSerializedVis = (vis: SerializedVis): ISavedVis => {
};
};
-export function createSavedVisClass(services: SavedObjectKibanaServices) {
- const SavedObjectClass = createSavedObjectClass(services);
+export function createSavedVisClass(services: SavedVisServices) {
const savedSearch = createSavedSearchesLoader(services);
- class SavedVis extends SavedObjectClass {
+ class SavedVis extends services.savedObjects.SavedObjectClass {
public static type: string = 'visualization';
public static mapping: Record = {
title: 'text',
@@ -130,5 +132,5 @@ export function createSavedVisClass(services: SavedObjectKibanaServices) {
}
}
- return SavedVis as new (opts: Record | string) => SavedObject;
+ return (SavedVis as unknown) as new (opts: Record | string) => SavedObject;
}
diff --git a/src/plugins/visualizations/public/saved_visualizations/saved_visualizations.ts b/src/plugins/visualizations/public/saved_visualizations/saved_visualizations.ts
index 0ec3c0dab2e9..760bf3cc7a36 100644
--- a/src/plugins/visualizations/public/saved_visualizations/saved_visualizations.ts
+++ b/src/plugins/visualizations/public/saved_visualizations/saved_visualizations.ts
@@ -16,19 +16,16 @@
* specific language governing permissions and limitations
* under the License.
*/
-import {
- SavedObjectLoader,
- SavedObjectKibanaServices,
-} from '../../../../plugins/saved_objects/public';
+import { SavedObjectLoader } from '../../../../plugins/saved_objects/public';
import { findListItems } from './find_list_items';
-import { createSavedVisClass } from './_saved_vis';
+import { createSavedVisClass, SavedVisServices } from './_saved_vis';
import { TypesStart } from '../vis_types';
-export interface SavedObjectKibanaServicesWithVisualizations extends SavedObjectKibanaServices {
+export interface SavedVisServicesWithVisualizations extends SavedVisServices {
visualizationTypes: TypesStart;
}
export type SavedVisualizationsLoader = ReturnType;
-export function createSavedVisLoader(services: SavedObjectKibanaServicesWithVisualizations) {
+export function createSavedVisLoader(services: SavedVisServicesWithVisualizations) {
const { savedObjectsClient, visualizationTypes } = services;
class SavedObjectLoaderVisualize extends SavedObjectLoader {
diff --git a/src/plugins/visualizations/server/usage_collector/register_visualizations_collector.test.ts b/src/plugins/visualizations/server/usage_collector/register_visualizations_collector.test.ts
index 38d88dd65001..7789e3de13e5 100644
--- a/src/plugins/visualizations/server/usage_collector/register_visualizations_collector.test.ts
+++ b/src/plugins/visualizations/server/usage_collector/register_visualizations_collector.test.ts
@@ -20,6 +20,7 @@
import { of } from 'rxjs';
import { mockStats, mockGetStats } from './get_usage_collector.mock';
import { createUsageCollectionSetupMock } from 'src/plugins/usage_collection/server/usage_collection.mock';
+import { createCollectorFetchContextMock } from 'src/plugins/usage_collection/server/mocks';
import { registerVisualizationsCollector } from './register_visualizations_collector';
@@ -58,10 +59,10 @@ describe('registerVisualizationsCollector', () => {
const mockCollectorSet = createUsageCollectionSetupMock();
registerVisualizationsCollector(mockCollectorSet, mockConfig);
const usageCollectorConfig = mockCollectorSet.makeUsageCollector.mock.calls[0][0];
- const mockCallCluster = jest.fn();
- const fetchResult = await usageCollectorConfig.fetch(mockCallCluster);
+ const mockCollectorFetchContext = createCollectorFetchContextMock();
+ const fetchResult = await usageCollectorConfig.fetch(mockCollectorFetchContext);
expect(mockGetStats).toBeCalledTimes(1);
- expect(mockGetStats).toBeCalledWith(mockCallCluster, mockIndex);
+ expect(mockGetStats).toBeCalledWith(mockCollectorFetchContext.callCluster, mockIndex);
expect(fetchResult).toBe(mockStats);
});
});
diff --git a/src/plugins/visualizations/server/usage_collector/register_visualizations_collector.ts b/src/plugins/visualizations/server/usage_collector/register_visualizations_collector.ts
index 5919b3d20642..4188f564ed5f 100644
--- a/src/plugins/visualizations/server/usage_collector/register_visualizations_collector.ts
+++ b/src/plugins/visualizations/server/usage_collector/register_visualizations_collector.ts
@@ -41,7 +41,7 @@ export function registerVisualizationsCollector(
saved_90_days_total: { type: 'long' },
},
},
- fetch: async (callCluster) => {
+ fetch: async ({ callCluster }) => {
const index = (await config.pipe(first()).toPromise()).kibana.index;
return await getStats(callCluster, index);
},
diff --git a/src/plugins/visualize/public/application/utils/get_visualization_instance.ts b/src/plugins/visualize/public/application/utils/get_visualization_instance.ts
index c5cfa5a4c639..6010c4f8b163 100644
--- a/src/plugins/visualize/public/application/utils/get_visualization_instance.ts
+++ b/src/plugins/visualize/public/application/utils/get_visualization_instance.ts
@@ -35,7 +35,12 @@ const createVisualizeEmbeddableAndLinkSavedSearch = async (
vis: Vis,
visualizeServices: VisualizeServices
) => {
- const { chrome, data, overlays, createVisEmbeddableFromObject, savedObjects } = visualizeServices;
+ const {
+ data,
+ createVisEmbeddableFromObject,
+ savedObjects,
+ savedObjectsPublic,
+ } = visualizeServices;
const embeddableHandler = (await createVisEmbeddableFromObject(vis, {
timeRange: data.query.timefilter.timefilter.getTime(),
filters: data.query.filterManager.getFilters(),
@@ -55,10 +60,7 @@ const createVisualizeEmbeddableAndLinkSavedSearch = async (
if (vis.data.savedSearchId) {
savedSearch = await createSavedSearchesLoader({
savedObjectsClient: savedObjects.client,
- indexPatterns: data.indexPatterns,
- search: data.search,
- chrome,
- overlays,
+ savedObjects: savedObjectsPublic,
}).get(vis.data.savedSearchId);
}
diff --git a/src/plugins/visualize/public/plugin.ts b/src/plugins/visualize/public/plugin.ts
index 86159a13379a..ef7d8ea18902 100644
--- a/src/plugins/visualize/public/plugin.ts
+++ b/src/plugins/visualize/public/plugin.ts
@@ -49,7 +49,7 @@ import { DEFAULT_APP_CATEGORIES } from '../../../core/public';
import { SavedObjectsStart } from '../../saved_objects/public';
import { EmbeddableStart } from '../../embeddable/public';
import { DashboardStart } from '../../dashboard/public';
-import { UiActionsStart, VISUALIZE_FIELD_TRIGGER } from '../../ui_actions/public';
+import { UiActionsSetup, VISUALIZE_FIELD_TRIGGER } from '../../ui_actions/public';
import {
setUISettings,
setApplication,
@@ -69,7 +69,6 @@ export interface VisualizePluginStartDependencies {
urlForwarding: UrlForwardingStart;
savedObjects: SavedObjectsStart;
dashboard: DashboardStart;
- uiActions: UiActionsStart;
}
export interface VisualizePluginSetupDependencies {
@@ -77,6 +76,7 @@ export interface VisualizePluginSetupDependencies {
urlForwarding: UrlForwardingSetup;
data: DataPublicPluginSetup;
share?: SharePluginSetup;
+ uiActions: UiActionsSetup;
}
export class VisualizePlugin
@@ -90,7 +90,7 @@ export class VisualizePlugin
public async setup(
core: CoreSetup,
- { home, urlForwarding, data, share }: VisualizePluginSetupDependencies
+ { home, urlForwarding, data, share, uiActions }: VisualizePluginSetupDependencies
) {
const {
appMounted,
@@ -135,6 +135,7 @@ export class VisualizePlugin
);
}
setUISettings(core.uiSettings);
+ uiActions.addTriggerAction(VISUALIZE_FIELD_TRIGGER, visualizeFieldAction);
core.application.register({
id: 'visualize',
@@ -236,7 +237,6 @@ export class VisualizePlugin
if (plugins.share) {
setShareService(plugins.share);
}
- plugins.uiActions.addTriggerAction(VISUALIZE_FIELD_TRIGGER, visualizeFieldAction);
}
stop() {
diff --git a/test/accessibility/apps/kibana_overview.ts b/test/accessibility/apps/kibana_overview.ts
new file mode 100644
index 000000000000..1f703c64bbde
--- /dev/null
+++ b/test/accessibility/apps/kibana_overview.ts
@@ -0,0 +1,55 @@
+/*
+ * Licensed to Elasticsearch B.V. under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch B.V. licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { FtrProviderContext } from '../ftr_provider_context';
+
+export default function ({ getService, getPageObjects }: FtrProviderContext) {
+ const PageObjects = getPageObjects(['common', 'home']);
+ const a11y = getService('a11y');
+
+ describe('Kibana overview', () => {
+ const esArchiver = getService('esArchiver');
+
+ before(async () => {
+ await esArchiver.load('empty_kibana');
+ await PageObjects.common.navigateToApp('kibanaOverview');
+ });
+
+ after(async () => {
+ await PageObjects.common.navigateToUrl('home', '/tutorial_directory/sampleData', {
+ useActualUrl: true,
+ });
+ await PageObjects.home.removeSampleDataSet('flights');
+ await esArchiver.unload('empty_kibana');
+ });
+
+ it('Getting started view', async () => {
+ await a11y.testAppSnapshot();
+ });
+
+ it('Overview view', async () => {
+ await PageObjects.common.navigateToUrl('home', '/tutorial_directory/sampleData', {
+ useActualUrl: true,
+ });
+ await PageObjects.home.addSampleDataSet('flights');
+ await PageObjects.common.navigateToApp('kibanaOverview');
+ await a11y.testAppSnapshot();
+ });
+ });
+}
diff --git a/test/accessibility/config.ts b/test/accessibility/config.ts
index 9068a7e06def..9730eae1e136 100644
--- a/test/accessibility/config.ts
+++ b/test/accessibility/config.ts
@@ -36,6 +36,7 @@ export default async function ({ readConfigFile }: FtrConfigProviderContext) {
require.resolve('./apps/console'),
require.resolve('./apps/home'),
require.resolve('./apps/filter_panel'),
+ require.resolve('./apps/kibana_overview'),
],
pageObjects,
services,
diff --git a/test/functional/apps/discover/_field_visualize.ts b/test/functional/apps/discover/_field_visualize.ts
index c95211e98cdb..1a1631b9db48 100644
--- a/test/functional/apps/discover/_field_visualize.ts
+++ b/test/functional/apps/discover/_field_visualize.ts
@@ -32,7 +32,10 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
defaultIndex: 'logstash-*',
};
- describe('discover field visualize button', () => {
+ describe('discover field visualize button', function () {
+ // unskipped on cloud as these tests test the navigation
+ // from Discover to Visualize which happens only on OSS
+ this.tags(['skipCloud']);
before(async function () {
log.debug('load kibana index with default index pattern');
await esArchiver.load('discover');
diff --git a/test/functional/apps/discover/_shared_links.js b/test/functional/apps/discover/_shared_links.js
index 94409a94e925..56c648562404 100644
--- a/test/functional/apps/discover/_shared_links.js
+++ b/test/functional/apps/discover/_shared_links.js
@@ -28,7 +28,8 @@ export default function ({ getService, getPageObjects }) {
const browser = getService('browser');
const toasts = getService('toasts');
- describe('shared links', function describeIndexTests() {
+ // FLAKY: https://github.com/elastic/kibana/issues/80104
+ describe.skip('shared links', function describeIndexTests() {
let baseUrl;
async function setup({ storeStateInSessionStorage }) {
diff --git a/test/functional/services/filter_bar.ts b/test/functional/services/filter_bar.ts
index 98ab1babd60f..de895918efbb 100644
--- a/test/functional/services/filter_bar.ts
+++ b/test/functional/services/filter_bar.ts
@@ -124,9 +124,10 @@ export function FilterBarProvider({ getService, getPageObjects }: FtrProviderCon
await comboBox.set('filterOperatorList', operator);
const params = await testSubjects.find('filterParams');
const paramsComboBoxes = await params.findAllByCssSelector(
- '[data-test-subj~="filterParamsComboBox"]'
+ '[data-test-subj~="filterParamsComboBox"]',
+ 1000
);
- const paramFields = await params.findAllByTagName('input');
+ const paramFields = await params.findAllByTagName('input', 1000);
for (let i = 0; i < values.length; i++) {
let fieldValues = values[i];
if (!Array.isArray(fieldValues)) {
diff --git a/x-pack/package.json b/x-pack/package.json
index 67efa9f474c0..484a64fdc262 100644
--- a/x-pack/package.json
+++ b/x-pack/package.json
@@ -198,7 +198,7 @@
"loader-utils": "^1.2.3",
"lz-string": "^1.4.4",
"madge": "3.4.4",
- "mapbox-gl": "^1.10.0",
+ "mapbox-gl": "^1.12.0",
"mapbox-gl-draw-rectangle-mode": "^1.0.4",
"marge": "^1.0.1",
"memoize-one": "^5.0.0",
diff --git a/x-pack/plugins/alerts/server/alerts_client.test.ts b/x-pack/plugins/alerts/server/alerts_client.test.ts
deleted file mode 100644
index 8617ea891edf..000000000000
--- a/x-pack/plugins/alerts/server/alerts_client.test.ts
+++ /dev/null
@@ -1,4567 +0,0 @@
-/*
- * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
- * or more contributor license agreements. Licensed under the Elastic License;
- * you may not use this file except in compliance with the Elastic License.
- */
-import uuid from 'uuid';
-import { schema } from '@kbn/config-schema';
-import { AlertsClient, CreateOptions, ConstructorOptions } from './alerts_client';
-import { savedObjectsClientMock, loggingSystemMock } from '../../../../src/core/server/mocks';
-import { nodeTypes } from '../../../../src/plugins/data/common';
-import { esKuery } from '../../../../src/plugins/data/server';
-import { taskManagerMock } from '../../task_manager/server/mocks';
-import { alertTypeRegistryMock } from './alert_type_registry.mock';
-import { alertsAuthorizationMock } from './authorization/alerts_authorization.mock';
-import { TaskStatus } from '../../task_manager/server';
-import { IntervalSchedule, RawAlert } from './types';
-import { resolvable } from './test_utils';
-import { encryptedSavedObjectsMock } from '../../encrypted_saved_objects/server/mocks';
-import { actionsClientMock, actionsAuthorizationMock } from '../../actions/server/mocks';
-import { AlertsAuthorization } from './authorization/alerts_authorization';
-import { ActionsAuthorization } from '../../actions/server';
-import { eventLogClientMock } from '../../event_log/server/mocks';
-import { QueryEventsBySavedObjectResult } from '../../event_log/server';
-import { SavedObject } from 'kibana/server';
-import { EventsFactory } from './lib/alert_instance_summary_from_event_log.test';
-
-const taskManager = taskManagerMock.createStart();
-const alertTypeRegistry = alertTypeRegistryMock.create();
-const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
-const eventLogClient = eventLogClientMock.create();
-
-const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
-const authorization = alertsAuthorizationMock.create();
-const actionsAuthorization = actionsAuthorizationMock.create();
-
-const kibanaVersion = 'v7.10.0';
-const alertsClientParams: jest.Mocked = {
- taskManager,
- alertTypeRegistry,
- unsecuredSavedObjectsClient,
- authorization: (authorization as unknown) as AlertsAuthorization,
- actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization,
- spaceId: 'default',
- namespace: 'default',
- getUserName: jest.fn(),
- createAPIKey: jest.fn(),
- invalidateAPIKey: jest.fn(),
- logger: loggingSystemMock.create().get(),
- encryptedSavedObjectsClient: encryptedSavedObjects,
- getActionsClient: jest.fn(),
- getEventLogClient: jest.fn(),
- kibanaVersion,
-};
-
-beforeEach(() => {
- jest.resetAllMocks();
- alertsClientParams.createAPIKey.mockResolvedValue({ apiKeysEnabled: false });
- alertsClientParams.invalidateAPIKey.mockResolvedValue({
- apiKeysEnabled: true,
- result: {
- invalidated_api_keys: [],
- previously_invalidated_api_keys: [],
- error_count: 0,
- },
- });
- alertsClientParams.getUserName.mockResolvedValue('elastic');
- taskManager.runNow.mockResolvedValue({ id: '' });
- const actionsClient = actionsClientMock.create();
- actionsClient.getBulk.mockResolvedValueOnce([
- {
- id: '1',
- isPreconfigured: false,
- actionTypeId: 'test',
- name: 'test',
- config: {
- foo: 'bar',
- },
- },
- {
- id: '2',
- isPreconfigured: false,
- actionTypeId: 'test2',
- name: 'test2',
- config: {
- foo: 'bar',
- },
- },
- {
- id: 'testPreconfigured',
- actionTypeId: '.slack',
- isPreconfigured: true,
- name: 'test',
- },
- ]);
- alertsClientParams.getActionsClient.mockResolvedValue(actionsClient);
-
- alertTypeRegistry.get.mockImplementation((id) => ({
- id: '123',
- name: 'Test',
- actionGroups: [{ id: 'default', name: 'Default' }],
- defaultActionGroupId: 'default',
- async executor() {},
- producer: 'alerts',
- }));
- alertsClientParams.getEventLogClient.mockResolvedValue(eventLogClient);
-});
-
-const mockedDateString = '2019-02-12T21:01:22.479Z';
-const mockedDate = new Date(mockedDateString);
-const DateOriginal = Date;
-
-// A version of date that responds to `new Date(null|undefined)` and `Date.now()`
-// by returning a fixed date, otherwise should be same as Date.
-/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
-(global as any).Date = class Date {
- constructor(...args: unknown[]) {
- // sometimes the ctor has no args, sometimes has a single `null` arg
- if (args[0] == null) {
- // @ts-ignore
- return mockedDate;
- } else {
- // @ts-ignore
- return new DateOriginal(...args);
- }
- }
- static now() {
- return mockedDate.getTime();
- }
- static parse(string: string) {
- return DateOriginal.parse(string);
- }
-};
-
-function getMockData(overwrites: Record = {}): CreateOptions['data'] {
- return {
- enabled: true,
- name: 'abc',
- tags: ['foo'],
- alertTypeId: '123',
- consumer: 'bar',
- schedule: { interval: '10s' },
- throttle: null,
- params: {
- bar: true,
- },
- actions: [
- {
- group: 'default',
- id: '1',
- params: {
- foo: true,
- },
- },
- ],
- ...overwrites,
- };
-}
-
-describe('create()', () => {
- let alertsClient: AlertsClient;
-
- beforeEach(() => {
- alertsClient = new AlertsClient(alertsClientParams);
- });
-
- describe('authorization', () => {
- function tryToExecuteOperation(options: CreateOptions): Promise {
- unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
- saved_objects: [
- {
- id: '1',
- type: 'action',
- attributes: {
- actions: [],
- actionTypeId: 'test',
- },
- references: [],
- },
- ],
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- alertTypeId: '123',
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- createdAt: '2019-02-12T21:01:22.479Z',
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- ],
- },
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
- taskManager.schedule.mockResolvedValueOnce({
- id: 'task-123',
- taskType: 'alerting:123',
- scheduledAt: new Date(),
- attempts: 1,
- status: TaskStatus.Idle,
- runAt: new Date(),
- startedAt: null,
- retryAt: null,
- state: {},
- params: {},
- ownerId: null,
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- actions: [],
- scheduledTaskId: 'task-123',
- },
- references: [
- {
- id: '1',
- name: 'action_0',
- type: 'action',
- },
- ],
- });
-
- return alertsClient.create(options);
- }
-
- test('ensures user is authorised to create this type of alert under the consumer', async () => {
- const data = getMockData({
- alertTypeId: 'myType',
- consumer: 'myApp',
- });
-
- await tryToExecuteOperation({ data });
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'create');
- });
-
- test('throws when user is not authorised to create this type of alert', async () => {
- const data = getMockData({
- alertTypeId: 'myType',
- consumer: 'myApp',
- });
-
- authorization.ensureAuthorized.mockRejectedValue(
- new Error(`Unauthorized to create a "myType" alert for "myApp"`)
- );
-
- await expect(tryToExecuteOperation({ data })).rejects.toMatchInlineSnapshot(
- `[Error: Unauthorized to create a "myType" alert for "myApp"]`
- );
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'create');
- });
- });
-
- test('creates an alert', async () => {
- const data = getMockData();
- const createdAttributes = {
- ...data,
- alertTypeId: '123',
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- createdAt: '2019-02-12T21:01:22.479Z',
- createdBy: 'elastic',
- updatedBy: 'elastic',
- muteAll: false,
- mutedInstanceIds: [],
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- ],
- };
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: createdAttributes,
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
- taskManager.schedule.mockResolvedValueOnce({
- id: 'task-123',
- taskType: 'alerting:123',
- scheduledAt: new Date(),
- attempts: 1,
- status: TaskStatus.Idle,
- runAt: new Date(),
- startedAt: null,
- retryAt: null,
- state: {},
- params: {},
- ownerId: null,
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- ...createdAttributes,
- scheduledTaskId: 'task-123',
- },
- references: [
- {
- id: '1',
- name: 'action_0',
- type: 'action',
- },
- ],
- });
- const result = await alertsClient.create({ data });
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('123', 'bar', 'create');
- expect(result).toMatchInlineSnapshot(`
- Object {
- "actions": Array [
- Object {
- "actionTypeId": "test",
- "group": "default",
- "id": "1",
- "params": Object {
- "foo": true,
- },
- },
- ],
- "alertTypeId": "123",
- "consumer": "bar",
- "createdAt": 2019-02-12T21:01:22.479Z,
- "createdBy": "elastic",
- "enabled": true,
- "id": "1",
- "muteAll": false,
- "mutedInstanceIds": Array [],
- "name": "abc",
- "params": Object {
- "bar": true,
- },
- "schedule": Object {
- "interval": "10s",
- },
- "scheduledTaskId": "task-123",
- "tags": Array [
- "foo",
- ],
- "throttle": null,
- "updatedAt": 2019-02-12T21:01:22.479Z,
- "updatedBy": "elastic",
- }
- `);
- expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1);
- expect(unsecuredSavedObjectsClient.create.mock.calls[0]).toHaveLength(3);
- expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual('alert');
- expect(unsecuredSavedObjectsClient.create.mock.calls[0][1]).toMatchInlineSnapshot(`
- Object {
- "actions": Array [
- Object {
- "actionRef": "action_0",
- "actionTypeId": "test",
- "group": "default",
- "params": Object {
- "foo": true,
- },
- },
- ],
- "alertTypeId": "123",
- "apiKey": null,
- "apiKeyOwner": null,
- "consumer": "bar",
- "createdAt": "2019-02-12T21:01:22.479Z",
- "createdBy": "elastic",
- "enabled": true,
- "executionStatus": Object {
- "error": null,
- "lastExecutionDate": "2019-02-12T21:01:22.479Z",
- "status": "pending",
- },
- "meta": Object {
- "versionApiKeyLastmodified": "v7.10.0",
- },
- "muteAll": false,
- "mutedInstanceIds": Array [],
- "name": "abc",
- "params": Object {
- "bar": true,
- },
- "schedule": Object {
- "interval": "10s",
- },
- "tags": Array [
- "foo",
- ],
- "throttle": null,
- "updatedBy": "elastic",
- }
- `);
- expect(unsecuredSavedObjectsClient.create.mock.calls[0][2]).toMatchInlineSnapshot(`
- Object {
- "references": Array [
- Object {
- "id": "1",
- "name": "action_0",
- "type": "action",
- },
- ],
- }
- `);
- expect(taskManager.schedule).toHaveBeenCalledTimes(1);
- expect(taskManager.schedule.mock.calls[0]).toMatchInlineSnapshot(`
- Array [
- Object {
- "params": Object {
- "alertId": "1",
- "spaceId": "default",
- },
- "scope": Array [
- "alerting",
- ],
- "state": Object {
- "alertInstances": Object {},
- "alertTypeState": Object {},
- "previousStartedAt": null,
- },
- "taskType": "alerting:123",
- },
- ]
- `);
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(1);
- expect(unsecuredSavedObjectsClient.update.mock.calls[0]).toHaveLength(3);
- expect(unsecuredSavedObjectsClient.update.mock.calls[0][0]).toEqual('alert');
- expect(unsecuredSavedObjectsClient.update.mock.calls[0][1]).toEqual('1');
- expect(unsecuredSavedObjectsClient.update.mock.calls[0][2]).toMatchInlineSnapshot(`
- Object {
- "scheduledTaskId": "task-123",
- }
- `);
- });
-
- test('creates an alert with multiple actions', async () => {
- const data = getMockData({
- actions: [
- {
- group: 'default',
- id: '1',
- params: {
- foo: true,
- },
- },
- {
- group: 'default',
- id: '1',
- params: {
- foo: true,
- },
- },
- {
- group: 'default',
- id: '2',
- params: {
- foo: true,
- },
- },
- ],
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- alertTypeId: '123',
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- createdAt: new Date().toISOString(),
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- {
- group: 'default',
- actionRef: 'action_1',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- {
- group: 'default',
- actionRef: 'action_2',
- actionTypeId: 'test2',
- params: {
- foo: true,
- },
- },
- ],
- },
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- {
- name: 'action_1',
- type: 'action',
- id: '1',
- },
- {
- name: 'action_2',
- type: 'action',
- id: '2',
- },
- ],
- });
- taskManager.schedule.mockResolvedValueOnce({
- id: 'task-123',
- taskType: 'alerting:123',
- scheduledAt: new Date(),
- attempts: 1,
- status: TaskStatus.Idle,
- runAt: new Date(),
- startedAt: null,
- retryAt: null,
- state: {},
- params: {},
- ownerId: null,
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- actions: [],
- scheduledTaskId: 'task-123',
- },
- references: [],
- });
- const result = await alertsClient.create({ data });
- expect(result).toMatchInlineSnapshot(`
- Object {
- "actions": Array [
- Object {
- "actionTypeId": "test",
- "group": "default",
- "id": "1",
- "params": Object {
- "foo": true,
- },
- },
- Object {
- "actionTypeId": "test",
- "group": "default",
- "id": "1",
- "params": Object {
- "foo": true,
- },
- },
- Object {
- "actionTypeId": "test2",
- "group": "default",
- "id": "2",
- "params": Object {
- "foo": true,
- },
- },
- ],
- "alertTypeId": "123",
- "createdAt": 2019-02-12T21:01:22.479Z,
- "id": "1",
- "params": Object {
- "bar": true,
- },
- "schedule": Object {
- "interval": "10s",
- },
- "scheduledTaskId": "task-123",
- "updatedAt": 2019-02-12T21:01:22.479Z,
- }
- `);
- });
-
- test('creates a disabled alert', async () => {
- const data = getMockData({ enabled: false });
- unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
- saved_objects: [
- {
- id: '1',
- type: 'action',
- attributes: {
- actions: [],
- actionTypeId: 'test',
- },
- references: [],
- },
- ],
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- enabled: false,
- alertTypeId: '123',
- schedule: { interval: 10000 },
- params: {
- bar: true,
- },
- createdAt: new Date().toISOString(),
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- ],
- },
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
- const result = await alertsClient.create({ data });
- expect(result).toMatchInlineSnapshot(`
- Object {
- "actions": Array [
- Object {
- "actionTypeId": "test",
- "group": "default",
- "id": "1",
- "params": Object {
- "foo": true,
- },
- },
- ],
- "alertTypeId": "123",
- "createdAt": 2019-02-12T21:01:22.479Z,
- "enabled": false,
- "id": "1",
- "params": Object {
- "bar": true,
- },
- "schedule": Object {
- "interval": 10000,
- },
- "updatedAt": 2019-02-12T21:01:22.479Z,
- }
- `);
- expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1);
- expect(taskManager.schedule).toHaveBeenCalledTimes(0);
- });
-
- test('should trim alert name when creating API key', async () => {
- const data = getMockData({ name: ' my alert name ' });
- unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
- saved_objects: [
- {
- id: '1',
- type: 'action',
- attributes: {
- actions: [],
- actionTypeId: 'test',
- },
- references: [],
- },
- ],
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- enabled: false,
- name: ' my alert name ',
- alertTypeId: '123',
- schedule: { interval: 10000 },
- params: {
- bar: true,
- },
- createdAt: new Date().toISOString(),
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- ],
- },
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
- taskManager.schedule.mockResolvedValueOnce({
- id: 'task-123',
- taskType: 'alerting:123',
- scheduledAt: new Date(),
- attempts: 1,
- status: TaskStatus.Idle,
- runAt: new Date(),
- startedAt: null,
- retryAt: null,
- state: {},
- params: {},
- ownerId: null,
- });
-
- await alertsClient.create({ data });
- expect(alertsClientParams.createAPIKey).toHaveBeenCalledWith('Alerting: 123/my alert name');
- });
-
- test('should validate params', async () => {
- const data = getMockData();
- alertTypeRegistry.get.mockReturnValue({
- id: '123',
- name: 'Test',
- actionGroups: [
- {
- id: 'default',
- name: 'Default',
- },
- ],
- defaultActionGroupId: 'default',
- validate: {
- params: schema.object({
- param1: schema.string(),
- threshold: schema.number({ min: 0, max: 1 }),
- }),
- },
- async executor() {},
- producer: 'alerts',
- });
- await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"params invalid: [param1]: expected value of type [string] but got [undefined]"`
- );
- });
-
- test('throws error if loading actions fails', async () => {
- const data = getMockData();
- const actionsClient = actionsClientMock.create();
- actionsClient.getBulk.mockRejectedValueOnce(new Error('Test Error'));
- alertsClientParams.getActionsClient.mockResolvedValue(actionsClient);
- await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"Test Error"`
- );
- expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled();
- expect(taskManager.schedule).not.toHaveBeenCalled();
- });
-
- test('throws error and invalidates API key when create saved object fails', async () => {
- const data = getMockData();
- alertsClientParams.createAPIKey.mockResolvedValueOnce({
- apiKeysEnabled: true,
- result: { id: '123', name: '123', api_key: 'abc' },
- });
- unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
- saved_objects: [
- {
- id: '1',
- type: 'action',
- attributes: {
- actions: [],
- actionTypeId: 'test',
- },
- references: [],
- },
- ],
- });
- unsecuredSavedObjectsClient.create.mockRejectedValueOnce(new Error('Test failure'));
- await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"Test failure"`
- );
- expect(taskManager.schedule).not.toHaveBeenCalled();
- expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' });
- });
-
- test('attempts to remove saved object if scheduling failed', async () => {
- const data = getMockData();
- unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
- saved_objects: [
- {
- id: '1',
- type: 'action',
- attributes: {
- actions: [],
- actionTypeId: 'test',
- },
- references: [],
- },
- ],
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- alertTypeId: '123',
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- ],
- },
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
- taskManager.schedule.mockRejectedValueOnce(new Error('Test failure'));
- unsecuredSavedObjectsClient.delete.mockResolvedValueOnce({});
- await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"Test failure"`
- );
- expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledTimes(1);
- expect(unsecuredSavedObjectsClient.delete.mock.calls[0]).toMatchInlineSnapshot(`
- Array [
- "alert",
- "1",
- ]
- `);
- });
-
- test('returns task manager error if cleanup fails, logs to console', async () => {
- const data = getMockData();
- unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
- saved_objects: [
- {
- id: '1',
- type: 'action',
- attributes: {
- actions: [],
- actionTypeId: 'test',
- },
- references: [],
- },
- ],
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- alertTypeId: '123',
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- ],
- },
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
- taskManager.schedule.mockRejectedValueOnce(new Error('Task manager error'));
- unsecuredSavedObjectsClient.delete.mockRejectedValueOnce(
- new Error('Saved object delete error')
- );
- await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"Task manager error"`
- );
- expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
- 'Failed to cleanup alert "1" after scheduling task failed. Error: Saved object delete error'
- );
- });
-
- test('throws an error if alert type not registerd', async () => {
- const data = getMockData();
- alertTypeRegistry.get.mockImplementation(() => {
- throw new Error('Invalid type');
- });
- await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"Invalid type"`
- );
- });
-
- test('calls the API key function', async () => {
- const data = getMockData();
- alertsClientParams.createAPIKey.mockResolvedValueOnce({
- apiKeysEnabled: true,
- result: { id: '123', name: '123', api_key: 'abc' },
- });
- unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
- saved_objects: [
- {
- id: '1',
- type: 'action',
- attributes: {
- actions: [],
- actionTypeId: 'test',
- },
- references: [],
- },
- ],
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- alertTypeId: '123',
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- ],
- },
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
- taskManager.schedule.mockResolvedValueOnce({
- id: 'task-123',
- taskType: 'alerting:123',
- scheduledAt: new Date(),
- attempts: 1,
- status: TaskStatus.Idle,
- runAt: new Date(),
- startedAt: null,
- retryAt: null,
- state: {},
- params: {},
- ownerId: null,
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- actions: [],
- scheduledTaskId: 'task-123',
- },
- references: [
- {
- id: '1',
- name: 'action_0',
- type: 'action',
- },
- ],
- });
- await alertsClient.create({ data });
-
- expect(alertsClientParams.createAPIKey).toHaveBeenCalledTimes(1);
- expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith(
- 'alert',
- {
- actions: [
- {
- actionRef: 'action_0',
- group: 'default',
- actionTypeId: 'test',
- params: { foo: true },
- },
- ],
- alertTypeId: '123',
- consumer: 'bar',
- name: 'abc',
- params: { bar: true },
- apiKey: Buffer.from('123:abc').toString('base64'),
- apiKeyOwner: 'elastic',
- createdBy: 'elastic',
- createdAt: '2019-02-12T21:01:22.479Z',
- updatedBy: 'elastic',
- enabled: true,
- meta: {
- versionApiKeyLastmodified: 'v7.10.0',
- },
- schedule: { interval: '10s' },
- throttle: null,
- muteAll: false,
- mutedInstanceIds: [],
- tags: ['foo'],
- executionStatus: {
- lastExecutionDate: '2019-02-12T21:01:22.479Z',
- status: 'pending',
- error: null,
- },
- },
- {
- references: [
- {
- id: '1',
- name: 'action_0',
- type: 'action',
- },
- ],
- }
- );
- });
-
- test(`doesn't create API key for disabled alerts`, async () => {
- const data = getMockData({ enabled: false });
- unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
- saved_objects: [
- {
- id: '1',
- type: 'action',
- attributes: {
- actions: [],
- actionTypeId: 'test',
- },
- references: [],
- },
- ],
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- alertTypeId: '123',
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- ],
- },
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
- taskManager.schedule.mockResolvedValueOnce({
- id: 'task-123',
- taskType: 'alerting:123',
- scheduledAt: new Date(),
- attempts: 1,
- status: TaskStatus.Idle,
- runAt: new Date(),
- startedAt: null,
- retryAt: null,
- state: {},
- params: {},
- ownerId: null,
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- actions: [],
- scheduledTaskId: 'task-123',
- },
- references: [
- {
- id: '1',
- name: 'action_0',
- type: 'action',
- },
- ],
- });
- await alertsClient.create({ data });
-
- expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled();
- expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith(
- 'alert',
- {
- actions: [
- {
- actionRef: 'action_0',
- group: 'default',
- actionTypeId: 'test',
- params: { foo: true },
- },
- ],
- alertTypeId: '123',
- consumer: 'bar',
- name: 'abc',
- params: { bar: true },
- apiKey: null,
- apiKeyOwner: null,
- createdBy: 'elastic',
- createdAt: '2019-02-12T21:01:22.479Z',
- updatedBy: 'elastic',
- enabled: false,
- meta: {
- versionApiKeyLastmodified: 'v7.10.0',
- },
- schedule: { interval: '10s' },
- throttle: null,
- muteAll: false,
- mutedInstanceIds: [],
- tags: ['foo'],
- executionStatus: {
- lastExecutionDate: '2019-02-12T21:01:22.479Z',
- status: 'pending',
- error: null,
- },
- },
- {
- references: [
- {
- id: '1',
- name: 'action_0',
- type: 'action',
- },
- ],
- }
- );
- });
-});
-
-describe('enable()', () => {
- let alertsClient: AlertsClient;
- const existingAlert = {
- id: '1',
- type: 'alert',
- attributes: {
- consumer: 'myApp',
- schedule: { interval: '10s' },
- alertTypeId: 'myType',
- enabled: false,
- actions: [
- {
- group: 'default',
- id: '1',
- actionTypeId: '1',
- actionRef: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- version: '123',
- references: [],
- };
-
- beforeEach(() => {
- alertsClient = new AlertsClient(alertsClientParams);
- encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingAlert);
- unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert);
- alertsClientParams.createAPIKey.mockResolvedValue({
- apiKeysEnabled: false,
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- ...existingAlert,
- attributes: {
- ...existingAlert.attributes,
- enabled: true,
- apiKey: null,
- apiKeyOwner: null,
- updatedBy: 'elastic',
- },
- });
- taskManager.schedule.mockResolvedValue({
- id: 'task-123',
- scheduledAt: new Date(),
- attempts: 0,
- status: TaskStatus.Idle,
- runAt: new Date(),
- state: {},
- params: {},
- taskType: '',
- startedAt: null,
- retryAt: null,
- ownerId: null,
- });
- });
-
- describe('authorization', () => {
- beforeEach(() => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingAlert);
- unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert);
- alertsClientParams.createAPIKey.mockResolvedValue({
- apiKeysEnabled: false,
- });
- taskManager.schedule.mockResolvedValue({
- id: 'task-123',
- scheduledAt: new Date(),
- attempts: 0,
- status: TaskStatus.Idle,
- runAt: new Date(),
- state: {},
- params: {},
- taskType: '',
- startedAt: null,
- retryAt: null,
- ownerId: null,
- });
- });
-
- test('ensures user is authorised to enable this type of alert under the consumer', async () => {
- await alertsClient.enable({ id: '1' });
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'enable');
- expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute');
- });
-
- test('throws when user is not authorised to enable this type of alert', async () => {
- authorization.ensureAuthorized.mockRejectedValue(
- new Error(`Unauthorized to enable a "myType" alert for "myApp"`)
- );
-
- await expect(alertsClient.enable({ id: '1' })).rejects.toMatchInlineSnapshot(
- `[Error: Unauthorized to enable a "myType" alert for "myApp"]`
- );
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'enable');
- });
- });
-
- test('enables an alert', async () => {
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- ...existingAlert,
- attributes: {
- ...existingAlert.attributes,
- enabled: true,
- apiKey: null,
- apiKeyOwner: null,
- updatedBy: 'elastic',
- },
- });
-
- await alertsClient.enable({ id: '1' });
- expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled();
- expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', {
- namespace: 'default',
- });
- expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
- expect(alertsClientParams.createAPIKey).toHaveBeenCalled();
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
- 'alert',
- '1',
- {
- schedule: { interval: '10s' },
- alertTypeId: 'myType',
- consumer: 'myApp',
- enabled: true,
- meta: {
- versionApiKeyLastmodified: kibanaVersion,
- },
- updatedBy: 'elastic',
- apiKey: null,
- apiKeyOwner: null,
- actions: [
- {
- group: 'default',
- id: '1',
- actionTypeId: '1',
- actionRef: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- {
- version: '123',
- }
- );
- expect(taskManager.schedule).toHaveBeenCalledWith({
- taskType: `alerting:myType`,
- params: {
- alertId: '1',
- spaceId: 'default',
- },
- state: {
- alertInstances: {},
- alertTypeState: {},
- previousStartedAt: null,
- },
- scope: ['alerting'],
- });
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith('alert', '1', {
- scheduledTaskId: 'task-123',
- });
- });
-
- test('invalidates API key if ever one existed prior to updating', async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue({
- ...existingAlert,
- attributes: {
- ...existingAlert.attributes,
- apiKey: Buffer.from('123:abc').toString('base64'),
- },
- });
-
- await alertsClient.enable({ id: '1' });
- expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled();
- expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', {
- namespace: 'default',
- });
- expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' });
- });
-
- test(`doesn't enable already enabled alerts`, async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValueOnce({
- ...existingAlert,
- attributes: {
- ...existingAlert.attributes,
- enabled: true,
- },
- });
-
- await alertsClient.enable({ id: '1' });
- expect(alertsClientParams.getUserName).not.toHaveBeenCalled();
- expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled();
- expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled();
- expect(taskManager.schedule).not.toHaveBeenCalled();
- });
-
- test('sets API key when createAPIKey returns one', async () => {
- alertsClientParams.createAPIKey.mockResolvedValueOnce({
- apiKeysEnabled: true,
- result: { id: '123', name: '123', api_key: 'abc' },
- });
-
- await alertsClient.enable({ id: '1' });
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
- 'alert',
- '1',
- {
- schedule: { interval: '10s' },
- alertTypeId: 'myType',
- consumer: 'myApp',
- enabled: true,
- meta: {
- versionApiKeyLastmodified: kibanaVersion,
- },
- apiKey: Buffer.from('123:abc').toString('base64'),
- apiKeyOwner: 'elastic',
- updatedBy: 'elastic',
- actions: [
- {
- group: 'default',
- id: '1',
- actionTypeId: '1',
- actionRef: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- {
- version: '123',
- }
- );
- });
-
- test('falls back when failing to getDecryptedAsInternalUser', async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail'));
-
- await alertsClient.enable({ id: '1' });
- expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1');
- expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
- 'enable(): Failed to load API key to invalidate on alert 1: Fail'
- );
- });
-
- test('throws error when failing to load the saved object using SOC', async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail'));
- unsecuredSavedObjectsClient.get.mockRejectedValueOnce(new Error('Fail to get'));
-
- await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"Fail to get"`
- );
- expect(alertsClientParams.getUserName).not.toHaveBeenCalled();
- expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled();
- expect(unsecuredSavedObjectsClient.update).not.toHaveBeenCalled();
- expect(taskManager.schedule).not.toHaveBeenCalled();
- });
-
- test('throws error when failing to update the first time', async () => {
- alertsClientParams.createAPIKey.mockResolvedValueOnce({
- apiKeysEnabled: true,
- result: { id: '123', name: '123', api_key: 'abc' },
- });
- unsecuredSavedObjectsClient.update.mockReset();
- unsecuredSavedObjectsClient.update.mockRejectedValueOnce(new Error('Fail to update'));
-
- await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"Fail to update"`
- );
- expect(alertsClientParams.getUserName).toHaveBeenCalled();
- expect(alertsClientParams.createAPIKey).toHaveBeenCalled();
- expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' });
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(1);
- expect(taskManager.schedule).not.toHaveBeenCalled();
- });
-
- test('throws error when failing to update the second time', async () => {
- unsecuredSavedObjectsClient.update.mockReset();
- unsecuredSavedObjectsClient.update.mockResolvedValueOnce({
- ...existingAlert,
- attributes: {
- ...existingAlert.attributes,
- enabled: true,
- },
- });
- unsecuredSavedObjectsClient.update.mockRejectedValueOnce(
- new Error('Fail to update second time')
- );
-
- await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"Fail to update second time"`
- );
- expect(alertsClientParams.getUserName).toHaveBeenCalled();
- expect(alertsClientParams.createAPIKey).toHaveBeenCalled();
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(2);
- expect(taskManager.schedule).toHaveBeenCalled();
- });
-
- test('throws error when failing to schedule task', async () => {
- taskManager.schedule.mockRejectedValueOnce(new Error('Fail to schedule'));
-
- await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"Fail to schedule"`
- );
- expect(alertsClientParams.getUserName).toHaveBeenCalled();
- expect(alertsClientParams.createAPIKey).toHaveBeenCalled();
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled();
- });
-});
-
-describe('disable()', () => {
- let alertsClient: AlertsClient;
- const existingAlert = {
- id: '1',
- type: 'alert',
- attributes: {
- consumer: 'myApp',
- schedule: { interval: '10s' },
- alertTypeId: 'myType',
- enabled: true,
- scheduledTaskId: 'task-123',
- actions: [
- {
- group: 'default',
- id: '1',
- actionTypeId: '1',
- actionRef: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- version: '123',
- references: [],
- };
- const existingDecryptedAlert = {
- ...existingAlert,
- attributes: {
- ...existingAlert.attributes,
- apiKey: Buffer.from('123:abc').toString('base64'),
- },
- version: '123',
- references: [],
- };
-
- beforeEach(() => {
- alertsClient = new AlertsClient(alertsClientParams);
- unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert);
- encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingDecryptedAlert);
- });
-
- describe('authorization', () => {
- test('ensures user is authorised to disable this type of alert under the consumer', async () => {
- await alertsClient.disable({ id: '1' });
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'disable');
- });
-
- test('throws when user is not authorised to disable this type of alert', async () => {
- authorization.ensureAuthorized.mockRejectedValue(
- new Error(`Unauthorized to disable a "myType" alert for "myApp"`)
- );
-
- await expect(alertsClient.disable({ id: '1' })).rejects.toMatchInlineSnapshot(
- `[Error: Unauthorized to disable a "myType" alert for "myApp"]`
- );
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'disable');
- });
- });
-
- test('disables an alert', async () => {
- await alertsClient.disable({ id: '1' });
- expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled();
- expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', {
- namespace: 'default',
- });
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
- 'alert',
- '1',
- {
- consumer: 'myApp',
- schedule: { interval: '10s' },
- alertTypeId: 'myType',
- enabled: false,
- meta: {
- versionApiKeyLastmodified: kibanaVersion,
- },
- scheduledTaskId: null,
- apiKey: null,
- apiKeyOwner: null,
- updatedBy: 'elastic',
- actions: [
- {
- group: 'default',
- id: '1',
- actionTypeId: '1',
- actionRef: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- {
- version: '123',
- }
- );
- expect(taskManager.remove).toHaveBeenCalledWith('task-123');
- expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' });
- });
-
- test('falls back when getDecryptedAsInternalUser throws an error', async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail'));
-
- await alertsClient.disable({ id: '1' });
- expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1');
- expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', {
- namespace: 'default',
- });
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
- 'alert',
- '1',
- {
- consumer: 'myApp',
- schedule: { interval: '10s' },
- alertTypeId: 'myType',
- enabled: false,
- meta: {
- versionApiKeyLastmodified: kibanaVersion,
- },
- scheduledTaskId: null,
- apiKey: null,
- apiKeyOwner: null,
- updatedBy: 'elastic',
- actions: [
- {
- group: 'default',
- id: '1',
- actionTypeId: '1',
- actionRef: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- {
- version: '123',
- }
- );
- expect(taskManager.remove).toHaveBeenCalledWith('task-123');
- expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
- });
-
- test(`doesn't disable already disabled alerts`, async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValueOnce({
- ...existingDecryptedAlert,
- attributes: {
- ...existingDecryptedAlert.attributes,
- actions: [],
- enabled: false,
- },
- });
-
- await alertsClient.disable({ id: '1' });
- expect(unsecuredSavedObjectsClient.update).not.toHaveBeenCalled();
- expect(taskManager.remove).not.toHaveBeenCalled();
- expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
- });
-
- test(`doesn't invalidate when no API key is used`, async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValueOnce(existingAlert);
-
- await alertsClient.disable({ id: '1' });
- expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
- });
-
- test('swallows error when failing to load decrypted saved object', async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail'));
-
- await alertsClient.disable({ id: '1' });
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled();
- expect(taskManager.remove).toHaveBeenCalled();
- expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
- expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
- 'disable(): Failed to load API key to invalidate on alert 1: Fail'
- );
- });
-
- test('throws when unsecuredSavedObjectsClient update fails', async () => {
- unsecuredSavedObjectsClient.update.mockRejectedValueOnce(new Error('Failed to update'));
-
- await expect(alertsClient.disable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"Failed to update"`
- );
- });
-
- test('swallows error when invalidate API key throws', async () => {
- alertsClientParams.invalidateAPIKey.mockRejectedValueOnce(new Error('Fail'));
-
- await alertsClient.disable({ id: '1' });
- expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
- 'Failed to invalidate API Key: Fail'
- );
- });
-
- test('throws when failing to remove task from task manager', async () => {
- taskManager.remove.mockRejectedValueOnce(new Error('Failed to remove task'));
-
- await expect(alertsClient.disable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"Failed to remove task"`
- );
- });
-});
-
-describe('muteAll()', () => {
- test('mutes an alert', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- actions: [
- {
- group: 'default',
- id: '1',
- actionTypeId: '1',
- actionRef: '1',
- params: {
- foo: true,
- },
- },
- ],
- muteAll: false,
- },
- references: [],
- version: '123',
- });
-
- await alertsClient.muteAll({ id: '1' });
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
- 'alert',
- '1',
- {
- muteAll: true,
- mutedInstanceIds: [],
- updatedBy: 'elastic',
- },
- {
- version: '123',
- }
- );
- });
-
- describe('authorization', () => {
- beforeEach(() => {
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- actions: [
- {
- group: 'default',
- id: '1',
- actionTypeId: '1',
- actionRef: '1',
- params: {
- foo: true,
- },
- },
- ],
- consumer: 'myApp',
- schedule: { interval: '10s' },
- alertTypeId: 'myType',
- apiKey: null,
- apiKeyOwner: null,
- enabled: false,
- scheduledTaskId: null,
- updatedBy: 'elastic',
- muteAll: false,
- },
- references: [],
- });
- });
-
- test('ensures user is authorised to muteAll this type of alert under the consumer', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- await alertsClient.muteAll({ id: '1' });
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'muteAll');
- expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute');
- });
-
- test('throws when user is not authorised to muteAll this type of alert', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- authorization.ensureAuthorized.mockRejectedValue(
- new Error(`Unauthorized to muteAll a "myType" alert for "myApp"`)
- );
-
- await expect(alertsClient.muteAll({ id: '1' })).rejects.toMatchInlineSnapshot(
- `[Error: Unauthorized to muteAll a "myType" alert for "myApp"]`
- );
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'muteAll');
- });
- });
-});
-
-describe('unmuteAll()', () => {
- test('unmutes an alert', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- actions: [
- {
- group: 'default',
- id: '1',
- actionTypeId: '1',
- actionRef: '1',
- params: {
- foo: true,
- },
- },
- ],
- muteAll: true,
- },
- references: [],
- version: '123',
- });
-
- await alertsClient.unmuteAll({ id: '1' });
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
- 'alert',
- '1',
- {
- muteAll: false,
- mutedInstanceIds: [],
- updatedBy: 'elastic',
- },
- {
- version: '123',
- }
- );
- });
-
- describe('authorization', () => {
- beforeEach(() => {
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- actions: [
- {
- group: 'default',
- id: '1',
- actionTypeId: '1',
- actionRef: '1',
- params: {
- foo: true,
- },
- },
- ],
- consumer: 'myApp',
- schedule: { interval: '10s' },
- alertTypeId: 'myType',
- apiKey: null,
- apiKeyOwner: null,
- enabled: false,
- scheduledTaskId: null,
- updatedBy: 'elastic',
- muteAll: false,
- },
- references: [],
- });
- });
-
- test('ensures user is authorised to unmuteAll this type of alert under the consumer', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- await alertsClient.unmuteAll({ id: '1' });
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'unmuteAll');
- expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute');
- });
-
- test('throws when user is not authorised to unmuteAll this type of alert', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- authorization.ensureAuthorized.mockRejectedValue(
- new Error(`Unauthorized to unmuteAll a "myType" alert for "myApp"`)
- );
-
- await expect(alertsClient.unmuteAll({ id: '1' })).rejects.toMatchInlineSnapshot(
- `[Error: Unauthorized to unmuteAll a "myType" alert for "myApp"]`
- );
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'unmuteAll');
- });
- });
-});
-
-describe('muteInstance()', () => {
- test('mutes an alert instance', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- actions: [],
- schedule: { interval: '10s' },
- alertTypeId: '2',
- enabled: true,
- scheduledTaskId: 'task-123',
- mutedInstanceIds: [],
- },
- version: '123',
- references: [],
- });
-
- await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' });
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
- 'alert',
- '1',
- {
- mutedInstanceIds: ['2'],
- updatedBy: 'elastic',
- },
- {
- version: '123',
- }
- );
- });
-
- test('skips muting when alert instance already muted', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- actions: [],
- schedule: { interval: '10s' },
- alertTypeId: '2',
- enabled: true,
- scheduledTaskId: 'task-123',
- mutedInstanceIds: ['2'],
- },
- references: [],
- });
-
- await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' });
- expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled();
- });
-
- test('skips muting when alert is muted', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- actions: [],
- schedule: { interval: '10s' },
- alertTypeId: '2',
- enabled: true,
- scheduledTaskId: 'task-123',
- mutedInstanceIds: [],
- muteAll: true,
- },
- references: [],
- });
-
- await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' });
- expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled();
- });
-
- describe('authorization', () => {
- beforeEach(() => {
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- actions: [
- {
- group: 'default',
- id: '1',
- actionTypeId: '1',
- actionRef: '1',
- params: {
- foo: true,
- },
- },
- ],
- schedule: { interval: '10s' },
- alertTypeId: 'myType',
- consumer: 'myApp',
- enabled: true,
- scheduledTaskId: 'task-123',
- mutedInstanceIds: [],
- },
- version: '123',
- references: [],
- });
- });
-
- test('ensures user is authorised to muteInstance this type of alert under the consumer', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' });
-
- expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute');
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith(
- 'myType',
- 'myApp',
- 'muteInstance'
- );
- });
-
- test('throws when user is not authorised to muteInstance this type of alert', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- authorization.ensureAuthorized.mockRejectedValue(
- new Error(`Unauthorized to muteInstance a "myType" alert for "myApp"`)
- );
-
- await expect(
- alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' })
- ).rejects.toMatchInlineSnapshot(
- `[Error: Unauthorized to muteInstance a "myType" alert for "myApp"]`
- );
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith(
- 'myType',
- 'myApp',
- 'muteInstance'
- );
- });
- });
-});
-
-describe('unmuteInstance()', () => {
- test('unmutes an alert instance', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- actions: [],
- schedule: { interval: '10s' },
- alertTypeId: '2',
- enabled: true,
- scheduledTaskId: 'task-123',
- mutedInstanceIds: ['2'],
- },
- version: '123',
- references: [],
- });
-
- await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' });
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
- 'alert',
- '1',
- {
- mutedInstanceIds: [],
- updatedBy: 'elastic',
- },
- { version: '123' }
- );
- });
-
- test('skips unmuting when alert instance not muted', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- actions: [],
- schedule: { interval: '10s' },
- alertTypeId: '2',
- enabled: true,
- scheduledTaskId: 'task-123',
- mutedInstanceIds: [],
- },
- references: [],
- });
-
- await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' });
- expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled();
- });
-
- test('skips unmuting when alert is muted', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- actions: [],
- schedule: { interval: '10s' },
- alertTypeId: '2',
- enabled: true,
- scheduledTaskId: 'task-123',
- mutedInstanceIds: [],
- muteAll: true,
- },
- references: [],
- });
-
- await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' });
- expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled();
- });
-
- describe('authorization', () => {
- beforeEach(() => {
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- actions: [
- {
- group: 'default',
- id: '1',
- actionTypeId: '1',
- actionRef: '1',
- params: {
- foo: true,
- },
- },
- ],
- alertTypeId: 'myType',
- consumer: 'myApp',
- schedule: { interval: '10s' },
- enabled: true,
- scheduledTaskId: 'task-123',
- mutedInstanceIds: ['2'],
- },
- version: '123',
- references: [],
- });
- });
-
- test('ensures user is authorised to unmuteInstance this type of alert under the consumer', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' });
-
- expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute');
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith(
- 'myType',
- 'myApp',
- 'unmuteInstance'
- );
- });
-
- test('throws when user is not authorised to unmuteInstance this type of alert', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- authorization.ensureAuthorized.mockRejectedValue(
- new Error(`Unauthorized to unmuteInstance a "myType" alert for "myApp"`)
- );
-
- await expect(
- alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' })
- ).rejects.toMatchInlineSnapshot(
- `[Error: Unauthorized to unmuteInstance a "myType" alert for "myApp"]`
- );
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith(
- 'myType',
- 'myApp',
- 'unmuteInstance'
- );
- });
- });
-});
-
-describe('get()', () => {
- test('calls saved objects client with given params', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- alertTypeId: '123',
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- createdAt: new Date().toISOString(),
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- params: {
- foo: true,
- },
- },
- ],
- },
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
- const result = await alertsClient.get({ id: '1' });
- expect(result).toMatchInlineSnapshot(`
- Object {
- "actions": Array [
- Object {
- "group": "default",
- "id": "1",
- "params": Object {
- "foo": true,
- },
- },
- ],
- "alertTypeId": "123",
- "createdAt": 2019-02-12T21:01:22.479Z,
- "id": "1",
- "params": Object {
- "bar": true,
- },
- "schedule": Object {
- "interval": "10s",
- },
- "updatedAt": 2019-02-12T21:01:22.479Z,
- }
- `);
- expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1);
- expect(unsecuredSavedObjectsClient.get.mock.calls[0]).toMatchInlineSnapshot(`
- Array [
- "alert",
- "1",
- ]
- `);
- });
-
- test(`throws an error when references aren't found`, async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- alertTypeId: '123',
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- params: {
- foo: true,
- },
- },
- ],
- },
- references: [],
- });
- await expect(alertsClient.get({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"Action reference \\"action_0\\" not found in alert id: 1"`
- );
- });
-
- describe('authorization', () => {
- beforeEach(() => {
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- alertTypeId: 'myType',
- consumer: 'myApp',
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- params: {
- foo: true,
- },
- },
- ],
- },
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
- });
-
- test('ensures user is authorised to get this type of alert under the consumer', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- await alertsClient.get({ id: '1' });
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'get');
- });
-
- test('throws when user is not authorised to get this type of alert', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- authorization.ensureAuthorized.mockRejectedValue(
- new Error(`Unauthorized to get a "myType" alert for "myApp"`)
- );
-
- await expect(alertsClient.get({ id: '1' })).rejects.toMatchInlineSnapshot(
- `[Error: Unauthorized to get a "myType" alert for "myApp"]`
- );
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'get');
- });
- });
-});
-
-describe('getAlertState()', () => {
- test('calls saved objects client with given params', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- alertTypeId: '123',
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- params: {
- foo: true,
- },
- },
- ],
- },
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
-
- taskManager.get.mockResolvedValueOnce({
- id: '1',
- taskType: 'alerting:123',
- scheduledAt: new Date(),
- attempts: 1,
- status: TaskStatus.Idle,
- runAt: new Date(),
- startedAt: null,
- retryAt: null,
- state: {},
- params: {},
- ownerId: null,
- });
-
- await alertsClient.getAlertState({ id: '1' });
- expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1);
- expect(unsecuredSavedObjectsClient.get.mock.calls[0]).toMatchInlineSnapshot(`
- Array [
- "alert",
- "1",
- ]
- `);
- });
-
- test('gets the underlying task from TaskManager', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
-
- const scheduledTaskId = 'task-123';
-
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- alertTypeId: '123',
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- params: {
- foo: true,
- },
- },
- ],
- enabled: true,
- scheduledTaskId,
- mutedInstanceIds: [],
- muteAll: true,
- },
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
-
- taskManager.get.mockResolvedValueOnce({
- id: scheduledTaskId,
- taskType: 'alerting:123',
- scheduledAt: new Date(),
- attempts: 1,
- status: TaskStatus.Idle,
- runAt: new Date(),
- startedAt: null,
- retryAt: null,
- state: {},
- params: {
- alertId: '1',
- },
- ownerId: null,
- });
-
- await alertsClient.getAlertState({ id: '1' });
- expect(taskManager.get).toHaveBeenCalledTimes(1);
- expect(taskManager.get).toHaveBeenCalledWith(scheduledTaskId);
- });
-
- describe('authorization', () => {
- beforeEach(() => {
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- alertTypeId: 'myType',
- consumer: 'myApp',
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- params: {
- foo: true,
- },
- },
- ],
- },
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
-
- taskManager.get.mockResolvedValueOnce({
- id: '1',
- taskType: 'alerting:123',
- scheduledAt: new Date(),
- attempts: 1,
- status: TaskStatus.Idle,
- runAt: new Date(),
- startedAt: null,
- retryAt: null,
- state: {},
- params: {},
- ownerId: null,
- });
- });
-
- test('ensures user is authorised to get this type of alert under the consumer', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- await alertsClient.getAlertState({ id: '1' });
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith(
- 'myType',
- 'myApp',
- 'getAlertState'
- );
- });
-
- test('throws when user is not authorised to getAlertState this type of alert', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- // `get` check
- authorization.ensureAuthorized.mockResolvedValueOnce();
- // `getAlertState` check
- authorization.ensureAuthorized.mockRejectedValueOnce(
- new Error(`Unauthorized to getAlertState a "myType" alert for "myApp"`)
- );
-
- await expect(alertsClient.getAlertState({ id: '1' })).rejects.toMatchInlineSnapshot(
- `[Error: Unauthorized to getAlertState a "myType" alert for "myApp"]`
- );
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith(
- 'myType',
- 'myApp',
- 'getAlertState'
- );
- });
- });
-});
-
-const AlertInstanceSummaryFindEventsResult: QueryEventsBySavedObjectResult = {
- page: 1,
- per_page: 10000,
- total: 0,
- data: [],
-};
-
-const AlertInstanceSummaryIntervalSeconds = 1;
-
-const BaseAlertInstanceSummarySavedObject: SavedObject = {
- id: '1',
- type: 'alert',
- attributes: {
- enabled: true,
- name: 'alert-name',
- tags: ['tag-1', 'tag-2'],
- alertTypeId: '123',
- consumer: 'alert-consumer',
- schedule: { interval: `${AlertInstanceSummaryIntervalSeconds}s` },
- actions: [],
- params: {},
- createdBy: null,
- updatedBy: null,
- createdAt: mockedDateString,
- apiKey: null,
- apiKeyOwner: null,
- throttle: null,
- muteAll: false,
- mutedInstanceIds: [],
- executionStatus: {
- status: 'unknown',
- lastExecutionDate: '2020-08-20T19:23:38Z',
- error: null,
- },
- },
- references: [],
-};
-
-function getAlertInstanceSummarySavedObject(
- attributes: Partial = {}
-): SavedObject {
- return {
- ...BaseAlertInstanceSummarySavedObject,
- attributes: { ...BaseAlertInstanceSummarySavedObject.attributes, ...attributes },
- };
-}
-
-describe('getAlertInstanceSummary()', () => {
- let alertsClient: AlertsClient;
-
- beforeEach(() => {
- alertsClient = new AlertsClient(alertsClientParams);
- });
-
- test('runs as expected with some event log data', async () => {
- const alertSO = getAlertInstanceSummarySavedObject({
- mutedInstanceIds: ['instance-muted-no-activity'],
- });
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce(alertSO);
-
- const eventsFactory = new EventsFactory(mockedDateString);
- const events = eventsFactory
- .addExecute()
- .addNewInstance('instance-currently-active')
- .addNewInstance('instance-previously-active')
- .addActiveInstance('instance-currently-active')
- .addActiveInstance('instance-previously-active')
- .advanceTime(10000)
- .addExecute()
- .addResolvedInstance('instance-previously-active')
- .addActiveInstance('instance-currently-active')
- .getEvents();
- const eventsResult = {
- ...AlertInstanceSummaryFindEventsResult,
- total: events.length,
- data: events,
- };
- eventLogClient.findEventsBySavedObject.mockResolvedValueOnce(eventsResult);
-
- const dateStart = new Date(Date.now() - 60 * 1000).toISOString();
-
- const result = await alertsClient.getAlertInstanceSummary({ id: '1', dateStart });
- expect(result).toMatchInlineSnapshot(`
- Object {
- "alertTypeId": "123",
- "consumer": "alert-consumer",
- "enabled": true,
- "errorMessages": Array [],
- "id": "1",
- "instances": Object {
- "instance-currently-active": Object {
- "activeStartDate": "2019-02-12T21:01:22.479Z",
- "muted": false,
- "status": "Active",
- },
- "instance-muted-no-activity": Object {
- "activeStartDate": undefined,
- "muted": true,
- "status": "OK",
- },
- "instance-previously-active": Object {
- "activeStartDate": undefined,
- "muted": false,
- "status": "OK",
- },
- },
- "lastRun": "2019-02-12T21:01:32.479Z",
- "muteAll": false,
- "name": "alert-name",
- "status": "Active",
- "statusEndDate": "2019-02-12T21:01:22.479Z",
- "statusStartDate": "2019-02-12T21:00:22.479Z",
- "tags": Array [
- "tag-1",
- "tag-2",
- ],
- "throttle": null,
- }
- `);
- });
-
- // Further tests don't check the result of `getAlertInstanceSummary()`, as the result
- // is just the result from the `alertInstanceSummaryFromEventLog()`, which itself
- // has a complete set of tests. These tests just make sure the data gets
- // sent into `getAlertInstanceSummary()` as appropriate.
-
- test('calls saved objects and event log client with default params', async () => {
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce(getAlertInstanceSummarySavedObject());
- eventLogClient.findEventsBySavedObject.mockResolvedValueOnce(
- AlertInstanceSummaryFindEventsResult
- );
-
- await alertsClient.getAlertInstanceSummary({ id: '1' });
-
- expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1);
- expect(eventLogClient.findEventsBySavedObject).toHaveBeenCalledTimes(1);
- expect(eventLogClient.findEventsBySavedObject.mock.calls[0]).toMatchInlineSnapshot(`
- Array [
- "alert",
- "1",
- Object {
- "end": "2019-02-12T21:01:22.479Z",
- "page": 1,
- "per_page": 10000,
- "sort_order": "desc",
- "start": "2019-02-12T21:00:22.479Z",
- },
- ]
- `);
- // calculate the expected start/end date for one test
- const { start, end } = eventLogClient.findEventsBySavedObject.mock.calls[0][2]!;
- expect(end).toBe(mockedDateString);
-
- const startMillis = Date.parse(start!);
- const endMillis = Date.parse(end!);
- const expectedDuration = 60 * AlertInstanceSummaryIntervalSeconds * 1000;
- expect(endMillis - startMillis).toBeGreaterThan(expectedDuration - 2);
- expect(endMillis - startMillis).toBeLessThan(expectedDuration + 2);
- });
-
- test('calls event log client with start date', async () => {
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce(getAlertInstanceSummarySavedObject());
- eventLogClient.findEventsBySavedObject.mockResolvedValueOnce(
- AlertInstanceSummaryFindEventsResult
- );
-
- const dateStart = new Date(
- Date.now() - 60 * AlertInstanceSummaryIntervalSeconds * 1000
- ).toISOString();
- await alertsClient.getAlertInstanceSummary({ id: '1', dateStart });
-
- expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1);
- expect(eventLogClient.findEventsBySavedObject).toHaveBeenCalledTimes(1);
- const { start, end } = eventLogClient.findEventsBySavedObject.mock.calls[0][2]!;
-
- expect({ start, end }).toMatchInlineSnapshot(`
- Object {
- "end": "2019-02-12T21:01:22.479Z",
- "start": "2019-02-12T21:00:22.479Z",
- }
- `);
- });
-
- test('calls event log client with relative start date', async () => {
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce(getAlertInstanceSummarySavedObject());
- eventLogClient.findEventsBySavedObject.mockResolvedValueOnce(
- AlertInstanceSummaryFindEventsResult
- );
-
- const dateStart = '2m';
- await alertsClient.getAlertInstanceSummary({ id: '1', dateStart });
-
- expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1);
- expect(eventLogClient.findEventsBySavedObject).toHaveBeenCalledTimes(1);
- const { start, end } = eventLogClient.findEventsBySavedObject.mock.calls[0][2]!;
-
- expect({ start, end }).toMatchInlineSnapshot(`
- Object {
- "end": "2019-02-12T21:01:22.479Z",
- "start": "2019-02-12T20:59:22.479Z",
- }
- `);
- });
-
- test('invalid start date throws an error', async () => {
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce(getAlertInstanceSummarySavedObject());
- eventLogClient.findEventsBySavedObject.mockResolvedValueOnce(
- AlertInstanceSummaryFindEventsResult
- );
-
- const dateStart = 'ain"t no way this will get parsed as a date';
- expect(
- alertsClient.getAlertInstanceSummary({ id: '1', dateStart })
- ).rejects.toMatchInlineSnapshot(
- `[Error: Invalid date for parameter dateStart: "ain"t no way this will get parsed as a date"]`
- );
- });
-
- test('saved object get throws an error', async () => {
- unsecuredSavedObjectsClient.get.mockRejectedValueOnce(new Error('OMG!'));
- eventLogClient.findEventsBySavedObject.mockResolvedValueOnce(
- AlertInstanceSummaryFindEventsResult
- );
-
- expect(alertsClient.getAlertInstanceSummary({ id: '1' })).rejects.toMatchInlineSnapshot(
- `[Error: OMG!]`
- );
- });
-
- test('findEvents throws an error', async () => {
- unsecuredSavedObjectsClient.get.mockResolvedValueOnce(getAlertInstanceSummarySavedObject());
- eventLogClient.findEventsBySavedObject.mockRejectedValueOnce(new Error('OMG 2!'));
-
- // error eaten but logged
- await alertsClient.getAlertInstanceSummary({ id: '1' });
- });
-});
-
-describe('find()', () => {
- const listedTypes = new Set([
- {
- actionGroups: [],
- actionVariables: undefined,
- defaultActionGroupId: 'default',
- id: 'myType',
- name: 'myType',
- producer: 'myApp',
- },
- ]);
- beforeEach(() => {
- authorization.getFindAuthorizationFilter.mockResolvedValue({
- ensureAlertTypeIsAuthorized() {},
- logSuccessfulAuthorization() {},
- });
- unsecuredSavedObjectsClient.find.mockResolvedValueOnce({
- total: 1,
- per_page: 10,
- page: 1,
- saved_objects: [
- {
- id: '1',
- type: 'alert',
- attributes: {
- alertTypeId: 'myType',
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- createdAt: new Date().toISOString(),
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- params: {
- foo: true,
- },
- },
- ],
- },
- score: 1,
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- },
- ],
- });
- alertTypeRegistry.list.mockReturnValue(listedTypes);
- authorization.filterByAlertTypeAuthorization.mockResolvedValue(
- new Set([
- {
- id: 'myType',
- name: 'Test',
- actionGroups: [{ id: 'default', name: 'Default' }],
- defaultActionGroupId: 'default',
- producer: 'alerts',
- authorizedConsumers: {
- myApp: { read: true, all: true },
- },
- },
- ])
- );
- });
-
- test('calls saved objects client with given params', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- const result = await alertsClient.find({ options: {} });
- expect(result).toMatchInlineSnapshot(`
- Object {
- "data": Array [
- Object {
- "actions": Array [
- Object {
- "group": "default",
- "id": "1",
- "params": Object {
- "foo": true,
- },
- },
- ],
- "alertTypeId": "myType",
- "createdAt": 2019-02-12T21:01:22.479Z,
- "id": "1",
- "params": Object {
- "bar": true,
- },
- "schedule": Object {
- "interval": "10s",
- },
- "updatedAt": 2019-02-12T21:01:22.479Z,
- },
- ],
- "page": 1,
- "perPage": 10,
- "total": 1,
- }
- `);
- expect(unsecuredSavedObjectsClient.find).toHaveBeenCalledTimes(1);
- expect(unsecuredSavedObjectsClient.find.mock.calls[0]).toMatchInlineSnapshot(`
- Array [
- Object {
- "fields": undefined,
- "filter": undefined,
- "type": "alert",
- },
- ]
- `);
- });
-
- describe('authorization', () => {
- test('ensures user is query filter types down to those the user is authorized to find', async () => {
- const filter = esKuery.fromKueryExpression(
- '((alert.attributes.alertTypeId:myType and alert.attributes.consumer:myApp) or (alert.attributes.alertTypeId:myOtherType and alert.attributes.consumer:myApp) or (alert.attributes.alertTypeId:myOtherType and alert.attributes.consumer:myOtherApp))'
- );
- authorization.getFindAuthorizationFilter.mockResolvedValue({
- filter,
- ensureAlertTypeIsAuthorized() {},
- logSuccessfulAuthorization() {},
- });
-
- const alertsClient = new AlertsClient(alertsClientParams);
- await alertsClient.find({ options: { filter: 'someTerm' } });
-
- const [options] = unsecuredSavedObjectsClient.find.mock.calls[0];
- expect(options.filter).toEqual(
- nodeTypes.function.buildNode('and', [esKuery.fromKueryExpression('someTerm'), filter])
- );
- expect(authorization.getFindAuthorizationFilter).toHaveBeenCalledTimes(1);
- });
-
- test('throws if user is not authorized to find any types', async () => {
- const alertsClient = new AlertsClient(alertsClientParams);
- authorization.getFindAuthorizationFilter.mockRejectedValue(new Error('not authorized'));
- await expect(alertsClient.find({ options: {} })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"not authorized"`
- );
- });
-
- test('ensures authorization even when the fields required to authorize are omitted from the find', async () => {
- const ensureAlertTypeIsAuthorized = jest.fn();
- const logSuccessfulAuthorization = jest.fn();
- authorization.getFindAuthorizationFilter.mockResolvedValue({
- ensureAlertTypeIsAuthorized,
- logSuccessfulAuthorization,
- });
-
- unsecuredSavedObjectsClient.find.mockReset();
- unsecuredSavedObjectsClient.find.mockResolvedValue({
- total: 1,
- per_page: 10,
- page: 1,
- saved_objects: [
- {
- id: '1',
- type: 'alert',
- attributes: {
- actions: [],
- alertTypeId: 'myType',
- consumer: 'myApp',
- tags: ['myTag'],
- },
- score: 1,
- references: [],
- },
- ],
- });
-
- const alertsClient = new AlertsClient(alertsClientParams);
- expect(await alertsClient.find({ options: { fields: ['tags'] } })).toMatchInlineSnapshot(`
- Object {
- "data": Array [
- Object {
- "actions": Array [],
- "id": "1",
- "schedule": undefined,
- "tags": Array [
- "myTag",
- ],
- },
- ],
- "page": 1,
- "perPage": 10,
- "total": 1,
- }
- `);
-
- expect(unsecuredSavedObjectsClient.find).toHaveBeenCalledWith({
- fields: ['tags', 'alertTypeId', 'consumer'],
- type: 'alert',
- });
- expect(ensureAlertTypeIsAuthorized).toHaveBeenCalledWith('myType', 'myApp');
- expect(logSuccessfulAuthorization).toHaveBeenCalled();
- });
- });
-});
-
-describe('delete()', () => {
- let alertsClient: AlertsClient;
- const existingAlert = {
- id: '1',
- type: 'alert',
- attributes: {
- alertTypeId: 'myType',
- consumer: 'myApp',
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- scheduledTaskId: 'task-123',
- actions: [
- {
- group: 'default',
- actionTypeId: '.no-op',
- actionRef: 'action_0',
- params: {
- foo: true,
- },
- },
- ],
- },
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- };
- const existingDecryptedAlert = {
- ...existingAlert,
- attributes: {
- ...existingAlert.attributes,
- apiKey: Buffer.from('123:abc').toString('base64'),
- },
- };
-
- beforeEach(() => {
- alertsClient = new AlertsClient(alertsClientParams);
- unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert);
- unsecuredSavedObjectsClient.delete.mockResolvedValue({
- success: true,
- });
- encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingDecryptedAlert);
- });
-
- test('successfully removes an alert', async () => {
- const result = await alertsClient.delete({ id: '1' });
- expect(result).toEqual({ success: true });
- expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledWith('alert', '1');
- expect(taskManager.remove).toHaveBeenCalledWith('task-123');
- expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' });
- expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', {
- namespace: 'default',
- });
- expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled();
- });
-
- test('falls back to SOC.get when getDecryptedAsInternalUser throws an error', async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail'));
-
- const result = await alertsClient.delete({ id: '1' });
- expect(result).toEqual({ success: true });
- expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledWith('alert', '1');
- expect(taskManager.remove).toHaveBeenCalledWith('task-123');
- expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
- expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1');
- expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
- 'delete(): Failed to load API key to invalidate on alert 1: Fail'
- );
- });
-
- test(`doesn't remove a task when scheduledTaskId is null`, async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue({
- ...existingDecryptedAlert,
- attributes: {
- ...existingDecryptedAlert.attributes,
- scheduledTaskId: null,
- },
- });
-
- await alertsClient.delete({ id: '1' });
- expect(taskManager.remove).not.toHaveBeenCalled();
- });
-
- test(`doesn't invalidate API key when apiKey is null`, async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue({
- ...existingAlert,
- attributes: {
- ...existingAlert.attributes,
- apiKey: null,
- },
- });
-
- await alertsClient.delete({ id: '1' });
- expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
- });
-
- test('swallows error when invalidate API key throws', async () => {
- alertsClientParams.invalidateAPIKey.mockRejectedValueOnce(new Error('Fail'));
-
- await alertsClient.delete({ id: '1' });
- expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' });
- expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
- 'Failed to invalidate API Key: Fail'
- );
- });
-
- test('swallows error when getDecryptedAsInternalUser throws an error', async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail'));
-
- await alertsClient.delete({ id: '1' });
- expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
- expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
- 'delete(): Failed to load API key to invalidate on alert 1: Fail'
- );
- });
-
- test('throws error when unsecuredSavedObjectsClient.get throws an error', async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail'));
- unsecuredSavedObjectsClient.get.mockRejectedValue(new Error('SOC Fail'));
-
- await expect(alertsClient.delete({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"SOC Fail"`
- );
- });
-
- test('throws error when taskManager.remove throws an error', async () => {
- taskManager.remove.mockRejectedValue(new Error('TM Fail'));
-
- await expect(alertsClient.delete({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"TM Fail"`
- );
- });
-
- describe('authorization', () => {
- test('ensures user is authorised to delete this type of alert under the consumer', async () => {
- await alertsClient.delete({ id: '1' });
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'delete');
- });
-
- test('throws when user is not authorised to delete this type of alert', async () => {
- authorization.ensureAuthorized.mockRejectedValue(
- new Error(`Unauthorized to delete a "myType" alert for "myApp"`)
- );
-
- await expect(alertsClient.delete({ id: '1' })).rejects.toMatchInlineSnapshot(
- `[Error: Unauthorized to delete a "myType" alert for "myApp"]`
- );
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'delete');
- });
- });
-});
-
-describe('update()', () => {
- let alertsClient: AlertsClient;
- const existingAlert = {
- id: '1',
- type: 'alert',
- attributes: {
- enabled: true,
- tags: ['foo'],
- alertTypeId: 'myType',
- schedule: { interval: '10s' },
- consumer: 'myApp',
- scheduledTaskId: 'task-123',
- params: {},
- throttle: null,
- actions: [
- {
- group: 'default',
- id: '1',
- actionTypeId: '1',
- actionRef: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- references: [],
- version: '123',
- };
- const existingDecryptedAlert = {
- ...existingAlert,
- attributes: {
- ...existingAlert.attributes,
- apiKey: Buffer.from('123:abc').toString('base64'),
- },
- };
-
- beforeEach(() => {
- alertsClient = new AlertsClient(alertsClientParams);
- unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert);
- encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingDecryptedAlert);
- alertTypeRegistry.get.mockReturnValue({
- id: 'myType',
- name: 'Test',
- actionGroups: [{ id: 'default', name: 'Default' }],
- defaultActionGroupId: 'default',
- async executor() {},
- producer: 'alerts',
- });
- });
-
- test('updates given parameters', async () => {
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- enabled: true,
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- {
- group: 'default',
- actionRef: 'action_1',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- {
- group: 'default',
- actionRef: 'action_2',
- actionTypeId: 'test2',
- params: {
- foo: true,
- },
- },
- ],
- scheduledTaskId: 'task-123',
- createdAt: new Date().toISOString(),
- },
- updated_at: new Date().toISOString(),
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- {
- name: 'action_1',
- type: 'action',
- id: '1',
- },
- {
- name: 'action_2',
- type: 'action',
- id: '2',
- },
- ],
- });
- const result = await alertsClient.update({
- id: '1',
- data: {
- schedule: { interval: '10s' },
- name: 'abc',
- tags: ['foo'],
- params: {
- bar: true,
- },
- throttle: null,
- actions: [
- {
- group: 'default',
- id: '1',
- params: {
- foo: true,
- },
- },
- {
- group: 'default',
- id: '1',
- params: {
- foo: true,
- },
- },
- {
- group: 'default',
- id: '2',
- params: {
- foo: true,
- },
- },
- ],
- },
- });
- expect(result).toMatchInlineSnapshot(`
- Object {
- "actions": Array [
- Object {
- "actionTypeId": "test",
- "group": "default",
- "id": "1",
- "params": Object {
- "foo": true,
- },
- },
- Object {
- "actionTypeId": "test",
- "group": "default",
- "id": "1",
- "params": Object {
- "foo": true,
- },
- },
- Object {
- "actionTypeId": "test2",
- "group": "default",
- "id": "2",
- "params": Object {
- "foo": true,
- },
- },
- ],
- "createdAt": 2019-02-12T21:01:22.479Z,
- "enabled": true,
- "id": "1",
- "params": Object {
- "bar": true,
- },
- "schedule": Object {
- "interval": "10s",
- },
- "scheduledTaskId": "task-123",
- "updatedAt": 2019-02-12T21:01:22.479Z,
- }
- `);
- expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', {
- namespace: 'default',
- });
- expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled();
- expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1);
- expect(unsecuredSavedObjectsClient.create.mock.calls[0]).toHaveLength(3);
- expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual('alert');
- expect(unsecuredSavedObjectsClient.create.mock.calls[0][1]).toMatchInlineSnapshot(`
- Object {
- "actions": Array [
- Object {
- "actionRef": "action_0",
- "actionTypeId": "test",
- "group": "default",
- "params": Object {
- "foo": true,
- },
- },
- Object {
- "actionRef": "action_1",
- "actionTypeId": "test",
- "group": "default",
- "params": Object {
- "foo": true,
- },
- },
- Object {
- "actionRef": "action_2",
- "actionTypeId": "test2",
- "group": "default",
- "params": Object {
- "foo": true,
- },
- },
- ],
- "alertTypeId": "myType",
- "apiKey": null,
- "apiKeyOwner": null,
- "consumer": "myApp",
- "enabled": true,
- "meta": Object {
- "versionApiKeyLastmodified": "v7.10.0",
- },
- "name": "abc",
- "params": Object {
- "bar": true,
- },
- "schedule": Object {
- "interval": "10s",
- },
- "scheduledTaskId": "task-123",
- "tags": Array [
- "foo",
- ],
- "throttle": null,
- "updatedBy": "elastic",
- }
- `);
- expect(unsecuredSavedObjectsClient.create.mock.calls[0][2]).toMatchInlineSnapshot(`
- Object {
- "id": "1",
- "overwrite": true,
- "references": Array [
- Object {
- "id": "1",
- "name": "action_0",
- "type": "action",
- },
- Object {
- "id": "1",
- "name": "action_1",
- "type": "action",
- },
- Object {
- "id": "2",
- "name": "action_2",
- "type": "action",
- },
- ],
- "version": "123",
- }
- `);
- });
-
- it('calls the createApiKey function', async () => {
- unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
- saved_objects: [
- {
- id: '1',
- type: 'action',
- attributes: {
- actions: [],
- actionTypeId: 'test',
- },
- references: [],
- },
- ],
- });
- alertsClientParams.createAPIKey.mockResolvedValueOnce({
- apiKeysEnabled: true,
- result: { id: '123', name: '123', api_key: 'abc' },
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- enabled: true,
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- createdAt: new Date().toISOString(),
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- ],
- apiKey: Buffer.from('123:abc').toString('base64'),
- scheduledTaskId: 'task-123',
- },
- updated_at: new Date().toISOString(),
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
- const result = await alertsClient.update({
- id: '1',
- data: {
- schedule: { interval: '10s' },
- name: 'abc',
- tags: ['foo'],
- params: {
- bar: true,
- },
- throttle: '5m',
- actions: [
- {
- group: 'default',
- id: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- });
- expect(result).toMatchInlineSnapshot(`
- Object {
- "actions": Array [
- Object {
- "actionTypeId": "test",
- "group": "default",
- "id": "1",
- "params": Object {
- "foo": true,
- },
- },
- ],
- "apiKey": "MTIzOmFiYw==",
- "createdAt": 2019-02-12T21:01:22.479Z,
- "enabled": true,
- "id": "1",
- "params": Object {
- "bar": true,
- },
- "schedule": Object {
- "interval": "10s",
- },
- "scheduledTaskId": "task-123",
- "updatedAt": 2019-02-12T21:01:22.479Z,
- }
- `);
- expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1);
- expect(unsecuredSavedObjectsClient.create.mock.calls[0]).toHaveLength(3);
- expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual('alert');
- expect(unsecuredSavedObjectsClient.create.mock.calls[0][1]).toMatchInlineSnapshot(`
- Object {
- "actions": Array [
- Object {
- "actionRef": "action_0",
- "actionTypeId": "test",
- "group": "default",
- "params": Object {
- "foo": true,
- },
- },
- ],
- "alertTypeId": "myType",
- "apiKey": "MTIzOmFiYw==",
- "apiKeyOwner": "elastic",
- "consumer": "myApp",
- "enabled": true,
- "meta": Object {
- "versionApiKeyLastmodified": "v7.10.0",
- },
- "name": "abc",
- "params": Object {
- "bar": true,
- },
- "schedule": Object {
- "interval": "10s",
- },
- "scheduledTaskId": "task-123",
- "tags": Array [
- "foo",
- ],
- "throttle": "5m",
- "updatedBy": "elastic",
- }
- `);
- expect(unsecuredSavedObjectsClient.create.mock.calls[0][2]).toMatchInlineSnapshot(`
- Object {
- "id": "1",
- "overwrite": true,
- "references": Array [
- Object {
- "id": "1",
- "name": "action_0",
- "type": "action",
- },
- ],
- "version": "123",
- }
- `);
- });
-
- it(`doesn't call the createAPIKey function when alert is disabled`, async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue({
- ...existingDecryptedAlert,
- attributes: {
- ...existingDecryptedAlert.attributes,
- enabled: false,
- },
- });
- unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
- saved_objects: [
- {
- id: '1',
- type: 'action',
- attributes: {
- actions: [],
- actionTypeId: 'test',
- },
- references: [],
- },
- ],
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- enabled: false,
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- createdAt: new Date().toISOString(),
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- ],
- scheduledTaskId: 'task-123',
- apiKey: null,
- },
- updated_at: new Date().toISOString(),
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
- const result = await alertsClient.update({
- id: '1',
- data: {
- schedule: { interval: '10s' },
- name: 'abc',
- tags: ['foo'],
- params: {
- bar: true,
- },
- throttle: '5m',
- actions: [
- {
- group: 'default',
- id: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- });
- expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled();
- expect(result).toMatchInlineSnapshot(`
- Object {
- "actions": Array [
- Object {
- "actionTypeId": "test",
- "group": "default",
- "id": "1",
- "params": Object {
- "foo": true,
- },
- },
- ],
- "apiKey": null,
- "createdAt": 2019-02-12T21:01:22.479Z,
- "enabled": false,
- "id": "1",
- "params": Object {
- "bar": true,
- },
- "schedule": Object {
- "interval": "10s",
- },
- "scheduledTaskId": "task-123",
- "updatedAt": 2019-02-12T21:01:22.479Z,
- }
- `);
- expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1);
- expect(unsecuredSavedObjectsClient.create.mock.calls[0]).toHaveLength(3);
- expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual('alert');
- expect(unsecuredSavedObjectsClient.create.mock.calls[0][1]).toMatchInlineSnapshot(`
- Object {
- "actions": Array [
- Object {
- "actionRef": "action_0",
- "actionTypeId": "test",
- "group": "default",
- "params": Object {
- "foo": true,
- },
- },
- ],
- "alertTypeId": "myType",
- "apiKey": null,
- "apiKeyOwner": null,
- "consumer": "myApp",
- "enabled": false,
- "meta": Object {
- "versionApiKeyLastmodified": "v7.10.0",
- },
- "name": "abc",
- "params": Object {
- "bar": true,
- },
- "schedule": Object {
- "interval": "10s",
- },
- "scheduledTaskId": "task-123",
- "tags": Array [
- "foo",
- ],
- "throttle": "5m",
- "updatedBy": "elastic",
- }
- `);
- expect(unsecuredSavedObjectsClient.create.mock.calls[0][2]).toMatchInlineSnapshot(`
- Object {
- "id": "1",
- "overwrite": true,
- "references": Array [
- Object {
- "id": "1",
- "name": "action_0",
- "type": "action",
- },
- ],
- "version": "123",
- }
- `);
- });
-
- it('should validate params', async () => {
- alertTypeRegistry.get.mockReturnValueOnce({
- id: '123',
- name: 'Test',
- actionGroups: [{ id: 'default', name: 'Default' }],
- defaultActionGroupId: 'default',
- validate: {
- params: schema.object({
- param1: schema.string(),
- }),
- },
- async executor() {},
- producer: 'alerts',
- });
- await expect(
- alertsClient.update({
- id: '1',
- data: {
- schedule: { interval: '10s' },
- name: 'abc',
- tags: ['foo'],
- params: {
- bar: true,
- },
- throttle: null,
- actions: [
- {
- group: 'default',
- id: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- })
- ).rejects.toThrowErrorMatchingInlineSnapshot(
- `"params invalid: [param1]: expected value of type [string] but got [undefined]"`
- );
- });
-
- it('should trim alert name in the API key name', async () => {
- unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
- saved_objects: [
- {
- id: '1',
- type: 'action',
- attributes: {
- actions: [],
- actionTypeId: 'test',
- },
- references: [],
- },
- ],
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- enabled: false,
- name: ' my alert name ',
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- createdAt: new Date().toISOString(),
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- ],
- scheduledTaskId: 'task-123',
- apiKey: null,
- },
- updated_at: new Date().toISOString(),
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
- await alertsClient.update({
- id: '1',
- data: {
- ...existingAlert.attributes,
- name: ' my alert name ',
- },
- });
-
- expect(alertsClientParams.createAPIKey).toHaveBeenCalledWith('Alerting: myType/my alert name');
- });
-
- it('swallows error when invalidate API key throws', async () => {
- alertsClientParams.invalidateAPIKey.mockRejectedValueOnce(new Error('Fail'));
- unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
- saved_objects: [
- {
- id: '1',
- type: 'action',
- attributes: {
- actions: [],
- actionTypeId: 'test',
- },
- references: [],
- },
- ],
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- enabled: true,
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- ],
- scheduledTaskId: 'task-123',
- },
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- ],
- });
- await alertsClient.update({
- id: '1',
- data: {
- schedule: { interval: '10s' },
- name: 'abc',
- tags: ['foo'],
- params: {
- bar: true,
- },
- throttle: null,
- actions: [
- {
- group: 'default',
- id: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- });
- expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
- 'Failed to invalidate API Key: Fail'
- );
- });
-
- it('swallows error when getDecryptedAsInternalUser throws', async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail'));
- unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
- saved_objects: [
- {
- id: '1',
- type: 'action',
- attributes: {
- actions: [],
- actionTypeId: 'test',
- },
- references: [],
- },
- {
- id: '2',
- type: 'action',
- attributes: {
- actions: [],
- actionTypeId: 'test2',
- },
- references: [],
- },
- ],
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- enabled: true,
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- {
- group: 'default',
- actionRef: 'action_1',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- {
- group: 'default',
- actionRef: 'action_2',
- actionTypeId: 'test2',
- params: {
- foo: true,
- },
- },
- ],
- scheduledTaskId: 'task-123',
- createdAt: new Date().toISOString(),
- },
- updated_at: new Date().toISOString(),
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: '1',
- },
- {
- name: 'action_1',
- type: 'action',
- id: '1',
- },
- {
- name: 'action_2',
- type: 'action',
- id: '2',
- },
- ],
- });
- await alertsClient.update({
- id: '1',
- data: {
- schedule: { interval: '10s' },
- name: 'abc',
- tags: ['foo'],
- params: {
- bar: true,
- },
- throttle: '5m',
- actions: [
- {
- group: 'default',
- id: '1',
- params: {
- foo: true,
- },
- },
- {
- group: 'default',
- id: '1',
- params: {
- foo: true,
- },
- },
- {
- group: 'default',
- id: '2',
- params: {
- foo: true,
- },
- },
- ],
- },
- });
- expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1');
- expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
- 'update(): Failed to load API key to invalidate on alert 1: Fail'
- );
- });
-
- test('throws when unsecuredSavedObjectsClient update fails and invalidates newly created API key', async () => {
- alertsClientParams.createAPIKey.mockResolvedValueOnce({
- apiKeysEnabled: true,
- result: { id: '234', name: '234', api_key: 'abc' },
- });
- unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
- saved_objects: [
- {
- id: '1',
- type: 'action',
- attributes: {
- actions: [],
- actionTypeId: 'test',
- },
- references: [],
- },
- ],
- });
- unsecuredSavedObjectsClient.create.mockRejectedValue(new Error('Fail'));
- await expect(
- alertsClient.update({
- id: '1',
- data: {
- schedule: { interval: '10s' },
- name: 'abc',
- tags: ['foo'],
- params: {
- bar: true,
- },
- throttle: null,
- actions: [
- {
- group: 'default',
- id: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- })
- ).rejects.toThrowErrorMatchingInlineSnapshot(`"Fail"`);
- expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalledWith({ id: '123' });
- expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '234' });
- });
-
- describe('updating an alert schedule', () => {
- function mockApiCalls(
- alertId: string,
- taskId: string,
- currentSchedule: IntervalSchedule,
- updatedSchedule: IntervalSchedule
- ) {
- // mock return values from deps
- alertTypeRegistry.get.mockReturnValueOnce({
- id: '123',
- name: 'Test',
- actionGroups: [{ id: 'default', name: 'Default' }],
- defaultActionGroupId: 'default',
- async executor() {},
- producer: 'alerts',
- });
- unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
- saved_objects: [
- {
- id: '1',
- type: 'action',
- attributes: {
- actions: [],
- actionTypeId: 'test',
- },
- references: [],
- },
- ],
- });
- encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValueOnce({
- id: alertId,
- type: 'alert',
- attributes: {
- actions: [],
- enabled: true,
- alertTypeId: '123',
- schedule: currentSchedule,
- scheduledTaskId: 'task-123',
- },
- references: [],
- version: '123',
- });
-
- taskManager.schedule.mockResolvedValueOnce({
- id: taskId,
- taskType: 'alerting:123',
- scheduledAt: new Date(),
- attempts: 1,
- status: TaskStatus.Idle,
- runAt: new Date(),
- startedAt: null,
- retryAt: null,
- state: {},
- params: {},
- ownerId: null,
- });
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: alertId,
- type: 'alert',
- attributes: {
- enabled: true,
- schedule: updatedSchedule,
- actions: [
- {
- group: 'default',
- actionRef: 'action_0',
- actionTypeId: 'test',
- params: {
- foo: true,
- },
- },
- ],
- scheduledTaskId: taskId,
- },
- references: [
- {
- name: 'action_0',
- type: 'action',
- id: alertId,
- },
- ],
- });
-
- taskManager.runNow.mockReturnValueOnce(Promise.resolve({ id: alertId }));
- }
-
- test('updating the alert schedule should rerun the task immediately', async () => {
- const alertId = uuid.v4();
- const taskId = uuid.v4();
-
- mockApiCalls(alertId, taskId, { interval: '60m' }, { interval: '10s' });
-
- await alertsClient.update({
- id: alertId,
- data: {
- schedule: { interval: '10s' },
- name: 'abc',
- tags: ['foo'],
- params: {
- bar: true,
- },
- throttle: null,
- actions: [
- {
- group: 'default',
- id: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- });
-
- expect(taskManager.runNow).toHaveBeenCalledWith(taskId);
- });
-
- test('updating the alert without changing the schedule should not rerun the task', async () => {
- const alertId = uuid.v4();
- const taskId = uuid.v4();
-
- mockApiCalls(alertId, taskId, { interval: '10s' }, { interval: '10s' });
-
- await alertsClient.update({
- id: alertId,
- data: {
- schedule: { interval: '10s' },
- name: 'abc',
- tags: ['foo'],
- params: {
- bar: true,
- },
- throttle: null,
- actions: [
- {
- group: 'default',
- id: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- });
-
- expect(taskManager.runNow).not.toHaveBeenCalled();
- });
-
- test('updating the alert should not wait for the rerun the task to complete', async () => {
- const alertId = uuid.v4();
- const taskId = uuid.v4();
-
- mockApiCalls(alertId, taskId, { interval: '10s' }, { interval: '30s' });
-
- const resolveAfterAlertUpdatedCompletes = resolvable<{ id: string }>();
-
- taskManager.runNow.mockReset();
- taskManager.runNow.mockReturnValue(resolveAfterAlertUpdatedCompletes);
-
- await alertsClient.update({
- id: alertId,
- data: {
- schedule: { interval: '10s' },
- name: 'abc',
- tags: ['foo'],
- params: {
- bar: true,
- },
- throttle: null,
- actions: [
- {
- group: 'default',
- id: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- });
-
- expect(taskManager.runNow).toHaveBeenCalled();
- resolveAfterAlertUpdatedCompletes.resolve({ id: alertId });
- });
-
- test('logs when the rerun of an alerts underlying task fails', async () => {
- const alertId = uuid.v4();
- const taskId = uuid.v4();
-
- mockApiCalls(alertId, taskId, { interval: '10s' }, { interval: '30s' });
-
- taskManager.runNow.mockReset();
- taskManager.runNow.mockRejectedValue(new Error('Failed to run alert'));
-
- await alertsClient.update({
- id: alertId,
- data: {
- schedule: { interval: '10s' },
- name: 'abc',
- tags: ['foo'],
- params: {
- bar: true,
- },
- throttle: null,
- actions: [
- {
- group: 'default',
- id: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- });
-
- expect(taskManager.runNow).toHaveBeenCalled();
-
- expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
- `Alert update failed to run its underlying task. TaskManager runNow failed with Error: Failed to run alert`
- );
- });
- });
-
- describe('authorization', () => {
- beforeEach(() => {
- unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
- id: '1',
- type: 'alert',
- attributes: {
- alertTypeId: 'myType',
- consumer: 'myApp',
- enabled: true,
- schedule: { interval: '10s' },
- params: {
- bar: true,
- },
- actions: [],
- scheduledTaskId: 'task-123',
- createdAt: new Date().toISOString(),
- },
- updated_at: new Date().toISOString(),
- references: [],
- });
- });
-
- test('ensures user is authorised to update this type of alert under the consumer', async () => {
- await alertsClient.update({
- id: '1',
- data: {
- schedule: { interval: '10s' },
- name: 'abc',
- tags: ['foo'],
- params: {
- bar: true,
- },
- throttle: null,
- actions: [],
- },
- });
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'update');
- });
-
- test('throws when user is not authorised to update this type of alert', async () => {
- authorization.ensureAuthorized.mockRejectedValue(
- new Error(`Unauthorized to update a "myType" alert for "myApp"`)
- );
-
- await expect(
- alertsClient.update({
- id: '1',
- data: {
- schedule: { interval: '10s' },
- name: 'abc',
- tags: ['foo'],
- params: {
- bar: true,
- },
- throttle: null,
- actions: [],
- },
- })
- ).rejects.toMatchInlineSnapshot(
- `[Error: Unauthorized to update a "myType" alert for "myApp"]`
- );
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'update');
- });
- });
-});
-
-describe('updateApiKey()', () => {
- let alertsClient: AlertsClient;
- const existingAlert = {
- id: '1',
- type: 'alert',
- attributes: {
- schedule: { interval: '10s' },
- alertTypeId: 'myType',
- consumer: 'myApp',
- enabled: true,
- actions: [
- {
- group: 'default',
- id: '1',
- actionTypeId: '1',
- actionRef: '1',
- params: {
- foo: true,
- },
- },
- ],
- },
- version: '123',
- references: [],
- };
- const existingEncryptedAlert = {
- ...existingAlert,
- attributes: {
- ...existingAlert.attributes,
- apiKey: Buffer.from('123:abc').toString('base64'),
- },
- };
-
- beforeEach(() => {
- alertsClient = new AlertsClient(alertsClientParams);
- unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert);
- encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingEncryptedAlert);
- alertsClientParams.createAPIKey.mockResolvedValueOnce({
- apiKeysEnabled: true,
- result: { id: '234', name: '123', api_key: 'abc' },
- });
- });
-
- test('updates the API key for the alert', async () => {
- await alertsClient.updateApiKey({ id: '1' });
- expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled();
- expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', {
- namespace: 'default',
- });
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
- 'alert',
- '1',
- {
- schedule: { interval: '10s' },
- alertTypeId: 'myType',
- consumer: 'myApp',
- enabled: true,
- apiKey: Buffer.from('234:abc').toString('base64'),
- apiKeyOwner: 'elastic',
- updatedBy: 'elastic',
- actions: [
- {
- group: 'default',
- id: '1',
- actionTypeId: '1',
- actionRef: '1',
- params: {
- foo: true,
- },
- },
- ],
- meta: {
- versionApiKeyLastmodified: kibanaVersion,
- },
- },
- { version: '123' }
- );
- expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' });
- });
-
- test('falls back to SOC when getDecryptedAsInternalUser throws an error', async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail'));
-
- await alertsClient.updateApiKey({ id: '1' });
- expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1');
- expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', {
- namespace: 'default',
- });
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
- 'alert',
- '1',
- {
- schedule: { interval: '10s' },
- alertTypeId: 'myType',
- consumer: 'myApp',
- enabled: true,
- apiKey: Buffer.from('234:abc').toString('base64'),
- apiKeyOwner: 'elastic',
- updatedBy: 'elastic',
- actions: [
- {
- group: 'default',
- id: '1',
- actionTypeId: '1',
- actionRef: '1',
- params: {
- foo: true,
- },
- },
- ],
- meta: {
- versionApiKeyLastmodified: kibanaVersion,
- },
- },
- { version: '123' }
- );
- expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
- });
-
- test('swallows error when invalidate API key throws', async () => {
- alertsClientParams.invalidateAPIKey.mockRejectedValue(new Error('Fail'));
-
- await alertsClient.updateApiKey({ id: '1' });
- expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
- 'Failed to invalidate API Key: Fail'
- );
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled();
- });
-
- test('swallows error when getting decrypted object throws', async () => {
- encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail'));
-
- await alertsClient.updateApiKey({ id: '1' });
- expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
- 'updateApiKey(): Failed to load API key to invalidate on alert 1: Fail'
- );
- expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled();
- expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
- });
-
- test('throws when unsecuredSavedObjectsClient update fails and invalidates newly created API key', async () => {
- alertsClientParams.createAPIKey.mockResolvedValueOnce({
- apiKeysEnabled: true,
- result: { id: '234', name: '234', api_key: 'abc' },
- });
- unsecuredSavedObjectsClient.update.mockRejectedValueOnce(new Error('Fail'));
-
- await expect(alertsClient.updateApiKey({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
- `"Fail"`
- );
- expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalledWith({ id: '123' });
- expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '234' });
- });
-
- describe('authorization', () => {
- test('ensures user is authorised to updateApiKey this type of alert under the consumer', async () => {
- await alertsClient.updateApiKey({ id: '1' });
-
- expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute');
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith(
- 'myType',
- 'myApp',
- 'updateApiKey'
- );
- });
-
- test('throws when user is not authorised to updateApiKey this type of alert', async () => {
- authorization.ensureAuthorized.mockRejectedValue(
- new Error(`Unauthorized to updateApiKey a "myType" alert for "myApp"`)
- );
-
- await expect(alertsClient.updateApiKey({ id: '1' })).rejects.toMatchInlineSnapshot(
- `[Error: Unauthorized to updateApiKey a "myType" alert for "myApp"]`
- );
-
- expect(authorization.ensureAuthorized).toHaveBeenCalledWith(
- 'myType',
- 'myApp',
- 'updateApiKey'
- );
- });
- });
-});
-
-describe('listAlertTypes', () => {
- let alertsClient: AlertsClient;
- const alertingAlertType = {
- actionGroups: [],
- actionVariables: undefined,
- defaultActionGroupId: 'default',
- id: 'alertingAlertType',
- name: 'alertingAlertType',
- producer: 'alerts',
- };
- const myAppAlertType = {
- actionGroups: [],
- actionVariables: undefined,
- defaultActionGroupId: 'default',
- id: 'myAppAlertType',
- name: 'myAppAlertType',
- producer: 'myApp',
- };
- const setOfAlertTypes = new Set([myAppAlertType, alertingAlertType]);
-
- const authorizedConsumers = {
- alerts: { read: true, all: true },
- myApp: { read: true, all: true },
- myOtherApp: { read: true, all: true },
- };
-
- beforeEach(() => {
- alertsClient = new AlertsClient(alertsClientParams);
- });
-
- test('should return a list of AlertTypes that exist in the registry', async () => {
- alertTypeRegistry.list.mockReturnValue(setOfAlertTypes);
- authorization.filterByAlertTypeAuthorization.mockResolvedValue(
- new Set([
- { ...myAppAlertType, authorizedConsumers },
- { ...alertingAlertType, authorizedConsumers },
- ])
- );
- expect(await alertsClient.listAlertTypes()).toEqual(
- new Set([
- { ...myAppAlertType, authorizedConsumers },
- { ...alertingAlertType, authorizedConsumers },
- ])
- );
- });
-
- describe('authorization', () => {
- const listedTypes = new Set([
- {
- actionGroups: [],
- actionVariables: undefined,
- defaultActionGroupId: 'default',
- id: 'myType',
- name: 'myType',
- producer: 'myApp',
- },
- {
- id: 'myOtherType',
- name: 'Test',
- actionGroups: [{ id: 'default', name: 'Default' }],
- defaultActionGroupId: 'default',
- producer: 'alerts',
- },
- ]);
- beforeEach(() => {
- alertTypeRegistry.list.mockReturnValue(listedTypes);
- });
-
- test('should return a list of AlertTypes that exist in the registry only if the user is authorised to get them', async () => {
- const authorizedTypes = new Set([
- {
- id: 'myType',
- name: 'Test',
- actionGroups: [{ id: 'default', name: 'Default' }],
- defaultActionGroupId: 'default',
- producer: 'alerts',
- authorizedConsumers: {
- myApp: { read: true, all: true },
- },
- },
- ]);
- authorization.filterByAlertTypeAuthorization.mockResolvedValue(authorizedTypes);
-
- expect(await alertsClient.listAlertTypes()).toEqual(authorizedTypes);
- });
- });
-});
diff --git a/x-pack/plugins/alerts/server/alerts_client.ts b/x-pack/plugins/alerts/server/alerts_client/alerts_client.ts
similarity index 96%
rename from x-pack/plugins/alerts/server/alerts_client.ts
rename to x-pack/plugins/alerts/server/alerts_client/alerts_client.ts
index bd278d39c622..ef3a9e42b983 100644
--- a/x-pack/plugins/alerts/server/alerts_client.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/alerts_client.ts
@@ -14,8 +14,8 @@ import {
SavedObject,
PluginInitializerContext,
} from 'src/core/server';
-import { esKuery } from '../../../../src/plugins/data/server';
-import { ActionsClient, ActionsAuthorization } from '../../actions/server';
+import { esKuery } from '../../../../../src/plugins/data/server';
+import { ActionsClient, ActionsAuthorization } from '../../../actions/server';
import {
Alert,
PartialAlert,
@@ -27,26 +27,26 @@ import {
SanitizedAlert,
AlertTaskState,
AlertInstanceSummary,
-} from './types';
-import { validateAlertTypeParams, alertExecutionStatusFromRaw } from './lib';
+} from '../types';
+import { validateAlertTypeParams, alertExecutionStatusFromRaw } from '../lib';
import {
InvalidateAPIKeyParams,
GrantAPIKeyResult as SecurityPluginGrantAPIKeyResult,
InvalidateAPIKeyResult as SecurityPluginInvalidateAPIKeyResult,
-} from '../../security/server';
-import { EncryptedSavedObjectsClient } from '../../encrypted_saved_objects/server';
-import { TaskManagerStartContract } from '../../task_manager/server';
-import { taskInstanceToAlertTaskInstance } from './task_runner/alert_task_instance';
-import { deleteTaskIfItExists } from './lib/delete_task_if_it_exists';
-import { RegistryAlertType } from './alert_type_registry';
-import { AlertsAuthorization, WriteOperations, ReadOperations, and } from './authorization';
-import { IEventLogClient } from '../../../plugins/event_log/server';
-import { parseIsoOrRelativeDate } from './lib/iso_or_relative_date';
-import { alertInstanceSummaryFromEventLog } from './lib/alert_instance_summary_from_event_log';
-import { IEvent } from '../../event_log/server';
-import { parseDuration } from '../common/parse_duration';
-import { retryIfConflicts } from './lib/retry_if_conflicts';
-import { partiallyUpdateAlert } from './saved_objects';
+} from '../../../security/server';
+import { EncryptedSavedObjectsClient } from '../../../encrypted_saved_objects/server';
+import { TaskManagerStartContract } from '../../../task_manager/server';
+import { taskInstanceToAlertTaskInstance } from '../task_runner/alert_task_instance';
+import { deleteTaskIfItExists } from '../lib/delete_task_if_it_exists';
+import { RegistryAlertType } from '../alert_type_registry';
+import { AlertsAuthorization, WriteOperations, ReadOperations, and } from '../authorization';
+import { IEventLogClient } from '../../../../plugins/event_log/server';
+import { parseIsoOrRelativeDate } from '../lib/iso_or_relative_date';
+import { alertInstanceSummaryFromEventLog } from '../lib/alert_instance_summary_from_event_log';
+import { IEvent } from '../../../event_log/server';
+import { parseDuration } from '../../common/parse_duration';
+import { retryIfConflicts } from '../lib/retry_if_conflicts';
+import { partiallyUpdateAlert } from '../saved_objects';
export interface RegistryAlertTypeWithAuth extends RegistryAlertType {
authorizedConsumers: string[];
diff --git a/x-pack/plugins/monitoring/public/lib/jquery_flot/index.js b/x-pack/plugins/alerts/server/alerts_client/index.ts
similarity index 85%
rename from x-pack/plugins/monitoring/public/lib/jquery_flot/index.js
rename to x-pack/plugins/alerts/server/alerts_client/index.ts
index abf060aca8c0..e40076a29fff 100644
--- a/x-pack/plugins/monitoring/public/lib/jquery_flot/index.js
+++ b/x-pack/plugins/alerts/server/alerts_client/index.ts
@@ -3,5 +3,4 @@
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
-
-export { default } from './jquery_flot';
+export * from './alerts_client';
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/create.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/create.test.ts
new file mode 100644
index 000000000000..d91896d17bf1
--- /dev/null
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/create.test.ts
@@ -0,0 +1,1097 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+import { schema } from '@kbn/config-schema';
+import { AlertsClient, ConstructorOptions, CreateOptions } from '../alerts_client';
+import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
+import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
+import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
+import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
+import { actionsClientMock, actionsAuthorizationMock } from '../../../../actions/server/mocks';
+import { AlertsAuthorization } from '../../authorization/alerts_authorization';
+import { ActionsAuthorization } from '../../../../actions/server';
+import { TaskStatus } from '../../../../task_manager/server';
+import { getBeforeSetup, setGlobalDate } from './lib';
+
+const taskManager = taskManagerMock.createStart();
+const alertTypeRegistry = alertTypeRegistryMock.create();
+const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
+const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
+const authorization = alertsAuthorizationMock.create();
+const actionsAuthorization = actionsAuthorizationMock.create();
+
+const kibanaVersion = 'v7.10.0';
+const alertsClientParams: jest.Mocked = {
+ taskManager,
+ alertTypeRegistry,
+ unsecuredSavedObjectsClient,
+ authorization: (authorization as unknown) as AlertsAuthorization,
+ actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization,
+ spaceId: 'default',
+ namespace: 'default',
+ getUserName: jest.fn(),
+ createAPIKey: jest.fn(),
+ invalidateAPIKey: jest.fn(),
+ logger: loggingSystemMock.create().get(),
+ encryptedSavedObjectsClient: encryptedSavedObjects,
+ getActionsClient: jest.fn(),
+ getEventLogClient: jest.fn(),
+ kibanaVersion,
+};
+
+beforeEach(() => {
+ getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry);
+});
+
+setGlobalDate();
+
+function getMockData(overwrites: Record = {}): CreateOptions['data'] {
+ return {
+ enabled: true,
+ name: 'abc',
+ tags: ['foo'],
+ alertTypeId: '123',
+ consumer: 'bar',
+ schedule: { interval: '10s' },
+ throttle: null,
+ params: {
+ bar: true,
+ },
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ ...overwrites,
+ };
+}
+
+describe('create()', () => {
+ let alertsClient: AlertsClient;
+
+ beforeEach(() => {
+ alertsClient = new AlertsClient(alertsClientParams);
+ });
+
+ describe('authorization', () => {
+ function tryToExecuteOperation(options: CreateOptions): Promise {
+ unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
+ saved_objects: [
+ {
+ id: '1',
+ type: 'action',
+ attributes: {
+ actions: [],
+ actionTypeId: 'test',
+ },
+ references: [],
+ },
+ ],
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ alertTypeId: '123',
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ createdAt: '2019-02-12T21:01:22.479Z',
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+ taskManager.schedule.mockResolvedValueOnce({
+ id: 'task-123',
+ taskType: 'alerting:123',
+ scheduledAt: new Date(),
+ attempts: 1,
+ status: TaskStatus.Idle,
+ runAt: new Date(),
+ startedAt: null,
+ retryAt: null,
+ state: {},
+ params: {},
+ ownerId: null,
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [],
+ scheduledTaskId: 'task-123',
+ },
+ references: [
+ {
+ id: '1',
+ name: 'action_0',
+ type: 'action',
+ },
+ ],
+ });
+
+ return alertsClient.create(options);
+ }
+
+ test('ensures user is authorised to create this type of alert under the consumer', async () => {
+ const data = getMockData({
+ alertTypeId: 'myType',
+ consumer: 'myApp',
+ });
+
+ await tryToExecuteOperation({ data });
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'create');
+ });
+
+ test('throws when user is not authorised to create this type of alert', async () => {
+ const data = getMockData({
+ alertTypeId: 'myType',
+ consumer: 'myApp',
+ });
+
+ authorization.ensureAuthorized.mockRejectedValue(
+ new Error(`Unauthorized to create a "myType" alert for "myApp"`)
+ );
+
+ await expect(tryToExecuteOperation({ data })).rejects.toMatchInlineSnapshot(
+ `[Error: Unauthorized to create a "myType" alert for "myApp"]`
+ );
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'create');
+ });
+ });
+
+ test('creates an alert', async () => {
+ const data = getMockData();
+ const createdAttributes = {
+ ...data,
+ alertTypeId: '123',
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ createdAt: '2019-02-12T21:01:22.479Z',
+ createdBy: 'elastic',
+ updatedBy: 'elastic',
+ muteAll: false,
+ mutedInstanceIds: [],
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ };
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: createdAttributes,
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+ taskManager.schedule.mockResolvedValueOnce({
+ id: 'task-123',
+ taskType: 'alerting:123',
+ scheduledAt: new Date(),
+ attempts: 1,
+ status: TaskStatus.Idle,
+ runAt: new Date(),
+ startedAt: null,
+ retryAt: null,
+ state: {},
+ params: {},
+ ownerId: null,
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ ...createdAttributes,
+ scheduledTaskId: 'task-123',
+ },
+ references: [
+ {
+ id: '1',
+ name: 'action_0',
+ type: 'action',
+ },
+ ],
+ });
+ const result = await alertsClient.create({ data });
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('123', 'bar', 'create');
+ expect(result).toMatchInlineSnapshot(`
+ Object {
+ "actions": Array [
+ Object {
+ "actionTypeId": "test",
+ "group": "default",
+ "id": "1",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ ],
+ "alertTypeId": "123",
+ "consumer": "bar",
+ "createdAt": 2019-02-12T21:01:22.479Z,
+ "createdBy": "elastic",
+ "enabled": true,
+ "id": "1",
+ "muteAll": false,
+ "mutedInstanceIds": Array [],
+ "name": "abc",
+ "params": Object {
+ "bar": true,
+ },
+ "schedule": Object {
+ "interval": "10s",
+ },
+ "scheduledTaskId": "task-123",
+ "tags": Array [
+ "foo",
+ ],
+ "throttle": null,
+ "updatedAt": 2019-02-12T21:01:22.479Z,
+ "updatedBy": "elastic",
+ }
+ `);
+ expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1);
+ expect(unsecuredSavedObjectsClient.create.mock.calls[0]).toHaveLength(3);
+ expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual('alert');
+ expect(unsecuredSavedObjectsClient.create.mock.calls[0][1]).toMatchInlineSnapshot(`
+ Object {
+ "actions": Array [
+ Object {
+ "actionRef": "action_0",
+ "actionTypeId": "test",
+ "group": "default",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ ],
+ "alertTypeId": "123",
+ "apiKey": null,
+ "apiKeyOwner": null,
+ "consumer": "bar",
+ "createdAt": "2019-02-12T21:01:22.479Z",
+ "createdBy": "elastic",
+ "enabled": true,
+ "executionStatus": Object {
+ "error": null,
+ "lastExecutionDate": "2019-02-12T21:01:22.479Z",
+ "status": "pending",
+ },
+ "meta": Object {
+ "versionApiKeyLastmodified": "v7.10.0",
+ },
+ "muteAll": false,
+ "mutedInstanceIds": Array [],
+ "name": "abc",
+ "params": Object {
+ "bar": true,
+ },
+ "schedule": Object {
+ "interval": "10s",
+ },
+ "tags": Array [
+ "foo",
+ ],
+ "throttle": null,
+ "updatedBy": "elastic",
+ }
+ `);
+ expect(unsecuredSavedObjectsClient.create.mock.calls[0][2]).toMatchInlineSnapshot(`
+ Object {
+ "references": Array [
+ Object {
+ "id": "1",
+ "name": "action_0",
+ "type": "action",
+ },
+ ],
+ }
+ `);
+ expect(taskManager.schedule).toHaveBeenCalledTimes(1);
+ expect(taskManager.schedule.mock.calls[0]).toMatchInlineSnapshot(`
+ Array [
+ Object {
+ "params": Object {
+ "alertId": "1",
+ "spaceId": "default",
+ },
+ "scope": Array [
+ "alerting",
+ ],
+ "state": Object {
+ "alertInstances": Object {},
+ "alertTypeState": Object {},
+ "previousStartedAt": null,
+ },
+ "taskType": "alerting:123",
+ },
+ ]
+ `);
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(1);
+ expect(unsecuredSavedObjectsClient.update.mock.calls[0]).toHaveLength(3);
+ expect(unsecuredSavedObjectsClient.update.mock.calls[0][0]).toEqual('alert');
+ expect(unsecuredSavedObjectsClient.update.mock.calls[0][1]).toEqual('1');
+ expect(unsecuredSavedObjectsClient.update.mock.calls[0][2]).toMatchInlineSnapshot(`
+ Object {
+ "scheduledTaskId": "task-123",
+ }
+ `);
+ });
+
+ test('creates an alert with multiple actions', async () => {
+ const data = getMockData({
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ params: {
+ foo: true,
+ },
+ },
+ {
+ group: 'default',
+ id: '1',
+ params: {
+ foo: true,
+ },
+ },
+ {
+ group: 'default',
+ id: '2',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ alertTypeId: '123',
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ createdAt: new Date().toISOString(),
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ {
+ group: 'default',
+ actionRef: 'action_1',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ {
+ group: 'default',
+ actionRef: 'action_2',
+ actionTypeId: 'test2',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ {
+ name: 'action_1',
+ type: 'action',
+ id: '1',
+ },
+ {
+ name: 'action_2',
+ type: 'action',
+ id: '2',
+ },
+ ],
+ });
+ taskManager.schedule.mockResolvedValueOnce({
+ id: 'task-123',
+ taskType: 'alerting:123',
+ scheduledAt: new Date(),
+ attempts: 1,
+ status: TaskStatus.Idle,
+ runAt: new Date(),
+ startedAt: null,
+ retryAt: null,
+ state: {},
+ params: {},
+ ownerId: null,
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [],
+ scheduledTaskId: 'task-123',
+ },
+ references: [],
+ });
+ const result = await alertsClient.create({ data });
+ expect(result).toMatchInlineSnapshot(`
+ Object {
+ "actions": Array [
+ Object {
+ "actionTypeId": "test",
+ "group": "default",
+ "id": "1",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ Object {
+ "actionTypeId": "test",
+ "group": "default",
+ "id": "1",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ Object {
+ "actionTypeId": "test2",
+ "group": "default",
+ "id": "2",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ ],
+ "alertTypeId": "123",
+ "createdAt": 2019-02-12T21:01:22.479Z,
+ "id": "1",
+ "params": Object {
+ "bar": true,
+ },
+ "schedule": Object {
+ "interval": "10s",
+ },
+ "scheduledTaskId": "task-123",
+ "updatedAt": 2019-02-12T21:01:22.479Z,
+ }
+ `);
+ });
+
+ test('creates a disabled alert', async () => {
+ const data = getMockData({ enabled: false });
+ unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
+ saved_objects: [
+ {
+ id: '1',
+ type: 'action',
+ attributes: {
+ actions: [],
+ actionTypeId: 'test',
+ },
+ references: [],
+ },
+ ],
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ enabled: false,
+ alertTypeId: '123',
+ schedule: { interval: 10000 },
+ params: {
+ bar: true,
+ },
+ createdAt: new Date().toISOString(),
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+ const result = await alertsClient.create({ data });
+ expect(result).toMatchInlineSnapshot(`
+ Object {
+ "actions": Array [
+ Object {
+ "actionTypeId": "test",
+ "group": "default",
+ "id": "1",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ ],
+ "alertTypeId": "123",
+ "createdAt": 2019-02-12T21:01:22.479Z,
+ "enabled": false,
+ "id": "1",
+ "params": Object {
+ "bar": true,
+ },
+ "schedule": Object {
+ "interval": 10000,
+ },
+ "updatedAt": 2019-02-12T21:01:22.479Z,
+ }
+ `);
+ expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1);
+ expect(taskManager.schedule).toHaveBeenCalledTimes(0);
+ });
+
+ test('should trim alert name when creating API key', async () => {
+ const data = getMockData({ name: ' my alert name ' });
+ unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
+ saved_objects: [
+ {
+ id: '1',
+ type: 'action',
+ attributes: {
+ actions: [],
+ actionTypeId: 'test',
+ },
+ references: [],
+ },
+ ],
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ enabled: false,
+ name: ' my alert name ',
+ alertTypeId: '123',
+ schedule: { interval: 10000 },
+ params: {
+ bar: true,
+ },
+ createdAt: new Date().toISOString(),
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+ taskManager.schedule.mockResolvedValueOnce({
+ id: 'task-123',
+ taskType: 'alerting:123',
+ scheduledAt: new Date(),
+ attempts: 1,
+ status: TaskStatus.Idle,
+ runAt: new Date(),
+ startedAt: null,
+ retryAt: null,
+ state: {},
+ params: {},
+ ownerId: null,
+ });
+
+ await alertsClient.create({ data });
+ expect(alertsClientParams.createAPIKey).toHaveBeenCalledWith('Alerting: 123/my alert name');
+ });
+
+ test('should validate params', async () => {
+ const data = getMockData();
+ alertTypeRegistry.get.mockReturnValue({
+ id: '123',
+ name: 'Test',
+ actionGroups: [
+ {
+ id: 'default',
+ name: 'Default',
+ },
+ ],
+ defaultActionGroupId: 'default',
+ validate: {
+ params: schema.object({
+ param1: schema.string(),
+ threshold: schema.number({ min: 0, max: 1 }),
+ }),
+ },
+ async executor() {},
+ producer: 'alerts',
+ });
+ await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"params invalid: [param1]: expected value of type [string] but got [undefined]"`
+ );
+ });
+
+ test('throws error if loading actions fails', async () => {
+ const data = getMockData();
+ const actionsClient = actionsClientMock.create();
+ actionsClient.getBulk.mockRejectedValueOnce(new Error('Test Error'));
+ alertsClientParams.getActionsClient.mockResolvedValue(actionsClient);
+ await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"Test Error"`
+ );
+ expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled();
+ expect(taskManager.schedule).not.toHaveBeenCalled();
+ });
+
+ test('throws error and invalidates API key when create saved object fails', async () => {
+ const data = getMockData();
+ alertsClientParams.createAPIKey.mockResolvedValueOnce({
+ apiKeysEnabled: true,
+ result: { id: '123', name: '123', api_key: 'abc' },
+ });
+ unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
+ saved_objects: [
+ {
+ id: '1',
+ type: 'action',
+ attributes: {
+ actions: [],
+ actionTypeId: 'test',
+ },
+ references: [],
+ },
+ ],
+ });
+ unsecuredSavedObjectsClient.create.mockRejectedValueOnce(new Error('Test failure'));
+ await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"Test failure"`
+ );
+ expect(taskManager.schedule).not.toHaveBeenCalled();
+ expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' });
+ });
+
+ test('attempts to remove saved object if scheduling failed', async () => {
+ const data = getMockData();
+ unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
+ saved_objects: [
+ {
+ id: '1',
+ type: 'action',
+ attributes: {
+ actions: [],
+ actionTypeId: 'test',
+ },
+ references: [],
+ },
+ ],
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ alertTypeId: '123',
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+ taskManager.schedule.mockRejectedValueOnce(new Error('Test failure'));
+ unsecuredSavedObjectsClient.delete.mockResolvedValueOnce({});
+ await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"Test failure"`
+ );
+ expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledTimes(1);
+ expect(unsecuredSavedObjectsClient.delete.mock.calls[0]).toMatchInlineSnapshot(`
+ Array [
+ "alert",
+ "1",
+ ]
+ `);
+ });
+
+ test('returns task manager error if cleanup fails, logs to console', async () => {
+ const data = getMockData();
+ unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
+ saved_objects: [
+ {
+ id: '1',
+ type: 'action',
+ attributes: {
+ actions: [],
+ actionTypeId: 'test',
+ },
+ references: [],
+ },
+ ],
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ alertTypeId: '123',
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+ taskManager.schedule.mockRejectedValueOnce(new Error('Task manager error'));
+ unsecuredSavedObjectsClient.delete.mockRejectedValueOnce(
+ new Error('Saved object delete error')
+ );
+ await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"Task manager error"`
+ );
+ expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
+ 'Failed to cleanup alert "1" after scheduling task failed. Error: Saved object delete error'
+ );
+ });
+
+ test('throws an error if alert type not registerd', async () => {
+ const data = getMockData();
+ alertTypeRegistry.get.mockImplementation(() => {
+ throw new Error('Invalid type');
+ });
+ await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"Invalid type"`
+ );
+ });
+
+ test('calls the API key function', async () => {
+ const data = getMockData();
+ alertsClientParams.createAPIKey.mockResolvedValueOnce({
+ apiKeysEnabled: true,
+ result: { id: '123', name: '123', api_key: 'abc' },
+ });
+ unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
+ saved_objects: [
+ {
+ id: '1',
+ type: 'action',
+ attributes: {
+ actions: [],
+ actionTypeId: 'test',
+ },
+ references: [],
+ },
+ ],
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ alertTypeId: '123',
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+ taskManager.schedule.mockResolvedValueOnce({
+ id: 'task-123',
+ taskType: 'alerting:123',
+ scheduledAt: new Date(),
+ attempts: 1,
+ status: TaskStatus.Idle,
+ runAt: new Date(),
+ startedAt: null,
+ retryAt: null,
+ state: {},
+ params: {},
+ ownerId: null,
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [],
+ scheduledTaskId: 'task-123',
+ },
+ references: [
+ {
+ id: '1',
+ name: 'action_0',
+ type: 'action',
+ },
+ ],
+ });
+ await alertsClient.create({ data });
+
+ expect(alertsClientParams.createAPIKey).toHaveBeenCalledTimes(1);
+ expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith(
+ 'alert',
+ {
+ actions: [
+ {
+ actionRef: 'action_0',
+ group: 'default',
+ actionTypeId: 'test',
+ params: { foo: true },
+ },
+ ],
+ alertTypeId: '123',
+ consumer: 'bar',
+ name: 'abc',
+ params: { bar: true },
+ apiKey: Buffer.from('123:abc').toString('base64'),
+ apiKeyOwner: 'elastic',
+ createdBy: 'elastic',
+ createdAt: '2019-02-12T21:01:22.479Z',
+ updatedBy: 'elastic',
+ enabled: true,
+ meta: {
+ versionApiKeyLastmodified: 'v7.10.0',
+ },
+ schedule: { interval: '10s' },
+ throttle: null,
+ muteAll: false,
+ mutedInstanceIds: [],
+ tags: ['foo'],
+ executionStatus: {
+ lastExecutionDate: '2019-02-12T21:01:22.479Z',
+ status: 'pending',
+ error: null,
+ },
+ },
+ {
+ references: [
+ {
+ id: '1',
+ name: 'action_0',
+ type: 'action',
+ },
+ ],
+ }
+ );
+ });
+
+ test(`doesn't create API key for disabled alerts`, async () => {
+ const data = getMockData({ enabled: false });
+ unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
+ saved_objects: [
+ {
+ id: '1',
+ type: 'action',
+ attributes: {
+ actions: [],
+ actionTypeId: 'test',
+ },
+ references: [],
+ },
+ ],
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ alertTypeId: '123',
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+ taskManager.schedule.mockResolvedValueOnce({
+ id: 'task-123',
+ taskType: 'alerting:123',
+ scheduledAt: new Date(),
+ attempts: 1,
+ status: TaskStatus.Idle,
+ runAt: new Date(),
+ startedAt: null,
+ retryAt: null,
+ state: {},
+ params: {},
+ ownerId: null,
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [],
+ scheduledTaskId: 'task-123',
+ },
+ references: [
+ {
+ id: '1',
+ name: 'action_0',
+ type: 'action',
+ },
+ ],
+ });
+ await alertsClient.create({ data });
+
+ expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled();
+ expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith(
+ 'alert',
+ {
+ actions: [
+ {
+ actionRef: 'action_0',
+ group: 'default',
+ actionTypeId: 'test',
+ params: { foo: true },
+ },
+ ],
+ alertTypeId: '123',
+ consumer: 'bar',
+ name: 'abc',
+ params: { bar: true },
+ apiKey: null,
+ apiKeyOwner: null,
+ createdBy: 'elastic',
+ createdAt: '2019-02-12T21:01:22.479Z',
+ updatedBy: 'elastic',
+ enabled: false,
+ meta: {
+ versionApiKeyLastmodified: 'v7.10.0',
+ },
+ schedule: { interval: '10s' },
+ throttle: null,
+ muteAll: false,
+ mutedInstanceIds: [],
+ tags: ['foo'],
+ executionStatus: {
+ lastExecutionDate: '2019-02-12T21:01:22.479Z',
+ status: 'pending',
+ error: null,
+ },
+ },
+ {
+ references: [
+ {
+ id: '1',
+ name: 'action_0',
+ type: 'action',
+ },
+ ],
+ }
+ );
+ });
+});
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/delete.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/delete.test.ts
new file mode 100644
index 000000000000..d9b253c3a56e
--- /dev/null
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/delete.test.ts
@@ -0,0 +1,204 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+import { AlertsClient, ConstructorOptions } from '../alerts_client';
+import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
+import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
+import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
+import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
+import { actionsAuthorizationMock } from '../../../../actions/server/mocks';
+import { AlertsAuthorization } from '../../authorization/alerts_authorization';
+import { ActionsAuthorization } from '../../../../actions/server';
+import { getBeforeSetup } from './lib';
+
+const taskManager = taskManagerMock.createStart();
+const alertTypeRegistry = alertTypeRegistryMock.create();
+const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
+const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
+const authorization = alertsAuthorizationMock.create();
+const actionsAuthorization = actionsAuthorizationMock.create();
+
+const kibanaVersion = 'v7.10.0';
+const alertsClientParams: jest.Mocked = {
+ taskManager,
+ alertTypeRegistry,
+ unsecuredSavedObjectsClient,
+ authorization: (authorization as unknown) as AlertsAuthorization,
+ actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization,
+ spaceId: 'default',
+ namespace: 'default',
+ getUserName: jest.fn(),
+ createAPIKey: jest.fn(),
+ invalidateAPIKey: jest.fn(),
+ logger: loggingSystemMock.create().get(),
+ encryptedSavedObjectsClient: encryptedSavedObjects,
+ getActionsClient: jest.fn(),
+ getEventLogClient: jest.fn(),
+ kibanaVersion,
+};
+
+beforeEach(() => {
+ getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry);
+});
+
+describe('delete()', () => {
+ let alertsClient: AlertsClient;
+ const existingAlert = {
+ id: '1',
+ type: 'alert',
+ attributes: {
+ alertTypeId: 'myType',
+ consumer: 'myApp',
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ scheduledTaskId: 'task-123',
+ actions: [
+ {
+ group: 'default',
+ actionTypeId: '.no-op',
+ actionRef: 'action_0',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ };
+ const existingDecryptedAlert = {
+ ...existingAlert,
+ attributes: {
+ ...existingAlert.attributes,
+ apiKey: Buffer.from('123:abc').toString('base64'),
+ },
+ };
+
+ beforeEach(() => {
+ alertsClient = new AlertsClient(alertsClientParams);
+ unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert);
+ unsecuredSavedObjectsClient.delete.mockResolvedValue({
+ success: true,
+ });
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingDecryptedAlert);
+ });
+
+ test('successfully removes an alert', async () => {
+ const result = await alertsClient.delete({ id: '1' });
+ expect(result).toEqual({ success: true });
+ expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledWith('alert', '1');
+ expect(taskManager.remove).toHaveBeenCalledWith('task-123');
+ expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' });
+ expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', {
+ namespace: 'default',
+ });
+ expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled();
+ });
+
+ test('falls back to SOC.get when getDecryptedAsInternalUser throws an error', async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail'));
+
+ const result = await alertsClient.delete({ id: '1' });
+ expect(result).toEqual({ success: true });
+ expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledWith('alert', '1');
+ expect(taskManager.remove).toHaveBeenCalledWith('task-123');
+ expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
+ expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1');
+ expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
+ 'delete(): Failed to load API key to invalidate on alert 1: Fail'
+ );
+ });
+
+ test(`doesn't remove a task when scheduledTaskId is null`, async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue({
+ ...existingDecryptedAlert,
+ attributes: {
+ ...existingDecryptedAlert.attributes,
+ scheduledTaskId: null,
+ },
+ });
+
+ await alertsClient.delete({ id: '1' });
+ expect(taskManager.remove).not.toHaveBeenCalled();
+ });
+
+ test(`doesn't invalidate API key when apiKey is null`, async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue({
+ ...existingAlert,
+ attributes: {
+ ...existingAlert.attributes,
+ apiKey: null,
+ },
+ });
+
+ await alertsClient.delete({ id: '1' });
+ expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
+ });
+
+ test('swallows error when invalidate API key throws', async () => {
+ alertsClientParams.invalidateAPIKey.mockRejectedValueOnce(new Error('Fail'));
+
+ await alertsClient.delete({ id: '1' });
+ expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' });
+ expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
+ 'Failed to invalidate API Key: Fail'
+ );
+ });
+
+ test('swallows error when getDecryptedAsInternalUser throws an error', async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail'));
+
+ await alertsClient.delete({ id: '1' });
+ expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
+ expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
+ 'delete(): Failed to load API key to invalidate on alert 1: Fail'
+ );
+ });
+
+ test('throws error when unsecuredSavedObjectsClient.get throws an error', async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail'));
+ unsecuredSavedObjectsClient.get.mockRejectedValue(new Error('SOC Fail'));
+
+ await expect(alertsClient.delete({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"SOC Fail"`
+ );
+ });
+
+ test('throws error when taskManager.remove throws an error', async () => {
+ taskManager.remove.mockRejectedValue(new Error('TM Fail'));
+
+ await expect(alertsClient.delete({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"TM Fail"`
+ );
+ });
+
+ describe('authorization', () => {
+ test('ensures user is authorised to delete this type of alert under the consumer', async () => {
+ await alertsClient.delete({ id: '1' });
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'delete');
+ });
+
+ test('throws when user is not authorised to delete this type of alert', async () => {
+ authorization.ensureAuthorized.mockRejectedValue(
+ new Error(`Unauthorized to delete a "myType" alert for "myApp"`)
+ );
+
+ await expect(alertsClient.delete({ id: '1' })).rejects.toMatchInlineSnapshot(
+ `[Error: Unauthorized to delete a "myType" alert for "myApp"]`
+ );
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'delete');
+ });
+ });
+});
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/disable.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/disable.test.ts
new file mode 100644
index 000000000000..d0557df62202
--- /dev/null
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/disable.test.ts
@@ -0,0 +1,253 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+import { AlertsClient, ConstructorOptions } from '../alerts_client';
+import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
+import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
+import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
+import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
+import { actionsAuthorizationMock } from '../../../../actions/server/mocks';
+import { AlertsAuthorization } from '../../authorization/alerts_authorization';
+import { ActionsAuthorization } from '../../../../actions/server';
+import { getBeforeSetup } from './lib';
+
+const taskManager = taskManagerMock.createStart();
+const alertTypeRegistry = alertTypeRegistryMock.create();
+const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
+
+const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
+const authorization = alertsAuthorizationMock.create();
+const actionsAuthorization = actionsAuthorizationMock.create();
+
+const kibanaVersion = 'v7.10.0';
+const alertsClientParams: jest.Mocked = {
+ taskManager,
+ alertTypeRegistry,
+ unsecuredSavedObjectsClient,
+ authorization: (authorization as unknown) as AlertsAuthorization,
+ actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization,
+ spaceId: 'default',
+ namespace: 'default',
+ getUserName: jest.fn(),
+ createAPIKey: jest.fn(),
+ invalidateAPIKey: jest.fn(),
+ logger: loggingSystemMock.create().get(),
+ encryptedSavedObjectsClient: encryptedSavedObjects,
+ getActionsClient: jest.fn(),
+ getEventLogClient: jest.fn(),
+ kibanaVersion,
+};
+
+beforeEach(() => {
+ getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry);
+});
+
+describe('disable()', () => {
+ let alertsClient: AlertsClient;
+ const existingAlert = {
+ id: '1',
+ type: 'alert',
+ attributes: {
+ consumer: 'myApp',
+ schedule: { interval: '10s' },
+ alertTypeId: 'myType',
+ enabled: true,
+ scheduledTaskId: 'task-123',
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ actionTypeId: '1',
+ actionRef: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ version: '123',
+ references: [],
+ };
+ const existingDecryptedAlert = {
+ ...existingAlert,
+ attributes: {
+ ...existingAlert.attributes,
+ apiKey: Buffer.from('123:abc').toString('base64'),
+ },
+ version: '123',
+ references: [],
+ };
+
+ beforeEach(() => {
+ alertsClient = new AlertsClient(alertsClientParams);
+ unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert);
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingDecryptedAlert);
+ });
+
+ describe('authorization', () => {
+ test('ensures user is authorised to disable this type of alert under the consumer', async () => {
+ await alertsClient.disable({ id: '1' });
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'disable');
+ });
+
+ test('throws when user is not authorised to disable this type of alert', async () => {
+ authorization.ensureAuthorized.mockRejectedValue(
+ new Error(`Unauthorized to disable a "myType" alert for "myApp"`)
+ );
+
+ await expect(alertsClient.disable({ id: '1' })).rejects.toMatchInlineSnapshot(
+ `[Error: Unauthorized to disable a "myType" alert for "myApp"]`
+ );
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'disable');
+ });
+ });
+
+ test('disables an alert', async () => {
+ await alertsClient.disable({ id: '1' });
+ expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled();
+ expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', {
+ namespace: 'default',
+ });
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
+ 'alert',
+ '1',
+ {
+ consumer: 'myApp',
+ schedule: { interval: '10s' },
+ alertTypeId: 'myType',
+ enabled: false,
+ meta: {
+ versionApiKeyLastmodified: kibanaVersion,
+ },
+ scheduledTaskId: null,
+ apiKey: null,
+ apiKeyOwner: null,
+ updatedBy: 'elastic',
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ actionTypeId: '1',
+ actionRef: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ {
+ version: '123',
+ }
+ );
+ expect(taskManager.remove).toHaveBeenCalledWith('task-123');
+ expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' });
+ });
+
+ test('falls back when getDecryptedAsInternalUser throws an error', async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail'));
+
+ await alertsClient.disable({ id: '1' });
+ expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1');
+ expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', {
+ namespace: 'default',
+ });
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
+ 'alert',
+ '1',
+ {
+ consumer: 'myApp',
+ schedule: { interval: '10s' },
+ alertTypeId: 'myType',
+ enabled: false,
+ meta: {
+ versionApiKeyLastmodified: kibanaVersion,
+ },
+ scheduledTaskId: null,
+ apiKey: null,
+ apiKeyOwner: null,
+ updatedBy: 'elastic',
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ actionTypeId: '1',
+ actionRef: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ {
+ version: '123',
+ }
+ );
+ expect(taskManager.remove).toHaveBeenCalledWith('task-123');
+ expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
+ });
+
+ test(`doesn't disable already disabled alerts`, async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValueOnce({
+ ...existingDecryptedAlert,
+ attributes: {
+ ...existingDecryptedAlert.attributes,
+ actions: [],
+ enabled: false,
+ },
+ });
+
+ await alertsClient.disable({ id: '1' });
+ expect(unsecuredSavedObjectsClient.update).not.toHaveBeenCalled();
+ expect(taskManager.remove).not.toHaveBeenCalled();
+ expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
+ });
+
+ test(`doesn't invalidate when no API key is used`, async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValueOnce(existingAlert);
+
+ await alertsClient.disable({ id: '1' });
+ expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
+ });
+
+ test('swallows error when failing to load decrypted saved object', async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail'));
+
+ await alertsClient.disable({ id: '1' });
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled();
+ expect(taskManager.remove).toHaveBeenCalled();
+ expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
+ expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
+ 'disable(): Failed to load API key to invalidate on alert 1: Fail'
+ );
+ });
+
+ test('throws when unsecuredSavedObjectsClient update fails', async () => {
+ unsecuredSavedObjectsClient.update.mockRejectedValueOnce(new Error('Failed to update'));
+
+ await expect(alertsClient.disable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"Failed to update"`
+ );
+ });
+
+ test('swallows error when invalidate API key throws', async () => {
+ alertsClientParams.invalidateAPIKey.mockRejectedValueOnce(new Error('Fail'));
+
+ await alertsClient.disable({ id: '1' });
+ expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
+ 'Failed to invalidate API Key: Fail'
+ );
+ });
+
+ test('throws when failing to remove task from task manager', async () => {
+ taskManager.remove.mockRejectedValueOnce(new Error('Failed to remove task'));
+
+ await expect(alertsClient.disable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"Failed to remove task"`
+ );
+ });
+});
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/enable.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/enable.test.ts
new file mode 100644
index 000000000000..f098bbcad8d0
--- /dev/null
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/enable.test.ts
@@ -0,0 +1,361 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+import { AlertsClient, ConstructorOptions } from '../alerts_client';
+import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
+import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
+import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
+import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
+import { actionsAuthorizationMock } from '../../../../actions/server/mocks';
+import { AlertsAuthorization } from '../../authorization/alerts_authorization';
+import { ActionsAuthorization } from '../../../../actions/server';
+import { TaskStatus } from '../../../../task_manager/server';
+import { getBeforeSetup } from './lib';
+
+const taskManager = taskManagerMock.createStart();
+const alertTypeRegistry = alertTypeRegistryMock.create();
+const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
+
+const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
+const authorization = alertsAuthorizationMock.create();
+const actionsAuthorization = actionsAuthorizationMock.create();
+
+const kibanaVersion = 'v7.10.0';
+const alertsClientParams: jest.Mocked = {
+ taskManager,
+ alertTypeRegistry,
+ unsecuredSavedObjectsClient,
+ authorization: (authorization as unknown) as AlertsAuthorization,
+ actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization,
+ spaceId: 'default',
+ namespace: 'default',
+ getUserName: jest.fn(),
+ createAPIKey: jest.fn(),
+ invalidateAPIKey: jest.fn(),
+ logger: loggingSystemMock.create().get(),
+ encryptedSavedObjectsClient: encryptedSavedObjects,
+ getActionsClient: jest.fn(),
+ getEventLogClient: jest.fn(),
+ kibanaVersion,
+};
+
+beforeEach(() => {
+ getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry);
+});
+
+describe('enable()', () => {
+ let alertsClient: AlertsClient;
+ const existingAlert = {
+ id: '1',
+ type: 'alert',
+ attributes: {
+ consumer: 'myApp',
+ schedule: { interval: '10s' },
+ alertTypeId: 'myType',
+ enabled: false,
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ actionTypeId: '1',
+ actionRef: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ version: '123',
+ references: [],
+ };
+
+ beforeEach(() => {
+ alertsClient = new AlertsClient(alertsClientParams);
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingAlert);
+ unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert);
+ alertsClientParams.createAPIKey.mockResolvedValue({
+ apiKeysEnabled: false,
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ ...existingAlert,
+ attributes: {
+ ...existingAlert.attributes,
+ enabled: true,
+ apiKey: null,
+ apiKeyOwner: null,
+ updatedBy: 'elastic',
+ },
+ });
+ taskManager.schedule.mockResolvedValue({
+ id: 'task-123',
+ scheduledAt: new Date(),
+ attempts: 0,
+ status: TaskStatus.Idle,
+ runAt: new Date(),
+ state: {},
+ params: {},
+ taskType: '',
+ startedAt: null,
+ retryAt: null,
+ ownerId: null,
+ });
+ });
+
+ describe('authorization', () => {
+ beforeEach(() => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingAlert);
+ unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert);
+ alertsClientParams.createAPIKey.mockResolvedValue({
+ apiKeysEnabled: false,
+ });
+ taskManager.schedule.mockResolvedValue({
+ id: 'task-123',
+ scheduledAt: new Date(),
+ attempts: 0,
+ status: TaskStatus.Idle,
+ runAt: new Date(),
+ state: {},
+ params: {},
+ taskType: '',
+ startedAt: null,
+ retryAt: null,
+ ownerId: null,
+ });
+ });
+
+ test('ensures user is authorised to enable this type of alert under the consumer', async () => {
+ await alertsClient.enable({ id: '1' });
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'enable');
+ expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute');
+ });
+
+ test('throws when user is not authorised to enable this type of alert', async () => {
+ authorization.ensureAuthorized.mockRejectedValue(
+ new Error(`Unauthorized to enable a "myType" alert for "myApp"`)
+ );
+
+ await expect(alertsClient.enable({ id: '1' })).rejects.toMatchInlineSnapshot(
+ `[Error: Unauthorized to enable a "myType" alert for "myApp"]`
+ );
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'enable');
+ });
+ });
+
+ test('enables an alert', async () => {
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ ...existingAlert,
+ attributes: {
+ ...existingAlert.attributes,
+ enabled: true,
+ apiKey: null,
+ apiKeyOwner: null,
+ updatedBy: 'elastic',
+ },
+ });
+
+ await alertsClient.enable({ id: '1' });
+ expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled();
+ expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', {
+ namespace: 'default',
+ });
+ expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
+ expect(alertsClientParams.createAPIKey).toHaveBeenCalled();
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
+ 'alert',
+ '1',
+ {
+ schedule: { interval: '10s' },
+ alertTypeId: 'myType',
+ consumer: 'myApp',
+ enabled: true,
+ meta: {
+ versionApiKeyLastmodified: kibanaVersion,
+ },
+ updatedBy: 'elastic',
+ apiKey: null,
+ apiKeyOwner: null,
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ actionTypeId: '1',
+ actionRef: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ {
+ version: '123',
+ }
+ );
+ expect(taskManager.schedule).toHaveBeenCalledWith({
+ taskType: `alerting:myType`,
+ params: {
+ alertId: '1',
+ spaceId: 'default',
+ },
+ state: {
+ alertInstances: {},
+ alertTypeState: {},
+ previousStartedAt: null,
+ },
+ scope: ['alerting'],
+ });
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith('alert', '1', {
+ scheduledTaskId: 'task-123',
+ });
+ });
+
+ test('invalidates API key if ever one existed prior to updating', async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue({
+ ...existingAlert,
+ attributes: {
+ ...existingAlert.attributes,
+ apiKey: Buffer.from('123:abc').toString('base64'),
+ },
+ });
+
+ await alertsClient.enable({ id: '1' });
+ expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled();
+ expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', {
+ namespace: 'default',
+ });
+ expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' });
+ });
+
+ test(`doesn't enable already enabled alerts`, async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValueOnce({
+ ...existingAlert,
+ attributes: {
+ ...existingAlert.attributes,
+ enabled: true,
+ },
+ });
+
+ await alertsClient.enable({ id: '1' });
+ expect(alertsClientParams.getUserName).not.toHaveBeenCalled();
+ expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled();
+ expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled();
+ expect(taskManager.schedule).not.toHaveBeenCalled();
+ });
+
+ test('sets API key when createAPIKey returns one', async () => {
+ alertsClientParams.createAPIKey.mockResolvedValueOnce({
+ apiKeysEnabled: true,
+ result: { id: '123', name: '123', api_key: 'abc' },
+ });
+
+ await alertsClient.enable({ id: '1' });
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
+ 'alert',
+ '1',
+ {
+ schedule: { interval: '10s' },
+ alertTypeId: 'myType',
+ consumer: 'myApp',
+ enabled: true,
+ meta: {
+ versionApiKeyLastmodified: kibanaVersion,
+ },
+ apiKey: Buffer.from('123:abc').toString('base64'),
+ apiKeyOwner: 'elastic',
+ updatedBy: 'elastic',
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ actionTypeId: '1',
+ actionRef: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ {
+ version: '123',
+ }
+ );
+ });
+
+ test('falls back when failing to getDecryptedAsInternalUser', async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail'));
+
+ await alertsClient.enable({ id: '1' });
+ expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1');
+ expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
+ 'enable(): Failed to load API key to invalidate on alert 1: Fail'
+ );
+ });
+
+ test('throws error when failing to load the saved object using SOC', async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail'));
+ unsecuredSavedObjectsClient.get.mockRejectedValueOnce(new Error('Fail to get'));
+
+ await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"Fail to get"`
+ );
+ expect(alertsClientParams.getUserName).not.toHaveBeenCalled();
+ expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled();
+ expect(unsecuredSavedObjectsClient.update).not.toHaveBeenCalled();
+ expect(taskManager.schedule).not.toHaveBeenCalled();
+ });
+
+ test('throws error when failing to update the first time', async () => {
+ alertsClientParams.createAPIKey.mockResolvedValueOnce({
+ apiKeysEnabled: true,
+ result: { id: '123', name: '123', api_key: 'abc' },
+ });
+ unsecuredSavedObjectsClient.update.mockReset();
+ unsecuredSavedObjectsClient.update.mockRejectedValueOnce(new Error('Fail to update'));
+
+ await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"Fail to update"`
+ );
+ expect(alertsClientParams.getUserName).toHaveBeenCalled();
+ expect(alertsClientParams.createAPIKey).toHaveBeenCalled();
+ expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' });
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(1);
+ expect(taskManager.schedule).not.toHaveBeenCalled();
+ });
+
+ test('throws error when failing to update the second time', async () => {
+ unsecuredSavedObjectsClient.update.mockReset();
+ unsecuredSavedObjectsClient.update.mockResolvedValueOnce({
+ ...existingAlert,
+ attributes: {
+ ...existingAlert.attributes,
+ enabled: true,
+ },
+ });
+ unsecuredSavedObjectsClient.update.mockRejectedValueOnce(
+ new Error('Fail to update second time')
+ );
+
+ await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"Fail to update second time"`
+ );
+ expect(alertsClientParams.getUserName).toHaveBeenCalled();
+ expect(alertsClientParams.createAPIKey).toHaveBeenCalled();
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(2);
+ expect(taskManager.schedule).toHaveBeenCalled();
+ });
+
+ test('throws error when failing to schedule task', async () => {
+ taskManager.schedule.mockRejectedValueOnce(new Error('Fail to schedule'));
+
+ await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"Fail to schedule"`
+ );
+ expect(alertsClientParams.getUserName).toHaveBeenCalled();
+ expect(alertsClientParams.createAPIKey).toHaveBeenCalled();
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled();
+ });
+});
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/find.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/find.test.ts
new file mode 100644
index 000000000000..c1adaddc80d9
--- /dev/null
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/find.test.ts
@@ -0,0 +1,251 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+import { AlertsClient, ConstructorOptions } from '../alerts_client';
+import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
+import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
+import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
+import { nodeTypes } from '../../../../../../src/plugins/data/common';
+import { esKuery } from '../../../../../../src/plugins/data/server';
+import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
+import { actionsAuthorizationMock } from '../../../../actions/server/mocks';
+import { AlertsAuthorization } from '../../authorization/alerts_authorization';
+import { ActionsAuthorization } from '../../../../actions/server';
+import { getBeforeSetup, setGlobalDate } from './lib';
+
+const taskManager = taskManagerMock.createStart();
+const alertTypeRegistry = alertTypeRegistryMock.create();
+const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
+
+const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
+const authorization = alertsAuthorizationMock.create();
+const actionsAuthorization = actionsAuthorizationMock.create();
+
+const kibanaVersion = 'v7.10.0';
+const alertsClientParams: jest.Mocked = {
+ taskManager,
+ alertTypeRegistry,
+ unsecuredSavedObjectsClient,
+ authorization: (authorization as unknown) as AlertsAuthorization,
+ actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization,
+ spaceId: 'default',
+ namespace: 'default',
+ getUserName: jest.fn(),
+ createAPIKey: jest.fn(),
+ invalidateAPIKey: jest.fn(),
+ logger: loggingSystemMock.create().get(),
+ encryptedSavedObjectsClient: encryptedSavedObjects,
+ getActionsClient: jest.fn(),
+ getEventLogClient: jest.fn(),
+ kibanaVersion,
+};
+
+beforeEach(() => {
+ getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry);
+});
+
+setGlobalDate();
+
+describe('find()', () => {
+ const listedTypes = new Set([
+ {
+ actionGroups: [],
+ actionVariables: undefined,
+ defaultActionGroupId: 'default',
+ id: 'myType',
+ name: 'myType',
+ producer: 'myApp',
+ },
+ ]);
+ beforeEach(() => {
+ authorization.getFindAuthorizationFilter.mockResolvedValue({
+ ensureAlertTypeIsAuthorized() {},
+ logSuccessfulAuthorization() {},
+ });
+ unsecuredSavedObjectsClient.find.mockResolvedValueOnce({
+ total: 1,
+ per_page: 10,
+ page: 1,
+ saved_objects: [
+ {
+ id: '1',
+ type: 'alert',
+ attributes: {
+ alertTypeId: 'myType',
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ createdAt: new Date().toISOString(),
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ score: 1,
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ },
+ ],
+ });
+ alertTypeRegistry.list.mockReturnValue(listedTypes);
+ authorization.filterByAlertTypeAuthorization.mockResolvedValue(
+ new Set([
+ {
+ id: 'myType',
+ name: 'Test',
+ actionGroups: [{ id: 'default', name: 'Default' }],
+ defaultActionGroupId: 'default',
+ producer: 'alerts',
+ authorizedConsumers: {
+ myApp: { read: true, all: true },
+ },
+ },
+ ])
+ );
+ });
+
+ test('calls saved objects client with given params', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ const result = await alertsClient.find({ options: {} });
+ expect(result).toMatchInlineSnapshot(`
+ Object {
+ "data": Array [
+ Object {
+ "actions": Array [
+ Object {
+ "group": "default",
+ "id": "1",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ ],
+ "alertTypeId": "myType",
+ "createdAt": 2019-02-12T21:01:22.479Z,
+ "id": "1",
+ "params": Object {
+ "bar": true,
+ },
+ "schedule": Object {
+ "interval": "10s",
+ },
+ "updatedAt": 2019-02-12T21:01:22.479Z,
+ },
+ ],
+ "page": 1,
+ "perPage": 10,
+ "total": 1,
+ }
+ `);
+ expect(unsecuredSavedObjectsClient.find).toHaveBeenCalledTimes(1);
+ expect(unsecuredSavedObjectsClient.find.mock.calls[0]).toMatchInlineSnapshot(`
+ Array [
+ Object {
+ "fields": undefined,
+ "filter": undefined,
+ "type": "alert",
+ },
+ ]
+ `);
+ });
+
+ describe('authorization', () => {
+ test('ensures user is query filter types down to those the user is authorized to find', async () => {
+ const filter = esKuery.fromKueryExpression(
+ '((alert.attributes.alertTypeId:myType and alert.attributes.consumer:myApp) or (alert.attributes.alertTypeId:myOtherType and alert.attributes.consumer:myApp) or (alert.attributes.alertTypeId:myOtherType and alert.attributes.consumer:myOtherApp))'
+ );
+ authorization.getFindAuthorizationFilter.mockResolvedValue({
+ filter,
+ ensureAlertTypeIsAuthorized() {},
+ logSuccessfulAuthorization() {},
+ });
+
+ const alertsClient = new AlertsClient(alertsClientParams);
+ await alertsClient.find({ options: { filter: 'someTerm' } });
+
+ const [options] = unsecuredSavedObjectsClient.find.mock.calls[0];
+ expect(options.filter).toEqual(
+ nodeTypes.function.buildNode('and', [esKuery.fromKueryExpression('someTerm'), filter])
+ );
+ expect(authorization.getFindAuthorizationFilter).toHaveBeenCalledTimes(1);
+ });
+
+ test('throws if user is not authorized to find any types', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ authorization.getFindAuthorizationFilter.mockRejectedValue(new Error('not authorized'));
+ await expect(alertsClient.find({ options: {} })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"not authorized"`
+ );
+ });
+
+ test('ensures authorization even when the fields required to authorize are omitted from the find', async () => {
+ const ensureAlertTypeIsAuthorized = jest.fn();
+ const logSuccessfulAuthorization = jest.fn();
+ authorization.getFindAuthorizationFilter.mockResolvedValue({
+ ensureAlertTypeIsAuthorized,
+ logSuccessfulAuthorization,
+ });
+
+ unsecuredSavedObjectsClient.find.mockReset();
+ unsecuredSavedObjectsClient.find.mockResolvedValue({
+ total: 1,
+ per_page: 10,
+ page: 1,
+ saved_objects: [
+ {
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [],
+ alertTypeId: 'myType',
+ consumer: 'myApp',
+ tags: ['myTag'],
+ },
+ score: 1,
+ references: [],
+ },
+ ],
+ });
+
+ const alertsClient = new AlertsClient(alertsClientParams);
+ expect(await alertsClient.find({ options: { fields: ['tags'] } })).toMatchInlineSnapshot(`
+ Object {
+ "data": Array [
+ Object {
+ "actions": Array [],
+ "id": "1",
+ "schedule": undefined,
+ "tags": Array [
+ "myTag",
+ ],
+ },
+ ],
+ "page": 1,
+ "perPage": 10,
+ "total": 1,
+ }
+ `);
+
+ expect(unsecuredSavedObjectsClient.find).toHaveBeenCalledWith({
+ fields: ['tags', 'alertTypeId', 'consumer'],
+ type: 'alert',
+ });
+ expect(ensureAlertTypeIsAuthorized).toHaveBeenCalledWith('myType', 'myApp');
+ expect(logSuccessfulAuthorization).toHaveBeenCalled();
+ });
+ });
+});
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/get.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/get.test.ts
new file mode 100644
index 000000000000..004230403de2
--- /dev/null
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/get.test.ts
@@ -0,0 +1,194 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+import { AlertsClient, ConstructorOptions } from '../alerts_client';
+import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
+import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
+import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
+import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
+import { actionsAuthorizationMock } from '../../../../actions/server/mocks';
+import { AlertsAuthorization } from '../../authorization/alerts_authorization';
+import { ActionsAuthorization } from '../../../../actions/server';
+import { getBeforeSetup, setGlobalDate } from './lib';
+
+const taskManager = taskManagerMock.createStart();
+const alertTypeRegistry = alertTypeRegistryMock.create();
+const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
+
+const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
+const authorization = alertsAuthorizationMock.create();
+const actionsAuthorization = actionsAuthorizationMock.create();
+
+const kibanaVersion = 'v7.10.0';
+const alertsClientParams: jest.Mocked = {
+ taskManager,
+ alertTypeRegistry,
+ unsecuredSavedObjectsClient,
+ authorization: (authorization as unknown) as AlertsAuthorization,
+ actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization,
+ spaceId: 'default',
+ namespace: 'default',
+ getUserName: jest.fn(),
+ createAPIKey: jest.fn(),
+ invalidateAPIKey: jest.fn(),
+ logger: loggingSystemMock.create().get(),
+ encryptedSavedObjectsClient: encryptedSavedObjects,
+ getActionsClient: jest.fn(),
+ getEventLogClient: jest.fn(),
+ kibanaVersion,
+};
+
+beforeEach(() => {
+ getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry);
+});
+
+setGlobalDate();
+
+describe('get()', () => {
+ test('calls saved objects client with given params', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ alertTypeId: '123',
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ createdAt: new Date().toISOString(),
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+ const result = await alertsClient.get({ id: '1' });
+ expect(result).toMatchInlineSnapshot(`
+ Object {
+ "actions": Array [
+ Object {
+ "group": "default",
+ "id": "1",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ ],
+ "alertTypeId": "123",
+ "createdAt": 2019-02-12T21:01:22.479Z,
+ "id": "1",
+ "params": Object {
+ "bar": true,
+ },
+ "schedule": Object {
+ "interval": "10s",
+ },
+ "updatedAt": 2019-02-12T21:01:22.479Z,
+ }
+ `);
+ expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1);
+ expect(unsecuredSavedObjectsClient.get.mock.calls[0]).toMatchInlineSnapshot(`
+ Array [
+ "alert",
+ "1",
+ ]
+ `);
+ });
+
+ test(`throws an error when references aren't found`, async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ alertTypeId: '123',
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ references: [],
+ });
+ await expect(alertsClient.get({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"Action reference \\"action_0\\" not found in alert id: 1"`
+ );
+ });
+
+ describe('authorization', () => {
+ beforeEach(() => {
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ alertTypeId: 'myType',
+ consumer: 'myApp',
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+ });
+
+ test('ensures user is authorised to get this type of alert under the consumer', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ await alertsClient.get({ id: '1' });
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'get');
+ });
+
+ test('throws when user is not authorised to get this type of alert', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ authorization.ensureAuthorized.mockRejectedValue(
+ new Error(`Unauthorized to get a "myType" alert for "myApp"`)
+ );
+
+ await expect(alertsClient.get({ id: '1' })).rejects.toMatchInlineSnapshot(
+ `[Error: Unauthorized to get a "myType" alert for "myApp"]`
+ );
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'get');
+ });
+ });
+});
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/get_alert_instance_summary.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/get_alert_instance_summary.test.ts
new file mode 100644
index 000000000000..a53e49337f38
--- /dev/null
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/get_alert_instance_summary.test.ts
@@ -0,0 +1,292 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+import { AlertsClient, ConstructorOptions } from '../alerts_client';
+import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
+import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
+import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
+import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
+import { actionsAuthorizationMock } from '../../../../actions/server/mocks';
+import { AlertsAuthorization } from '../../authorization/alerts_authorization';
+import { ActionsAuthorization } from '../../../../actions/server';
+import { eventLogClientMock } from '../../../../event_log/server/mocks';
+import { QueryEventsBySavedObjectResult } from '../../../../event_log/server';
+import { SavedObject } from 'kibana/server';
+import { EventsFactory } from '../../lib/alert_instance_summary_from_event_log.test';
+import { RawAlert } from '../../types';
+import { getBeforeSetup, mockedDateString, setGlobalDate } from './lib';
+
+const taskManager = taskManagerMock.createStart();
+const alertTypeRegistry = alertTypeRegistryMock.create();
+const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
+const eventLogClient = eventLogClientMock.create();
+
+const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
+const authorization = alertsAuthorizationMock.create();
+const actionsAuthorization = actionsAuthorizationMock.create();
+
+const kibanaVersion = 'v7.10.0';
+const alertsClientParams: jest.Mocked = {
+ taskManager,
+ alertTypeRegistry,
+ unsecuredSavedObjectsClient,
+ authorization: (authorization as unknown) as AlertsAuthorization,
+ actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization,
+ spaceId: 'default',
+ namespace: 'default',
+ getUserName: jest.fn(),
+ createAPIKey: jest.fn(),
+ invalidateAPIKey: jest.fn(),
+ logger: loggingSystemMock.create().get(),
+ encryptedSavedObjectsClient: encryptedSavedObjects,
+ getActionsClient: jest.fn(),
+ getEventLogClient: jest.fn(),
+ kibanaVersion,
+};
+
+beforeEach(() => {
+ getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry, eventLogClient);
+});
+
+setGlobalDate();
+
+const AlertInstanceSummaryFindEventsResult: QueryEventsBySavedObjectResult = {
+ page: 1,
+ per_page: 10000,
+ total: 0,
+ data: [],
+};
+
+const AlertInstanceSummaryIntervalSeconds = 1;
+
+const BaseAlertInstanceSummarySavedObject: SavedObject = {
+ id: '1',
+ type: 'alert',
+ attributes: {
+ enabled: true,
+ name: 'alert-name',
+ tags: ['tag-1', 'tag-2'],
+ alertTypeId: '123',
+ consumer: 'alert-consumer',
+ schedule: { interval: `${AlertInstanceSummaryIntervalSeconds}s` },
+ actions: [],
+ params: {},
+ createdBy: null,
+ updatedBy: null,
+ createdAt: mockedDateString,
+ apiKey: null,
+ apiKeyOwner: null,
+ throttle: null,
+ muteAll: false,
+ mutedInstanceIds: [],
+ executionStatus: {
+ status: 'unknown',
+ lastExecutionDate: '2020-08-20T19:23:38Z',
+ error: null,
+ },
+ },
+ references: [],
+};
+
+function getAlertInstanceSummarySavedObject(
+ attributes: Partial = {}
+): SavedObject {
+ return {
+ ...BaseAlertInstanceSummarySavedObject,
+ attributes: { ...BaseAlertInstanceSummarySavedObject.attributes, ...attributes },
+ };
+}
+
+describe('getAlertInstanceSummary()', () => {
+ let alertsClient: AlertsClient;
+
+ beforeEach(() => {
+ alertsClient = new AlertsClient(alertsClientParams);
+ });
+
+ test('runs as expected with some event log data', async () => {
+ const alertSO = getAlertInstanceSummarySavedObject({
+ mutedInstanceIds: ['instance-muted-no-activity'],
+ });
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce(alertSO);
+
+ const eventsFactory = new EventsFactory(mockedDateString);
+ const events = eventsFactory
+ .addExecute()
+ .addNewInstance('instance-currently-active')
+ .addNewInstance('instance-previously-active')
+ .addActiveInstance('instance-currently-active')
+ .addActiveInstance('instance-previously-active')
+ .advanceTime(10000)
+ .addExecute()
+ .addResolvedInstance('instance-previously-active')
+ .addActiveInstance('instance-currently-active')
+ .getEvents();
+ const eventsResult = {
+ ...AlertInstanceSummaryFindEventsResult,
+ total: events.length,
+ data: events,
+ };
+ eventLogClient.findEventsBySavedObject.mockResolvedValueOnce(eventsResult);
+
+ const dateStart = new Date(Date.now() - 60 * 1000).toISOString();
+
+ const result = await alertsClient.getAlertInstanceSummary({ id: '1', dateStart });
+ expect(result).toMatchInlineSnapshot(`
+ Object {
+ "alertTypeId": "123",
+ "consumer": "alert-consumer",
+ "enabled": true,
+ "errorMessages": Array [],
+ "id": "1",
+ "instances": Object {
+ "instance-currently-active": Object {
+ "activeStartDate": "2019-02-12T21:01:22.479Z",
+ "muted": false,
+ "status": "Active",
+ },
+ "instance-muted-no-activity": Object {
+ "activeStartDate": undefined,
+ "muted": true,
+ "status": "OK",
+ },
+ "instance-previously-active": Object {
+ "activeStartDate": undefined,
+ "muted": false,
+ "status": "OK",
+ },
+ },
+ "lastRun": "2019-02-12T21:01:32.479Z",
+ "muteAll": false,
+ "name": "alert-name",
+ "status": "Active",
+ "statusEndDate": "2019-02-12T21:01:22.479Z",
+ "statusStartDate": "2019-02-12T21:00:22.479Z",
+ "tags": Array [
+ "tag-1",
+ "tag-2",
+ ],
+ "throttle": null,
+ }
+ `);
+ });
+
+ // Further tests don't check the result of `getAlertInstanceSummary()`, as the result
+ // is just the result from the `alertInstanceSummaryFromEventLog()`, which itself
+ // has a complete set of tests. These tests just make sure the data gets
+ // sent into `getAlertInstanceSummary()` as appropriate.
+
+ test('calls saved objects and event log client with default params', async () => {
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce(getAlertInstanceSummarySavedObject());
+ eventLogClient.findEventsBySavedObject.mockResolvedValueOnce(
+ AlertInstanceSummaryFindEventsResult
+ );
+
+ await alertsClient.getAlertInstanceSummary({ id: '1' });
+
+ expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1);
+ expect(eventLogClient.findEventsBySavedObject).toHaveBeenCalledTimes(1);
+ expect(eventLogClient.findEventsBySavedObject.mock.calls[0]).toMatchInlineSnapshot(`
+ Array [
+ "alert",
+ "1",
+ Object {
+ "end": "2019-02-12T21:01:22.479Z",
+ "page": 1,
+ "per_page": 10000,
+ "sort_order": "desc",
+ "start": "2019-02-12T21:00:22.479Z",
+ },
+ ]
+ `);
+ // calculate the expected start/end date for one test
+ const { start, end } = eventLogClient.findEventsBySavedObject.mock.calls[0][2]!;
+ expect(end).toBe(mockedDateString);
+
+ const startMillis = Date.parse(start!);
+ const endMillis = Date.parse(end!);
+ const expectedDuration = 60 * AlertInstanceSummaryIntervalSeconds * 1000;
+ expect(endMillis - startMillis).toBeGreaterThan(expectedDuration - 2);
+ expect(endMillis - startMillis).toBeLessThan(expectedDuration + 2);
+ });
+
+ test('calls event log client with start date', async () => {
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce(getAlertInstanceSummarySavedObject());
+ eventLogClient.findEventsBySavedObject.mockResolvedValueOnce(
+ AlertInstanceSummaryFindEventsResult
+ );
+
+ const dateStart = new Date(
+ Date.now() - 60 * AlertInstanceSummaryIntervalSeconds * 1000
+ ).toISOString();
+ await alertsClient.getAlertInstanceSummary({ id: '1', dateStart });
+
+ expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1);
+ expect(eventLogClient.findEventsBySavedObject).toHaveBeenCalledTimes(1);
+ const { start, end } = eventLogClient.findEventsBySavedObject.mock.calls[0][2]!;
+
+ expect({ start, end }).toMatchInlineSnapshot(`
+ Object {
+ "end": "2019-02-12T21:01:22.479Z",
+ "start": "2019-02-12T21:00:22.479Z",
+ }
+ `);
+ });
+
+ test('calls event log client with relative start date', async () => {
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce(getAlertInstanceSummarySavedObject());
+ eventLogClient.findEventsBySavedObject.mockResolvedValueOnce(
+ AlertInstanceSummaryFindEventsResult
+ );
+
+ const dateStart = '2m';
+ await alertsClient.getAlertInstanceSummary({ id: '1', dateStart });
+
+ expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1);
+ expect(eventLogClient.findEventsBySavedObject).toHaveBeenCalledTimes(1);
+ const { start, end } = eventLogClient.findEventsBySavedObject.mock.calls[0][2]!;
+
+ expect({ start, end }).toMatchInlineSnapshot(`
+ Object {
+ "end": "2019-02-12T21:01:22.479Z",
+ "start": "2019-02-12T20:59:22.479Z",
+ }
+ `);
+ });
+
+ test('invalid start date throws an error', async () => {
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce(getAlertInstanceSummarySavedObject());
+ eventLogClient.findEventsBySavedObject.mockResolvedValueOnce(
+ AlertInstanceSummaryFindEventsResult
+ );
+
+ const dateStart = 'ain"t no way this will get parsed as a date';
+ expect(
+ alertsClient.getAlertInstanceSummary({ id: '1', dateStart })
+ ).rejects.toMatchInlineSnapshot(
+ `[Error: Invalid date for parameter dateStart: "ain"t no way this will get parsed as a date"]`
+ );
+ });
+
+ test('saved object get throws an error', async () => {
+ unsecuredSavedObjectsClient.get.mockRejectedValueOnce(new Error('OMG!'));
+ eventLogClient.findEventsBySavedObject.mockResolvedValueOnce(
+ AlertInstanceSummaryFindEventsResult
+ );
+
+ expect(alertsClient.getAlertInstanceSummary({ id: '1' })).rejects.toMatchInlineSnapshot(
+ `[Error: OMG!]`
+ );
+ });
+
+ test('findEvents throws an error', async () => {
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce(getAlertInstanceSummarySavedObject());
+ eventLogClient.findEventsBySavedObject.mockRejectedValueOnce(new Error('OMG 2!'));
+
+ // error eaten but logged
+ await alertsClient.getAlertInstanceSummary({ id: '1' });
+ });
+});
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/get_alert_state.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/get_alert_state.test.ts
new file mode 100644
index 000000000000..8b32f05f6d5a
--- /dev/null
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/get_alert_state.test.ts
@@ -0,0 +1,239 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+import { AlertsClient, ConstructorOptions } from '../alerts_client';
+import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
+import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
+import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
+import { TaskStatus } from '../../../../task_manager/server';
+import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
+import { actionsAuthorizationMock } from '../../../../actions/server/mocks';
+import { AlertsAuthorization } from '../../authorization/alerts_authorization';
+import { ActionsAuthorization } from '../../../../actions/server';
+import { getBeforeSetup } from './lib';
+
+const taskManager = taskManagerMock.createStart();
+const alertTypeRegistry = alertTypeRegistryMock.create();
+const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
+
+const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
+const authorization = alertsAuthorizationMock.create();
+const actionsAuthorization = actionsAuthorizationMock.create();
+
+const kibanaVersion = 'v7.10.0';
+const alertsClientParams: jest.Mocked = {
+ taskManager,
+ alertTypeRegistry,
+ unsecuredSavedObjectsClient,
+ authorization: (authorization as unknown) as AlertsAuthorization,
+ actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization,
+ spaceId: 'default',
+ namespace: 'default',
+ getUserName: jest.fn(),
+ createAPIKey: jest.fn(),
+ invalidateAPIKey: jest.fn(),
+ logger: loggingSystemMock.create().get(),
+ encryptedSavedObjectsClient: encryptedSavedObjects,
+ getActionsClient: jest.fn(),
+ getEventLogClient: jest.fn(),
+ kibanaVersion,
+};
+
+beforeEach(() => {
+ getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry);
+});
+
+describe('getAlertState()', () => {
+ test('calls saved objects client with given params', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ alertTypeId: '123',
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+
+ taskManager.get.mockResolvedValueOnce({
+ id: '1',
+ taskType: 'alerting:123',
+ scheduledAt: new Date(),
+ attempts: 1,
+ status: TaskStatus.Idle,
+ runAt: new Date(),
+ startedAt: null,
+ retryAt: null,
+ state: {},
+ params: {},
+ ownerId: null,
+ });
+
+ await alertsClient.getAlertState({ id: '1' });
+ expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1);
+ expect(unsecuredSavedObjectsClient.get.mock.calls[0]).toMatchInlineSnapshot(`
+ Array [
+ "alert",
+ "1",
+ ]
+ `);
+ });
+
+ test('gets the underlying task from TaskManager', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+
+ const scheduledTaskId = 'task-123';
+
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ alertTypeId: '123',
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ enabled: true,
+ scheduledTaskId,
+ mutedInstanceIds: [],
+ muteAll: true,
+ },
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+
+ taskManager.get.mockResolvedValueOnce({
+ id: scheduledTaskId,
+ taskType: 'alerting:123',
+ scheduledAt: new Date(),
+ attempts: 1,
+ status: TaskStatus.Idle,
+ runAt: new Date(),
+ startedAt: null,
+ retryAt: null,
+ state: {},
+ params: {
+ alertId: '1',
+ },
+ ownerId: null,
+ });
+
+ await alertsClient.getAlertState({ id: '1' });
+ expect(taskManager.get).toHaveBeenCalledTimes(1);
+ expect(taskManager.get).toHaveBeenCalledWith(scheduledTaskId);
+ });
+
+ describe('authorization', () => {
+ beforeEach(() => {
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ alertTypeId: 'myType',
+ consumer: 'myApp',
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+
+ taskManager.get.mockResolvedValueOnce({
+ id: '1',
+ taskType: 'alerting:123',
+ scheduledAt: new Date(),
+ attempts: 1,
+ status: TaskStatus.Idle,
+ runAt: new Date(),
+ startedAt: null,
+ retryAt: null,
+ state: {},
+ params: {},
+ ownerId: null,
+ });
+ });
+
+ test('ensures user is authorised to get this type of alert under the consumer', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ await alertsClient.getAlertState({ id: '1' });
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith(
+ 'myType',
+ 'myApp',
+ 'getAlertState'
+ );
+ });
+
+ test('throws when user is not authorised to getAlertState this type of alert', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ // `get` check
+ authorization.ensureAuthorized.mockResolvedValueOnce();
+ // `getAlertState` check
+ authorization.ensureAuthorized.mockRejectedValueOnce(
+ new Error(`Unauthorized to getAlertState a "myType" alert for "myApp"`)
+ );
+
+ await expect(alertsClient.getAlertState({ id: '1' })).rejects.toMatchInlineSnapshot(
+ `[Error: Unauthorized to getAlertState a "myType" alert for "myApp"]`
+ );
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith(
+ 'myType',
+ 'myApp',
+ 'getAlertState'
+ );
+ });
+ });
+});
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/lib.ts b/x-pack/plugins/alerts/server/alerts_client/tests/lib.ts
new file mode 100644
index 000000000000..96e49e21b904
--- /dev/null
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/lib.ts
@@ -0,0 +1,103 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+// eslint-disable-next-line @kbn/eslint/no-restricted-paths
+import { TaskManager } from '../../../../task_manager/server/task_manager';
+import { IEventLogClient } from '../../../../event_log/server';
+import { actionsClientMock } from '../../../../actions/server/mocks';
+import { ConstructorOptions } from '../alerts_client';
+import { eventLogClientMock } from '../../../../event_log/server/mocks';
+import { AlertTypeRegistry } from '../../alert_type_registry';
+
+export const mockedDateString = '2019-02-12T21:01:22.479Z';
+
+export function setGlobalDate() {
+ const mockedDate = new Date(mockedDateString);
+ const DateOriginal = Date;
+ // A version of date that responds to `new Date(null|undefined)` and `Date.now()`
+ // by returning a fixed date, otherwise should be same as Date.
+ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
+ (global as any).Date = class Date {
+ constructor(...args: unknown[]) {
+ // sometimes the ctor has no args, sometimes has a single `null` arg
+ if (args[0] == null) {
+ // @ts-ignore
+ return mockedDate;
+ } else {
+ // @ts-ignore
+ return new DateOriginal(...args);
+ }
+ }
+ static now() {
+ return mockedDate.getTime();
+ }
+ static parse(string: string) {
+ return DateOriginal.parse(string);
+ }
+ };
+}
+
+export function getBeforeSetup(
+ alertsClientParams: jest.Mocked,
+ taskManager: jest.Mocked<
+ Pick
+ >,
+ alertTypeRegistry: jest.Mocked>,
+ eventLogClient?: jest.Mocked
+) {
+ jest.resetAllMocks();
+ alertsClientParams.createAPIKey.mockResolvedValue({ apiKeysEnabled: false });
+ alertsClientParams.invalidateAPIKey.mockResolvedValue({
+ apiKeysEnabled: true,
+ result: {
+ invalidated_api_keys: [],
+ previously_invalidated_api_keys: [],
+ error_count: 0,
+ },
+ });
+ alertsClientParams.getUserName.mockResolvedValue('elastic');
+ taskManager.runNow.mockResolvedValue({ id: '' });
+ const actionsClient = actionsClientMock.create();
+
+ actionsClient.getBulk.mockResolvedValueOnce([
+ {
+ id: '1',
+ isPreconfigured: false,
+ actionTypeId: 'test',
+ name: 'test',
+ config: {
+ foo: 'bar',
+ },
+ },
+ {
+ id: '2',
+ isPreconfigured: false,
+ actionTypeId: 'test2',
+ name: 'test2',
+ config: {
+ foo: 'bar',
+ },
+ },
+ {
+ id: 'testPreconfigured',
+ actionTypeId: '.slack',
+ isPreconfigured: true,
+ name: 'test',
+ },
+ ]);
+ alertsClientParams.getActionsClient.mockResolvedValue(actionsClient);
+
+ alertTypeRegistry.get.mockImplementation(() => ({
+ id: '123',
+ name: 'Test',
+ actionGroups: [{ id: 'default', name: 'Default' }],
+ defaultActionGroupId: 'default',
+ async executor() {},
+ producer: 'alerts',
+ }));
+ alertsClientParams.getEventLogClient.mockResolvedValue(
+ eventLogClient ?? eventLogClientMock.create()
+ );
+}
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/list_alert_types.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/list_alert_types.test.ts
new file mode 100644
index 000000000000..b2f5c5498f84
--- /dev/null
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/list_alert_types.test.ts
@@ -0,0 +1,134 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+import { AlertsClient, ConstructorOptions } from '../alerts_client';
+import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
+import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
+import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
+import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
+import { actionsAuthorizationMock } from '../../../../actions/server/mocks';
+import { AlertsAuthorization } from '../../authorization/alerts_authorization';
+import { ActionsAuthorization } from '../../../../actions/server';
+import { getBeforeSetup } from './lib';
+
+const taskManager = taskManagerMock.createStart();
+const alertTypeRegistry = alertTypeRegistryMock.create();
+const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
+
+const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
+const authorization = alertsAuthorizationMock.create();
+const actionsAuthorization = actionsAuthorizationMock.create();
+
+const kibanaVersion = 'v7.10.0';
+const alertsClientParams: jest.Mocked = {
+ taskManager,
+ alertTypeRegistry,
+ unsecuredSavedObjectsClient,
+ authorization: (authorization as unknown) as AlertsAuthorization,
+ actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization,
+ spaceId: 'default',
+ namespace: 'default',
+ getUserName: jest.fn(),
+ createAPIKey: jest.fn(),
+ invalidateAPIKey: jest.fn(),
+ logger: loggingSystemMock.create().get(),
+ encryptedSavedObjectsClient: encryptedSavedObjects,
+ getActionsClient: jest.fn(),
+ getEventLogClient: jest.fn(),
+ kibanaVersion,
+};
+
+beforeEach(() => {
+ getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry);
+});
+
+describe('listAlertTypes', () => {
+ let alertsClient: AlertsClient;
+ const alertingAlertType = {
+ actionGroups: [],
+ actionVariables: undefined,
+ defaultActionGroupId: 'default',
+ id: 'alertingAlertType',
+ name: 'alertingAlertType',
+ producer: 'alerts',
+ };
+ const myAppAlertType = {
+ actionGroups: [],
+ actionVariables: undefined,
+ defaultActionGroupId: 'default',
+ id: 'myAppAlertType',
+ name: 'myAppAlertType',
+ producer: 'myApp',
+ };
+ const setOfAlertTypes = new Set([myAppAlertType, alertingAlertType]);
+
+ const authorizedConsumers = {
+ alerts: { read: true, all: true },
+ myApp: { read: true, all: true },
+ myOtherApp: { read: true, all: true },
+ };
+
+ beforeEach(() => {
+ alertsClient = new AlertsClient(alertsClientParams);
+ });
+
+ test('should return a list of AlertTypes that exist in the registry', async () => {
+ alertTypeRegistry.list.mockReturnValue(setOfAlertTypes);
+ authorization.filterByAlertTypeAuthorization.mockResolvedValue(
+ new Set([
+ { ...myAppAlertType, authorizedConsumers },
+ { ...alertingAlertType, authorizedConsumers },
+ ])
+ );
+ expect(await alertsClient.listAlertTypes()).toEqual(
+ new Set([
+ { ...myAppAlertType, authorizedConsumers },
+ { ...alertingAlertType, authorizedConsumers },
+ ])
+ );
+ });
+
+ describe('authorization', () => {
+ const listedTypes = new Set([
+ {
+ actionGroups: [],
+ actionVariables: undefined,
+ defaultActionGroupId: 'default',
+ id: 'myType',
+ name: 'myType',
+ producer: 'myApp',
+ },
+ {
+ id: 'myOtherType',
+ name: 'Test',
+ actionGroups: [{ id: 'default', name: 'Default' }],
+ defaultActionGroupId: 'default',
+ producer: 'alerts',
+ },
+ ]);
+ beforeEach(() => {
+ alertTypeRegistry.list.mockReturnValue(listedTypes);
+ });
+
+ test('should return a list of AlertTypes that exist in the registry only if the user is authorised to get them', async () => {
+ const authorizedTypes = new Set([
+ {
+ id: 'myType',
+ name: 'Test',
+ actionGroups: [{ id: 'default', name: 'Default' }],
+ defaultActionGroupId: 'default',
+ producer: 'alerts',
+ authorizedConsumers: {
+ myApp: { read: true, all: true },
+ },
+ },
+ ]);
+ authorization.filterByAlertTypeAuthorization.mockResolvedValue(authorizedTypes);
+
+ expect(await alertsClient.listAlertTypes()).toEqual(authorizedTypes);
+ });
+ });
+});
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/mute_all.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/mute_all.test.ts
new file mode 100644
index 000000000000..88199dfd1f7b
--- /dev/null
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/mute_all.test.ts
@@ -0,0 +1,138 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+import { AlertsClient, ConstructorOptions } from '../alerts_client';
+import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
+import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
+import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
+import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
+import { actionsAuthorizationMock } from '../../../../actions/server/mocks';
+import { AlertsAuthorization } from '../../authorization/alerts_authorization';
+import { ActionsAuthorization } from '../../../../actions/server';
+import { getBeforeSetup } from './lib';
+
+const taskManager = taskManagerMock.createStart();
+const alertTypeRegistry = alertTypeRegistryMock.create();
+const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
+const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
+const authorization = alertsAuthorizationMock.create();
+const actionsAuthorization = actionsAuthorizationMock.create();
+
+const kibanaVersion = 'v7.10.0';
+const alertsClientParams: jest.Mocked = {
+ taskManager,
+ alertTypeRegistry,
+ unsecuredSavedObjectsClient,
+ authorization: (authorization as unknown) as AlertsAuthorization,
+ actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization,
+ spaceId: 'default',
+ namespace: 'default',
+ getUserName: jest.fn(),
+ createAPIKey: jest.fn(),
+ invalidateAPIKey: jest.fn(),
+ logger: loggingSystemMock.create().get(),
+ encryptedSavedObjectsClient: encryptedSavedObjects,
+ getActionsClient: jest.fn(),
+ getEventLogClient: jest.fn(),
+ kibanaVersion,
+};
+
+beforeEach(() => {
+ getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry);
+});
+
+describe('muteAll()', () => {
+ test('mutes an alert', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ actionTypeId: '1',
+ actionRef: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ muteAll: false,
+ },
+ references: [],
+ version: '123',
+ });
+
+ await alertsClient.muteAll({ id: '1' });
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
+ 'alert',
+ '1',
+ {
+ muteAll: true,
+ mutedInstanceIds: [],
+ updatedBy: 'elastic',
+ },
+ {
+ version: '123',
+ }
+ );
+ });
+
+ describe('authorization', () => {
+ beforeEach(() => {
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ actionTypeId: '1',
+ actionRef: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ consumer: 'myApp',
+ schedule: { interval: '10s' },
+ alertTypeId: 'myType',
+ apiKey: null,
+ apiKeyOwner: null,
+ enabled: false,
+ scheduledTaskId: null,
+ updatedBy: 'elastic',
+ muteAll: false,
+ },
+ references: [],
+ });
+ });
+
+ test('ensures user is authorised to muteAll this type of alert under the consumer', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ await alertsClient.muteAll({ id: '1' });
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'muteAll');
+ expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute');
+ });
+
+ test('throws when user is not authorised to muteAll this type of alert', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ authorization.ensureAuthorized.mockRejectedValue(
+ new Error(`Unauthorized to muteAll a "myType" alert for "myApp"`)
+ );
+
+ await expect(alertsClient.muteAll({ id: '1' })).rejects.toMatchInlineSnapshot(
+ `[Error: Unauthorized to muteAll a "myType" alert for "myApp"]`
+ );
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'muteAll');
+ });
+ });
+});
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/mute_instance.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/mute_instance.test.ts
new file mode 100644
index 000000000000..cd7112b3551b
--- /dev/null
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/mute_instance.test.ts
@@ -0,0 +1,181 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+import { AlertsClient, ConstructorOptions } from '../alerts_client';
+import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
+import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
+import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
+import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
+import { actionsAuthorizationMock } from '../../../../actions/server/mocks';
+import { AlertsAuthorization } from '../../authorization/alerts_authorization';
+import { ActionsAuthorization } from '../../../../actions/server';
+import { getBeforeSetup } from './lib';
+
+const taskManager = taskManagerMock.createStart();
+const alertTypeRegistry = alertTypeRegistryMock.create();
+const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
+
+const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
+const authorization = alertsAuthorizationMock.create();
+const actionsAuthorization = actionsAuthorizationMock.create();
+
+const kibanaVersion = 'v7.10.0';
+const alertsClientParams: jest.Mocked = {
+ taskManager,
+ alertTypeRegistry,
+ unsecuredSavedObjectsClient,
+ authorization: (authorization as unknown) as AlertsAuthorization,
+ actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization,
+ spaceId: 'default',
+ namespace: 'default',
+ getUserName: jest.fn(),
+ createAPIKey: jest.fn(),
+ invalidateAPIKey: jest.fn(),
+ logger: loggingSystemMock.create().get(),
+ encryptedSavedObjectsClient: encryptedSavedObjects,
+ getActionsClient: jest.fn(),
+ getEventLogClient: jest.fn(),
+ kibanaVersion,
+};
+
+beforeEach(() => {
+ getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry);
+});
+
+describe('muteInstance()', () => {
+ test('mutes an alert instance', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [],
+ schedule: { interval: '10s' },
+ alertTypeId: '2',
+ enabled: true,
+ scheduledTaskId: 'task-123',
+ mutedInstanceIds: [],
+ },
+ version: '123',
+ references: [],
+ });
+
+ await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' });
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
+ 'alert',
+ '1',
+ {
+ mutedInstanceIds: ['2'],
+ updatedBy: 'elastic',
+ },
+ {
+ version: '123',
+ }
+ );
+ });
+
+ test('skips muting when alert instance already muted', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [],
+ schedule: { interval: '10s' },
+ alertTypeId: '2',
+ enabled: true,
+ scheduledTaskId: 'task-123',
+ mutedInstanceIds: ['2'],
+ },
+ references: [],
+ });
+
+ await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' });
+ expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled();
+ });
+
+ test('skips muting when alert is muted', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [],
+ schedule: { interval: '10s' },
+ alertTypeId: '2',
+ enabled: true,
+ scheduledTaskId: 'task-123',
+ mutedInstanceIds: [],
+ muteAll: true,
+ },
+ references: [],
+ });
+
+ await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' });
+ expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled();
+ });
+
+ describe('authorization', () => {
+ beforeEach(() => {
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ actionTypeId: '1',
+ actionRef: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ schedule: { interval: '10s' },
+ alertTypeId: 'myType',
+ consumer: 'myApp',
+ enabled: true,
+ scheduledTaskId: 'task-123',
+ mutedInstanceIds: [],
+ },
+ version: '123',
+ references: [],
+ });
+ });
+
+ test('ensures user is authorised to muteInstance this type of alert under the consumer', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' });
+
+ expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute');
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith(
+ 'myType',
+ 'myApp',
+ 'muteInstance'
+ );
+ });
+
+ test('throws when user is not authorised to muteInstance this type of alert', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ authorization.ensureAuthorized.mockRejectedValue(
+ new Error(`Unauthorized to muteInstance a "myType" alert for "myApp"`)
+ );
+
+ await expect(
+ alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' })
+ ).rejects.toMatchInlineSnapshot(
+ `[Error: Unauthorized to muteInstance a "myType" alert for "myApp"]`
+ );
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith(
+ 'myType',
+ 'myApp',
+ 'muteInstance'
+ );
+ });
+ });
+});
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/unmute_all.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/unmute_all.test.ts
new file mode 100644
index 000000000000..07666c1cc626
--- /dev/null
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/unmute_all.test.ts
@@ -0,0 +1,139 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+import { AlertsClient, ConstructorOptions } from '../alerts_client';
+import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
+import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
+import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
+import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
+import { actionsAuthorizationMock } from '../../../../actions/server/mocks';
+import { AlertsAuthorization } from '../../authorization/alerts_authorization';
+import { ActionsAuthorization } from '../../../../actions/server';
+import { getBeforeSetup } from './lib';
+
+const taskManager = taskManagerMock.createStart();
+const alertTypeRegistry = alertTypeRegistryMock.create();
+const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
+
+const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
+const authorization = alertsAuthorizationMock.create();
+const actionsAuthorization = actionsAuthorizationMock.create();
+
+const kibanaVersion = 'v7.10.0';
+const alertsClientParams: jest.Mocked = {
+ taskManager,
+ alertTypeRegistry,
+ unsecuredSavedObjectsClient,
+ authorization: (authorization as unknown) as AlertsAuthorization,
+ actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization,
+ spaceId: 'default',
+ namespace: 'default',
+ getUserName: jest.fn(),
+ createAPIKey: jest.fn(),
+ invalidateAPIKey: jest.fn(),
+ logger: loggingSystemMock.create().get(),
+ encryptedSavedObjectsClient: encryptedSavedObjects,
+ getActionsClient: jest.fn(),
+ getEventLogClient: jest.fn(),
+ kibanaVersion,
+};
+
+beforeEach(() => {
+ getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry);
+});
+
+describe('unmuteAll()', () => {
+ test('unmutes an alert', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ actionTypeId: '1',
+ actionRef: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ muteAll: true,
+ },
+ references: [],
+ version: '123',
+ });
+
+ await alertsClient.unmuteAll({ id: '1' });
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
+ 'alert',
+ '1',
+ {
+ muteAll: false,
+ mutedInstanceIds: [],
+ updatedBy: 'elastic',
+ },
+ {
+ version: '123',
+ }
+ );
+ });
+
+ describe('authorization', () => {
+ beforeEach(() => {
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ actionTypeId: '1',
+ actionRef: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ consumer: 'myApp',
+ schedule: { interval: '10s' },
+ alertTypeId: 'myType',
+ apiKey: null,
+ apiKeyOwner: null,
+ enabled: false,
+ scheduledTaskId: null,
+ updatedBy: 'elastic',
+ muteAll: false,
+ },
+ references: [],
+ });
+ });
+
+ test('ensures user is authorised to unmuteAll this type of alert under the consumer', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ await alertsClient.unmuteAll({ id: '1' });
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'unmuteAll');
+ expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute');
+ });
+
+ test('throws when user is not authorised to unmuteAll this type of alert', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ authorization.ensureAuthorized.mockRejectedValue(
+ new Error(`Unauthorized to unmuteAll a "myType" alert for "myApp"`)
+ );
+
+ await expect(alertsClient.unmuteAll({ id: '1' })).rejects.toMatchInlineSnapshot(
+ `[Error: Unauthorized to unmuteAll a "myType" alert for "myApp"]`
+ );
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'unmuteAll');
+ });
+ });
+});
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/unmute_instance.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/unmute_instance.test.ts
new file mode 100644
index 000000000000..97711b8c1457
--- /dev/null
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/unmute_instance.test.ts
@@ -0,0 +1,179 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+import { AlertsClient, ConstructorOptions } from '../alerts_client';
+import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
+import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
+import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
+import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
+import { actionsAuthorizationMock } from '../../../../actions/server/mocks';
+import { AlertsAuthorization } from '../../authorization/alerts_authorization';
+import { ActionsAuthorization } from '../../../../actions/server';
+import { getBeforeSetup } from './lib';
+
+const taskManager = taskManagerMock.createStart();
+const alertTypeRegistry = alertTypeRegistryMock.create();
+const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
+
+const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
+const authorization = alertsAuthorizationMock.create();
+const actionsAuthorization = actionsAuthorizationMock.create();
+
+const kibanaVersion = 'v7.10.0';
+const alertsClientParams: jest.Mocked = {
+ taskManager,
+ alertTypeRegistry,
+ unsecuredSavedObjectsClient,
+ authorization: (authorization as unknown) as AlertsAuthorization,
+ actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization,
+ spaceId: 'default',
+ namespace: 'default',
+ getUserName: jest.fn(),
+ createAPIKey: jest.fn(),
+ invalidateAPIKey: jest.fn(),
+ logger: loggingSystemMock.create().get(),
+ encryptedSavedObjectsClient: encryptedSavedObjects,
+ getActionsClient: jest.fn(),
+ getEventLogClient: jest.fn(),
+ kibanaVersion,
+};
+
+beforeEach(() => {
+ getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry);
+});
+
+describe('unmuteInstance()', () => {
+ test('unmutes an alert instance', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [],
+ schedule: { interval: '10s' },
+ alertTypeId: '2',
+ enabled: true,
+ scheduledTaskId: 'task-123',
+ mutedInstanceIds: ['2'],
+ },
+ version: '123',
+ references: [],
+ });
+
+ await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' });
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
+ 'alert',
+ '1',
+ {
+ mutedInstanceIds: [],
+ updatedBy: 'elastic',
+ },
+ { version: '123' }
+ );
+ });
+
+ test('skips unmuting when alert instance not muted', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [],
+ schedule: { interval: '10s' },
+ alertTypeId: '2',
+ enabled: true,
+ scheduledTaskId: 'task-123',
+ mutedInstanceIds: [],
+ },
+ references: [],
+ });
+
+ await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' });
+ expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled();
+ });
+
+ test('skips unmuting when alert is muted', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [],
+ schedule: { interval: '10s' },
+ alertTypeId: '2',
+ enabled: true,
+ scheduledTaskId: 'task-123',
+ mutedInstanceIds: [],
+ muteAll: true,
+ },
+ references: [],
+ });
+
+ await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' });
+ expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled();
+ });
+
+ describe('authorization', () => {
+ beforeEach(() => {
+ unsecuredSavedObjectsClient.get.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ actionTypeId: '1',
+ actionRef: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ alertTypeId: 'myType',
+ consumer: 'myApp',
+ schedule: { interval: '10s' },
+ enabled: true,
+ scheduledTaskId: 'task-123',
+ mutedInstanceIds: ['2'],
+ },
+ version: '123',
+ references: [],
+ });
+ });
+
+ test('ensures user is authorised to unmuteInstance this type of alert under the consumer', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' });
+
+ expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute');
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith(
+ 'myType',
+ 'myApp',
+ 'unmuteInstance'
+ );
+ });
+
+ test('throws when user is not authorised to unmuteInstance this type of alert', async () => {
+ const alertsClient = new AlertsClient(alertsClientParams);
+ authorization.ensureAuthorized.mockRejectedValue(
+ new Error(`Unauthorized to unmuteInstance a "myType" alert for "myApp"`)
+ );
+
+ await expect(
+ alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' })
+ ).rejects.toMatchInlineSnapshot(
+ `[Error: Unauthorized to unmuteInstance a "myType" alert for "myApp"]`
+ );
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith(
+ 'myType',
+ 'myApp',
+ 'unmuteInstance'
+ );
+ });
+ });
+});
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/update.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/update.test.ts
new file mode 100644
index 000000000000..146f8ac400ad
--- /dev/null
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/update.test.ts
@@ -0,0 +1,1257 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+import uuid from 'uuid';
+import { schema } from '@kbn/config-schema';
+import { AlertsClient, ConstructorOptions } from '../alerts_client';
+import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
+import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
+import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
+import { IntervalSchedule } from '../../types';
+import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
+import { actionsAuthorizationMock } from '../../../../actions/server/mocks';
+import { AlertsAuthorization } from '../../authorization/alerts_authorization';
+import { resolvable } from '../../test_utils';
+import { ActionsAuthorization } from '../../../../actions/server';
+import { TaskStatus } from '../../../../task_manager/server';
+import { getBeforeSetup, setGlobalDate } from './lib';
+
+const taskManager = taskManagerMock.createStart();
+const alertTypeRegistry = alertTypeRegistryMock.create();
+const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
+
+const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
+const authorization = alertsAuthorizationMock.create();
+const actionsAuthorization = actionsAuthorizationMock.create();
+
+const kibanaVersion = 'v7.10.0';
+const alertsClientParams: jest.Mocked = {
+ taskManager,
+ alertTypeRegistry,
+ unsecuredSavedObjectsClient,
+ authorization: (authorization as unknown) as AlertsAuthorization,
+ actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization,
+ spaceId: 'default',
+ namespace: 'default',
+ getUserName: jest.fn(),
+ createAPIKey: jest.fn(),
+ invalidateAPIKey: jest.fn(),
+ logger: loggingSystemMock.create().get(),
+ encryptedSavedObjectsClient: encryptedSavedObjects,
+ getActionsClient: jest.fn(),
+ getEventLogClient: jest.fn(),
+ kibanaVersion,
+};
+
+beforeEach(() => {
+ getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry);
+});
+
+setGlobalDate();
+
+describe('update()', () => {
+ let alertsClient: AlertsClient;
+ const existingAlert = {
+ id: '1',
+ type: 'alert',
+ attributes: {
+ enabled: true,
+ tags: ['foo'],
+ alertTypeId: 'myType',
+ schedule: { interval: '10s' },
+ consumer: 'myApp',
+ scheduledTaskId: 'task-123',
+ params: {},
+ throttle: null,
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ actionTypeId: '1',
+ actionRef: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ references: [],
+ version: '123',
+ };
+ const existingDecryptedAlert = {
+ ...existingAlert,
+ attributes: {
+ ...existingAlert.attributes,
+ apiKey: Buffer.from('123:abc').toString('base64'),
+ },
+ };
+
+ beforeEach(() => {
+ alertsClient = new AlertsClient(alertsClientParams);
+ unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert);
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingDecryptedAlert);
+ alertTypeRegistry.get.mockReturnValue({
+ id: 'myType',
+ name: 'Test',
+ actionGroups: [{ id: 'default', name: 'Default' }],
+ defaultActionGroupId: 'default',
+ async executor() {},
+ producer: 'alerts',
+ });
+ });
+
+ test('updates given parameters', async () => {
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ enabled: true,
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ {
+ group: 'default',
+ actionRef: 'action_1',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ {
+ group: 'default',
+ actionRef: 'action_2',
+ actionTypeId: 'test2',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ scheduledTaskId: 'task-123',
+ createdAt: new Date().toISOString(),
+ },
+ updated_at: new Date().toISOString(),
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ {
+ name: 'action_1',
+ type: 'action',
+ id: '1',
+ },
+ {
+ name: 'action_2',
+ type: 'action',
+ id: '2',
+ },
+ ],
+ });
+ const result = await alertsClient.update({
+ id: '1',
+ data: {
+ schedule: { interval: '10s' },
+ name: 'abc',
+ tags: ['foo'],
+ params: {
+ bar: true,
+ },
+ throttle: null,
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ params: {
+ foo: true,
+ },
+ },
+ {
+ group: 'default',
+ id: '1',
+ params: {
+ foo: true,
+ },
+ },
+ {
+ group: 'default',
+ id: '2',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ });
+ expect(result).toMatchInlineSnapshot(`
+ Object {
+ "actions": Array [
+ Object {
+ "actionTypeId": "test",
+ "group": "default",
+ "id": "1",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ Object {
+ "actionTypeId": "test",
+ "group": "default",
+ "id": "1",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ Object {
+ "actionTypeId": "test2",
+ "group": "default",
+ "id": "2",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ ],
+ "createdAt": 2019-02-12T21:01:22.479Z,
+ "enabled": true,
+ "id": "1",
+ "params": Object {
+ "bar": true,
+ },
+ "schedule": Object {
+ "interval": "10s",
+ },
+ "scheduledTaskId": "task-123",
+ "updatedAt": 2019-02-12T21:01:22.479Z,
+ }
+ `);
+ expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', {
+ namespace: 'default',
+ });
+ expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled();
+ expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1);
+ expect(unsecuredSavedObjectsClient.create.mock.calls[0]).toHaveLength(3);
+ expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual('alert');
+ expect(unsecuredSavedObjectsClient.create.mock.calls[0][1]).toMatchInlineSnapshot(`
+ Object {
+ "actions": Array [
+ Object {
+ "actionRef": "action_0",
+ "actionTypeId": "test",
+ "group": "default",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ Object {
+ "actionRef": "action_1",
+ "actionTypeId": "test",
+ "group": "default",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ Object {
+ "actionRef": "action_2",
+ "actionTypeId": "test2",
+ "group": "default",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ ],
+ "alertTypeId": "myType",
+ "apiKey": null,
+ "apiKeyOwner": null,
+ "consumer": "myApp",
+ "enabled": true,
+ "meta": Object {
+ "versionApiKeyLastmodified": "v7.10.0",
+ },
+ "name": "abc",
+ "params": Object {
+ "bar": true,
+ },
+ "schedule": Object {
+ "interval": "10s",
+ },
+ "scheduledTaskId": "task-123",
+ "tags": Array [
+ "foo",
+ ],
+ "throttle": null,
+ "updatedBy": "elastic",
+ }
+ `);
+ expect(unsecuredSavedObjectsClient.create.mock.calls[0][2]).toMatchInlineSnapshot(`
+ Object {
+ "id": "1",
+ "overwrite": true,
+ "references": Array [
+ Object {
+ "id": "1",
+ "name": "action_0",
+ "type": "action",
+ },
+ Object {
+ "id": "1",
+ "name": "action_1",
+ "type": "action",
+ },
+ Object {
+ "id": "2",
+ "name": "action_2",
+ "type": "action",
+ },
+ ],
+ "version": "123",
+ }
+ `);
+ });
+
+ it('calls the createApiKey function', async () => {
+ unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
+ saved_objects: [
+ {
+ id: '1',
+ type: 'action',
+ attributes: {
+ actions: [],
+ actionTypeId: 'test',
+ },
+ references: [],
+ },
+ ],
+ });
+ alertsClientParams.createAPIKey.mockResolvedValueOnce({
+ apiKeysEnabled: true,
+ result: { id: '123', name: '123', api_key: 'abc' },
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ enabled: true,
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ createdAt: new Date().toISOString(),
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ apiKey: Buffer.from('123:abc').toString('base64'),
+ scheduledTaskId: 'task-123',
+ },
+ updated_at: new Date().toISOString(),
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+ const result = await alertsClient.update({
+ id: '1',
+ data: {
+ schedule: { interval: '10s' },
+ name: 'abc',
+ tags: ['foo'],
+ params: {
+ bar: true,
+ },
+ throttle: '5m',
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ });
+ expect(result).toMatchInlineSnapshot(`
+ Object {
+ "actions": Array [
+ Object {
+ "actionTypeId": "test",
+ "group": "default",
+ "id": "1",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ ],
+ "apiKey": "MTIzOmFiYw==",
+ "createdAt": 2019-02-12T21:01:22.479Z,
+ "enabled": true,
+ "id": "1",
+ "params": Object {
+ "bar": true,
+ },
+ "schedule": Object {
+ "interval": "10s",
+ },
+ "scheduledTaskId": "task-123",
+ "updatedAt": 2019-02-12T21:01:22.479Z,
+ }
+ `);
+ expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1);
+ expect(unsecuredSavedObjectsClient.create.mock.calls[0]).toHaveLength(3);
+ expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual('alert');
+ expect(unsecuredSavedObjectsClient.create.mock.calls[0][1]).toMatchInlineSnapshot(`
+ Object {
+ "actions": Array [
+ Object {
+ "actionRef": "action_0",
+ "actionTypeId": "test",
+ "group": "default",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ ],
+ "alertTypeId": "myType",
+ "apiKey": "MTIzOmFiYw==",
+ "apiKeyOwner": "elastic",
+ "consumer": "myApp",
+ "enabled": true,
+ "meta": Object {
+ "versionApiKeyLastmodified": "v7.10.0",
+ },
+ "name": "abc",
+ "params": Object {
+ "bar": true,
+ },
+ "schedule": Object {
+ "interval": "10s",
+ },
+ "scheduledTaskId": "task-123",
+ "tags": Array [
+ "foo",
+ ],
+ "throttle": "5m",
+ "updatedBy": "elastic",
+ }
+ `);
+ expect(unsecuredSavedObjectsClient.create.mock.calls[0][2]).toMatchInlineSnapshot(`
+ Object {
+ "id": "1",
+ "overwrite": true,
+ "references": Array [
+ Object {
+ "id": "1",
+ "name": "action_0",
+ "type": "action",
+ },
+ ],
+ "version": "123",
+ }
+ `);
+ });
+
+ it(`doesn't call the createAPIKey function when alert is disabled`, async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue({
+ ...existingDecryptedAlert,
+ attributes: {
+ ...existingDecryptedAlert.attributes,
+ enabled: false,
+ },
+ });
+ unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
+ saved_objects: [
+ {
+ id: '1',
+ type: 'action',
+ attributes: {
+ actions: [],
+ actionTypeId: 'test',
+ },
+ references: [],
+ },
+ ],
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ enabled: false,
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ createdAt: new Date().toISOString(),
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ scheduledTaskId: 'task-123',
+ apiKey: null,
+ },
+ updated_at: new Date().toISOString(),
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+ const result = await alertsClient.update({
+ id: '1',
+ data: {
+ schedule: { interval: '10s' },
+ name: 'abc',
+ tags: ['foo'],
+ params: {
+ bar: true,
+ },
+ throttle: '5m',
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ });
+ expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled();
+ expect(result).toMatchInlineSnapshot(`
+ Object {
+ "actions": Array [
+ Object {
+ "actionTypeId": "test",
+ "group": "default",
+ "id": "1",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ ],
+ "apiKey": null,
+ "createdAt": 2019-02-12T21:01:22.479Z,
+ "enabled": false,
+ "id": "1",
+ "params": Object {
+ "bar": true,
+ },
+ "schedule": Object {
+ "interval": "10s",
+ },
+ "scheduledTaskId": "task-123",
+ "updatedAt": 2019-02-12T21:01:22.479Z,
+ }
+ `);
+ expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1);
+ expect(unsecuredSavedObjectsClient.create.mock.calls[0]).toHaveLength(3);
+ expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual('alert');
+ expect(unsecuredSavedObjectsClient.create.mock.calls[0][1]).toMatchInlineSnapshot(`
+ Object {
+ "actions": Array [
+ Object {
+ "actionRef": "action_0",
+ "actionTypeId": "test",
+ "group": "default",
+ "params": Object {
+ "foo": true,
+ },
+ },
+ ],
+ "alertTypeId": "myType",
+ "apiKey": null,
+ "apiKeyOwner": null,
+ "consumer": "myApp",
+ "enabled": false,
+ "meta": Object {
+ "versionApiKeyLastmodified": "v7.10.0",
+ },
+ "name": "abc",
+ "params": Object {
+ "bar": true,
+ },
+ "schedule": Object {
+ "interval": "10s",
+ },
+ "scheduledTaskId": "task-123",
+ "tags": Array [
+ "foo",
+ ],
+ "throttle": "5m",
+ "updatedBy": "elastic",
+ }
+ `);
+ expect(unsecuredSavedObjectsClient.create.mock.calls[0][2]).toMatchInlineSnapshot(`
+ Object {
+ "id": "1",
+ "overwrite": true,
+ "references": Array [
+ Object {
+ "id": "1",
+ "name": "action_0",
+ "type": "action",
+ },
+ ],
+ "version": "123",
+ }
+ `);
+ });
+
+ it('should validate params', async () => {
+ alertTypeRegistry.get.mockReturnValueOnce({
+ id: '123',
+ name: 'Test',
+ actionGroups: [{ id: 'default', name: 'Default' }],
+ defaultActionGroupId: 'default',
+ validate: {
+ params: schema.object({
+ param1: schema.string(),
+ }),
+ },
+ async executor() {},
+ producer: 'alerts',
+ });
+ await expect(
+ alertsClient.update({
+ id: '1',
+ data: {
+ schedule: { interval: '10s' },
+ name: 'abc',
+ tags: ['foo'],
+ params: {
+ bar: true,
+ },
+ throttle: null,
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ })
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"params invalid: [param1]: expected value of type [string] but got [undefined]"`
+ );
+ });
+
+ it('should trim alert name in the API key name', async () => {
+ unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
+ saved_objects: [
+ {
+ id: '1',
+ type: 'action',
+ attributes: {
+ actions: [],
+ actionTypeId: 'test',
+ },
+ references: [],
+ },
+ ],
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ enabled: false,
+ name: ' my alert name ',
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ createdAt: new Date().toISOString(),
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ scheduledTaskId: 'task-123',
+ apiKey: null,
+ },
+ updated_at: new Date().toISOString(),
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+ await alertsClient.update({
+ id: '1',
+ data: {
+ ...existingAlert.attributes,
+ name: ' my alert name ',
+ },
+ });
+
+ expect(alertsClientParams.createAPIKey).toHaveBeenCalledWith('Alerting: myType/my alert name');
+ });
+
+ it('swallows error when invalidate API key throws', async () => {
+ alertsClientParams.invalidateAPIKey.mockRejectedValueOnce(new Error('Fail'));
+ unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
+ saved_objects: [
+ {
+ id: '1',
+ type: 'action',
+ attributes: {
+ actions: [],
+ actionTypeId: 'test',
+ },
+ references: [],
+ },
+ ],
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ enabled: true,
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ scheduledTaskId: 'task-123',
+ },
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ ],
+ });
+ await alertsClient.update({
+ id: '1',
+ data: {
+ schedule: { interval: '10s' },
+ name: 'abc',
+ tags: ['foo'],
+ params: {
+ bar: true,
+ },
+ throttle: null,
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ });
+ expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
+ 'Failed to invalidate API Key: Fail'
+ );
+ });
+
+ it('swallows error when getDecryptedAsInternalUser throws', async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail'));
+ unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
+ saved_objects: [
+ {
+ id: '1',
+ type: 'action',
+ attributes: {
+ actions: [],
+ actionTypeId: 'test',
+ },
+ references: [],
+ },
+ {
+ id: '2',
+ type: 'action',
+ attributes: {
+ actions: [],
+ actionTypeId: 'test2',
+ },
+ references: [],
+ },
+ ],
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ enabled: true,
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ {
+ group: 'default',
+ actionRef: 'action_1',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ {
+ group: 'default',
+ actionRef: 'action_2',
+ actionTypeId: 'test2',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ scheduledTaskId: 'task-123',
+ createdAt: new Date().toISOString(),
+ },
+ updated_at: new Date().toISOString(),
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: '1',
+ },
+ {
+ name: 'action_1',
+ type: 'action',
+ id: '1',
+ },
+ {
+ name: 'action_2',
+ type: 'action',
+ id: '2',
+ },
+ ],
+ });
+ await alertsClient.update({
+ id: '1',
+ data: {
+ schedule: { interval: '10s' },
+ name: 'abc',
+ tags: ['foo'],
+ params: {
+ bar: true,
+ },
+ throttle: '5m',
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ params: {
+ foo: true,
+ },
+ },
+ {
+ group: 'default',
+ id: '1',
+ params: {
+ foo: true,
+ },
+ },
+ {
+ group: 'default',
+ id: '2',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ });
+ expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1');
+ expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
+ 'update(): Failed to load API key to invalidate on alert 1: Fail'
+ );
+ });
+
+ test('throws when unsecuredSavedObjectsClient update fails and invalidates newly created API key', async () => {
+ alertsClientParams.createAPIKey.mockResolvedValueOnce({
+ apiKeysEnabled: true,
+ result: { id: '234', name: '234', api_key: 'abc' },
+ });
+ unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
+ saved_objects: [
+ {
+ id: '1',
+ type: 'action',
+ attributes: {
+ actions: [],
+ actionTypeId: 'test',
+ },
+ references: [],
+ },
+ ],
+ });
+ unsecuredSavedObjectsClient.create.mockRejectedValue(new Error('Fail'));
+ await expect(
+ alertsClient.update({
+ id: '1',
+ data: {
+ schedule: { interval: '10s' },
+ name: 'abc',
+ tags: ['foo'],
+ params: {
+ bar: true,
+ },
+ throttle: null,
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ })
+ ).rejects.toThrowErrorMatchingInlineSnapshot(`"Fail"`);
+ expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalledWith({ id: '123' });
+ expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '234' });
+ });
+
+ describe('updating an alert schedule', () => {
+ function mockApiCalls(
+ alertId: string,
+ taskId: string,
+ currentSchedule: IntervalSchedule,
+ updatedSchedule: IntervalSchedule
+ ) {
+ // mock return values from deps
+ alertTypeRegistry.get.mockReturnValueOnce({
+ id: '123',
+ name: 'Test',
+ actionGroups: [{ id: 'default', name: 'Default' }],
+ defaultActionGroupId: 'default',
+ async executor() {},
+ producer: 'alerts',
+ });
+ unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({
+ saved_objects: [
+ {
+ id: '1',
+ type: 'action',
+ attributes: {
+ actions: [],
+ actionTypeId: 'test',
+ },
+ references: [],
+ },
+ ],
+ });
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValueOnce({
+ id: alertId,
+ type: 'alert',
+ attributes: {
+ actions: [],
+ enabled: true,
+ alertTypeId: '123',
+ schedule: currentSchedule,
+ scheduledTaskId: 'task-123',
+ },
+ references: [],
+ version: '123',
+ });
+
+ taskManager.schedule.mockResolvedValueOnce({
+ id: taskId,
+ taskType: 'alerting:123',
+ scheduledAt: new Date(),
+ attempts: 1,
+ status: TaskStatus.Idle,
+ runAt: new Date(),
+ startedAt: null,
+ retryAt: null,
+ state: {},
+ params: {},
+ ownerId: null,
+ });
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: alertId,
+ type: 'alert',
+ attributes: {
+ enabled: true,
+ schedule: updatedSchedule,
+ actions: [
+ {
+ group: 'default',
+ actionRef: 'action_0',
+ actionTypeId: 'test',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ scheduledTaskId: taskId,
+ },
+ references: [
+ {
+ name: 'action_0',
+ type: 'action',
+ id: alertId,
+ },
+ ],
+ });
+
+ taskManager.runNow.mockReturnValueOnce(Promise.resolve({ id: alertId }));
+ }
+
+ test('updating the alert schedule should rerun the task immediately', async () => {
+ const alertId = uuid.v4();
+ const taskId = uuid.v4();
+
+ mockApiCalls(alertId, taskId, { interval: '60m' }, { interval: '10s' });
+
+ await alertsClient.update({
+ id: alertId,
+ data: {
+ schedule: { interval: '10s' },
+ name: 'abc',
+ tags: ['foo'],
+ params: {
+ bar: true,
+ },
+ throttle: null,
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ });
+
+ expect(taskManager.runNow).toHaveBeenCalledWith(taskId);
+ });
+
+ test('updating the alert without changing the schedule should not rerun the task', async () => {
+ const alertId = uuid.v4();
+ const taskId = uuid.v4();
+
+ mockApiCalls(alertId, taskId, { interval: '10s' }, { interval: '10s' });
+
+ await alertsClient.update({
+ id: alertId,
+ data: {
+ schedule: { interval: '10s' },
+ name: 'abc',
+ tags: ['foo'],
+ params: {
+ bar: true,
+ },
+ throttle: null,
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ });
+
+ expect(taskManager.runNow).not.toHaveBeenCalled();
+ });
+
+ test('updating the alert should not wait for the rerun the task to complete', async () => {
+ const alertId = uuid.v4();
+ const taskId = uuid.v4();
+
+ mockApiCalls(alertId, taskId, { interval: '10s' }, { interval: '30s' });
+
+ const resolveAfterAlertUpdatedCompletes = resolvable<{ id: string }>();
+
+ taskManager.runNow.mockReset();
+ taskManager.runNow.mockReturnValue(resolveAfterAlertUpdatedCompletes);
+
+ await alertsClient.update({
+ id: alertId,
+ data: {
+ schedule: { interval: '10s' },
+ name: 'abc',
+ tags: ['foo'],
+ params: {
+ bar: true,
+ },
+ throttle: null,
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ });
+
+ expect(taskManager.runNow).toHaveBeenCalled();
+ resolveAfterAlertUpdatedCompletes.resolve({ id: alertId });
+ });
+
+ test('logs when the rerun of an alerts underlying task fails', async () => {
+ const alertId = uuid.v4();
+ const taskId = uuid.v4();
+
+ mockApiCalls(alertId, taskId, { interval: '10s' }, { interval: '30s' });
+
+ taskManager.runNow.mockReset();
+ taskManager.runNow.mockRejectedValue(new Error('Failed to run alert'));
+
+ await alertsClient.update({
+ id: alertId,
+ data: {
+ schedule: { interval: '10s' },
+ name: 'abc',
+ tags: ['foo'],
+ params: {
+ bar: true,
+ },
+ throttle: null,
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ });
+
+ expect(taskManager.runNow).toHaveBeenCalled();
+
+ expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
+ `Alert update failed to run its underlying task. TaskManager runNow failed with Error: Failed to run alert`
+ );
+ });
+ });
+
+ describe('authorization', () => {
+ beforeEach(() => {
+ unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
+ id: '1',
+ type: 'alert',
+ attributes: {
+ alertTypeId: 'myType',
+ consumer: 'myApp',
+ enabled: true,
+ schedule: { interval: '10s' },
+ params: {
+ bar: true,
+ },
+ actions: [],
+ scheduledTaskId: 'task-123',
+ createdAt: new Date().toISOString(),
+ },
+ updated_at: new Date().toISOString(),
+ references: [],
+ });
+ });
+
+ test('ensures user is authorised to update this type of alert under the consumer', async () => {
+ await alertsClient.update({
+ id: '1',
+ data: {
+ schedule: { interval: '10s' },
+ name: 'abc',
+ tags: ['foo'],
+ params: {
+ bar: true,
+ },
+ throttle: null,
+ actions: [],
+ },
+ });
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'update');
+ });
+
+ test('throws when user is not authorised to update this type of alert', async () => {
+ authorization.ensureAuthorized.mockRejectedValue(
+ new Error(`Unauthorized to update a "myType" alert for "myApp"`)
+ );
+
+ await expect(
+ alertsClient.update({
+ id: '1',
+ data: {
+ schedule: { interval: '10s' },
+ name: 'abc',
+ tags: ['foo'],
+ params: {
+ bar: true,
+ },
+ throttle: null,
+ actions: [],
+ },
+ })
+ ).rejects.toMatchInlineSnapshot(
+ `[Error: Unauthorized to update a "myType" alert for "myApp"]`
+ );
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'update');
+ });
+ });
+});
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/update_api_key.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/update_api_key.test.ts
new file mode 100644
index 000000000000..1f3b567b2c03
--- /dev/null
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/update_api_key.test.ts
@@ -0,0 +1,229 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+import { AlertsClient, ConstructorOptions } from '../alerts_client';
+import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
+import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
+import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
+import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
+import { actionsAuthorizationMock } from '../../../../actions/server/mocks';
+import { AlertsAuthorization } from '../../authorization/alerts_authorization';
+import { ActionsAuthorization } from '../../../../actions/server';
+import { getBeforeSetup } from './lib';
+
+const taskManager = taskManagerMock.createStart();
+const alertTypeRegistry = alertTypeRegistryMock.create();
+const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
+const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
+const authorization = alertsAuthorizationMock.create();
+const actionsAuthorization = actionsAuthorizationMock.create();
+
+const kibanaVersion = 'v7.10.0';
+const alertsClientParams: jest.Mocked = {
+ taskManager,
+ alertTypeRegistry,
+ unsecuredSavedObjectsClient,
+ authorization: (authorization as unknown) as AlertsAuthorization,
+ actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization,
+ spaceId: 'default',
+ namespace: 'default',
+ getUserName: jest.fn(),
+ createAPIKey: jest.fn(),
+ invalidateAPIKey: jest.fn(),
+ logger: loggingSystemMock.create().get(),
+ encryptedSavedObjectsClient: encryptedSavedObjects,
+ getActionsClient: jest.fn(),
+ getEventLogClient: jest.fn(),
+ kibanaVersion,
+};
+
+beforeEach(() => {
+ getBeforeSetup(alertsClientParams, taskManager, alertTypeRegistry);
+});
+
+describe('updateApiKey()', () => {
+ let alertsClient: AlertsClient;
+ const existingAlert = {
+ id: '1',
+ type: 'alert',
+ attributes: {
+ schedule: { interval: '10s' },
+ alertTypeId: 'myType',
+ consumer: 'myApp',
+ enabled: true,
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ actionTypeId: '1',
+ actionRef: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ },
+ version: '123',
+ references: [],
+ };
+ const existingEncryptedAlert = {
+ ...existingAlert,
+ attributes: {
+ ...existingAlert.attributes,
+ apiKey: Buffer.from('123:abc').toString('base64'),
+ },
+ };
+
+ beforeEach(() => {
+ alertsClient = new AlertsClient(alertsClientParams);
+ unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert);
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingEncryptedAlert);
+ alertsClientParams.createAPIKey.mockResolvedValueOnce({
+ apiKeysEnabled: true,
+ result: { id: '234', name: '123', api_key: 'abc' },
+ });
+ });
+
+ test('updates the API key for the alert', async () => {
+ await alertsClient.updateApiKey({ id: '1' });
+ expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled();
+ expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', {
+ namespace: 'default',
+ });
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
+ 'alert',
+ '1',
+ {
+ schedule: { interval: '10s' },
+ alertTypeId: 'myType',
+ consumer: 'myApp',
+ enabled: true,
+ apiKey: Buffer.from('234:abc').toString('base64'),
+ apiKeyOwner: 'elastic',
+ updatedBy: 'elastic',
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ actionTypeId: '1',
+ actionRef: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ meta: {
+ versionApiKeyLastmodified: kibanaVersion,
+ },
+ },
+ { version: '123' }
+ );
+ expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' });
+ });
+
+ test('falls back to SOC when getDecryptedAsInternalUser throws an error', async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail'));
+
+ await alertsClient.updateApiKey({ id: '1' });
+ expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1');
+ expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', {
+ namespace: 'default',
+ });
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith(
+ 'alert',
+ '1',
+ {
+ schedule: { interval: '10s' },
+ alertTypeId: 'myType',
+ consumer: 'myApp',
+ enabled: true,
+ apiKey: Buffer.from('234:abc').toString('base64'),
+ apiKeyOwner: 'elastic',
+ updatedBy: 'elastic',
+ actions: [
+ {
+ group: 'default',
+ id: '1',
+ actionTypeId: '1',
+ actionRef: '1',
+ params: {
+ foo: true,
+ },
+ },
+ ],
+ meta: {
+ versionApiKeyLastmodified: kibanaVersion,
+ },
+ },
+ { version: '123' }
+ );
+ expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
+ });
+
+ test('swallows error when invalidate API key throws', async () => {
+ alertsClientParams.invalidateAPIKey.mockRejectedValue(new Error('Fail'));
+
+ await alertsClient.updateApiKey({ id: '1' });
+ expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
+ 'Failed to invalidate API Key: Fail'
+ );
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled();
+ });
+
+ test('swallows error when getting decrypted object throws', async () => {
+ encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail'));
+
+ await alertsClient.updateApiKey({ id: '1' });
+ expect(alertsClientParams.logger.error).toHaveBeenCalledWith(
+ 'updateApiKey(): Failed to load API key to invalidate on alert 1: Fail'
+ );
+ expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled();
+ expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled();
+ });
+
+ test('throws when unsecuredSavedObjectsClient update fails and invalidates newly created API key', async () => {
+ alertsClientParams.createAPIKey.mockResolvedValueOnce({
+ apiKeysEnabled: true,
+ result: { id: '234', name: '234', api_key: 'abc' },
+ });
+ unsecuredSavedObjectsClient.update.mockRejectedValueOnce(new Error('Fail'));
+
+ await expect(alertsClient.updateApiKey({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"Fail"`
+ );
+ expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalledWith({ id: '123' });
+ expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '234' });
+ });
+
+ describe('authorization', () => {
+ test('ensures user is authorised to updateApiKey this type of alert under the consumer', async () => {
+ await alertsClient.updateApiKey({ id: '1' });
+
+ expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute');
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith(
+ 'myType',
+ 'myApp',
+ 'updateApiKey'
+ );
+ });
+
+ test('throws when user is not authorised to updateApiKey this type of alert', async () => {
+ authorization.ensureAuthorized.mockRejectedValue(
+ new Error(`Unauthorized to updateApiKey a "myType" alert for "myApp"`)
+ );
+
+ await expect(alertsClient.updateApiKey({ id: '1' })).rejects.toMatchInlineSnapshot(
+ `[Error: Unauthorized to updateApiKey a "myType" alert for "myApp"]`
+ );
+
+ expect(authorization.ensureAuthorized).toHaveBeenCalledWith(
+ 'myType',
+ 'myApp',
+ 'updateApiKey'
+ );
+ });
+ });
+});
diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/ExceptionStacktrace.stories.tsx b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/ExceptionStacktrace.stories.tsx
index 5ad6fd547169..ff95d6fd1254 100644
--- a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/ExceptionStacktrace.stories.tsx
+++ b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/ExceptionStacktrace.stories.tsx
@@ -4,804 +4,2538 @@
* you may not use this file except in compliance with the Elastic License.
*/
-import { storiesOf } from '@storybook/react';
-import React from 'react';
+import React, { ComponentType } from 'react';
import { EuiThemeProvider } from '../../../../../../observability/public';
import { Exception } from '../../../../../typings/es_schemas/raw/error_raw';
import { ExceptionStacktrace } from './ExceptionStacktrace';
-storiesOf('app/ErrorGroupDetails/DetailView/ExceptionStacktrace', module)
- .addDecorator((storyFn) => {
- return {storyFn()};
- })
- .add('JavaScript with some context', () => {
- const exceptions: Exception[] = [
- {
- code: '503',
- stacktrace: [
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'node_modules/elastic-apm-http-client/index.js',
- abs_path: '/app/node_modules/elastic-apm-http-client/index.js',
- line: {
- number: 711,
- context:
- " const err = new Error('Unexpected APM Server response when polling config')",
- },
- function: 'processConfigErrorResponse',
- context: {
- pre: ['', 'function processConfigErrorResponse (res, buf) {'],
- post: ['', ' err.code = res.statusCode'],
- },
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'node_modules/elastic-apm-http-client/index.js',
- abs_path: '/app/node_modules/elastic-apm-http-client/index.js',
- line: {
- number: 196,
- context:
- ' res.destroy(processConfigErrorResponse(res, buf))',
- },
- function: '',
- context: {
- pre: [' }', ' } else {'],
- post: [' }', ' })'],
- },
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'node_modules/fast-stream-to-buffer/index.js',
- abs_path: '/app/node_modules/fast-stream-to-buffer/index.js',
- line: {
- number: 20,
- context: ' cb(err, buffers[0], stream)',
- },
- function: 'IncomingMessage.',
- context: {
- pre: [' break', ' case 1:'],
- post: [' break', ' default:'],
- },
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'node_modules/once/once.js',
- abs_path: '/app/node_modules/once/once.js',
- line: {
- number: 25,
- context: ' return f.value = fn.apply(this, arguments)',
- },
- function: 'f',
- context: {
- pre: [' if (f.called) return f.value', ' f.called = true'],
- post: [' }', ' f.called = false'],
- },
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'node_modules/end-of-stream/index.js',
- abs_path: '/app/node_modules/end-of-stream/index.js',
- line: {
- number: 36,
- context: '\t\tif (!writable) callback.call(stream);',
- },
- function: 'onend',
- context: {
- pre: ['\tvar onend = function() {', '\t\treadable = false;'],
- post: ['\t};', ''],
- },
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- abs_path: 'events.js',
- filename: 'events.js',
- line: {
- number: 327,
- },
- function: 'emit',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: '_stream_readable.js',
- abs_path: '_stream_readable.js',
- line: {
- number: 1220,
- },
- function: 'endReadableNT',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'internal/process/task_queues.js',
- abs_path: 'internal/process/task_queues.js',
- line: {
- number: 84,
- },
- function: 'processTicksAndRejections',
- },
- ],
- module: 'elastic-apm-http-client',
- handled: false,
- attributes: {
- response:
- '\r\n503 Service Temporarily Unavailable\r\n\r\n503 Service Temporarily Unavailable\r\n nginx/1.17.7\r\n\r\n\r\n',
- },
- type: 'Error',
- message: 'Unexpected APM Server response when polling config',
- },
- ];
+export default {
+ title: 'app/ErrorGroupDetails/DetailView/ExceptionStacktrace',
+ component: ExceptionStacktrace,
+ decorators: [
+ (Story: ComponentType) => {
+ return (
+
+
+
+ );
+ },
+ ],
+};
+export function JavaWithLongLines() {
+ const exceptions: Exception[] = [
+ {
+ stacktrace: [
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'AbstractJackson2HttpMessageConverter.java',
+ classname:
+ 'org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter',
+ line: {
+ number: 296,
+ },
+ module: 'org.springframework.http.converter.json',
+ function: 'writeInternal',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'AbstractGenericHttpMessageConverter.java',
+ classname:
+ 'org.springframework.http.converter.AbstractGenericHttpMessageConverter',
+ line: {
+ number: 102,
+ },
+ module: 'org.springframework.http.converter',
+ function: 'write',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'AbstractMessageConverterMethodProcessor.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor',
+ line: {
+ number: 272,
+ },
+ module: 'org.springframework.web.servlet.mvc.method.annotation',
+ function: 'writeWithMessageConverters',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'RequestResponseBodyMethodProcessor.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor',
+ line: {
+ number: 180,
+ },
+ module: 'org.springframework.web.servlet.mvc.method.annotation',
+ function: 'handleReturnValue',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'HandlerMethodReturnValueHandlerComposite.java',
+ classname:
+ 'org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite',
+ line: {
+ number: 82,
+ },
+ module: 'org.springframework.web.method.support',
+ function: 'handleReturnValue',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ServletInvocableHandlerMethod.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod',
+ line: {
+ number: 119,
+ },
+ module: 'org.springframework.web.servlet.mvc.method.annotation',
+ function: 'invokeAndHandle',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'RequestMappingHandlerAdapter.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter',
+ line: {
+ number: 877,
+ },
+ module: 'org.springframework.web.servlet.mvc.method.annotation',
+ function: 'invokeHandlerMethod',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'RequestMappingHandlerAdapter.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter',
+ line: {
+ number: 783,
+ },
+ module: 'org.springframework.web.servlet.mvc.method.annotation',
+ function: 'handleInternal',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'AbstractHandlerMethodAdapter.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter',
+ line: {
+ number: 87,
+ },
+ function: 'handle',
+ module: 'org.springframework.web.servlet.mvc.method',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'DispatcherServlet.java',
+ classname: 'org.springframework.web.servlet.DispatcherServlet',
+ line: {
+ number: 991,
+ },
+ module: 'org.springframework.web.servlet',
+ function: 'doDispatch',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'DispatcherServlet.java',
+ classname: 'org.springframework.web.servlet.DispatcherServlet',
+ line: {
+ number: 925,
+ },
+ module: 'org.springframework.web.servlet',
+ function: 'doService',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'FrameworkServlet.java',
+ classname: 'org.springframework.web.servlet.FrameworkServlet',
+ line: {
+ number: 974,
+ },
+ module: 'org.springframework.web.servlet',
+ function: 'processRequest',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'FrameworkServlet.java',
+ classname: 'org.springframework.web.servlet.FrameworkServlet',
+ line: {
+ number: 866,
+ },
+ module: 'org.springframework.web.servlet',
+ function: 'doGet',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'HttpServlet.java',
+ classname: 'javax.servlet.http.HttpServlet',
+ line: {
+ number: 635,
+ },
+ function: 'service',
+ module: 'javax.servlet.http',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'FrameworkServlet.java',
+ classname: 'org.springframework.web.servlet.FrameworkServlet',
+ line: {
+ number: 851,
+ },
+ module: 'org.springframework.web.servlet',
+ function: 'service',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'HttpServlet.java',
+ classname: 'javax.servlet.http.HttpServlet',
+ line: {
+ number: 742,
+ },
+ module: 'javax.servlet.http',
+ function: 'service',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 231,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'WsFilter.java',
+ classname: 'org.apache.tomcat.websocket.server.WsFilter',
+ line: {
+ number: 52,
+ },
+ module: 'org.apache.tomcat.websocket.server',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 193,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'RequestContextFilter.java',
+ classname: 'org.springframework.web.filter.RequestContextFilter',
+ line: {
+ number: 99,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilterInternal',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'OncePerRequestFilter.java',
+ classname: 'org.springframework.web.filter.OncePerRequestFilter',
+ line: {
+ number: 107,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilter',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 193,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'HttpPutFormContentFilter.java',
+ classname: 'org.springframework.web.filter.HttpPutFormContentFilter',
+ line: {
+ number: 109,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilterInternal',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'OncePerRequestFilter.java',
+ classname: 'org.springframework.web.filter.OncePerRequestFilter',
+ line: {
+ number: 107,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 193,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'HiddenHttpMethodFilter.java',
+ classname: 'org.springframework.web.filter.HiddenHttpMethodFilter',
+ line: {
+ number: 81,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilterInternal',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'OncePerRequestFilter.java',
+ classname: 'org.springframework.web.filter.OncePerRequestFilter',
+ line: {
+ number: 107,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 193,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'CharacterEncodingFilter.java',
+ classname: 'org.springframework.web.filter.CharacterEncodingFilter',
+ line: {
+ number: 200,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilterInternal',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'OncePerRequestFilter.java',
+ classname: 'org.springframework.web.filter.OncePerRequestFilter',
+ line: {
+ number: 107,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 193,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'StandardWrapperValve.java',
+ classname: 'org.apache.catalina.core.StandardWrapperValve',
+ line: {
+ number: 198,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'invoke',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'StandardContextValve.java',
+ classname: 'org.apache.catalina.core.StandardContextValve',
+ line: {
+ number: 96,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'invoke',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'AuthenticatorBase.java',
+ classname: 'org.apache.catalina.authenticator.AuthenticatorBase',
+ line: {
+ number: 496,
+ },
+ module: 'org.apache.catalina.authenticator',
+ function: 'invoke',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'StandardHostValve.java',
+ classname: 'org.apache.catalina.core.StandardHostValve',
+ line: {
+ number: 140,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'invoke',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ErrorReportValve.java',
+ classname: 'org.apache.catalina.valves.ErrorReportValve',
+ line: {
+ number: 81,
+ },
+ module: 'org.apache.catalina.valves',
+ function: 'invoke',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'StandardEngineValve.java',
+ classname: 'org.apache.catalina.core.StandardEngineValve',
+ line: {
+ number: 87,
+ },
+ function: 'invoke',
+ module: 'org.apache.catalina.core',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'CoyoteAdapter.java',
+ classname: 'org.apache.catalina.connector.CoyoteAdapter',
+ line: {
+ number: 342,
+ },
+ module: 'org.apache.catalina.connector',
+ function: 'service',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'Http11Processor.java',
+ classname: 'org.apache.coyote.http11.Http11Processor',
+ line: {
+ number: 803,
+ },
+ module: 'org.apache.coyote.http11',
+ function: 'service',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'AbstractProcessorLight.java',
+ classname: 'org.apache.coyote.AbstractProcessorLight',
+ line: {
+ number: 66,
+ },
+ module: 'org.apache.coyote',
+ function: 'process',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'AbstractProtocol.java',
+ classname: 'org.apache.coyote.AbstractProtocol$ConnectionHandler',
+ line: {
+ number: 790,
+ },
+ module: 'org.apache.coyote',
+ function: 'process',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'NioEndpoint.java',
+ classname: 'org.apache.tomcat.util.net.NioEndpoint$SocketProcessor',
+ line: {
+ number: 1468,
+ },
+ function: 'doRun',
+ module: 'org.apache.tomcat.util.net',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'SocketProcessorBase.java',
+ classname: 'org.apache.tomcat.util.net.SocketProcessorBase',
+ line: {
+ number: 49,
+ },
+ module: 'org.apache.tomcat.util.net',
+ function: 'run',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'TaskThread.java',
+ classname:
+ 'org.apache.tomcat.util.threads.TaskThread$WrappingRunnable',
+ line: {
+ number: 61,
+ },
+ function: 'run',
+ module: 'org.apache.tomcat.util.threads',
+ },
+ ],
+ type:
+ 'org.springframework.http.converter.HttpMessageNotWritableException',
+ message:
+ 'Could not write JSON: Null return value from advice does not match primitive return type for: public abstract double co.elastic.apm.opbeans.repositories.Numbers.getRevenue(); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Null return value from advice does not match primitive return type for: public abstract double co.elastic.apm.opbeans.repositories.Numbers.getRevenue() (through reference chain: co.elastic.apm.opbeans.repositories.Stats["numbers"]->com.sun.proxy.$Proxy128["revenue"])',
+ },
+ {
+ stacktrace: [
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'JsonMappingException.java',
+ classname: 'com.fasterxml.jackson.databind.JsonMappingException',
+ line: {
+ number: 391,
+ },
+ module: 'com.fasterxml.jackson.databind',
+ function: 'wrapWithPath',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'JsonMappingException.java',
+ classname: 'com.fasterxml.jackson.databind.JsonMappingException',
+ line: {
+ number: 351,
+ },
+ module: 'com.fasterxml.jackson.databind',
+ function: 'wrapWithPath',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'StdSerializer.java',
+ classname: 'com.fasterxml.jackson.databind.ser.std.StdSerializer',
+ line: {
+ number: 316,
+ },
+ function: 'wrapAndThrow',
+ module: 'com.fasterxml.jackson.databind.ser.std',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'BeanSerializerBase.java',
+ classname:
+ 'com.fasterxml.jackson.databind.ser.std.BeanSerializerBase',
+ line: {
+ number: 727,
+ },
+ module: 'com.fasterxml.jackson.databind.ser.std',
+ function: 'serializeFields',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'BeanSerializer.java',
+ classname: 'com.fasterxml.jackson.databind.ser.BeanSerializer',
+ line: {
+ number: 155,
+ },
+ module: 'com.fasterxml.jackson.databind.ser',
+ function: 'serialize',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'BeanPropertyWriter.java',
+ classname: 'com.fasterxml.jackson.databind.ser.BeanPropertyWriter',
+ line: {
+ number: 727,
+ },
+ module: 'com.fasterxml.jackson.databind.ser',
+ function: 'serializeAsField',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'BeanSerializerBase.java',
+ classname:
+ 'com.fasterxml.jackson.databind.ser.std.BeanSerializerBase',
+ line: {
+ number: 719,
+ },
+ module: 'com.fasterxml.jackson.databind.ser.std',
+ function: 'serializeFields',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'BeanSerializer.java',
+ classname: 'com.fasterxml.jackson.databind.ser.BeanSerializer',
+ line: {
+ number: 155,
+ },
+ module: 'com.fasterxml.jackson.databind.ser',
+ function: 'serialize',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'DefaultSerializerProvider.java',
+ classname:
+ 'com.fasterxml.jackson.databind.ser.DefaultSerializerProvider',
+ line: {
+ number: 480,
+ },
+ module: 'com.fasterxml.jackson.databind.ser',
+ function: '_serialize',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'DefaultSerializerProvider.java',
+ classname:
+ 'com.fasterxml.jackson.databind.ser.DefaultSerializerProvider',
+ line: {
+ number: 319,
+ },
+ module: 'com.fasterxml.jackson.databind.ser',
+ function: 'serializeValue',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ObjectWriter.java',
+ classname: 'com.fasterxml.jackson.databind.ObjectWriter$Prefetch',
+ line: {
+ number: 1396,
+ },
+ module: 'com.fasterxml.jackson.databind',
+ function: 'serialize',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ObjectWriter.java',
+ classname: 'com.fasterxml.jackson.databind.ObjectWriter',
+ line: {
+ number: 913,
+ },
+ module: 'com.fasterxml.jackson.databind',
+ function: 'writeValue',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'AbstractJackson2HttpMessageConverter.java',
+ classname:
+ 'org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter',
+ line: {
+ number: 286,
+ },
+ module: 'org.springframework.http.converter.json',
+ function: 'writeInternal',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'AbstractGenericHttpMessageConverter.java',
+ classname:
+ 'org.springframework.http.converter.AbstractGenericHttpMessageConverter',
+ line: {
+ number: 102,
+ },
+ module: 'org.springframework.http.converter',
+ function: 'write',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'AbstractMessageConverterMethodProcessor.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor',
+ line: {
+ number: 272,
+ },
+ module: 'org.springframework.web.servlet.mvc.method.annotation',
+ function: 'writeWithMessageConverters',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'RequestResponseBodyMethodProcessor.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor',
+ line: {
+ number: 180,
+ },
+ module: 'org.springframework.web.servlet.mvc.method.annotation',
+ function: 'handleReturnValue',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'HandlerMethodReturnValueHandlerComposite.java',
+ classname:
+ 'org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite',
+ line: {
+ number: 82,
+ },
+ module: 'org.springframework.web.method.support',
+ function: 'handleReturnValue',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ServletInvocableHandlerMethod.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod',
+ line: {
+ number: 119,
+ },
+ module: 'org.springframework.web.servlet.mvc.method.annotation',
+ function: 'invokeAndHandle',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'RequestMappingHandlerAdapter.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter',
+ line: {
+ number: 877,
+ },
+ module: 'org.springframework.web.servlet.mvc.method.annotation',
+ function: 'invokeHandlerMethod',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'RequestMappingHandlerAdapter.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter',
+ line: {
+ number: 783,
+ },
+ function: 'handleInternal',
+ module: 'org.springframework.web.servlet.mvc.method.annotation',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'AbstractHandlerMethodAdapter.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter',
+ line: {
+ number: 87,
+ },
+ module: 'org.springframework.web.servlet.mvc.method',
+ function: 'handle',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'DispatcherServlet.java',
+ classname: 'org.springframework.web.servlet.DispatcherServlet',
+ line: {
+ number: 991,
+ },
+ module: 'org.springframework.web.servlet',
+ function: 'doDispatch',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'DispatcherServlet.java',
+ classname: 'org.springframework.web.servlet.DispatcherServlet',
+ line: {
+ number: 925,
+ },
+ module: 'org.springframework.web.servlet',
+ function: 'doService',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'FrameworkServlet.java',
+ classname: 'org.springframework.web.servlet.FrameworkServlet',
+ line: {
+ number: 974,
+ },
+ module: 'org.springframework.web.servlet',
+ function: 'processRequest',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'FrameworkServlet.java',
+ classname: 'org.springframework.web.servlet.FrameworkServlet',
+ line: {
+ number: 866,
+ },
+ module: 'org.springframework.web.servlet',
+ function: 'doGet',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'HttpServlet.java',
+ classname: 'javax.servlet.http.HttpServlet',
+ line: {
+ number: 635,
+ },
+ module: 'javax.servlet.http',
+ function: 'service',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'FrameworkServlet.java',
+ classname: 'org.springframework.web.servlet.FrameworkServlet',
+ line: {
+ number: 851,
+ },
+ module: 'org.springframework.web.servlet',
+ function: 'service',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'HttpServlet.java',
+ classname: 'javax.servlet.http.HttpServlet',
+ line: {
+ number: 742,
+ },
+ module: 'javax.servlet.http',
+ function: 'service',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 231,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'WsFilter.java',
+ classname: 'org.apache.tomcat.websocket.server.WsFilter',
+ line: {
+ number: 52,
+ },
+ module: 'org.apache.tomcat.websocket.server',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 193,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'RequestContextFilter.java',
+ classname: 'org.springframework.web.filter.RequestContextFilter',
+ line: {
+ number: 99,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilterInternal',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'OncePerRequestFilter.java',
+ classname: 'org.springframework.web.filter.OncePerRequestFilter',
+ line: {
+ number: 107,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 193,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'HttpPutFormContentFilter.java',
+ classname: 'org.springframework.web.filter.HttpPutFormContentFilter',
+ line: {
+ number: 109,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilterInternal',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'OncePerRequestFilter.java',
+ classname: 'org.springframework.web.filter.OncePerRequestFilter',
+ line: {
+ number: 107,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 193,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'doFilter',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'HiddenHttpMethodFilter.java',
+ classname: 'org.springframework.web.filter.HiddenHttpMethodFilter',
+ line: {
+ number: 81,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilterInternal',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'OncePerRequestFilter.java',
+ classname: 'org.springframework.web.filter.OncePerRequestFilter',
+ line: {
+ number: 107,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 193,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'doFilter',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'CharacterEncodingFilter.java',
+ classname: 'org.springframework.web.filter.CharacterEncodingFilter',
+ line: {
+ number: 200,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilterInternal',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'OncePerRequestFilter.java',
+ classname: 'org.springframework.web.filter.OncePerRequestFilter',
+ line: {
+ number: 107,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 193,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ function: 'doFilter',
+ module: 'org.apache.catalina.core',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'StandardWrapperValve.java',
+ classname: 'org.apache.catalina.core.StandardWrapperValve',
+ line: {
+ number: 198,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'invoke',
+ },
+ ],
+ message:
+ 'Null return value from advice does not match primitive return type for: public abstract double co.elastic.apm.opbeans.repositories.Numbers.getRevenue() (through reference chain: co.elastic.apm.opbeans.repositories.Stats["numbers"]->com.sun.proxy.$Proxy128["revenue"])',
+ type: 'com.fasterxml.jackson.databind.JsonMappingException',
+ },
+ {
+ stacktrace: [
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'JdkDynamicAopProxy.java',
+ classname: 'org.springframework.aop.framework.JdkDynamicAopProxy',
+ line: {
+ number: 226,
+ },
+ module: 'org.springframework.aop.framework',
+ function: 'invoke',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'BeanPropertyWriter.java',
+ classname: 'com.fasterxml.jackson.databind.ser.BeanPropertyWriter',
+ line: {
+ number: 688,
+ },
+ module: 'com.fasterxml.jackson.databind.ser',
+ function: 'serializeAsField',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'BeanSerializerBase.java',
+ classname:
+ 'com.fasterxml.jackson.databind.ser.std.BeanSerializerBase',
+ line: {
+ number: 719,
+ },
+ module: 'com.fasterxml.jackson.databind.ser.std',
+ function: 'serializeFields',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'BeanSerializer.java',
+ classname: 'com.fasterxml.jackson.databind.ser.BeanSerializer',
+ line: {
+ number: 155,
+ },
+ module: 'com.fasterxml.jackson.databind.ser',
+ function: 'serialize',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'BeanPropertyWriter.java',
+ classname: 'com.fasterxml.jackson.databind.ser.BeanPropertyWriter',
+ line: {
+ number: 727,
+ },
+ module: 'com.fasterxml.jackson.databind.ser',
+ function: 'serializeAsField',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'BeanSerializerBase.java',
+ classname:
+ 'com.fasterxml.jackson.databind.ser.std.BeanSerializerBase',
+ line: {
+ number: 719,
+ },
+ module: 'com.fasterxml.jackson.databind.ser.std',
+ function: 'serializeFields',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'BeanSerializer.java',
+ classname: 'com.fasterxml.jackson.databind.ser.BeanSerializer',
+ line: {
+ number: 155,
+ },
+ module: 'com.fasterxml.jackson.databind.ser',
+ function: 'serialize',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'DefaultSerializerProvider.java',
+ classname:
+ 'com.fasterxml.jackson.databind.ser.DefaultSerializerProvider',
+ line: {
+ number: 480,
+ },
+ module: 'com.fasterxml.jackson.databind.ser',
+ function: '_serialize',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'DefaultSerializerProvider.java',
+ classname:
+ 'com.fasterxml.jackson.databind.ser.DefaultSerializerProvider',
+ line: {
+ number: 319,
+ },
+ module: 'com.fasterxml.jackson.databind.ser',
+ function: 'serializeValue',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ObjectWriter.java',
+ classname: 'com.fasterxml.jackson.databind.ObjectWriter$Prefetch',
+ line: {
+ number: 1396,
+ },
+ module: 'com.fasterxml.jackson.databind',
+ function: 'serialize',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'ObjectWriter.java',
+ classname: 'com.fasterxml.jackson.databind.ObjectWriter',
+ line: {
+ number: 913,
+ },
+ module: 'com.fasterxml.jackson.databind',
+ function: 'writeValue',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'AbstractJackson2HttpMessageConverter.java',
+ classname:
+ 'org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter',
+ line: {
+ number: 286,
+ },
+ module: 'org.springframework.http.converter.json',
+ function: 'writeInternal',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'AbstractGenericHttpMessageConverter.java',
+ classname:
+ 'org.springframework.http.converter.AbstractGenericHttpMessageConverter',
+ line: {
+ number: 102,
+ },
+ module: 'org.springframework.http.converter',
+ function: 'write',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'AbstractMessageConverterMethodProcessor.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor',
+ line: {
+ number: 272,
+ },
+ module: 'org.springframework.web.servlet.mvc.method.annotation',
+ function: 'writeWithMessageConverters',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'RequestResponseBodyMethodProcessor.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor',
+ line: {
+ number: 180,
+ },
+ function: 'handleReturnValue',
+ module: 'org.springframework.web.servlet.mvc.method.annotation',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'HandlerMethodReturnValueHandlerComposite.java',
+ classname:
+ 'org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite',
+ line: {
+ number: 82,
+ },
+ module: 'org.springframework.web.method.support',
+ function: 'handleReturnValue',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ServletInvocableHandlerMethod.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod',
+ line: {
+ number: 119,
+ },
+ function: 'invokeAndHandle',
+ module: 'org.springframework.web.servlet.mvc.method.annotation',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'RequestMappingHandlerAdapter.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter',
+ line: {
+ number: 877,
+ },
+ module: 'org.springframework.web.servlet.mvc.method.annotation',
+ function: 'invokeHandlerMethod',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'RequestMappingHandlerAdapter.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter',
+ line: {
+ number: 783,
+ },
+ module: 'org.springframework.web.servlet.mvc.method.annotation',
+ function: 'handleInternal',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'AbstractHandlerMethodAdapter.java',
+ classname:
+ 'org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter',
+ line: {
+ number: 87,
+ },
+ module: 'org.springframework.web.servlet.mvc.method',
+ function: 'handle',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'DispatcherServlet.java',
+ classname: 'org.springframework.web.servlet.DispatcherServlet',
+ line: {
+ number: 991,
+ },
+ module: 'org.springframework.web.servlet',
+ function: 'doDispatch',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'DispatcherServlet.java',
+ classname: 'org.springframework.web.servlet.DispatcherServlet',
+ line: {
+ number: 925,
+ },
+ module: 'org.springframework.web.servlet',
+ function: 'doService',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'FrameworkServlet.java',
+ classname: 'org.springframework.web.servlet.FrameworkServlet',
+ line: {
+ number: 974,
+ },
+ module: 'org.springframework.web.servlet',
+ function: 'processRequest',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'FrameworkServlet.java',
+ classname: 'org.springframework.web.servlet.FrameworkServlet',
+ line: {
+ number: 866,
+ },
+ module: 'org.springframework.web.servlet',
+ function: 'doGet',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'HttpServlet.java',
+ classname: 'javax.servlet.http.HttpServlet',
+ line: {
+ number: 635,
+ },
+ module: 'javax.servlet.http',
+ function: 'service',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'FrameworkServlet.java',
+ classname: 'org.springframework.web.servlet.FrameworkServlet',
+ line: {
+ number: 851,
+ },
+ module: 'org.springframework.web.servlet',
+ function: 'service',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'HttpServlet.java',
+ classname: 'javax.servlet.http.HttpServlet',
+ line: {
+ number: 742,
+ },
+ module: 'javax.servlet.http',
+ function: 'service',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 231,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'doFilter',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'WsFilter.java',
+ classname: 'org.apache.tomcat.websocket.server.WsFilter',
+ line: {
+ number: 52,
+ },
+ module: 'org.apache.tomcat.websocket.server',
+ function: 'doFilter',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 193,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'RequestContextFilter.java',
+ classname: 'org.springframework.web.filter.RequestContextFilter',
+ line: {
+ number: 99,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilterInternal',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'OncePerRequestFilter.java',
+ classname: 'org.springframework.web.filter.OncePerRequestFilter',
+ line: {
+ number: 107,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 193,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'HttpPutFormContentFilter.java',
+ classname: 'org.springframework.web.filter.HttpPutFormContentFilter',
+ line: {
+ number: 109,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilterInternal',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'OncePerRequestFilter.java',
+ classname: 'org.springframework.web.filter.OncePerRequestFilter',
+ line: {
+ number: 107,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 193,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'HiddenHttpMethodFilter.java',
+ classname: 'org.springframework.web.filter.HiddenHttpMethodFilter',
+ line: {
+ number: 81,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilterInternal',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'OncePerRequestFilter.java',
+ classname: 'org.springframework.web.filter.OncePerRequestFilter',
+ line: {
+ number: 107,
+ },
+ function: 'doFilter',
+ module: 'org.springframework.web.filter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 193,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ function: 'doFilter',
+ module: 'org.apache.catalina.core',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'CharacterEncodingFilter.java',
+ classname: 'org.springframework.web.filter.CharacterEncodingFilter',
+ line: {
+ number: 200,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilterInternal',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'OncePerRequestFilter.java',
+ classname: 'org.springframework.web.filter.OncePerRequestFilter',
+ line: {
+ number: 107,
+ },
+ module: 'org.springframework.web.filter',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 193,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'internalDoFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'ApplicationFilterChain.java',
+ classname: 'org.apache.catalina.core.ApplicationFilterChain',
+ line: {
+ number: 166,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'doFilter',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'StandardWrapperValve.java',
+ classname: 'org.apache.catalina.core.StandardWrapperValve',
+ line: {
+ number: 198,
+ },
+ module: 'org.apache.catalina.core',
+ function: 'invoke',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'StandardContextValve.java',
+ classname: 'org.apache.catalina.core.StandardContextValve',
+ line: {
+ number: 96,
+ },
+ function: 'invoke',
+ module: 'org.apache.catalina.core',
+ },
+ ],
+ message:
+ 'Null return value from advice does not match primitive return type for: public abstract double co.elastic.apm.opbeans.repositories.Numbers.getRevenue()',
+ type: 'org.springframework.aop.AopInvocationException',
+ },
+ ];
+
+ return ;
+}
+JavaWithLongLines.decorators = [
+ (Story: ComponentType) => {
return (
-
+
+
+
);
- })
- .add('Ruby with context and library frames', () => {
- const exceptions: Exception[] = [
- {
- stacktrace: [
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'active_record/core.rb',
- abs_path:
- '/usr/local/bundle/gems/activerecord-5.2.4.1/lib/active_record/core.rb',
- line: {
- number: 177,
- },
- function: 'find',
- },
- {
- library_frame: false,
- exclude_from_grouping: false,
- filename: 'api/orders_controller.rb',
- abs_path: '/app/app/controllers/api/orders_controller.rb',
- line: {
- number: 23,
- context: ' render json: Order.find(params[:id])\n',
- },
- function: 'show',
- context: {
- pre: ['\n', ' def show\n'],
- post: [' end\n', ' end\n'],
- },
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_controller/metal/basic_implicit_render.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_controller/metal/basic_implicit_render.rb',
- line: {
- number: 6,
- },
- function: 'send_action',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'abstract_controller/base.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/abstract_controller/base.rb',
- line: {
- number: 194,
- },
- function: 'process_action',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_controller/metal/rendering.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_controller/metal/rendering.rb',
- line: {
- number: 30,
- },
- function: 'process_action',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'abstract_controller/callbacks.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/abstract_controller/callbacks.rb',
- line: {
- number: 42,
- },
- function: 'block in process_action',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'active_support/callbacks.rb',
- abs_path:
- '/usr/local/bundle/gems/activesupport-5.2.4.1/lib/active_support/callbacks.rb',
- line: {
- number: 132,
- },
- function: 'run_callbacks',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'abstract_controller/callbacks.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/abstract_controller/callbacks.rb',
- line: {
- number: 41,
- },
- function: 'process_action',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_controller/metal/rescue.rb',
- filename: 'action_controller/metal/rescue.rb',
- line: {
- number: 22,
- },
- function: 'process_action',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_controller/metal/instrumentation.rb',
- filename: 'action_controller/metal/instrumentation.rb',
- line: {
- number: 34,
- },
- function: 'block in process_action',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'active_support/notifications.rb',
- abs_path:
- '/usr/local/bundle/gems/activesupport-5.2.4.1/lib/active_support/notifications.rb',
- line: {
- number: 168,
- },
- function: 'block in instrument',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'active_support/notifications/instrumenter.rb',
- abs_path:
- '/usr/local/bundle/gems/activesupport-5.2.4.1/lib/active_support/notifications/instrumenter.rb',
- line: {
- number: 23,
- },
- function: 'instrument',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'active_support/notifications.rb',
- abs_path:
- '/usr/local/bundle/gems/activesupport-5.2.4.1/lib/active_support/notifications.rb',
- line: {
- number: 168,
- },
- function: 'instrument',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_controller/metal/instrumentation.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_controller/metal/instrumentation.rb',
- line: {
- number: 32,
- },
- function: 'process_action',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_controller/metal/params_wrapper.rb',
- filename: 'action_controller/metal/params_wrapper.rb',
- line: {
- number: 256,
- },
- function: 'process_action',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'active_record/railties/controller_runtime.rb',
- abs_path:
- '/usr/local/bundle/gems/activerecord-5.2.4.1/lib/active_record/railties/controller_runtime.rb',
- line: {
- number: 24,
- },
- function: 'process_action',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'abstract_controller/base.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/abstract_controller/base.rb',
- line: {
- number: 134,
- },
- function: 'process',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_view/rendering.rb',
- abs_path:
- '/usr/local/bundle/gems/actionview-5.2.4.1/lib/action_view/rendering.rb',
- line: {
- number: 32,
- },
- function: 'process',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_controller/metal.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_controller/metal.rb',
- line: {
- number: 191,
- },
- function: 'dispatch',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_controller/metal.rb',
- filename: 'action_controller/metal.rb',
- line: {
- number: 252,
- },
- function: 'dispatch',
- },
- {
- exclude_from_grouping: false,
- library_frame: true,
- filename: 'action_dispatch/routing/route_set.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/routing/route_set.rb',
- line: {
- number: 52,
- },
- function: 'dispatch',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_dispatch/routing/route_set.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/routing/route_set.rb',
- line: {
- number: 34,
- },
- function: 'serve',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/journey/router.rb',
- filename: 'action_dispatch/journey/router.rb',
- line: {
- number: 52,
- },
- function: 'block in serve',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_dispatch/journey/router.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/journey/router.rb',
- line: {
- number: 35,
- },
- function: 'each',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_dispatch/journey/router.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/journey/router.rb',
- line: {
- number: 35,
- },
- function: 'serve',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_dispatch/routing/route_set.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/routing/route_set.rb',
- line: {
- number: 840,
- },
- function: 'call',
- },
- {
- exclude_from_grouping: false,
- library_frame: true,
- filename: 'rack/static.rb',
- abs_path: '/usr/local/bundle/gems/rack-2.2.3/lib/rack/static.rb',
- line: {
- number: 161,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'rack/tempfile_reaper.rb',
- abs_path:
- '/usr/local/bundle/gems/rack-2.2.3/lib/rack/tempfile_reaper.rb',
- line: {
- number: 15,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'rack/etag.rb',
- abs_path: '/usr/local/bundle/gems/rack-2.2.3/lib/rack/etag.rb',
- line: {
- number: 27,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'rack/conditional_get.rb',
- abs_path:
- '/usr/local/bundle/gems/rack-2.2.3/lib/rack/conditional_get.rb',
- line: {
- number: 27,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'rack/head.rb',
- abs_path: '/usr/local/bundle/gems/rack-2.2.3/lib/rack/head.rb',
- line: {
- number: 12,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_dispatch/http/content_security_policy.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/http/content_security_policy.rb',
- line: {
- number: 18,
- },
- function: 'call',
- },
- {
- exclude_from_grouping: false,
- library_frame: true,
- filename: 'rack/session/abstract/id.rb',
- abs_path:
- '/usr/local/bundle/gems/rack-2.2.3/lib/rack/session/abstract/id.rb',
- line: {
- number: 266,
- },
- function: 'context',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'rack/session/abstract/id.rb',
- abs_path:
- '/usr/local/bundle/gems/rack-2.2.3/lib/rack/session/abstract/id.rb',
- line: {
- number: 260,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_dispatch/middleware/cookies.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/cookies.rb',
- line: {
- number: 670,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_dispatch/middleware/callbacks.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/callbacks.rb',
- line: {
- number: 28,
- },
- function: 'block in call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'active_support/callbacks.rb',
- abs_path:
- '/usr/local/bundle/gems/activesupport-5.2.4.1/lib/active_support/callbacks.rb',
- line: {
- number: 98,
- },
- function: 'run_callbacks',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_dispatch/middleware/callbacks.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/callbacks.rb',
- line: {
- number: 26,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_dispatch/middleware/debug_exceptions.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/debug_exceptions.rb',
- line: {
- number: 61,
- },
- function: 'call',
- },
- {
- exclude_from_grouping: false,
- library_frame: true,
- filename: 'action_dispatch/middleware/show_exceptions.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/show_exceptions.rb',
- line: {
- number: 33,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'lograge/rails_ext/rack/logger.rb',
- abs_path:
- '/usr/local/bundle/gems/lograge-0.11.2/lib/lograge/rails_ext/rack/logger.rb',
- line: {
- number: 15,
- },
- function: 'call_app',
- },
- {
- exclude_from_grouping: false,
- library_frame: true,
- filename: 'rails/rack/logger.rb',
- abs_path:
- '/usr/local/bundle/gems/railties-5.2.4.1/lib/rails/rack/logger.rb',
- line: {
- number: 28,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/remote_ip.rb',
- filename: 'action_dispatch/middleware/remote_ip.rb',
- line: {
- number: 81,
- },
- function: 'call',
- },
- {
- exclude_from_grouping: false,
- library_frame: true,
- filename: 'request_store/middleware.rb',
- abs_path:
- '/usr/local/bundle/gems/request_store-1.5.0/lib/request_store/middleware.rb',
- line: {
- number: 19,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_dispatch/middleware/request_id.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/request_id.rb',
- line: {
- number: 27,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'rack/method_override.rb',
- abs_path:
- '/usr/local/bundle/gems/rack-2.2.3/lib/rack/method_override.rb',
- line: {
- number: 24,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'rack/runtime.rb',
- abs_path: '/usr/local/bundle/gems/rack-2.2.3/lib/rack/runtime.rb',
- line: {
- number: 22,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'active_support/cache/strategy/local_cache_middleware.rb',
- abs_path:
- '/usr/local/bundle/gems/activesupport-5.2.4.1/lib/active_support/cache/strategy/local_cache_middleware.rb',
- line: {
- number: 29,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_dispatch/middleware/executor.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/executor.rb',
- line: {
- number: 14,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'action_dispatch/middleware/static.rb',
- abs_path:
- '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/static.rb',
- line: {
- number: 127,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'rack/sendfile.rb',
- abs_path: '/usr/local/bundle/gems/rack-2.2.3/lib/rack/sendfile.rb',
- line: {
- number: 110,
- },
- function: 'call',
- },
- {
- library_frame: false,
- exclude_from_grouping: false,
- filename: 'opbeans_shuffle.rb',
- abs_path: '/app/lib/opbeans_shuffle.rb',
- line: {
- number: 32,
- context: ' @app.call(env)\n',
- },
- function: 'call',
- context: {
- pre: [' end\n', ' else\n'],
- post: [' end\n', ' rescue Timeout::Error\n'],
- },
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'elastic_apm/middleware.rb',
- abs_path:
- '/usr/local/bundle/gems/elastic-apm-3.8.0/lib/elastic_apm/middleware.rb',
- line: {
- number: 36,
- },
- function: 'call',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'rails/engine.rb',
- abs_path:
- '/usr/local/bundle/gems/railties-5.2.4.1/lib/rails/engine.rb',
- line: {
- number: 524,
- },
- function: 'call',
- },
- {
- exclude_from_grouping: false,
- library_frame: true,
- filename: 'puma/configuration.rb',
- abs_path:
- '/usr/local/bundle/gems/puma-4.3.5/lib/puma/configuration.rb',
- line: {
- number: 228,
- },
- function: 'call',
- },
- {
- exclude_from_grouping: false,
- library_frame: true,
- filename: 'puma/server.rb',
- abs_path: '/usr/local/bundle/gems/puma-4.3.5/lib/puma/server.rb',
- line: {
- number: 713,
- },
- function: 'handle_request',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'puma/server.rb',
- abs_path: '/usr/local/bundle/gems/puma-4.3.5/lib/puma/server.rb',
- line: {
- number: 472,
- },
- function: 'process_client',
- },
- {
- library_frame: true,
- exclude_from_grouping: false,
- filename: 'puma/server.rb',
- abs_path: '/usr/local/bundle/gems/puma-4.3.5/lib/puma/server.rb',
- line: {
- number: 328,
- },
- function: 'block in run',
- },
- {
- exclude_from_grouping: false,
- library_frame: true,
- filename: 'puma/thread_pool.rb',
- abs_path:
- '/usr/local/bundle/gems/puma-4.3.5/lib/puma/thread_pool.rb',
- line: {
- number: 134,
- },
- function: 'block in spawn_thread',
- },
- ],
- handled: false,
- module: 'ActiveRecord',
- message: "Couldn't find Order with 'id'=956",
- type: 'ActiveRecord::RecordNotFound',
+ },
+];
+
+export function JavaScriptWithSomeContext() {
+ const exceptions: Exception[] = [
+ {
+ code: '503',
+ stacktrace: [
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'node_modules/elastic-apm-http-client/index.js',
+ abs_path: '/app/node_modules/elastic-apm-http-client/index.js',
+ line: {
+ number: 711,
+ context:
+ " const err = new Error('Unexpected APM Server response when polling config')",
+ },
+ function: 'processConfigErrorResponse',
+ context: {
+ pre: ['', 'function processConfigErrorResponse (res, buf) {'],
+ post: ['', ' err.code = res.statusCode'],
+ },
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'node_modules/elastic-apm-http-client/index.js',
+ abs_path: '/app/node_modules/elastic-apm-http-client/index.js',
+ line: {
+ number: 196,
+ context:
+ ' res.destroy(processConfigErrorResponse(res, buf))',
+ },
+ function: '',
+ context: {
+ pre: [' }', ' } else {'],
+ post: [' }', ' })'],
+ },
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'node_modules/fast-stream-to-buffer/index.js',
+ abs_path: '/app/node_modules/fast-stream-to-buffer/index.js',
+ line: {
+ number: 20,
+ context: ' cb(err, buffers[0], stream)',
+ },
+ function: 'IncomingMessage.',
+ context: {
+ pre: [' break', ' case 1:'],
+ post: [' break', ' default:'],
+ },
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'node_modules/once/once.js',
+ abs_path: '/app/node_modules/once/once.js',
+ line: {
+ number: 25,
+ context: ' return f.value = fn.apply(this, arguments)',
+ },
+ function: 'f',
+ context: {
+ pre: [' if (f.called) return f.value', ' f.called = true'],
+ post: [' }', ' f.called = false'],
+ },
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'node_modules/end-of-stream/index.js',
+ abs_path: '/app/node_modules/end-of-stream/index.js',
+ line: {
+ number: 36,
+ context: '\t\tif (!writable) callback.call(stream);',
+ },
+ function: 'onend',
+ context: {
+ pre: ['\tvar onend = function() {', '\t\treadable = false;'],
+ post: ['\t};', ''],
+ },
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ abs_path: 'events.js',
+ filename: 'events.js',
+ line: {
+ number: 327,
+ },
+ function: 'emit',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: '_stream_readable.js',
+ abs_path: '_stream_readable.js',
+ line: {
+ number: 1220,
+ },
+ function: 'endReadableNT',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'internal/process/task_queues.js',
+ abs_path: 'internal/process/task_queues.js',
+ line: {
+ number: 84,
+ },
+ function: 'processTicksAndRejections',
+ },
+ ],
+ module: 'elastic-apm-http-client',
+ handled: false,
+ attributes: {
+ response:
+ '\r\n503 Service Temporarily Unavailable\r\n\r\n503 Service Temporarily Unavailable\r\n nginx/1.17.7\r\n\r\n\r\n',
},
- ];
+ type: 'Error',
+ message: 'Unexpected APM Server response when polling config',
+ },
+ ];
+
+ return (
+
+ );
+}
+JavaScriptWithSomeContext.storyName = 'JavaScript With Some Context';
+
+export function RubyWithContextAndLibraryFrames() {
+ const exceptions: Exception[] = [
+ {
+ stacktrace: [
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'active_record/core.rb',
+ abs_path:
+ '/usr/local/bundle/gems/activerecord-5.2.4.1/lib/active_record/core.rb',
+ line: {
+ number: 177,
+ },
+ function: 'find',
+ },
+ {
+ library_frame: false,
+ exclude_from_grouping: false,
+ filename: 'api/orders_controller.rb',
+ abs_path: '/app/app/controllers/api/orders_controller.rb',
+ line: {
+ number: 23,
+ context: ' render json: Order.find(params[:id])\n',
+ },
+ function: 'show',
+ context: {
+ pre: ['\n', ' def show\n'],
+ post: [' end\n', ' end\n'],
+ },
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_controller/metal/basic_implicit_render.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_controller/metal/basic_implicit_render.rb',
+ line: {
+ number: 6,
+ },
+ function: 'send_action',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'abstract_controller/base.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/abstract_controller/base.rb',
+ line: {
+ number: 194,
+ },
+ function: 'process_action',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_controller/metal/rendering.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_controller/metal/rendering.rb',
+ line: {
+ number: 30,
+ },
+ function: 'process_action',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'abstract_controller/callbacks.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/abstract_controller/callbacks.rb',
+ line: {
+ number: 42,
+ },
+ function: 'block in process_action',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'active_support/callbacks.rb',
+ abs_path:
+ '/usr/local/bundle/gems/activesupport-5.2.4.1/lib/active_support/callbacks.rb',
+ line: {
+ number: 132,
+ },
+ function: 'run_callbacks',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'abstract_controller/callbacks.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/abstract_controller/callbacks.rb',
+ line: {
+ number: 41,
+ },
+ function: 'process_action',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_controller/metal/rescue.rb',
+ filename: 'action_controller/metal/rescue.rb',
+ line: {
+ number: 22,
+ },
+ function: 'process_action',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_controller/metal/instrumentation.rb',
+ filename: 'action_controller/metal/instrumentation.rb',
+ line: {
+ number: 34,
+ },
+ function: 'block in process_action',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'active_support/notifications.rb',
+ abs_path:
+ '/usr/local/bundle/gems/activesupport-5.2.4.1/lib/active_support/notifications.rb',
+ line: {
+ number: 168,
+ },
+ function: 'block in instrument',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'active_support/notifications/instrumenter.rb',
+ abs_path:
+ '/usr/local/bundle/gems/activesupport-5.2.4.1/lib/active_support/notifications/instrumenter.rb',
+ line: {
+ number: 23,
+ },
+ function: 'instrument',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'active_support/notifications.rb',
+ abs_path:
+ '/usr/local/bundle/gems/activesupport-5.2.4.1/lib/active_support/notifications.rb',
+ line: {
+ number: 168,
+ },
+ function: 'instrument',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_controller/metal/instrumentation.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_controller/metal/instrumentation.rb',
+ line: {
+ number: 32,
+ },
+ function: 'process_action',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_controller/metal/params_wrapper.rb',
+ filename: 'action_controller/metal/params_wrapper.rb',
+ line: {
+ number: 256,
+ },
+ function: 'process_action',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'active_record/railties/controller_runtime.rb',
+ abs_path:
+ '/usr/local/bundle/gems/activerecord-5.2.4.1/lib/active_record/railties/controller_runtime.rb',
+ line: {
+ number: 24,
+ },
+ function: 'process_action',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'abstract_controller/base.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/abstract_controller/base.rb',
+ line: {
+ number: 134,
+ },
+ function: 'process',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_view/rendering.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionview-5.2.4.1/lib/action_view/rendering.rb',
+ line: {
+ number: 32,
+ },
+ function: 'process',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_controller/metal.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_controller/metal.rb',
+ line: {
+ number: 191,
+ },
+ function: 'dispatch',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_controller/metal.rb',
+ filename: 'action_controller/metal.rb',
+ line: {
+ number: 252,
+ },
+ function: 'dispatch',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'action_dispatch/routing/route_set.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/routing/route_set.rb',
+ line: {
+ number: 52,
+ },
+ function: 'dispatch',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_dispatch/routing/route_set.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/routing/route_set.rb',
+ line: {
+ number: 34,
+ },
+ function: 'serve',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/journey/router.rb',
+ filename: 'action_dispatch/journey/router.rb',
+ line: {
+ number: 52,
+ },
+ function: 'block in serve',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_dispatch/journey/router.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/journey/router.rb',
+ line: {
+ number: 35,
+ },
+ function: 'each',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_dispatch/journey/router.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/journey/router.rb',
+ line: {
+ number: 35,
+ },
+ function: 'serve',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_dispatch/routing/route_set.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/routing/route_set.rb',
+ line: {
+ number: 840,
+ },
+ function: 'call',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'rack/static.rb',
+ abs_path: '/usr/local/bundle/gems/rack-2.2.3/lib/rack/static.rb',
+ line: {
+ number: 161,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'rack/tempfile_reaper.rb',
+ abs_path:
+ '/usr/local/bundle/gems/rack-2.2.3/lib/rack/tempfile_reaper.rb',
+ line: {
+ number: 15,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'rack/etag.rb',
+ abs_path: '/usr/local/bundle/gems/rack-2.2.3/lib/rack/etag.rb',
+ line: {
+ number: 27,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'rack/conditional_get.rb',
+ abs_path:
+ '/usr/local/bundle/gems/rack-2.2.3/lib/rack/conditional_get.rb',
+ line: {
+ number: 27,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'rack/head.rb',
+ abs_path: '/usr/local/bundle/gems/rack-2.2.3/lib/rack/head.rb',
+ line: {
+ number: 12,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_dispatch/http/content_security_policy.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/http/content_security_policy.rb',
+ line: {
+ number: 18,
+ },
+ function: 'call',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'rack/session/abstract/id.rb',
+ abs_path:
+ '/usr/local/bundle/gems/rack-2.2.3/lib/rack/session/abstract/id.rb',
+ line: {
+ number: 266,
+ },
+ function: 'context',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'rack/session/abstract/id.rb',
+ abs_path:
+ '/usr/local/bundle/gems/rack-2.2.3/lib/rack/session/abstract/id.rb',
+ line: {
+ number: 260,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_dispatch/middleware/cookies.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/cookies.rb',
+ line: {
+ number: 670,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_dispatch/middleware/callbacks.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/callbacks.rb',
+ line: {
+ number: 28,
+ },
+ function: 'block in call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'active_support/callbacks.rb',
+ abs_path:
+ '/usr/local/bundle/gems/activesupport-5.2.4.1/lib/active_support/callbacks.rb',
+ line: {
+ number: 98,
+ },
+ function: 'run_callbacks',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_dispatch/middleware/callbacks.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/callbacks.rb',
+ line: {
+ number: 26,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_dispatch/middleware/debug_exceptions.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/debug_exceptions.rb',
+ line: {
+ number: 61,
+ },
+ function: 'call',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'action_dispatch/middleware/show_exceptions.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/show_exceptions.rb',
+ line: {
+ number: 33,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'lograge/rails_ext/rack/logger.rb',
+ abs_path:
+ '/usr/local/bundle/gems/lograge-0.11.2/lib/lograge/rails_ext/rack/logger.rb',
+ line: {
+ number: 15,
+ },
+ function: 'call_app',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'rails/rack/logger.rb',
+ abs_path:
+ '/usr/local/bundle/gems/railties-5.2.4.1/lib/rails/rack/logger.rb',
+ line: {
+ number: 28,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/remote_ip.rb',
+ filename: 'action_dispatch/middleware/remote_ip.rb',
+ line: {
+ number: 81,
+ },
+ function: 'call',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'request_store/middleware.rb',
+ abs_path:
+ '/usr/local/bundle/gems/request_store-1.5.0/lib/request_store/middleware.rb',
+ line: {
+ number: 19,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_dispatch/middleware/request_id.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/request_id.rb',
+ line: {
+ number: 27,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'rack/method_override.rb',
+ abs_path:
+ '/usr/local/bundle/gems/rack-2.2.3/lib/rack/method_override.rb',
+ line: {
+ number: 24,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'rack/runtime.rb',
+ abs_path: '/usr/local/bundle/gems/rack-2.2.3/lib/rack/runtime.rb',
+ line: {
+ number: 22,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'active_support/cache/strategy/local_cache_middleware.rb',
+ abs_path:
+ '/usr/local/bundle/gems/activesupport-5.2.4.1/lib/active_support/cache/strategy/local_cache_middleware.rb',
+ line: {
+ number: 29,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_dispatch/middleware/executor.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/executor.rb',
+ line: {
+ number: 14,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'action_dispatch/middleware/static.rb',
+ abs_path:
+ '/usr/local/bundle/gems/actionpack-5.2.4.1/lib/action_dispatch/middleware/static.rb',
+ line: {
+ number: 127,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'rack/sendfile.rb',
+ abs_path: '/usr/local/bundle/gems/rack-2.2.3/lib/rack/sendfile.rb',
+ line: {
+ number: 110,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: false,
+ exclude_from_grouping: false,
+ filename: 'opbeans_shuffle.rb',
+ abs_path: '/app/lib/opbeans_shuffle.rb',
+ line: {
+ number: 32,
+ context: ' @app.call(env)\n',
+ },
+ function: 'call',
+ context: {
+ pre: [' end\n', ' else\n'],
+ post: [' end\n', ' rescue Timeout::Error\n'],
+ },
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'elastic_apm/middleware.rb',
+ abs_path:
+ '/usr/local/bundle/gems/elastic-apm-3.8.0/lib/elastic_apm/middleware.rb',
+ line: {
+ number: 36,
+ },
+ function: 'call',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'rails/engine.rb',
+ abs_path:
+ '/usr/local/bundle/gems/railties-5.2.4.1/lib/rails/engine.rb',
+ line: {
+ number: 524,
+ },
+ function: 'call',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'puma/configuration.rb',
+ abs_path:
+ '/usr/local/bundle/gems/puma-4.3.5/lib/puma/configuration.rb',
+ line: {
+ number: 228,
+ },
+ function: 'call',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'puma/server.rb',
+ abs_path: '/usr/local/bundle/gems/puma-4.3.5/lib/puma/server.rb',
+ line: {
+ number: 713,
+ },
+ function: 'handle_request',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'puma/server.rb',
+ abs_path: '/usr/local/bundle/gems/puma-4.3.5/lib/puma/server.rb',
+ line: {
+ number: 472,
+ },
+ function: 'process_client',
+ },
+ {
+ library_frame: true,
+ exclude_from_grouping: false,
+ filename: 'puma/server.rb',
+ abs_path: '/usr/local/bundle/gems/puma-4.3.5/lib/puma/server.rb',
+ line: {
+ number: 328,
+ },
+ function: 'block in run',
+ },
+ {
+ exclude_from_grouping: false,
+ library_frame: true,
+ filename: 'puma/thread_pool.rb',
+ abs_path: '/usr/local/bundle/gems/puma-4.3.5/lib/puma/thread_pool.rb',
+ line: {
+ number: 134,
+ },
+ function: 'block in spawn_thread',
+ },
+ ],
+ handled: false,
+ module: 'ActiveRecord',
+ message: "Couldn't find Order with 'id'=956",
+ type: 'ActiveRecord::RecordNotFound',
+ },
+ ];
- return ;
- });
+ return ;
+}
diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.tsx
index d65ce1879ce0..7b944ed1b6ce 100644
--- a/x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.tsx
+++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.tsx
@@ -84,6 +84,11 @@ function CytoscapeComponent({
cy.elements().forEach((element) => {
if (!elementIds.includes(element.data('id'))) {
cy.remove(element);
+ } else {
+ // Doing an "add" with an element with the same id will keep the original
+ // element. Set the data with the new element data.
+ const newElement = elements.find((el) => el.data.id === element.id());
+ element.data(newElement?.data ?? element.data());
}
});
cy.trigger('custom:data', [fit]);
diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Info.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Info.tsx
index 7771a232a5c9..d0902c427aac 100644
--- a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Info.tsx
+++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Info.tsx
@@ -10,7 +10,7 @@ import {
} from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import cytoscape from 'cytoscape';
-import React from 'react';
+import React, { Fragment } from 'react';
import styled from 'styled-components';
import {
SPAN_SUBTYPE,
@@ -71,7 +71,7 @@ export function Info(data: InfoProps) {
resource.label || resource['span.destination.service.resource'];
const desc = `${resource['span.type']} (${resource['span.subtype']})`;
return (
- <>
+
{desc}
- >
+
);
})}
@@ -97,8 +97,8 @@ export function Info(data: InfoProps) {
{listItems.map(
({ title, description }) =>
description && (
-
-
+
+
{title}
diff --git a/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/__test__/props.json b/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/__fixtures__/props.json
similarity index 89%
rename from x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/__test__/props.json
rename to x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/__fixtures__/props.json
index 7f24ad8b0d30..2e213c44bccf 100644
--- a/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/__test__/props.json
+++ b/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/__fixtures__/props.json
@@ -11,10 +11,7 @@
"value": 46.06666666666667,
"timeseries": []
},
- "avgResponseTime": null,
- "environments": [
- "test"
- ]
+ "environments": ["test"]
},
{
"serviceName": "opbeans-python",
diff --git a/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/__test__/List.test.js b/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/__test__/List.test.js
deleted file mode 100644
index 7c306c16cca1..000000000000
--- a/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/__test__/List.test.js
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
- * or more contributor license agreements. Licensed under the Elastic License;
- * you may not use this file except in compliance with the Elastic License.
- */
-
-import React from 'react';
-import { shallow } from 'enzyme';
-import { ServiceList, SERVICE_COLUMNS } from '../index';
-import props from './props.json';
-import { mockMoment } from '../../../../../utils/testHelpers';
-import { ServiceHealthStatus } from '../../../../../../common/service_health_status';
-
-describe('ServiceOverview -> List', () => {
- beforeAll(() => {
- mockMoment();
- });
-
- it('renders empty state', () => {
- const wrapper = shallow();
- expect(wrapper).toMatchSnapshot();
- });
-
- it('renders with data', () => {
- const wrapper = shallow();
- expect(wrapper).toMatchSnapshot();
- });
-
- it('renders columns correctly', () => {
- const service = {
- serviceName: 'opbeans-python',
- agentName: 'python',
- transactionsPerMinute: {
- value: 86.93333333333334,
- timeseries: [],
- },
- errorsPerMinute: {
- value: 12.6,
- timeseries: [],
- },
- avgResponseTime: {
- value: 91535.42944785276,
- timeseries: [],
- },
- environments: ['test'],
- };
- const renderedColumns = SERVICE_COLUMNS.map((c) =>
- c.render(service[c.field], service)
- );
-
- expect(renderedColumns[0]).toMatchSnapshot();
- });
-
- describe('without ML data', () => {
- it('does not render health column', () => {
- const wrapper = shallow();
-
- const columns = wrapper.props().columns;
-
- expect(columns[0].field).not.toBe('healthStatus');
- });
- });
-
- describe('with ML data', () => {
- it('renders health column', () => {
- const wrapper = shallow(
- ({
- ...item,
- healthStatus: ServiceHealthStatus.warning,
- }))}
- />
- );
-
- const columns = wrapper.props().columns;
-
- expect(columns[0].field).toBe('healthStatus');
- });
- });
-});
diff --git a/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/__test__/__snapshots__/List.test.js.snap b/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/__test__/__snapshots__/List.test.js.snap
deleted file mode 100644
index e6a9823f3ee2..000000000000
--- a/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/__test__/__snapshots__/List.test.js.snap
+++ /dev/null
@@ -1,153 +0,0 @@
-// Jest Snapshot v1, https://goo.gl/fbAQLP
-
-exports[`ServiceOverview -> List renders columns correctly 1`] = `
-
-`;
-
-exports[`ServiceOverview -> List renders empty state 1`] = `
-
-`;
-
-exports[`ServiceOverview -> List renders with data 1`] = `
-
-`;
diff --git a/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/index.tsx b/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/index.tsx
index aa0222582b89..49319f167703 100644
--- a/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/index.tsx
+++ b/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/index.tsx
@@ -191,18 +191,20 @@ export function ServiceList({ items, noItemsMessage }: Props) {
const columns = displayHealthStatus
? SERVICE_COLUMNS
: SERVICE_COLUMNS.filter((column) => column.field !== 'healthStatus');
+ const initialSortField = displayHealthStatus
+ ? 'healthStatus'
+ : 'transactionsPerMinute';
return (
{
// For healthStatus, sort items by healthStatus first, then by TPM
-
return sortField === 'healthStatus'
? orderBy(
itemsToSort,
diff --git a/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/service_list.test.tsx b/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/service_list.test.tsx
new file mode 100644
index 000000000000..daddd0a60fe1
--- /dev/null
+++ b/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/service_list.test.tsx
@@ -0,0 +1,122 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+
+import React, { ReactNode } from 'react';
+import { MemoryRouter } from 'react-router-dom';
+import { ServiceHealthStatus } from '../../../../../common/service_health_status';
+// eslint-disable-next-line @kbn/eslint/no-restricted-paths
+import { ServiceListAPIResponse } from '../../../../../server/lib/services/get_services';
+import { MockApmPluginContextWrapper } from '../../../../context/ApmPluginContext/MockApmPluginContext';
+import { mockMoment, renderWithTheme } from '../../../../utils/testHelpers';
+import { ServiceList, SERVICE_COLUMNS } from './';
+import props from './__fixtures__/props.json';
+
+function Wrapper({ children }: { children?: ReactNode }) {
+ return (
+
+ {children}
+
+ );
+}
+
+describe('ServiceList', () => {
+ beforeAll(() => {
+ mockMoment();
+ });
+
+ it('renders empty state', () => {
+ expect(() =>
+ renderWithTheme(, { wrapper: Wrapper })
+ ).not.toThrowError();
+ });
+
+ it('renders with data', () => {
+ expect(() =>
+ // Types of property 'avgResponseTime' are incompatible.
+ // Type 'null' is not assignable to type '{ value: number | null; timeseries: { x: number; y: number | null; }[]; } | undefined'.ts(2322)
+ renderWithTheme(
+ ,
+ { wrapper: Wrapper }
+ )
+ ).not.toThrowError();
+ });
+
+ it('renders columns correctly', () => {
+ const service: any = {
+ serviceName: 'opbeans-python',
+ agentName: 'python',
+ transactionsPerMinute: {
+ value: 86.93333333333334,
+ timeseries: [],
+ },
+ errorsPerMinute: {
+ value: 12.6,
+ timeseries: [],
+ },
+ avgResponseTime: {
+ value: 91535.42944785276,
+ timeseries: [],
+ },
+ environments: ['test'],
+ };
+ const renderedColumns = SERVICE_COLUMNS.map((c) =>
+ c.render!(service[c.field!], service)
+ );
+
+ expect(renderedColumns[0]).toMatchInlineSnapshot(`
+
+ `);
+ });
+
+ describe('without ML data', () => {
+ it('does not render the health column', () => {
+ const { queryByText } = renderWithTheme(
+ ,
+ {
+ wrapper: Wrapper,
+ }
+ );
+ const healthHeading = queryByText('Health');
+
+ expect(healthHeading).toBeNull();
+ });
+
+ it('sorts by transactions per minute', async () => {
+ const { findByTitle } = renderWithTheme(
+ ,
+ {
+ wrapper: Wrapper,
+ }
+ );
+
+ expect(
+ await findByTitle('Trans. per minute; Sorted in descending order')
+ ).toBeInTheDocument();
+ });
+ });
+
+ describe('with ML data', () => {
+ it('renders the health column', async () => {
+ const { findByTitle } = renderWithTheme(
+ ({
+ ...item,
+ healthStatus: ServiceHealthStatus.warning,
+ })
+ )}
+ />,
+ { wrapper: Wrapper }
+ );
+
+ expect(
+ await findByTitle('Health; Sorted in descending order')
+ ).toBeInTheDocument();
+ });
+ });
+});
diff --git a/x-pack/plugins/apm/public/components/app/TransactionOverview/index.tsx b/x-pack/plugins/apm/public/components/app/TransactionOverview/index.tsx
index 7c887da6dc5e..8c7d088d36eb 100644
--- a/x-pack/plugins/apm/public/components/app/TransactionOverview/index.tsx
+++ b/x-pack/plugins/apm/public/components/app/TransactionOverview/index.tsx
@@ -36,7 +36,7 @@ import { TransactionTypeFilter } from '../../shared/LocalUIFilters/TransactionTy
import { TransactionList } from './TransactionList';
import { useRedirect } from './useRedirect';
import { TRANSACTION_PAGE_LOAD } from '../../../../common/transaction_types';
-import { ClientSideMonitoringCallout } from './ClientSideMonitoringCallout';
+import { UserExperienceCallout } from './user_experience_callout';
function getRedirectLocation({
urlParams,
@@ -129,7 +129,7 @@ export function TransactionOverview({ serviceName }: TransactionOverviewProps) {
{transactionType === TRANSACTION_PAGE_LOAD && (
<>
-
+
>
)}
diff --git a/x-pack/plugins/apm/public/components/app/TransactionOverview/ClientSideMonitoringCallout.tsx b/x-pack/plugins/apm/public/components/app/TransactionOverview/user_experience_callout.tsx
similarity index 75%
rename from x-pack/plugins/apm/public/components/app/TransactionOverview/ClientSideMonitoringCallout.tsx
rename to x-pack/plugins/apm/public/components/app/TransactionOverview/user_experience_callout.tsx
index becae4d7eb5d..41e84d4acfba 100644
--- a/x-pack/plugins/apm/public/components/app/TransactionOverview/ClientSideMonitoringCallout.tsx
+++ b/x-pack/plugins/apm/public/components/app/TransactionOverview/user_experience_callout.tsx
@@ -9,21 +9,21 @@ import { EuiButton, EuiCallOut, EuiSpacer, EuiText } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { useApmPluginContext } from '../../../hooks/useApmPluginContext';
-export function ClientSideMonitoringCallout() {
+export function UserExperienceCallout() {
const { core } = useApmPluginContext();
- const clientSideMonitoringHref = core.http.basePath.prepend(`/app/ux`);
+ const userExperienceHref = core.http.basePath.prepend(`/app/ux`);
return (
{i18n.translate(
- 'xpack.apm.transactionOverview.clientSideMonitoring.calloutText',
+ 'xpack.apm.transactionOverview.userExperience.calloutText',
{
defaultMessage:
'We are beyond excited to introduce a new experience for analyzing the user experience metrics specifically for your RUM services. It provides insights into the core vitals and visitor breakdown by browser and location. The app is always available in the left sidebar among the other Observability views.',
@@ -31,9 +31,9 @@ export function ClientSideMonitoringCallout() {
)}
-
+
{i18n.translate(
- 'xpack.apm.transactionOverview.clientSideMonitoring.linkLabel',
+ 'xpack.apm.transactionOverview.userExperience.linkLabel',
{ defaultMessage: 'Take me there' }
)}
diff --git a/x-pack/plugins/apm/public/components/shared/Stacktrace/FrameHeading.tsx b/x-pack/plugins/apm/public/components/shared/Stacktrace/FrameHeading.tsx
index dfeb537b0486..6632b22b5996 100644
--- a/x-pack/plugins/apm/public/components/shared/Stacktrace/FrameHeading.tsx
+++ b/x-pack/plugins/apm/public/components/shared/Stacktrace/FrameHeading.tsx
@@ -27,10 +27,12 @@ const FileDetails = styled.div`
const LibraryFrameFileDetail = styled.span`
color: ${({ theme }) => theme.eui.euiColorDarkShade};
+ word-break: break-word;
`;
const AppFrameFileDetail = styled.span`
color: ${({ theme }) => theme.eui.euiColorFullShade};
+ word-break: break-word;
`;
interface Props {
diff --git a/x-pack/plugins/apm/scripts/kibana-security/setup-custom-kibana-user-role.ts b/x-pack/plugins/apm/scripts/kibana-security/setup-custom-kibana-user-role.ts
index b0083da69cf8..cf17c9dbbf2e 100644
--- a/x-pack/plugins/apm/scripts/kibana-security/setup-custom-kibana-user-role.ts
+++ b/x-pack/plugins/apm/scripts/kibana-security/setup-custom-kibana-user-role.ts
@@ -122,11 +122,69 @@ async function init() {
});
await createRole({
roleName: KIBANA_READ_ROLE,
- kibanaPrivileges: { base: ['read'] },
+ kibanaPrivileges: {
+ feature: {
+ // core
+ discover: ['read'],
+ dashboard: ['read'],
+ canvas: ['read'],
+ ml: ['read'],
+ maps: ['read'],
+ graph: ['read'],
+ visualize: ['read'],
+
+ // observability
+ logs: ['read'],
+ infrastructure: ['read'],
+ apm: ['read'],
+ uptime: ['read'],
+
+ // security
+ siem: ['read'],
+
+ // management
+ dev_tools: ['read'],
+ advancedSettings: ['read'],
+ indexPatterns: ['read'],
+ savedObjectsManagement: ['read'],
+ stackAlerts: ['read'],
+ ingestManager: ['read'],
+ actions: ['read'],
+ },
+ },
});
await createRole({
roleName: KIBANA_WRITE_ROLE,
- kibanaPrivileges: { base: ['all'] },
+ kibanaPrivileges: {
+ feature: {
+ // core
+ discover: ['all'],
+ dashboard: ['all'],
+ canvas: ['all'],
+ ml: ['all'],
+ maps: ['all'],
+ graph: ['all'],
+ visualize: ['all'],
+
+ // observability
+ logs: ['all'],
+ infrastructure: ['all'],
+ apm: ['all'],
+ uptime: ['all'],
+
+ // security
+ siem: ['all'],
+
+ // management
+ dev_tools: ['all'],
+ advancedSettings: ['all'],
+ indexPatterns: ['all'],
+ savedObjectsManagement: ['all'],
+ stackAlerts: ['all'],
+ ingestManager: ['all'],
+ actions: ['all'],
+ },
+ },
});
// read access only to APM + apm index access
diff --git a/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/API.md b/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/API.md
deleted file mode 100644
index cd3927b4b9df..000000000000
--- a/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/API.md
+++ /dev/null
@@ -1,1498 +0,0 @@
-# Flot Reference #
-
-**Table of Contents**
-
-[Introduction](#introduction)
-| [Data Format](#data-format)
-| [Plot Options](#plot-options)
-| [Customizing the legend](#customizing-the-legend)
-| [Customizing the axes](#customizing-the-axes)
-| [Multiple axes](#multiple-axes)
-| [Time series data](#time-series-data)
-| [Customizing the data series](#customizing-the-data-series)
-| [Customizing the grid](#customizing-the-grid)
-| [Specifying gradients](#specifying-gradients)
-| [Plot Methods](#plot-methods)
-| [Hooks](#hooks)
-| [Plugins](#plugins)
-| [Version number](#version-number)
-
----
-
-## Introduction ##
-
-Consider a call to the plot function:
-
-```js
-var plot = $.plot(placeholder, data, options)
-```
-
-The placeholder is a jQuery object or DOM element or jQuery expression
-that the plot will be put into. This placeholder needs to have its
-width and height set as explained in the [README](README.md) (go read that now if
-you haven't, it's short). The plot will modify some properties of the
-placeholder so it's recommended you simply pass in a div that you
-don't use for anything else. Make sure you check any fancy styling
-you apply to the div, e.g. background images have been reported to be a
-problem on IE 7.
-
-The plot function can also be used as a jQuery chainable property. This form
-naturally can't return the plot object directly, but you can still access it
-via the 'plot' data key, like this:
-
-```js
-var plot = $("#placeholder").plot(data, options).data("plot");
-```
-
-The format of the data is documented below, as is the available
-options. The plot object returned from the call has some methods you
-can call. These are documented separately below.
-
-Note that in general Flot gives no guarantees if you change any of the
-objects you pass in to the plot function or get out of it since
-they're not necessarily deep-copied.
-
-
-## Data Format ##
-
-The data is an array of data series:
-
-```js
-[ series1, series2, ... ]
-```
-
-A series can either be raw data or an object with properties. The raw
-data format is an array of points:
-
-```js
-[ [x1, y1], [x2, y2], ... ]
-```
-
-E.g.
-
-```js
-[ [1, 3], [2, 14.01], [3.5, 3.14] ]
-```
-
-Note that to simplify the internal logic in Flot both the x and y
-values must be numbers (even if specifying time series, see below for
-how to do this). This is a common problem because you might retrieve
-data from the database and serialize them directly to JSON without
-noticing the wrong type. If you're getting mysterious errors, double
-check that you're inputting numbers and not strings.
-
-If a null is specified as a point or if one of the coordinates is null
-or couldn't be converted to a number, the point is ignored when
-drawing. As a special case, a null value for lines is interpreted as a
-line segment end, i.e. the points before and after the null value are
-not connected.
-
-Lines and points take two coordinates. For filled lines and bars, you
-can specify a third coordinate which is the bottom of the filled
-area/bar (defaults to 0).
-
-The format of a single series object is as follows:
-
-```js
-{
- color: color or number
- data: rawdata
- label: string
- lines: specific lines options
- bars: specific bars options
- points: specific points options
- xaxis: number
- yaxis: number
- clickable: boolean
- hoverable: boolean
- shadowSize: number
- highlightColor: color or number
-}
-```
-
-You don't have to specify any of them except the data, the rest are
-options that will get default values. Typically you'd only specify
-label and data, like this:
-
-```js
-{
- label: "y = 3",
- data: [[0, 3], [10, 3]]
-}
-```
-
-The label is used for the legend, if you don't specify one, the series
-will not show up in the legend.
-
-If you don't specify color, the series will get a color from the
-auto-generated colors. The color is either a CSS color specification
-(like "rgb(255, 100, 123)") or an integer that specifies which of
-auto-generated colors to select, e.g. 0 will get color no. 0, etc.
-
-The latter is mostly useful if you let the user add and remove series,
-in which case you can hard-code the color index to prevent the colors
-from jumping around between the series.
-
-The "xaxis" and "yaxis" options specify which axis to use. The axes
-are numbered from 1 (default), so { yaxis: 2} means that the series
-should be plotted against the second y axis.
-
-"clickable" and "hoverable" can be set to false to disable
-interactivity for specific series if interactivity is turned on in
-the plot, see below.
-
-The rest of the options are all documented below as they are the same
-as the default options passed in via the options parameter in the plot
-command. When you specify them for a specific data series, they will
-override the default options for the plot for that data series.
-
-Here's a complete example of a simple data specification:
-
-```js
-[ { label: "Foo", data: [ [10, 1], [17, -14], [30, 5] ] },
- { label: "Bar", data: [ [11, 13], [19, 11], [30, -7] ] }
-]
-```
-
-
-## Plot Options ##
-
-All options are completely optional. They are documented individually
-below, to change them you just specify them in an object, e.g.
-
-```js
-var options = {
- series: {
- lines: { show: true },
- points: { show: true }
- }
-};
-
-$.plot(placeholder, data, options);
-```
-
-
-## Customizing the legend ##
-
-```js
-legend: {
- show: boolean
- labelFormatter: null or (fn: string, series object -> string)
- labelBoxBorderColor: color
- noColumns: number
- position: "ne" or "nw" or "se" or "sw"
- margin: number of pixels or [x margin, y margin]
- backgroundColor: null or color
- backgroundOpacity: number between 0 and 1
- container: null or jQuery object/DOM element/jQuery expression
- sorted: null/false, true, "ascending", "descending", "reverse", or a comparator
-}
-```
-
-The legend is generated as a table with the data series labels and
-small label boxes with the color of the series. If you want to format
-the labels in some way, e.g. make them to links, you can pass in a
-function for "labelFormatter". Here's an example that makes them
-clickable:
-
-```js
-labelFormatter: function(label, series) {
- // series is the series object for the label
- return '' + label + '';
-}
-```
-
-To prevent a series from showing up in the legend, simply have the function
-return null.
-
-"noColumns" is the number of columns to divide the legend table into.
-"position" specifies the overall placement of the legend within the
-plot (top-right, top-left, etc.) and margin the distance to the plot
-edge (this can be either a number or an array of two numbers like [x,
-y]). "backgroundColor" and "backgroundOpacity" specifies the
-background. The default is a partly transparent auto-detected
-background.
-
-If you want the legend to appear somewhere else in the DOM, you can
-specify "container" as a jQuery object/expression to put the legend
-table into. The "position" and "margin" etc. options will then be
-ignored. Note that Flot will overwrite the contents of the container.
-
-Legend entries appear in the same order as their series by default. If "sorted"
-is "reverse" then they appear in the opposite order from their series. To sort
-them alphabetically, you can specify true, "ascending" or "descending", where
-true and "ascending" are equivalent.
-
-You can also provide your own comparator function that accepts two
-objects with "label" and "color" properties, and returns zero if they
-are equal, a positive value if the first is greater than the second,
-and a negative value if the first is less than the second.
-
-```js
-sorted: function(a, b) {
- // sort alphabetically in ascending order
- return a.label == b.label ? 0 : (
- a.label > b.label ? 1 : -1
- )
-}
-```
-
-
-## Customizing the axes ##
-
-```js
-xaxis, yaxis: {
- show: null or true/false
- position: "bottom" or "top" or "left" or "right"
- mode: null or "time" ("time" requires jquery.flot.time.js plugin)
- timezone: null, "browser" or timezone (only makes sense for mode: "time")
-
- color: null or color spec
- tickColor: null or color spec
- font: null or font spec object
-
- min: null or number
- max: null or number
- autoscaleMargin: null or number
-
- transform: null or fn: number -> number
- inverseTransform: null or fn: number -> number
-
- ticks: null or number or ticks array or (fn: axis -> ticks array)
- tickSize: number or array
- minTickSize: number or array
- tickFormatter: (fn: number, object -> string) or string
- tickDecimals: null or number
-
- labelWidth: null or number
- labelHeight: null or number
- reserveSpace: null or true
-
- tickLength: null or number
-
- alignTicksWithAxis: null or number
-}
-```
-
-All axes have the same kind of options. The following describes how to
-configure one axis, see below for what to do if you've got more than
-one x axis or y axis.
-
-If you don't set the "show" option (i.e. it is null), visibility is
-auto-detected, i.e. the axis will show up if there's data associated
-with it. You can override this by setting the "show" option to true or
-false.
-
-The "position" option specifies where the axis is placed, bottom or
-top for x axes, left or right for y axes. The "mode" option determines
-how the data is interpreted, the default of null means as decimal
-numbers. Use "time" for time series data; see the time series data
-section. The time plugin (jquery.flot.time.js) is required for time
-series support.
-
-The "color" option determines the color of the line and ticks for the axis, and
-defaults to the grid color with transparency. For more fine-grained control you
-can also set the color of the ticks separately with "tickColor".
-
-You can customize the font and color used to draw the axis tick labels with CSS
-or directly via the "font" option. When "font" is null - the default - each
-tick label is given the 'flot-tick-label' class. For compatibility with Flot
-0.7 and earlier the labels are also given the 'tickLabel' class, but this is
-deprecated and scheduled to be removed with the release of version 1.0.0.
-
-To enable more granular control over styles, labels are divided between a set
-of text containers, with each holding the labels for one axis. These containers
-are given the classes 'flot-[x|y]-axis', and 'flot-[x|y]#-axis', where '#' is
-the number of the axis when there are multiple axes. For example, the x-axis
-labels for a simple plot with only a single x-axis might look like this:
-
-```html
-
-```
-
-For direct control over label styles you can also provide "font" as an object
-with this format:
-
-```js
-{
- size: 11,
- lineHeight: 13,
- style: "italic",
- weight: "bold",
- family: "sans-serif",
- variant: "small-caps",
- color: "#545454"
-}
-```
-
-The size and lineHeight must be expressed in pixels; CSS units such as 'em'
-or 'smaller' are not allowed.
-
-The options "min"/"max" are the precise minimum/maximum value on the
-scale. If you don't specify either of them, a value will automatically
-be chosen based on the minimum/maximum data values. Note that Flot
-always examines all the data values you feed to it, even if a
-restriction on another axis may make some of them invisible (this
-makes interactive use more stable).
-
-The "autoscaleMargin" is a bit esoteric: it's the fraction of margin
-that the scaling algorithm will add to avoid that the outermost points
-ends up on the grid border. Note that this margin is only applied when
-a min or max value is not explicitly set. If a margin is specified,
-the plot will furthermore extend the axis end-point to the nearest
-whole tick. The default value is "null" for the x axes and 0.02 for y
-axes which seems appropriate for most cases.
-
-"transform" and "inverseTransform" are callbacks you can put in to
-change the way the data is drawn. You can design a function to
-compress or expand certain parts of the axis non-linearly, e.g.
-suppress weekends or compress far away points with a logarithm or some
-other means. When Flot draws the plot, each value is first put through
-the transform function. Here's an example, the x axis can be turned
-into a natural logarithm axis with the following code:
-
-```js
-xaxis: {
- transform: function (v) { return Math.log(v); },
- inverseTransform: function (v) { return Math.exp(v); }
-}
-```
-
-Similarly, for reversing the y axis so the values appear in inverse
-order:
-
-```js
-yaxis: {
- transform: function (v) { return -v; },
- inverseTransform: function (v) { return -v; }
-}
-```
-
-Note that for finding extrema, Flot assumes that the transform
-function does not reorder values (it should be monotone).
-
-The inverseTransform is simply the inverse of the transform function
-(so v == inverseTransform(transform(v)) for all relevant v). It is
-required for converting from canvas coordinates to data coordinates,
-e.g. for a mouse interaction where a certain pixel is clicked. If you
-don't use any interactive features of Flot, you may not need it.
-
-
-The rest of the options deal with the ticks.
-
-If you don't specify any ticks, a tick generator algorithm will make
-some for you. The algorithm has two passes. It first estimates how
-many ticks would be reasonable and uses this number to compute a nice
-round tick interval size. Then it generates the ticks.
-
-You can specify how many ticks the algorithm aims for by setting
-"ticks" to a number. The algorithm always tries to generate reasonably
-round tick values so even if you ask for three ticks, you might get
-five if that fits better with the rounding. If you don't want any
-ticks at all, set "ticks" to 0 or an empty array.
-
-Another option is to skip the rounding part and directly set the tick
-interval size with "tickSize". If you set it to 2, you'll get ticks at
-2, 4, 6, etc. Alternatively, you can specify that you just don't want
-ticks at a size less than a specific tick size with "minTickSize".
-Note that for time series, the format is an array like [2, "month"],
-see the next section.
-
-If you want to completely override the tick algorithm, you can specify
-an array for "ticks", either like this:
-
-```js
-ticks: [0, 1.2, 2.4]
-```
-
-Or like this where the labels are also customized:
-
-```js
-ticks: [[0, "zero"], [1.2, "one mark"], [2.4, "two marks"]]
-```
-
-You can mix the two if you like.
-
-For extra flexibility you can specify a function as the "ticks"
-parameter. The function will be called with an object with the axis
-min and max and should return a ticks array. Here's a simplistic tick
-generator that spits out intervals of pi, suitable for use on the x
-axis for trigonometric functions:
-
-```js
-function piTickGenerator(axis) {
- var res = [], i = Math.floor(axis.min / Math.PI);
- do {
- var v = i * Math.PI;
- res.push([v, i + "\u03c0"]);
- ++i;
- } while (v < axis.max);
- return res;
-}
-```
-
-You can control how the ticks look like with "tickDecimals", the
-number of decimals to display (default is auto-detected).
-
-Alternatively, for ultimate control over how ticks are formatted you can
-provide a function to "tickFormatter". The function is passed two
-parameters, the tick value and an axis object with information, and
-should return a string. The default formatter looks like this:
-
-```js
-function formatter(val, axis) {
- return val.toFixed(axis.tickDecimals);
-}
-```
-
-The axis object has "min" and "max" with the range of the axis,
-"tickDecimals" with the number of decimals to round the value to and
-"tickSize" with the size of the interval between ticks as calculated
-by the automatic axis scaling algorithm (or specified by you). Here's
-an example of a custom formatter:
-
-```js
-function suffixFormatter(val, axis) {
- if (val > 1000000)
- return (val / 1000000).toFixed(axis.tickDecimals) + " MB";
- else if (val > 1000)
- return (val / 1000).toFixed(axis.tickDecimals) + " kB";
- else
- return val.toFixed(axis.tickDecimals) + " B";
-}
-```
-
-"labelWidth" and "labelHeight" specifies a fixed size of the tick
-labels in pixels. They're useful in case you need to align several
-plots. "reserveSpace" means that even if an axis isn't shown, Flot
-should reserve space for it - it is useful in combination with
-labelWidth and labelHeight for aligning multi-axis charts.
-
-"tickLength" is the length of the tick lines in pixels. By default, the
-innermost axes will have ticks that extend all across the plot, while
-any extra axes use small ticks. A value of null means use the default,
-while a number means small ticks of that length - set it to 0 to hide
-the lines completely.
-
-If you set "alignTicksWithAxis" to the number of another axis, e.g.
-alignTicksWithAxis: 1, Flot will ensure that the autogenerated ticks
-of this axis are aligned with the ticks of the other axis. This may
-improve the looks, e.g. if you have one y axis to the left and one to
-the right, because the grid lines will then match the ticks in both
-ends. The trade-off is that the forced ticks won't necessarily be at
-natural places.
-
-
-## Multiple axes ##
-
-If you need more than one x axis or y axis, you need to specify for
-each data series which axis they are to use, as described under the
-format of the data series, e.g. { data: [...], yaxis: 2 } specifies
-that a series should be plotted against the second y axis.
-
-To actually configure that axis, you can't use the xaxis/yaxis options
-directly - instead there are two arrays in the options:
-
-```js
-xaxes: []
-yaxes: []
-```
-
-Here's an example of configuring a single x axis and two y axes (we
-can leave options of the first y axis empty as the defaults are fine):
-
-```js
-{
- xaxes: [ { position: "top" } ],
- yaxes: [ { }, { position: "right", min: 20 } ]
-}
-```
-
-The arrays get their default values from the xaxis/yaxis settings, so
-say you want to have all y axes start at zero, you can simply specify
-yaxis: { min: 0 } instead of adding a min parameter to all the axes.
-
-Generally, the various interfaces in Flot dealing with data points
-either accept an xaxis/yaxis parameter to specify which axis number to
-use (starting from 1), or lets you specify the coordinate directly as
-x2/x3/... or x2axis/x3axis/... instead of "x" or "xaxis".
-
-
-## Time series data ##
-
-Please note that it is now required to include the time plugin,
-jquery.flot.time.js, for time series support.
-
-Time series are a bit more difficult than scalar data because
-calendars don't follow a simple base 10 system. For many cases, Flot
-abstracts most of this away, but it can still be a bit difficult to
-get the data into Flot. So we'll first discuss the data format.
-
-The time series support in Flot is based on Javascript timestamps,
-i.e. everywhere a time value is expected or handed over, a Javascript
-timestamp number is used. This is a number, not a Date object. A
-Javascript timestamp is the number of milliseconds since January 1,
-1970 00:00:00 UTC. This is almost the same as Unix timestamps, except it's
-in milliseconds, so remember to multiply by 1000!
-
-You can see a timestamp like this
-
-```js
-alert((new Date()).getTime())
-```
-
-There are different schools of thought when it comes to display of
-timestamps. Many will want the timestamps to be displayed according to
-a certain time zone, usually the time zone in which the data has been
-produced. Some want the localized experience, where the timestamps are
-displayed according to the local time of the visitor. Flot supports
-both. Optionally you can include a third-party library to get
-additional timezone support.
-
-Default behavior is that Flot always displays timestamps according to
-UTC. The reason being that the core Javascript Date object does not
-support other fixed time zones. Often your data is at another time
-zone, so it may take a little bit of tweaking to work around this
-limitation.
-
-The easiest way to think about it is to pretend that the data
-production time zone is UTC, even if it isn't. So if you have a
-datapoint at 2002-02-20 08:00, you can generate a timestamp for eight
-o'clock UTC even if it really happened eight o'clock UTC+0200.
-
-In PHP you can get an appropriate timestamp with:
-
-```php
-strtotime("2002-02-20 UTC") * 1000
-```
-
-In Python you can get it with something like:
-
-```python
-calendar.timegm(datetime_object.timetuple()) * 1000
-```
-In Ruby you can get it using the `#to_i` method on the
-[`Time`](http://apidock.com/ruby/Time/to_i) object. If you're using the
-`active_support` gem (default for Ruby on Rails applications) `#to_i` is also
-available on the `DateTime` and `ActiveSupport::TimeWithZone` objects. You
-simply need to multiply the result by 1000:
-
-```ruby
-Time.now.to_i * 1000 # => 1383582043000
-# ActiveSupport examples:
-DateTime.now.to_i * 1000 # => 1383582043000
-ActiveSupport::TimeZone.new('Asia/Shanghai').now.to_i * 1000
-# => 1383582043000
-```
-
-In .NET you can get it with something like:
-
-```aspx
-public static int GetJavascriptTimestamp(System.DateTime input)
-{
- System.TimeSpan span = new System.TimeSpan(System.DateTime.Parse("1/1/1970").Ticks);
- System.DateTime time = input.Subtract(span);
- return (long)(time.Ticks / 10000);
-}
-```
-
-Javascript also has some support for parsing date strings, so it is
-possible to generate the timestamps manually client-side.
-
-If you've already got the real UTC timestamp, it's too late to use the
-pretend trick described above. But you can fix up the timestamps by
-adding the time zone offset, e.g. for UTC+0200 you would add 2 hours
-to the UTC timestamp you got. Then it'll look right on the plot. Most
-programming environments have some means of getting the timezone
-offset for a specific date (note that you need to get the offset for
-each individual timestamp to account for daylight savings).
-
-The alternative with core Javascript is to interpret the timestamps
-according to the time zone that the visitor is in, which means that
-the ticks will shift with the time zone and daylight savings of each
-visitor. This behavior is enabled by setting the axis option
-"timezone" to the value "browser".
-
-If you need more time zone functionality than this, there is still
-another option. If you include the "timezone-js" library
- in the page and set axis.timezone
-to a value recognized by said library, Flot will use timezone-js to
-interpret the timestamps according to that time zone.
-
-Once you've gotten the timestamps into the data and specified "time"
-as the axis mode, Flot will automatically generate relevant ticks and
-format them. As always, you can tweak the ticks via the "ticks" option
-- just remember that the values should be timestamps (numbers), not
-Date objects.
-
-Tick generation and formatting can also be controlled separately
-through the following axis options:
-
-```js
-minTickSize: array
-timeformat: null or format string
-monthNames: null or array of size 12 of strings
-dayNames: null or array of size 7 of strings
-twelveHourClock: boolean
-```
-
-Here "timeformat" is a format string to use. You might use it like
-this:
-
-```js
-xaxis: {
- mode: "time",
- timeformat: "%Y/%m/%d"
-}
-```
-
-This will result in tick labels like "2000/12/24". A subset of the
-standard strftime specifiers are supported (plus the nonstandard %q):
-
-```js
-%a: weekday name (customizable)
-%b: month name (customizable)
-%d: day of month, zero-padded (01-31)
-%e: day of month, space-padded ( 1-31)
-%H: hours, 24-hour time, zero-padded (00-23)
-%I: hours, 12-hour time, zero-padded (01-12)
-%m: month, zero-padded (01-12)
-%M: minutes, zero-padded (00-59)
-%q: quarter (1-4)
-%S: seconds, zero-padded (00-59)
-%y: year (two digits)
-%Y: year (four digits)
-%p: am/pm
-%P: AM/PM (uppercase version of %p)
-%w: weekday as number (0-6, 0 being Sunday)
-```
-
-Flot 0.8 switched from %h to the standard %H hours specifier. The %h specifier
-is still available, for backwards-compatibility, but is deprecated and
-scheduled to be removed permanently with the release of version 1.0.
-
-You can customize the month names with the "monthNames" option. For
-instance, for Danish you might specify:
-
-```js
-monthNames: ["jan", "feb", "mar", "apr", "maj", "jun", "jul", "aug", "sep", "okt", "nov", "dec"]
-```
-
-Similarly you can customize the weekday names with the "dayNames"
-option. An example in French:
-
-```js
-dayNames: ["dim", "lun", "mar", "mer", "jeu", "ven", "sam"]
-```
-
-If you set "twelveHourClock" to true, the autogenerated timestamps
-will use 12 hour AM/PM timestamps instead of 24 hour. This only
-applies if you have not set "timeformat". Use the "%I" and "%p" or
-"%P" options if you want to build your own format string with 12-hour
-times.
-
-If the Date object has a strftime property (and it is a function), it
-will be used instead of the built-in formatter. Thus you can include
-a strftime library such as http://hacks.bluesmoon.info/strftime/ for
-more powerful date/time formatting.
-
-If everything else fails, you can control the formatting by specifying
-a custom tick formatter function as usual. Here's a simple example
-which will format December 24 as 24/12:
-
-```js
-tickFormatter: function (val, axis) {
- var d = new Date(val);
- return d.getUTCDate() + "/" + (d.getUTCMonth() + 1);
-}
-```
-
-Note that for the time mode "tickSize" and "minTickSize" are a bit
-special in that they are arrays on the form "[value, unit]" where unit
-is one of "second", "minute", "hour", "day", "month" and "year". So
-you can specify
-
-```js
-minTickSize: [1, "month"]
-```
-
-to get a tick interval size of at least 1 month and correspondingly,
-if axis.tickSize is [2, "day"] in the tick formatter, the ticks have
-been produced with two days in-between.
-
-
-## Customizing the data series ##
-
-```js
-series: {
- lines, points, bars: {
- show: boolean
- lineWidth: number
- fill: boolean or number
- fillColor: null or color/gradient
- }
-
- lines, bars: {
- zero: boolean
- }
-
- points: {
- radius: number
- symbol: "circle" or function
- }
-
- bars: {
- barWidth: number
- align: "left", "right" or "center"
- horizontal: boolean
- }
-
- lines: {
- steps: boolean
- }
-
- shadowSize: number
- highlightColor: color or number
-}
-
-colors: [ color1, color2, ... ]
-```
-
-The options inside "series: {}" are copied to each of the series. So
-you can specify that all series should have bars by putting it in the
-global options, or override it for individual series by specifying
-bars in a particular the series object in the array of data.
-
-The most important options are "lines", "points" and "bars" that
-specify whether and how lines, points and bars should be shown for
-each data series. In case you don't specify anything at all, Flot will
-default to showing lines (you can turn this off with
-lines: { show: false }). You can specify the various types
-independently of each other, and Flot will happily draw each of them
-in turn (this is probably only useful for lines and points), e.g.
-
-```js
-var options = {
- series: {
- lines: { show: true, fill: true, fillColor: "rgba(255, 255, 255, 0.8)" },
- points: { show: true, fill: false }
- }
-};
-```
-
-"lineWidth" is the thickness of the line or outline in pixels. You can
-set it to 0 to prevent a line or outline from being drawn; this will
-also hide the shadow.
-
-"fill" is whether the shape should be filled. For lines, this produces
-area graphs. You can use "fillColor" to specify the color of the fill.
-If "fillColor" evaluates to false (default for everything except
-points which are filled with white), the fill color is auto-set to the
-color of the data series. You can adjust the opacity of the fill by
-setting fill to a number between 0 (fully transparent) and 1 (fully
-opaque).
-
-For bars, fillColor can be a gradient, see the gradient documentation
-below. "barWidth" is the width of the bars in units of the x axis (or
-the y axis if "horizontal" is true), contrary to most other measures
-that are specified in pixels. For instance, for time series the unit
-is milliseconds so 24 * 60 * 60 * 1000 produces bars with the width of
-a day. "align" specifies whether a bar should be left-aligned
-(default), right-aligned or centered on top of the value it represents.
-When "horizontal" is on, the bars are drawn horizontally, i.e. from the
-y axis instead of the x axis; note that the bar end points are still
-defined in the same way so you'll probably want to swap the
-coordinates if you've been plotting vertical bars first.
-
-Area and bar charts normally start from zero, regardless of the data's range.
-This is because they convey information through size, and starting from a
-different value would distort their meaning. In cases where the fill is purely
-for decorative purposes, however, "zero" allows you to override this behavior.
-It defaults to true for filled lines and bars; setting it to false tells the
-series to use the same automatic scaling as an un-filled line.
-
-For lines, "steps" specifies whether two adjacent data points are
-connected with a straight (possibly diagonal) line or with first a
-horizontal and then a vertical line. Note that this transforms the
-data by adding extra points.
-
-For points, you can specify the radius and the symbol. The only
-built-in symbol type is circles, for other types you can use a plugin
-or define them yourself by specifying a callback:
-
-```js
-function cross(ctx, x, y, radius, shadow) {
- var size = radius * Math.sqrt(Math.PI) / 2;
- ctx.moveTo(x - size, y - size);
- ctx.lineTo(x + size, y + size);
- ctx.moveTo(x - size, y + size);
- ctx.lineTo(x + size, y - size);
-}
-```
-
-The parameters are the drawing context, x and y coordinates of the
-center of the point, a radius which corresponds to what the circle
-would have used and whether the call is to draw a shadow (due to
-limited canvas support, shadows are currently faked through extra
-draws). It's good practice to ensure that the area covered by the
-symbol is the same as for the circle with the given radius, this
-ensures that all symbols have approximately the same visual weight.
-
-"shadowSize" is the default size of shadows in pixels. Set it to 0 to
-remove shadows.
-
-"highlightColor" is the default color of the translucent overlay used
-to highlight the series when the mouse hovers over it.
-
-The "colors" array specifies a default color theme to get colors for
-the data series from. You can specify as many colors as you like, like
-this:
-
-```js
-colors: ["#d18b2c", "#dba255", "#919733"]
-```
-
-If there are more data series than colors, Flot will try to generate
-extra colors by lightening and darkening colors in the theme.
-
-
-## Customizing the grid ##
-
-```js
-grid: {
- show: boolean
- aboveData: boolean
- color: color
- backgroundColor: color/gradient or null
- margin: number or margin object
- labelMargin: number
- axisMargin: number
- markings: array of markings or (fn: axes -> array of markings)
- borderWidth: number or object with "top", "right", "bottom" and "left" properties with different widths
- borderColor: color or null or object with "top", "right", "bottom" and "left" properties with different colors
- minBorderMargin: number or null
- clickable: boolean
- hoverable: boolean
- autoHighlight: boolean
- mouseActiveRadius: number
-}
-
-interaction: {
- redrawOverlayInterval: number or -1
-}
-```
-
-The grid is the thing with the axes and a number of ticks. Many of the
-things in the grid are configured under the individual axes, but not
-all. "color" is the color of the grid itself whereas "backgroundColor"
-specifies the background color inside the grid area, here null means
-that the background is transparent. You can also set a gradient, see
-the gradient documentation below.
-
-You can turn off the whole grid including tick labels by setting
-"show" to false. "aboveData" determines whether the grid is drawn
-above the data or below (below is default).
-
-"margin" is the space in pixels between the canvas edge and the grid,
-which can be either a number or an object with individual margins for
-each side, in the form:
-
-```js
-margin: {
- top: top margin in pixels
- left: left margin in pixels
- bottom: bottom margin in pixels
- right: right margin in pixels
-}
-```
-
-"labelMargin" is the space in pixels between tick labels and axis
-line, and "axisMargin" is the space in pixels between axes when there
-are two next to each other.
-
-"borderWidth" is the width of the border around the plot. Set it to 0
-to disable the border. Set it to an object with "top", "right",
-"bottom" and "left" properties to use different widths. You can
-also set "borderColor" if you want the border to have a different color
-than the grid lines. Set it to an object with "top", "right", "bottom"
-and "left" properties to use different colors. "minBorderMargin" controls
-the default minimum margin around the border - it's used to make sure
-that points aren't accidentally clipped by the canvas edge so by default
-the value is computed from the point radius.
-
-"markings" is used to draw simple lines and rectangular areas in the
-background of the plot. You can either specify an array of ranges on
-the form { xaxis: { from, to }, yaxis: { from, to } } (with multiple
-axes, you can specify coordinates for other axes instead, e.g. as
-x2axis/x3axis/...) or with a function that returns such an array given
-the axes for the plot in an object as the first parameter.
-
-You can set the color of markings by specifying "color" in the ranges
-object. Here's an example array:
-
-```js
-markings: [ { xaxis: { from: 0, to: 2 }, yaxis: { from: 10, to: 10 }, color: "#bb0000" }, ... ]
-```
-
-If you leave out one of the values, that value is assumed to go to the
-border of the plot. So for example if you only specify { xaxis: {
-from: 0, to: 2 } } it means an area that extends from the top to the
-bottom of the plot in the x range 0-2.
-
-A line is drawn if from and to are the same, e.g.
-
-```js
-markings: [ { yaxis: { from: 1, to: 1 } }, ... ]
-```
-
-would draw a line parallel to the x axis at y = 1. You can control the
-line width with "lineWidth" in the range object.
-
-An example function that makes vertical stripes might look like this:
-
-```js
-markings: function (axes) {
- var markings = [];
- for (var x = Math.floor(axes.xaxis.min); x < axes.xaxis.max; x += 2)
- markings.push({ xaxis: { from: x, to: x + 1 } });
- return markings;
-}
-```
-
-If you set "clickable" to true, the plot will listen for click events
-on the plot area and fire a "plotclick" event on the placeholder with
-a position and a nearby data item object as parameters. The coordinates
-are available both in the unit of the axes (not in pixels) and in
-global screen coordinates.
-
-Likewise, if you set "hoverable" to true, the plot will listen for
-mouse move events on the plot area and fire a "plothover" event with
-the same parameters as the "plotclick" event. If "autoHighlight" is
-true (the default), nearby data items are highlighted automatically.
-If needed, you can disable highlighting and control it yourself with
-the highlight/unhighlight plot methods described elsewhere.
-
-You can use "plotclick" and "plothover" events like this:
-
-```js
-$.plot($("#placeholder"), [ d ], { grid: { clickable: true } });
-
-$("#placeholder").bind("plotclick", function (event, pos, item) {
- alert("You clicked at " + pos.x + ", " + pos.y);
- // axis coordinates for other axes, if present, are in pos.x2, pos.x3, ...
- // if you need global screen coordinates, they are pos.pageX, pos.pageY
-
- if (item) {
- highlight(item.series, item.datapoint);
- alert("You clicked a point!");
- }
-});
-```
-
-The item object in this example is either null or a nearby object on the form:
-
-```js
-item: {
- datapoint: the point, e.g. [0, 2]
- dataIndex: the index of the point in the data array
- series: the series object
- seriesIndex: the index of the series
- pageX, pageY: the global screen coordinates of the point
-}
-```
-
-For instance, if you have specified the data like this
-
-```js
-$.plot($("#placeholder"), [ { label: "Foo", data: [[0, 10], [7, 3]] } ], ...);
-```
-
-and the mouse is near the point (7, 3), "datapoint" is [7, 3],
-"dataIndex" will be 1, "series" is a normalized series object with
-among other things the "Foo" label in series.label and the color in
-series.color, and "seriesIndex" is 0. Note that plugins and options
-that transform the data can shift the indexes from what you specified
-in the original data array.
-
-If you use the above events to update some other information and want
-to clear out that info in case the mouse goes away, you'll probably
-also need to listen to "mouseout" events on the placeholder div.
-
-"mouseActiveRadius" specifies how far the mouse can be from an item
-and still activate it. If there are two or more points within this
-radius, Flot chooses the closest item. For bars, the top-most bar
-(from the latest specified data series) is chosen.
-
-If you want to disable interactivity for a specific data series, you
-can set "hoverable" and "clickable" to false in the options for that
-series, like this:
-
-```js
-{ data: [...], label: "Foo", clickable: false }
-```
-
-"redrawOverlayInterval" specifies the maximum time to delay a redraw
-of interactive things (this works as a rate limiting device). The
-default is capped to 60 frames per second. You can set it to -1 to
-disable the rate limiting.
-
-
-## Specifying gradients ##
-
-A gradient is specified like this:
-
-```js
-{ colors: [ color1, color2, ... ] }
-```
-
-For instance, you might specify a background on the grid going from
-black to gray like this:
-
-```js
-grid: {
- backgroundColor: { colors: ["#000", "#999"] }
-}
-```
-
-For the series you can specify the gradient as an object that
-specifies the scaling of the brightness and the opacity of the series
-color, e.g.
-
-```js
-{ colors: [{ opacity: 0.8 }, { brightness: 0.6, opacity: 0.8 } ] }
-```
-
-where the first color simply has its alpha scaled, whereas the second
-is also darkened. For instance, for bars the following makes the bars
-gradually disappear, without outline:
-
-```js
-bars: {
- show: true,
- lineWidth: 0,
- fill: true,
- fillColor: { colors: [ { opacity: 0.8 }, { opacity: 0.1 } ] }
-}
-```
-
-Flot currently only supports vertical gradients drawn from top to
-bottom because that's what works with IE.
-
-
-## Plot Methods ##
-
-The Plot object returned from the plot function has some methods you
-can call:
-
- - highlight(series, datapoint)
-
- Highlight a specific datapoint in the data series. You can either
- specify the actual objects, e.g. if you got them from a
- "plotclick" event, or you can specify the indices, e.g.
- highlight(1, 3) to highlight the fourth point in the second series
- (remember, zero-based indexing).
-
- - unhighlight(series, datapoint) or unhighlight()
-
- Remove the highlighting of the point, same parameters as
- highlight.
-
- If you call unhighlight with no parameters, e.g. as
- plot.unhighlight(), all current highlights are removed.
-
- - setData(data)
-
- You can use this to reset the data used. Note that axis scaling,
- ticks, legend etc. will not be recomputed (use setupGrid() to do
- that). You'll probably want to call draw() afterwards.
-
- You can use this function to speed up redrawing a small plot if
- you know that the axes won't change. Put in the new data with
- setData(newdata), call draw(), and you're good to go. Note that
- for large datasets, almost all the time is consumed in draw()
- plotting the data so in this case don't bother.
-
- - setupGrid()
-
- Recalculate and set axis scaling, ticks, legend etc.
-
- Note that because of the drawing model of the canvas, this
- function will immediately redraw (actually reinsert in the DOM)
- the labels and the legend, but not the actual tick lines because
- they're drawn on the canvas. You need to call draw() to get the
- canvas redrawn.
-
- - draw()
-
- Redraws the plot canvas.
-
- - triggerRedrawOverlay()
-
- Schedules an update of an overlay canvas used for drawing
- interactive things like a selection and point highlights. This
- is mostly useful for writing plugins. The redraw doesn't happen
- immediately, instead a timer is set to catch multiple successive
- redraws (e.g. from a mousemove). You can get to the overlay by
- setting up a drawOverlay hook.
-
- - width()/height()
-
- Gets the width and height of the plotting area inside the grid.
- This is smaller than the canvas or placeholder dimensions as some
- extra space is needed (e.g. for labels).
-
- - offset()
-
- Returns the offset of the plotting area inside the grid relative
- to the document, useful for instance for calculating mouse
- positions (event.pageX/Y minus this offset is the pixel position
- inside the plot).
-
- - pointOffset({ x: xpos, y: ypos })
-
- Returns the calculated offset of the data point at (x, y) in data
- space within the placeholder div. If you are working with multiple
- axes, you can specify the x and y axis references, e.g.
-
- ```js
- o = pointOffset({ x: xpos, y: ypos, xaxis: 2, yaxis: 3 })
- // o.left and o.top now contains the offset within the div
- ````
-
- - resize()
-
- Tells Flot to resize the drawing canvas to the size of the
- placeholder. You need to run setupGrid() and draw() afterwards as
- canvas resizing is a destructive operation. This is used
- internally by the resize plugin.
-
- - shutdown()
-
- Cleans up any event handlers Flot has currently registered. This
- is used internally.
-
-There are also some members that let you peek inside the internal
-workings of Flot which is useful in some cases. Note that if you change
-something in the objects returned, you're changing the objects used by
-Flot to keep track of its state, so be careful.
-
- - getData()
-
- Returns an array of the data series currently used in normalized
- form with missing settings filled in according to the global
- options. So for instance to find out what color Flot has assigned
- to the data series, you could do this:
-
- ```js
- var series = plot.getData();
- for (var i = 0; i < series.length; ++i)
- alert(series[i].color);
- ```
-
- A notable other interesting field besides color is datapoints
- which has a field "points" with the normalized data points in a
- flat array (the field "pointsize" is the increment in the flat
- array to get to the next point so for a dataset consisting only of
- (x,y) pairs it would be 2).
-
- - getAxes()
-
- Gets an object with the axes. The axes are returned as the
- attributes of the object, so for instance getAxes().xaxis is the
- x axis.
-
- Various things are stuffed inside an axis object, e.g. you could
- use getAxes().xaxis.ticks to find out what the ticks are for the
- xaxis. Two other useful attributes are p2c and c2p, functions for
- transforming from data point space to the canvas plot space and
- back. Both returns values that are offset with the plot offset.
- Check the Flot source code for the complete set of attributes (or
- output an axis with console.log() and inspect it).
-
- With multiple axes, the extra axes are returned as x2axis, x3axis,
- etc., e.g. getAxes().y2axis is the second y axis. You can check
- y2axis.used to see whether the axis is associated with any data
- points and y2axis.show to see if it is currently shown.
-
- - getPlaceholder()
-
- Returns placeholder that the plot was put into. This can be useful
- for plugins for adding DOM elements or firing events.
-
- - getCanvas()
-
- Returns the canvas used for drawing in case you need to hack on it
- yourself. You'll probably need to get the plot offset too.
-
- - getPlotOffset()
-
- Gets the offset that the grid has within the canvas as an object
- with distances from the canvas edges as "left", "right", "top",
- "bottom". I.e., if you draw a circle on the canvas with the center
- placed at (left, top), its center will be at the top-most, left
- corner of the grid.
-
- - getOptions()
-
- Gets the options for the plot, normalized, with default values
- filled in. You get a reference to actual values used by Flot, so
- if you modify the values in here, Flot will use the new values.
- If you change something, you probably have to call draw() or
- setupGrid() or triggerRedrawOverlay() to see the change.
-
-
-## Hooks ##
-
-In addition to the public methods, the Plot object also has some hooks
-that can be used to modify the plotting process. You can install a
-callback function at various points in the process, the function then
-gets access to the internal data structures in Flot.
-
-Here's an overview of the phases Flot goes through:
-
- 1. Plugin initialization, parsing options
-
- 2. Constructing the canvases used for drawing
-
- 3. Set data: parsing data specification, calculating colors,
- copying raw data points into internal format,
- normalizing them, finding max/min for axis auto-scaling
-
- 4. Grid setup: calculating axis spacing, ticks, inserting tick
- labels, the legend
-
- 5. Draw: drawing the grid, drawing each of the series in turn
-
- 6. Setting up event handling for interactive features
-
- 7. Responding to events, if any
-
- 8. Shutdown: this mostly happens in case a plot is overwritten
-
-Each hook is simply a function which is put in the appropriate array.
-You can add them through the "hooks" option, and they are also available
-after the plot is constructed as the "hooks" attribute on the returned
-plot object, e.g.
-
-```js
- // define a simple draw hook
- function hellohook(plot, canvascontext) { alert("hello!"); };
-
- // pass it in, in an array since we might want to specify several
- var plot = $.plot(placeholder, data, { hooks: { draw: [hellohook] } });
-
- // we can now find it again in plot.hooks.draw[0] unless a plugin
- // has added other hooks
-```
-
-The available hooks are described below. All hook callbacks get the
-plot object as first parameter. You can find some examples of defined
-hooks in the plugins bundled with Flot.
-
- - processOptions [phase 1]
-
- ```function(plot, options)```
-
- Called after Flot has parsed and merged options. Useful in the
- instance where customizations beyond simple merging of default
- values is needed. A plugin might use it to detect that it has been
- enabled and then turn on or off other options.
-
-
- - processRawData [phase 3]
-
- ```function(plot, series, data, datapoints)```
-
- Called before Flot copies and normalizes the raw data for the given
- series. If the function fills in datapoints.points with normalized
- points and sets datapoints.pointsize to the size of the points,
- Flot will skip the copying/normalization step for this series.
-
- In any case, you might be interested in setting datapoints.format,
- an array of objects for specifying how a point is normalized and
- how it interferes with axis scaling. It accepts the following options:
-
- ```js
- {
- x, y: boolean,
- number: boolean,
- required: boolean,
- defaultValue: value,
- autoscale: boolean
- }
- ```
-
- "x" and "y" specify whether the value is plotted against the x or y axis,
- and is currently used only to calculate axis min-max ranges. The default
- format array, for example, looks like this:
-
- ```js
- [
- { x: true, number: true, required: true },
- { y: true, number: true, required: true }
- ]
- ```
-
- This indicates that a point, i.e. [0, 25], consists of two values, with the
- first being plotted on the x axis and the second on the y axis.
-
- If "number" is true, then the value must be numeric, and is set to null if
- it cannot be converted to a number.
-
- "defaultValue" provides a fallback in case the original value is null. This
- is for instance handy for bars, where one can omit the third coordinate
- (the bottom of the bar), which then defaults to zero.
-
- If "required" is true, then the value must exist (be non-null) for the
- point as a whole to be valid. If no value is provided, then the entire
- point is cleared out with nulls, turning it into a gap in the series.
-
- "autoscale" determines whether the value is considered when calculating an
- automatic min-max range for the axes that the value is plotted against.
-
- - processDatapoints [phase 3]
-
- ```function(plot, series, datapoints)```
-
- Called after normalization of the given series but before finding
- min/max of the data points. This hook is useful for implementing data
- transformations. "datapoints" contains the normalized data points in
- a flat array as datapoints.points with the size of a single point
- given in datapoints.pointsize. Here's a simple transform that
- multiplies all y coordinates by 2:
-
- ```js
- function multiply(plot, series, datapoints) {
- var points = datapoints.points, ps = datapoints.pointsize;
- for (var i = 0; i < points.length; i += ps)
- points[i + 1] *= 2;
- }
- ```
-
- Note that you must leave datapoints in a good condition as Flot
- doesn't check it or do any normalization on it afterwards.
-
- - processOffset [phase 4]
-
- ```function(plot, offset)```
-
- Called after Flot has initialized the plot's offset, but before it
- draws any axes or plot elements. This hook is useful for customizing
- the margins between the grid and the edge of the canvas. "offset" is
- an object with attributes "top", "bottom", "left" and "right",
- corresponding to the margins on the four sides of the plot.
-
- - drawBackground [phase 5]
-
- ```function(plot, canvascontext)```
-
- Called before all other drawing operations. Used to draw backgrounds
- or other custom elements before the plot or axes have been drawn.
-
- - drawSeries [phase 5]
-
- ```function(plot, canvascontext, series)```
-
- Hook for custom drawing of a single series. Called just before the
- standard drawing routine has been called in the loop that draws
- each series.
-
- - draw [phase 5]
-
- ```function(plot, canvascontext)```
-
- Hook for drawing on the canvas. Called after the grid is drawn
- (unless it's disabled or grid.aboveData is set) and the series have
- been plotted (in case any points, lines or bars have been turned
- on). For examples of how to draw things, look at the source code.
-
- - bindEvents [phase 6]
-
- ```function(plot, eventHolder)```
-
- Called after Flot has setup its event handlers. Should set any
- necessary event handlers on eventHolder, a jQuery object with the
- canvas, e.g.
-
- ```js
- function (plot, eventHolder) {
- eventHolder.mousedown(function (e) {
- alert("You pressed the mouse at " + e.pageX + " " + e.pageY);
- });
- }
- ```
-
- Interesting events include click, mousemove, mouseup/down. You can
- use all jQuery events. Usually, the event handlers will update the
- state by drawing something (add a drawOverlay hook and call
- triggerRedrawOverlay) or firing an externally visible event for
- user code. See the crosshair plugin for an example.
-
- Currently, eventHolder actually contains both the static canvas
- used for the plot itself and the overlay canvas used for
- interactive features because some versions of IE get the stacking
- order wrong. The hook only gets one event, though (either for the
- overlay or for the static canvas).
-
- Note that custom plot events generated by Flot are not generated on
- eventHolder, but on the div placeholder supplied as the first
- argument to the plot call. You can get that with
- plot.getPlaceholder() - that's probably also the one you should use
- if you need to fire a custom event.
-
- - drawOverlay [phase 7]
-
- ```function (plot, canvascontext)```
-
- The drawOverlay hook is used for interactive things that need a
- canvas to draw on. The model currently used by Flot works the way
- that an extra overlay canvas is positioned on top of the static
- canvas. This overlay is cleared and then completely redrawn
- whenever something interesting happens. This hook is called when
- the overlay canvas is to be redrawn.
-
- "canvascontext" is the 2D context of the overlay canvas. You can
- use this to draw things. You'll most likely need some of the
- metrics computed by Flot, e.g. plot.width()/plot.height(). See the
- crosshair plugin for an example.
-
- - shutdown [phase 8]
-
- ```function (plot, eventHolder)```
-
- Run when plot.shutdown() is called, which usually only happens in
- case a plot is overwritten by a new plot. If you're writing a
- plugin that adds extra DOM elements or event handlers, you should
- add a callback to clean up after you. Take a look at the section in
- the [PLUGINS](PLUGINS.md) document for more info.
-
-
-## Plugins ##
-
-Plugins extend the functionality of Flot. To use a plugin, simply
-include its Javascript file after Flot in the HTML page.
-
-If you're worried about download size/latency, you can concatenate all
-the plugins you use, and Flot itself for that matter, into one big file
-(make sure you get the order right), then optionally run it through a
-Javascript minifier such as YUI Compressor.
-
-Here's a brief explanation of how the plugin plumbings work:
-
-Each plugin registers itself in the global array $.plot.plugins. When
-you make a new plot object with $.plot, Flot goes through this array
-calling the "init" function of each plugin and merging default options
-from the "option" attribute of the plugin. The init function gets a
-reference to the plot object created and uses this to register hooks
-and add new public methods if needed.
-
-See the [PLUGINS](PLUGINS.md) document for details on how to write a plugin. As the
-above description hints, it's actually pretty easy.
-
-
-## Version number ##
-
-The version number of Flot is available in ```$.plot.version```.
diff --git a/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/index.js b/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/index.js
deleted file mode 100644
index ff3de33b017a..000000000000
--- a/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/index.js
+++ /dev/null
@@ -1,15 +0,0 @@
-// TODO: This is bad. We aren't loading jQuery again, because Kibana already has, but we aren't really assured of that.
-// That could change at any moment.
-
-//import $ from 'jquery';
-//if (window) window.jQuery = $;
-require('./jquery.flot');
-require('./jquery.flot.time');
-require('./jquery.flot.canvas');
-require('./jquery.flot.symbol');
-require('./jquery.flot.crosshair');
-require('./jquery.flot.selection');
-require('./jquery.flot.stack');
-require('./jquery.flot.threshold');
-require('./jquery.flot.fillbetween');
-//module.exports = $;
diff --git a/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/jquery.flot.crosshair.js b/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/jquery.flot.crosshair.js
deleted file mode 100644
index 5111695e3d12..000000000000
--- a/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/jquery.flot.crosshair.js
+++ /dev/null
@@ -1,176 +0,0 @@
-/* Flot plugin for showing crosshairs when the mouse hovers over the plot.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-The plugin supports these options:
-
- crosshair: {
- mode: null or "x" or "y" or "xy"
- color: color
- lineWidth: number
- }
-
-Set the mode to one of "x", "y" or "xy". The "x" mode enables a vertical
-crosshair that lets you trace the values on the x axis, "y" enables a
-horizontal crosshair and "xy" enables them both. "color" is the color of the
-crosshair (default is "rgba(170, 0, 0, 0.80)"), "lineWidth" is the width of
-the drawn lines (default is 1).
-
-The plugin also adds four public methods:
-
- - setCrosshair( pos )
-
- Set the position of the crosshair. Note that this is cleared if the user
- moves the mouse. "pos" is in coordinates of the plot and should be on the
- form { x: xpos, y: ypos } (you can use x2/x3/... if you're using multiple
- axes), which is coincidentally the same format as what you get from a
- "plothover" event. If "pos" is null, the crosshair is cleared.
-
- - clearCrosshair()
-
- Clear the crosshair.
-
- - lockCrosshair(pos)
-
- Cause the crosshair to lock to the current location, no longer updating if
- the user moves the mouse. Optionally supply a position (passed on to
- setCrosshair()) to move it to.
-
- Example usage:
-
- var myFlot = $.plot( $("#graph"), ..., { crosshair: { mode: "x" } } };
- $("#graph").bind( "plothover", function ( evt, position, item ) {
- if ( item ) {
- // Lock the crosshair to the data point being hovered
- myFlot.lockCrosshair({
- x: item.datapoint[ 0 ],
- y: item.datapoint[ 1 ]
- });
- } else {
- // Return normal crosshair operation
- myFlot.unlockCrosshair();
- }
- });
-
- - unlockCrosshair()
-
- Free the crosshair to move again after locking it.
-*/
-
-(function ($) {
- var options = {
- crosshair: {
- mode: null, // one of null, "x", "y" or "xy",
- color: "rgba(170, 0, 0, 0.80)",
- lineWidth: 1
- }
- };
-
- function init(plot) {
- // position of crosshair in pixels
- var crosshair = { x: -1, y: -1, locked: false };
-
- plot.setCrosshair = function setCrosshair(pos) {
- if (!pos)
- crosshair.x = -1;
- else {
- var o = plot.p2c(pos);
- crosshair.x = Math.max(0, Math.min(o.left, plot.width()));
- crosshair.y = Math.max(0, Math.min(o.top, plot.height()));
- }
-
- plot.triggerRedrawOverlay();
- };
-
- plot.clearCrosshair = plot.setCrosshair; // passes null for pos
-
- plot.lockCrosshair = function lockCrosshair(pos) {
- if (pos)
- plot.setCrosshair(pos);
- crosshair.locked = true;
- };
-
- plot.unlockCrosshair = function unlockCrosshair() {
- crosshair.locked = false;
- };
-
- function onMouseOut(e) {
- if (crosshair.locked)
- return;
-
- if (crosshair.x != -1) {
- crosshair.x = -1;
- plot.triggerRedrawOverlay();
- }
- }
-
- function onMouseMove(e) {
- if (crosshair.locked)
- return;
-
- if (plot.getSelection && plot.getSelection()) {
- crosshair.x = -1; // hide the crosshair while selecting
- return;
- }
-
- var offset = plot.offset();
- crosshair.x = Math.max(0, Math.min(e.pageX - offset.left, plot.width()));
- crosshair.y = Math.max(0, Math.min(e.pageY - offset.top, plot.height()));
- plot.triggerRedrawOverlay();
- }
-
- plot.hooks.bindEvents.push(function (plot, eventHolder) {
- if (!plot.getOptions().crosshair.mode)
- return;
-
- eventHolder.mouseout(onMouseOut);
- eventHolder.mousemove(onMouseMove);
- });
-
- plot.hooks.drawOverlay.push(function (plot, ctx) {
- var c = plot.getOptions().crosshair;
- if (!c.mode)
- return;
-
- var plotOffset = plot.getPlotOffset();
-
- ctx.save();
- ctx.translate(plotOffset.left, plotOffset.top);
-
- if (crosshair.x != -1) {
- var adj = plot.getOptions().crosshair.lineWidth % 2 ? 0.5 : 0;
-
- ctx.strokeStyle = c.color;
- ctx.lineWidth = c.lineWidth;
- ctx.lineJoin = "round";
-
- ctx.beginPath();
- if (c.mode.indexOf("x") != -1) {
- var drawX = Math.floor(crosshair.x) + adj;
- ctx.moveTo(drawX, 0);
- ctx.lineTo(drawX, plot.height());
- }
- if (c.mode.indexOf("y") != -1) {
- var drawY = Math.floor(crosshair.y) + adj;
- ctx.moveTo(0, drawY);
- ctx.lineTo(plot.width(), drawY);
- }
- ctx.stroke();
- }
- ctx.restore();
- });
-
- plot.hooks.shutdown.push(function (plot, eventHolder) {
- eventHolder.unbind("mouseout", onMouseOut);
- eventHolder.unbind("mousemove", onMouseMove);
- });
- }
-
- $.plot.plugins.push({
- init: init,
- options: options,
- name: 'crosshair',
- version: '1.0'
- });
-})(jQuery);
diff --git a/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/jquery.flot.errorbars.js b/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/jquery.flot.errorbars.js
deleted file mode 100644
index 2583d5c20c32..000000000000
--- a/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/jquery.flot.errorbars.js
+++ /dev/null
@@ -1,353 +0,0 @@
-/* Flot plugin for plotting error bars.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-Error bars are used to show standard deviation and other statistical
-properties in a plot.
-
-* Created by Rui Pereira - rui (dot) pereira (at) gmail (dot) com
-
-This plugin allows you to plot error-bars over points. Set "errorbars" inside
-the points series to the axis name over which there will be error values in
-your data array (*even* if you do not intend to plot them later, by setting
-"show: null" on xerr/yerr).
-
-The plugin supports these options:
-
- series: {
- points: {
- errorbars: "x" or "y" or "xy",
- xerr: {
- show: null/false or true,
- asymmetric: null/false or true,
- upperCap: null or "-" or function,
- lowerCap: null or "-" or function,
- color: null or color,
- radius: null or number
- },
- yerr: { same options as xerr }
- }
- }
-
-Each data point array is expected to be of the type:
-
- "x" [ x, y, xerr ]
- "y" [ x, y, yerr ]
- "xy" [ x, y, xerr, yerr ]
-
-Where xerr becomes xerr_lower,xerr_upper for the asymmetric error case, and
-equivalently for yerr. Eg., a datapoint for the "xy" case with symmetric
-error-bars on X and asymmetric on Y would be:
-
- [ x, y, xerr, yerr_lower, yerr_upper ]
-
-By default no end caps are drawn. Setting upperCap and/or lowerCap to "-" will
-draw a small cap perpendicular to the error bar. They can also be set to a
-user-defined drawing function, with (ctx, x, y, radius) as parameters, as eg.
-
- function drawSemiCircle( ctx, x, y, radius ) {
- ctx.beginPath();
- ctx.arc( x, y, radius, 0, Math.PI, false );
- ctx.moveTo( x - radius, y );
- ctx.lineTo( x + radius, y );
- ctx.stroke();
- }
-
-Color and radius both default to the same ones of the points series if not
-set. The independent radius parameter on xerr/yerr is useful for the case when
-we may want to add error-bars to a line, without showing the interconnecting
-points (with radius: 0), and still showing end caps on the error-bars.
-shadowSize and lineWidth are derived as well from the points series.
-
-*/
-
-(function ($) {
- var options = {
- series: {
- points: {
- errorbars: null, //should be 'x', 'y' or 'xy'
- xerr: { err: 'x', show: null, asymmetric: null, upperCap: null, lowerCap: null, color: null, radius: null},
- yerr: { err: 'y', show: null, asymmetric: null, upperCap: null, lowerCap: null, color: null, radius: null}
- }
- }
- };
-
- function processRawData(plot, series, data, datapoints){
- if (!series.points.errorbars)
- return;
-
- // x,y values
- var format = [
- { x: true, number: true, required: true },
- { y: true, number: true, required: true }
- ];
-
- var errors = series.points.errorbars;
- // error bars - first X then Y
- if (errors == 'x' || errors == 'xy') {
- // lower / upper error
- if (series.points.xerr.asymmetric) {
- format.push({ x: true, number: true, required: true });
- format.push({ x: true, number: true, required: true });
- } else
- format.push({ x: true, number: true, required: true });
- }
- if (errors == 'y' || errors == 'xy') {
- // lower / upper error
- if (series.points.yerr.asymmetric) {
- format.push({ y: true, number: true, required: true });
- format.push({ y: true, number: true, required: true });
- } else
- format.push({ y: true, number: true, required: true });
- }
- datapoints.format = format;
- }
-
- function parseErrors(series, i){
-
- var points = series.datapoints.points;
-
- // read errors from points array
- var exl = null,
- exu = null,
- eyl = null,
- eyu = null;
- var xerr = series.points.xerr,
- yerr = series.points.yerr;
-
- var eb = series.points.errorbars;
- // error bars - first X
- if (eb == 'x' || eb == 'xy') {
- if (xerr.asymmetric) {
- exl = points[i + 2];
- exu = points[i + 3];
- if (eb == 'xy')
- if (yerr.asymmetric){
- eyl = points[i + 4];
- eyu = points[i + 5];
- } else eyl = points[i + 4];
- } else {
- exl = points[i + 2];
- if (eb == 'xy')
- if (yerr.asymmetric) {
- eyl = points[i + 3];
- eyu = points[i + 4];
- } else eyl = points[i + 3];
- }
- // only Y
- } else if (eb == 'y')
- if (yerr.asymmetric) {
- eyl = points[i + 2];
- eyu = points[i + 3];
- } else eyl = points[i + 2];
-
- // symmetric errors?
- if (exu == null) exu = exl;
- if (eyu == null) eyu = eyl;
-
- var errRanges = [exl, exu, eyl, eyu];
- // nullify if not showing
- if (!xerr.show){
- errRanges[0] = null;
- errRanges[1] = null;
- }
- if (!yerr.show){
- errRanges[2] = null;
- errRanges[3] = null;
- }
- return errRanges;
- }
-
- function drawSeriesErrors(plot, ctx, s){
-
- var points = s.datapoints.points,
- ps = s.datapoints.pointsize,
- ax = [s.xaxis, s.yaxis],
- radius = s.points.radius,
- err = [s.points.xerr, s.points.yerr];
-
- //sanity check, in case some inverted axis hack is applied to flot
- var invertX = false;
- if (ax[0].p2c(ax[0].max) < ax[0].p2c(ax[0].min)) {
- invertX = true;
- var tmp = err[0].lowerCap;
- err[0].lowerCap = err[0].upperCap;
- err[0].upperCap = tmp;
- }
-
- var invertY = false;
- if (ax[1].p2c(ax[1].min) < ax[1].p2c(ax[1].max)) {
- invertY = true;
- var tmp = err[1].lowerCap;
- err[1].lowerCap = err[1].upperCap;
- err[1].upperCap = tmp;
- }
-
- for (var i = 0; i < s.datapoints.points.length; i += ps) {
-
- //parse
- var errRanges = parseErrors(s, i);
-
- //cycle xerr & yerr
- for (var e = 0; e < err.length; e++){
-
- var minmax = [ax[e].min, ax[e].max];
-
- //draw this error?
- if (errRanges[e * err.length]){
-
- //data coordinates
- var x = points[i],
- y = points[i + 1];
-
- //errorbar ranges
- var upper = [x, y][e] + errRanges[e * err.length + 1],
- lower = [x, y][e] - errRanges[e * err.length];
-
- //points outside of the canvas
- if (err[e].err == 'x')
- if (y > ax[1].max || y < ax[1].min || upper < ax[0].min || lower > ax[0].max)
- continue;
- if (err[e].err == 'y')
- if (x > ax[0].max || x < ax[0].min || upper < ax[1].min || lower > ax[1].max)
- continue;
-
- // prevent errorbars getting out of the canvas
- var drawUpper = true,
- drawLower = true;
-
- if (upper > minmax[1]) {
- drawUpper = false;
- upper = minmax[1];
- }
- if (lower < minmax[0]) {
- drawLower = false;
- lower = minmax[0];
- }
-
- //sanity check, in case some inverted axis hack is applied to flot
- if ((err[e].err == 'x' && invertX) || (err[e].err == 'y' && invertY)) {
- //swap coordinates
- var tmp = lower;
- lower = upper;
- upper = tmp;
- tmp = drawLower;
- drawLower = drawUpper;
- drawUpper = tmp;
- tmp = minmax[0];
- minmax[0] = minmax[1];
- minmax[1] = tmp;
- }
-
- // convert to pixels
- x = ax[0].p2c(x),
- y = ax[1].p2c(y),
- upper = ax[e].p2c(upper);
- lower = ax[e].p2c(lower);
- minmax[0] = ax[e].p2c(minmax[0]);
- minmax[1] = ax[e].p2c(minmax[1]);
-
- //same style as points by default
- var lw = err[e].lineWidth ? err[e].lineWidth : s.points.lineWidth,
- sw = s.points.shadowSize != null ? s.points.shadowSize : s.shadowSize;
-
- //shadow as for points
- if (lw > 0 && sw > 0) {
- var w = sw / 2;
- ctx.lineWidth = w;
- ctx.strokeStyle = "rgba(0,0,0,0.1)";
- drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, w + w/2, minmax);
-
- ctx.strokeStyle = "rgba(0,0,0,0.2)";
- drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, w/2, minmax);
- }
-
- ctx.strokeStyle = err[e].color? err[e].color: s.color;
- ctx.lineWidth = lw;
- //draw it
- drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, 0, minmax);
- }
- }
- }
- }
-
- function drawError(ctx,err,x,y,upper,lower,drawUpper,drawLower,radius,offset,minmax){
-
- //shadow offset
- y += offset;
- upper += offset;
- lower += offset;
-
- // error bar - avoid plotting over circles
- if (err.err == 'x'){
- if (upper > x + radius) drawPath(ctx, [[upper,y],[Math.max(x + radius,minmax[0]),y]]);
- else drawUpper = false;
- if (lower < x - radius) drawPath(ctx, [[Math.min(x - radius,minmax[1]),y],[lower,y]] );
- else drawLower = false;
- }
- else {
- if (upper < y - radius) drawPath(ctx, [[x,upper],[x,Math.min(y - radius,minmax[0])]] );
- else drawUpper = false;
- if (lower > y + radius) drawPath(ctx, [[x,Math.max(y + radius,minmax[1])],[x,lower]] );
- else drawLower = false;
- }
-
- //internal radius value in errorbar, allows to plot radius 0 points and still keep proper sized caps
- //this is a way to get errorbars on lines without visible connecting dots
- radius = err.radius != null? err.radius: radius;
-
- // upper cap
- if (drawUpper) {
- if (err.upperCap == '-'){
- if (err.err=='x') drawPath(ctx, [[upper,y - radius],[upper,y + radius]] );
- else drawPath(ctx, [[x - radius,upper],[x + radius,upper]] );
- } else if ($.isFunction(err.upperCap)){
- if (err.err=='x') err.upperCap(ctx, upper, y, radius);
- else err.upperCap(ctx, x, upper, radius);
- }
- }
- // lower cap
- if (drawLower) {
- if (err.lowerCap == '-'){
- if (err.err=='x') drawPath(ctx, [[lower,y - radius],[lower,y + radius]] );
- else drawPath(ctx, [[x - radius,lower],[x + radius,lower]] );
- } else if ($.isFunction(err.lowerCap)){
- if (err.err=='x') err.lowerCap(ctx, lower, y, radius);
- else err.lowerCap(ctx, x, lower, radius);
- }
- }
- }
-
- function drawPath(ctx, pts){
- ctx.beginPath();
- ctx.moveTo(pts[0][0], pts[0][1]);
- for (var p=1; p < pts.length; p++)
- ctx.lineTo(pts[p][0], pts[p][1]);
- ctx.stroke();
- }
-
- function draw(plot, ctx){
- var plotOffset = plot.getPlotOffset();
-
- ctx.save();
- ctx.translate(plotOffset.left, plotOffset.top);
- $.each(plot.getData(), function (i, s) {
- if (s.points.errorbars && (s.points.xerr.show || s.points.yerr.show))
- drawSeriesErrors(plot, ctx, s);
- });
- ctx.restore();
- }
-
- function init(plot) {
- plot.hooks.processRawData.push(processRawData);
- plot.hooks.draw.push(draw);
- }
-
- $.plot.plugins.push({
- init: init,
- options: options,
- name: 'errorbars',
- version: '1.0'
- });
-})(jQuery);
diff --git a/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/jquery.flot.image.js b/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/jquery.flot.image.js
deleted file mode 100644
index 625a03571d27..000000000000
--- a/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/jquery.flot.image.js
+++ /dev/null
@@ -1,241 +0,0 @@
-/* Flot plugin for plotting images.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-The data syntax is [ [ image, x1, y1, x2, y2 ], ... ] where (x1, y1) and
-(x2, y2) are where you intend the two opposite corners of the image to end up
-in the plot. Image must be a fully loaded Javascript image (you can make one
-with new Image()). If the image is not complete, it's skipped when plotting.
-
-There are two helpers included for retrieving images. The easiest work the way
-that you put in URLs instead of images in the data, like this:
-
- [ "myimage.png", 0, 0, 10, 10 ]
-
-Then call $.plot.image.loadData( data, options, callback ) where data and
-options are the same as you pass in to $.plot. This loads the images, replaces
-the URLs in the data with the corresponding images and calls "callback" when
-all images are loaded (or failed loading). In the callback, you can then call
-$.plot with the data set. See the included example.
-
-A more low-level helper, $.plot.image.load(urls, callback) is also included.
-Given a list of URLs, it calls callback with an object mapping from URL to
-Image object when all images are loaded or have failed loading.
-
-The plugin supports these options:
-
- series: {
- images: {
- show: boolean
- anchor: "corner" or "center"
- alpha: [ 0, 1 ]
- }
- }
-
-They can be specified for a specific series:
-
- $.plot( $("#placeholder"), [{
- data: [ ... ],
- images: { ... }
- ])
-
-Note that because the data format is different from usual data points, you
-can't use images with anything else in a specific data series.
-
-Setting "anchor" to "center" causes the pixels in the image to be anchored at
-the corner pixel centers inside of at the pixel corners, effectively letting
-half a pixel stick out to each side in the plot.
-
-A possible future direction could be support for tiling for large images (like
-Google Maps).
-
-*/
-
-(function ($) {
- var options = {
- series: {
- images: {
- show: false,
- alpha: 1,
- anchor: "corner" // or "center"
- }
- }
- };
-
- $.plot.image = {};
-
- $.plot.image.loadDataImages = function (series, options, callback) {
- var urls = [], points = [];
-
- var defaultShow = options.series.images.show;
-
- $.each(series, function (i, s) {
- if (!(defaultShow || s.images.show))
- return;
-
- if (s.data)
- s = s.data;
-
- $.each(s, function (i, p) {
- if (typeof p[0] == "string") {
- urls.push(p[0]);
- points.push(p);
- }
- });
- });
-
- $.plot.image.load(urls, function (loadedImages) {
- $.each(points, function (i, p) {
- var url = p[0];
- if (loadedImages[url])
- p[0] = loadedImages[url];
- });
-
- callback();
- });
- }
-
- $.plot.image.load = function (urls, callback) {
- var missing = urls.length, loaded = {};
- if (missing == 0)
- callback({});
-
- $.each(urls, function (i, url) {
- var handler = function () {
- --missing;
-
- loaded[url] = this;
-
- if (missing == 0)
- callback(loaded);
- };
-
- $('').load(handler).error(handler).attr('src', url);
- });
- };
-
- function drawSeries(plot, ctx, series) {
- var plotOffset = plot.getPlotOffset();
-
- if (!series.images || !series.images.show)
- return;
-
- var points = series.datapoints.points,
- ps = series.datapoints.pointsize;
-
- for (var i = 0; i < points.length; i += ps) {
- var img = points[i],
- x1 = points[i + 1], y1 = points[i + 2],
- x2 = points[i + 3], y2 = points[i + 4],
- xaxis = series.xaxis, yaxis = series.yaxis,
- tmp;
-
- // actually we should check img.complete, but it
- // appears to be a somewhat unreliable indicator in
- // IE6 (false even after load event)
- if (!img || img.width <= 0 || img.height <= 0)
- continue;
-
- if (x1 > x2) {
- tmp = x2;
- x2 = x1;
- x1 = tmp;
- }
- if (y1 > y2) {
- tmp = y2;
- y2 = y1;
- y1 = tmp;
- }
-
- // if the anchor is at the center of the pixel, expand the
- // image by 1/2 pixel in each direction
- if (series.images.anchor == "center") {
- tmp = 0.5 * (x2-x1) / (img.width - 1);
- x1 -= tmp;
- x2 += tmp;
- tmp = 0.5 * (y2-y1) / (img.height - 1);
- y1 -= tmp;
- y2 += tmp;
- }
-
- // clip
- if (x1 == x2 || y1 == y2 ||
- x1 >= xaxis.max || x2 <= xaxis.min ||
- y1 >= yaxis.max || y2 <= yaxis.min)
- continue;
-
- var sx1 = 0, sy1 = 0, sx2 = img.width, sy2 = img.height;
- if (x1 < xaxis.min) {
- sx1 += (sx2 - sx1) * (xaxis.min - x1) / (x2 - x1);
- x1 = xaxis.min;
- }
-
- if (x2 > xaxis.max) {
- sx2 += (sx2 - sx1) * (xaxis.max - x2) / (x2 - x1);
- x2 = xaxis.max;
- }
-
- if (y1 < yaxis.min) {
- sy2 += (sy1 - sy2) * (yaxis.min - y1) / (y2 - y1);
- y1 = yaxis.min;
- }
-
- if (y2 > yaxis.max) {
- sy1 += (sy1 - sy2) * (yaxis.max - y2) / (y2 - y1);
- y2 = yaxis.max;
- }
-
- x1 = xaxis.p2c(x1);
- x2 = xaxis.p2c(x2);
- y1 = yaxis.p2c(y1);
- y2 = yaxis.p2c(y2);
-
- // the transformation may have swapped us
- if (x1 > x2) {
- tmp = x2;
- x2 = x1;
- x1 = tmp;
- }
- if (y1 > y2) {
- tmp = y2;
- y2 = y1;
- y1 = tmp;
- }
-
- tmp = ctx.globalAlpha;
- ctx.globalAlpha *= series.images.alpha;
- ctx.drawImage(img,
- sx1, sy1, sx2 - sx1, sy2 - sy1,
- x1 + plotOffset.left, y1 + plotOffset.top,
- x2 - x1, y2 - y1);
- ctx.globalAlpha = tmp;
- }
- }
-
- function processRawData(plot, series, data, datapoints) {
- if (!series.images.show)
- return;
-
- // format is Image, x1, y1, x2, y2 (opposite corners)
- datapoints.format = [
- { required: true },
- { x: true, number: true, required: true },
- { y: true, number: true, required: true },
- { x: true, number: true, required: true },
- { y: true, number: true, required: true }
- ];
- }
-
- function init(plot) {
- plot.hooks.processRawData.push(processRawData);
- plot.hooks.drawSeries.push(drawSeries);
- }
-
- $.plot.plugins.push({
- init: init,
- options: options,
- name: 'image',
- version: '1.1'
- });
-})(jQuery);
diff --git a/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/jquery.flot.js b/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/jquery.flot.js
deleted file mode 100644
index 39f3e4cf3efe..000000000000
--- a/x-pack/plugins/canvas/canvas_plugin_src/lib/flot-charts/jquery.flot.js
+++ /dev/null
@@ -1,3168 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-
-// first an inline dependency, jquery.colorhelpers.js, we inline it here
-// for convenience
-
-/* Plugin for jQuery for working with colors.
- *
- * Version 1.1.
- *
- * Inspiration from jQuery color animation plugin by John Resig.
- *
- * Released under the MIT license by Ole Laursen, October 2009.
- *
- * Examples:
- *
- * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
- * var c = $.color.extract($("#mydiv"), 'background-color');
- * console.log(c.r, c.g, c.b, c.a);
- * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
- *
- * Note that .scale() and .add() return the same modified object
- * instead of making a new one.
- *
- * V. 1.1: Fix error handling so e.g. parsing an empty string does
- * produce a color rather than just crashing.
- */
-(function($){$.color={};$.color.make=function(r,g,b,a){var o={};o.r=r||0;o.g=g||0;o.b=b||0;o.a=a!=null?a:1;o.add=function(c,d){for(var i=0;i=1){return"rgb("+[o.r,o.g,o.b].join(",")+")"}else{return"rgba("+[o.r,o.g,o.b,o.a].join(",")+")"}};o.normalize=function(){function clamp(min,value,max){return valuemax?max:value}o.r=clamp(0,parseInt(o.r),255);o.g=clamp(0,parseInt(o.g),255);o.b=clamp(0,parseInt(o.b),255);o.a=clamp(0,o.a,1);return o};o.clone=function(){return $.color.make(o.r,o.b,o.g,o.a)};return o.normalize()};$.color.extract=function(elem,css){var c;do{c=elem.css(css).toLowerCase();if(c!=""&&c!="transparent")break;elem=elem.parent()}while(elem.length&&!$.nodeName(elem.get(0),"body"));if(c=="rgba(0, 0, 0, 0)")c="transparent";return $.color.parse(c)};$.color.parse=function(str){var res,m=$.color.make;if(res=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10));if(res=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10),parseFloat(res[4]));if(res=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55);if(res=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55,parseFloat(res[4]));if(res=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))return m(parseInt(res[1],16),parseInt(res[2],16),parseInt(res[3],16));if(res=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))return m(parseInt(res[1]+res[1],16),parseInt(res[2]+res[2],16),parseInt(res[3]+res[3],16));var name=$.trim(str).toLowerCase();if(name=="transparent")return m(255,255,255,0);else{res=lookupColors[name]||[0,0,0];return m(res[0],res[1],res[2])}};var lookupColors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);
-
-// the actual Flot code
-(function($) {
-
- // Cache the prototype hasOwnProperty for faster access
-
- var hasOwnProperty = Object.prototype.hasOwnProperty;
-
- // A shim to provide 'detach' to jQuery versions prior to 1.4. Using a DOM
- // operation produces the same effect as detach, i.e. removing the element
- // without touching its jQuery data.
-
- // Do not merge this into Flot 0.9, since it requires jQuery 1.4.4+.
-
- if (!$.fn.detach) {
- $.fn.detach = function() {
- return this.each(function() {
- if (this.parentNode) {
- this.parentNode.removeChild( this );
- }
- });
- };
- }
-
- ///////////////////////////////////////////////////////////////////////////
- // The Canvas object is a wrapper around an HTML5 |