"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.useQuery = exports.redirectToDetections = exports.getStepsData = exports.getScheduleStepsData = exports.getPrePackagedTimelineInstallationStatus = exports.getModifiedAboutDetailsData = exports.getHumanizedDuration = exports.getDefineStepsData = exports.getAllActionMessageParams = exports.getActionsStepsData = exports.getActionMessageRuleParams = exports.getActionMessageParams = exports.getAboutStepsData = exports.fillEmptySeverityMappings = exports.determineDetailsValue = exports.convertHistoryStartToSize = exports.MaxWidthEuiFlexItem = void 0; var _datemath = _interopRequireDefault(require("@kbn/datemath")); var _moment = _interopRequireDefault(require("moment")); var _memoizeOne = _interopRequireDefault(require("memoize-one")); var _reactRouterDom = require("react-router-dom"); var _styledComponents = _interopRequireDefault(require("styled-components")); var _eui = require("@elastic/eui"); var _securitysolutionListConstants = require("@kbn/securitysolution-list-constants"); var _utils = require("../../../../../common/detection_engine/utils"); var _rule_schema = require("../../../../../common/api/detection_engine/model/rule_schema"); var _utility_types = require("../../../../../common/utility_types"); var _transform_actions = require("../../../../../common/detection_engine/transform_actions"); var _types = require("./types"); var _data = require("../../../components/rules/step_about_rule/data"); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ const getStepsData = ({ rule, detailsView = false }) => { const defineRuleData = getDefineStepsData(rule); const aboutRuleData = getAboutStepsData(rule, detailsView); const modifiedAboutRuleDetailsData = getModifiedAboutDetailsData(rule); const scheduleRuleData = getScheduleStepsData(rule); const ruleActionsData = getActionsStepsData(rule); return { aboutRuleData, modifiedAboutRuleDetailsData, defineRuleData, scheduleRuleData, ruleActionsData }; }; exports.getStepsData = getStepsData; const getActionsStepsData = rule => { const { enabled, meta, actions = [], response_actions: responseActions } = rule; return { actions: actions === null || actions === void 0 ? void 0 : actions.map(_transform_actions.transformRuleToAlertAction), responseActions: responseActions === null || responseActions === void 0 ? void 0 : responseActions.map(_transform_actions.transformRuleToAlertResponseAction), kibanaSiemAppUrl: meta === null || meta === void 0 ? void 0 : meta.kibana_siem_app_url, enabled }; }; /* eslint-disable complexity */ exports.getActionsStepsData = getActionsStepsData; const getDefineStepsData = rule => { var _rule$anomaly_thresho, _rule$machine_learnin, _rule$index, _rule$threat_index, _rule$threat_query, _rule$threat_language, _rule$threat_filters, _rule$threat_mapping, _rule$query, _rule$language, _rule$filters, _rule$saved_id, _rule$related_integra, _rule$required_fields, _rule$timeline_id, _rule$timeline_title, _rule$threshold, _rule$threshold2, _rule$threshold3, _rule$threshold3$card, _rule$new_terms_field, _rule$alert_suppressi, _rule$alert_suppressi2, _rule$alert_suppressi3, _rule$alert_suppressi4, _rule$alert_suppressi5, _rule$alert_suppressi6, _rule$alert_suppressi7; return { ruleType: rule.type, anomalyThreshold: (_rule$anomaly_thresho = rule.anomaly_threshold) !== null && _rule$anomaly_thresho !== void 0 ? _rule$anomaly_thresho : 50, machineLearningJobId: (_rule$machine_learnin = rule.machine_learning_job_id) !== null && _rule$machine_learnin !== void 0 ? _rule$machine_learnin : [], index: (_rule$index = rule.index) !== null && _rule$index !== void 0 ? _rule$index : [], dataViewId: rule.data_view_id, threatIndex: (_rule$threat_index = rule.threat_index) !== null && _rule$threat_index !== void 0 ? _rule$threat_index : [], threatQueryBar: { query: { query: (_rule$threat_query = rule.threat_query) !== null && _rule$threat_query !== void 0 ? _rule$threat_query : '', language: (_rule$threat_language = rule.threat_language) !== null && _rule$threat_language !== void 0 ? _rule$threat_language : '' }, filters: (_rule$threat_filters = rule.threat_filters) !== null && _rule$threat_filters !== void 0 ? _rule$threat_filters : [], saved_id: null }, threatMapping: (_rule$threat_mapping = rule.threat_mapping) !== null && _rule$threat_mapping !== void 0 ? _rule$threat_mapping : [], queryBar: { query: { query: (_rule$query = rule.query) !== null && _rule$query !== void 0 ? _rule$query : '', language: (_rule$language = rule.language) !== null && _rule$language !== void 0 ? _rule$language : '' }, filters: (_rule$filters = rule.filters) !== null && _rule$filters !== void 0 ? _rule$filters : [], saved_id: (_rule$saved_id = rule.saved_id) !== null && _rule$saved_id !== void 0 ? _rule$saved_id : null }, relatedIntegrations: (_rule$related_integra = rule.related_integrations) !== null && _rule$related_integra !== void 0 ? _rule$related_integra : [], requiredFields: (_rule$required_fields = rule.required_fields) !== null && _rule$required_fields !== void 0 ? _rule$required_fields : [], timeline: { id: (_rule$timeline_id = rule.timeline_id) !== null && _rule$timeline_id !== void 0 ? _rule$timeline_id : null, title: (_rule$timeline_title = rule.timeline_title) !== null && _rule$timeline_title !== void 0 ? _rule$timeline_title : null }, threshold: { field: (0, _utils.normalizeThresholdField)((_rule$threshold = rule.threshold) === null || _rule$threshold === void 0 ? void 0 : _rule$threshold.field), value: `${((_rule$threshold2 = rule.threshold) === null || _rule$threshold2 === void 0 ? void 0 : _rule$threshold2.value) || 100}`, ...((_rule$threshold3 = rule.threshold) !== null && _rule$threshold3 !== void 0 && (_rule$threshold3$card = _rule$threshold3.cardinality) !== null && _rule$threshold3$card !== void 0 && _rule$threshold3$card.length ? { cardinality: { field: [`${rule.threshold.cardinality[0].field}`], value: `${rule.threshold.cardinality[0].value}` } } : {}) }, eqlOptions: { timestampField: rule.timestamp_field, eventCategoryField: rule.event_category_override, tiebreakerField: rule.tiebreaker_field }, dataSourceType: rule.data_view_id ? _types.DataSourceType.DataView : _types.DataSourceType.IndexPatterns, newTermsFields: (_rule$new_terms_field = rule.new_terms_fields) !== null && _rule$new_terms_field !== void 0 ? _rule$new_terms_field : [], historyWindowSize: rule.history_window_start ? convertHistoryStartToSize(rule.history_window_start) : '7d', shouldLoadQueryDynamically: Boolean(rule.type === 'saved_query' && rule.saved_id), groupByFields: (_rule$alert_suppressi = (_rule$alert_suppressi2 = rule.alert_suppression) === null || _rule$alert_suppressi2 === void 0 ? void 0 : _rule$alert_suppressi2.group_by) !== null && _rule$alert_suppressi !== void 0 ? _rule$alert_suppressi : [], groupByRadioSelection: (_rule$alert_suppressi3 = rule.alert_suppression) !== null && _rule$alert_suppressi3 !== void 0 && _rule$alert_suppressi3.duration ? _types.GroupByOptions.PerTimePeriod : _types.GroupByOptions.PerRuleExecution, groupByDuration: (_rule$alert_suppressi4 = (_rule$alert_suppressi5 = rule.alert_suppression) === null || _rule$alert_suppressi5 === void 0 ? void 0 : _rule$alert_suppressi5.duration) !== null && _rule$alert_suppressi4 !== void 0 ? _rule$alert_suppressi4 : { value: 5, unit: 'm' }, suppressionMissingFields: (_rule$alert_suppressi6 = (_rule$alert_suppressi7 = rule.alert_suppression) === null || _rule$alert_suppressi7 === void 0 ? void 0 : _rule$alert_suppressi7.missing_fields_strategy) !== null && _rule$alert_suppressi6 !== void 0 ? _rule$alert_suppressi6 : _rule_schema.DEFAULT_SUPPRESSION_MISSING_FIELDS_STRATEGY }; }; exports.getDefineStepsData = getDefineStepsData; const convertHistoryStartToSize = relativeTime => { if (relativeTime.startsWith('now-')) { return relativeTime.substring(4); } else { return relativeTime; } }; exports.convertHistoryStartToSize = convertHistoryStartToSize; const getScheduleStepsData = rule => { const { interval, from } = rule; const fromHumanizedValue = getHumanizedDuration(from, interval); return { interval, from: fromHumanizedValue }; }; exports.getScheduleStepsData = getScheduleStepsData; const getHumanizedDuration = (from, interval) => { var _dateMath$parse, _dateMath$parse2; const fromValue = (_dateMath$parse = _datemath.default.parse(from)) !== null && _dateMath$parse !== void 0 ? _dateMath$parse : (0, _moment.default)(); const intervalValue = (_dateMath$parse2 = _datemath.default.parse(`now-${interval}`)) !== null && _dateMath$parse2 !== void 0 ? _dateMath$parse2 : (0, _moment.default)(); const fromDuration = _moment.default.duration(intervalValue.diff(fromValue)); // Basing calculations off floored seconds count as moment durations weren't precise const intervalDuration = Math.floor(fromDuration.asSeconds()); // For consistency of display value if (intervalDuration === 0) { return `0s`; } if (intervalDuration % 3600 === 0) { return `${intervalDuration / 3600}h`; } else if (intervalDuration % 60 === 0) { return `${intervalDuration / 60}m`; } else { return `${intervalDuration}s`; } }; exports.getHumanizedDuration = getHumanizedDuration; const getAboutStepsData = (rule, detailsView) => { var _exceptionsList$some; const { name, description, note } = determineDetailsValue(rule, detailsView); const { author, building_block_type: buildingBlockType, exceptions_list: exceptionsList, license, risk_score_mapping: riskScoreMapping, rule_name_override: ruleNameOverride, severity_mapping: severityMapping, timestamp_override: timestampOverride, timestamp_override_fallback_disabled: timestampOverrideFallbackDisabled, references, severity, false_positives: falsePositives, risk_score: riskScore, investigation_fields: investigationFields, tags, threat, threat_indicator_path: threatIndicatorPath } = rule; return { author, isAssociatedToEndpointList: (_exceptionsList$some = exceptionsList === null || exceptionsList === void 0 ? void 0 : exceptionsList.some(({ id }) => id === _securitysolutionListConstants.ENDPOINT_LIST_ID)) !== null && _exceptionsList$some !== void 0 ? _exceptionsList$some : false, isBuildingBlock: buildingBlockType !== undefined, license: license !== null && license !== void 0 ? license : '', ruleNameOverride: ruleNameOverride !== null && ruleNameOverride !== void 0 ? ruleNameOverride : '', timestampOverride: timestampOverride !== null && timestampOverride !== void 0 ? timestampOverride : '', timestampOverrideFallbackDisabled, name, description, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion note: note, references, severity: { value: severity, mapping: fillEmptySeverityMappings(severityMapping), isMappingChecked: severityMapping.length > 0 }, tags, riskScore: { value: riskScore, mapping: riskScoreMapping, isMappingChecked: riskScoreMapping.length > 0 }, falsePositives, investigationFields: investigationFields !== null && investigationFields !== void 0 ? investigationFields : [], threat: threat, threatIndicatorPath }; }; exports.getAboutStepsData = getAboutStepsData; const severitySortMapping = { low: 0, medium: 1, high: 2, critical: 3 }; const fillEmptySeverityMappings = mappings => { const missingMappings = _data.severityOptions.flatMap(so => mappings.find(mapping => mapping.severity === so.value) == null ? [{ field: '', value: '', operator: 'equals', severity: so.value }] : []); return [...mappings, ...missingMappings].sort((a, b) => severitySortMapping[a.severity] - severitySortMapping[b.severity]); }; exports.fillEmptySeverityMappings = fillEmptySeverityMappings; const determineDetailsValue = (rule, detailsView) => { const { name, description, note } = rule; if (detailsView) { return { name: '', description: '', note: '' }; } return { name, description, note: note !== null && note !== void 0 ? note : '' }; }; exports.determineDetailsValue = determineDetailsValue; const getModifiedAboutDetailsData = rule => { var _rule$note, _rule$setup; return { note: (_rule$note = rule.note) !== null && _rule$note !== void 0 ? _rule$note : '', description: rule.description, setup: (_rule$setup = rule.setup) !== null && _rule$setup !== void 0 ? _rule$setup : '' }; }; exports.getModifiedAboutDetailsData = getModifiedAboutDetailsData; const useQuery = () => new URLSearchParams((0, _reactRouterDom.useLocation)().search); exports.useQuery = useQuery; const getPrePackagedTimelineInstallationStatus = (timelinesInstalled, timelinesNotInstalled, timelinesNotUpdated) => { if (timelinesNotInstalled != null && timelinesInstalled === 0 && timelinesNotInstalled > 0 && timelinesNotUpdated === 0) { return 'timelinesNotInstalled'; } else if (timelinesInstalled != null && timelinesInstalled > 0 && timelinesNotInstalled === 0 && timelinesNotUpdated === 0) { return 'timelinesInstalled'; } else if (timelinesInstalled != null && timelinesNotInstalled != null && timelinesInstalled > 0 && timelinesNotInstalled > 0 && timelinesNotUpdated === 0) { return 'someTimelineUninstall'; } else if (timelinesInstalled != null && timelinesNotInstalled != null && timelinesNotUpdated != null && timelinesInstalled > 0 && timelinesNotInstalled >= 0 && timelinesNotUpdated > 0) { return 'timelineNeedUpdate'; } return 'unknown'; }; exports.getPrePackagedTimelineInstallationStatus = getPrePackagedTimelineInstallationStatus; const redirectToDetections = (isSignalIndexExists, isAuthenticated, hasEncryptionKey, needsListsConfiguration) => isSignalIndexExists === false || isAuthenticated === false || hasEncryptionKey === false || needsListsConfiguration; exports.redirectToDetections = redirectToDetections; const commonRuleParamsKeys = ['id', 'name', 'description', 'false_positives', 'investigation_fields', 'rule_id', 'max_signals', 'risk_score', 'output_index', 'references', 'severity', 'timeline_id', 'timeline_title', 'threat', 'type', 'version']; const queryRuleParams = ['index', 'filters', 'language', 'query', 'saved_id', 'response_actions']; const machineLearningRuleParams = ['anomaly_threshold', 'machine_learning_job_id']; const thresholdRuleParams = ['threshold', ...queryRuleParams]; const getAllRuleParamsKeys = () => { const allRuleParamsKeys = [...commonRuleParamsKeys, ...queryRuleParams, ...machineLearningRuleParams, ...thresholdRuleParams].sort(); return Array.from(new Set(allRuleParamsKeys)); }; const getRuleSpecificRuleParamKeys = ruleType => { switch (ruleType) { case 'machine_learning': return machineLearningRuleParams; case 'threshold': return thresholdRuleParams; case 'new_terms': case 'threat_match': case 'query': case 'saved_query': case 'eql': return queryRuleParams; } (0, _utility_types.assertUnreachable)(ruleType); }; const getActionMessageRuleParams = ruleType => { const ruleParamsKeys = [...commonRuleParamsKeys, ...getRuleSpecificRuleParamKeys(ruleType)].sort(); return ruleParamsKeys; }; exports.getActionMessageRuleParams = getActionMessageRuleParams; const transformRuleKeysToActionVariables = actionMessageRuleParams => { return { state: [{ name: 'signals_count', description: 'state.signals_count' }], params: [], context: [{ name: 'results_link', description: 'context.results_link', useWithTripleBracesInTemplates: true }, { name: 'alerts', description: 'context.alerts' }, ...actionMessageRuleParams.map(param => { const extendedParam = `rule.${param}`; return { name: extendedParam, description: `context.${extendedParam}` }; })] }; }; const getActionMessageParams = (0, _memoizeOne.default)(ruleType => { if (!ruleType) { return { state: [], params: [] }; } const actionMessageRuleParams = getActionMessageRuleParams(ruleType); return transformRuleKeysToActionVariables(actionMessageRuleParams); }); /** * returns action variables available for all rule types */ exports.getActionMessageParams = getActionMessageParams; const getAllActionMessageParams = () => transformRuleKeysToActionVariables(getAllRuleParamsKeys()); exports.getAllActionMessageParams = getAllActionMessageParams; const MaxWidthEuiFlexItem = (0, _styledComponents.default)(_eui.EuiFlexItem)` max-width: 1000px; overflow: hidden; `; exports.MaxWidthEuiFlexItem = MaxWidthEuiFlexItem;