"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.tlsAlertFactory = exports.getCertSummary = void 0; var _moment = _interopRequireDefault(require("moment")); var _configSchema = require("@kbn/config-schema"); var _common = require("@kbn/observability-plugin/common"); var _ruleDataUtils = require("@kbn/rule-data-utils"); var _std = require("@kbn/std"); var _status_check = require("./status_check"); var _common2 = require("./common"); var _uptime_alerts = require("../../../../common/constants/uptime_alerts"); var _constants = require("../../../../common/constants"); var _translations = require("./translations"); var _translations2 = require("../../../../common/rules/legacy_uptime/translations"); var _saved_objects = require("../saved_objects/saved_objects"); var _lib = require("../lib"); var _action_variables = require("./action_variables"); /* * 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 mapCertsToSummaryString = (cert, certLimitMessage) => certLimitMessage(cert); const getValidAfter = ({ not_after: date }) => { if (!date) return { summary: 'Error, missing `certificate_not_valid_after` date.' }; const relativeDate = (0, _moment.default)().diff(date, 'days'); const formattedDate = (0, _moment.default)(date).format('MMM D, YYYY z'); return relativeDate >= 0 ? { summary: _translations.tlsTranslations.validAfterExpiredString(formattedDate, relativeDate), status: _translations.tlsTranslations.expiredLabel } : { summary: _translations.tlsTranslations.validAfterExpiringString(formattedDate, Math.abs(relativeDate)), status: _translations.tlsTranslations.expiringLabel }; }; const getValidBefore = ({ not_before: date }) => { if (!date) return { summary: 'Error, missing `certificate_not_valid_before` date.' }; const relativeDate = (0, _moment.default)().diff(date, 'days'); const formattedDate = (0, _moment.default)(date).format('MMM D, YYYY z'); return relativeDate >= 0 ? { summary: _translations.tlsTranslations.validBeforeExpiredString(formattedDate, relativeDate), status: _translations.tlsTranslations.agingLabel } : { summary: _translations.tlsTranslations.validBeforeExpiringString(formattedDate, Math.abs(relativeDate)), status: _translations.tlsTranslations.invalidLabel }; }; const getCertSummary = (cert, expirationThreshold, ageThreshold) => { var _cert$not_after, _cert$not_before, _cert$common_name, _cert$issuer; const isExpiring = new Date((_cert$not_after = cert.not_after) !== null && _cert$not_after !== void 0 ? _cert$not_after : '').valueOf() < expirationThreshold; const isAging = new Date((_cert$not_before = cert.not_before) !== null && _cert$not_before !== void 0 ? _cert$not_before : '').valueOf() < ageThreshold; let content = null; if (isExpiring) { content = mapCertsToSummaryString(cert, getValidAfter); } else if (isAging) { content = mapCertsToSummaryString(cert, getValidBefore); } const { summary = '', status = '' } = content || {}; return { commonName: (_cert$common_name = cert.common_name) !== null && _cert$common_name !== void 0 ? _cert$common_name : '', issuer: (_cert$issuer = cert.issuer) !== null && _cert$issuer !== void 0 ? _cert$issuer : '', summary, status }; }; exports.getCertSummary = getCertSummary; const tlsAlertFactory = (_server, libs, plugins) => ({ id: _uptime_alerts.CLIENT_ALERT_TYPES.TLS, producer: 'uptime', name: _translations.tlsTranslations.alertFactoryName, validate: { params: _configSchema.schema.object({ stackVersion: _configSchema.schema.maybe(_configSchema.schema.string()), search: _configSchema.schema.maybe(_configSchema.schema.string()), certExpirationThreshold: _configSchema.schema.maybe(_configSchema.schema.number()), certAgeThreshold: _configSchema.schema.maybe(_configSchema.schema.number()) }) }, defaultActionGroupId: _uptime_alerts.TLS.id, actionGroups: [{ id: _uptime_alerts.TLS.id, name: _uptime_alerts.TLS.name }], actionVariables: { context: [..._translations.tlsTranslations.actionVariables, ..._translations.commonStateTranslations, _action_variables.ACTION_VARIABLES[_action_variables.ALERT_DETAILS_URL]], state: [..._translations.tlsTranslations.actionVariables, ..._translations.commonStateTranslations] }, isExportable: true, minimumLicenseRequired: 'basic', doesSetRecoveryContext: true, async executor({ params, services: { alertFactory, alertWithLifecycle, getAlertStartedDate, getAlertUuid, savedObjectsClient, scopedClusterClient }, spaceId, startedAt, state, rule }) { var _params$stackVersion, _ref, _params$certExpiratio, _ref2, _params$certAgeThresh; const { share, basePath } = _server; const alertsLocator = share.url.locators.get(_common.alertsLocatorID); const dynamicSettings = await _saved_objects.savedObjectsAdapter.getUptimeDynamicSettings(savedObjectsClient); const uptimeEsClient = new _lib.UptimeEsClient(savedObjectsClient, scopedClusterClient.asCurrentUser, { stackVersion: (_params$stackVersion = params.stackVersion) !== null && _params$stackVersion !== void 0 ? _params$stackVersion : '8.9.0' }); const certExpirationThreshold = (_ref = (_params$certExpiratio = params.certExpirationThreshold) !== null && _params$certExpiratio !== void 0 ? _params$certExpiratio : dynamicSettings === null || dynamicSettings === void 0 ? void 0 : dynamicSettings.certExpirationThreshold) !== null && _ref !== void 0 ? _ref : _constants.DYNAMIC_SETTINGS_DEFAULTS.certExpirationThreshold; const certAgeThreshold = (_ref2 = (_params$certAgeThresh = params.certAgeThreshold) !== null && _params$certAgeThresh !== void 0 ? _params$certAgeThresh : dynamicSettings === null || dynamicSettings === void 0 ? void 0 : dynamicSettings.certAgeThreshold) !== null && _ref2 !== void 0 ? _ref2 : _constants.DYNAMIC_SETTINGS_DEFAULTS.certAgeThreshold; let filters; if (params.search) { filters = await (0, _status_check.formatFilterString)(uptimeEsClient, undefined, params.search, libs); } const { certs, total } = await libs.requests.getCerts({ uptimeEsClient, pageIndex: 0, size: 1000, notValidAfter: `now+${certExpirationThreshold}d`, notValidBefore: `now-${certAgeThreshold}d`, sortBy: 'common_name', direction: 'desc', filters }); const foundCerts = total > 0; if (foundCerts) { await (0, _std.asyncForEach)(certs, async cert => { var _cert$issuer2, _getAlertStartedDate; const absoluteExpirationThreshold = (0, _moment.default)().add(certExpirationThreshold, 'd').valueOf(); const absoluteAgeThreshold = (0, _moment.default)().subtract(certAgeThreshold, 'd').valueOf(); const summary = getCertSummary(cert, absoluteExpirationThreshold, absoluteAgeThreshold); if (!summary.summary || !summary.status) { return; } const alertId = `${cert.common_name}-${(_cert$issuer2 = cert.issuer) === null || _cert$issuer2 === void 0 ? void 0 : _cert$issuer2.replace(/\s/g, '_')}-${cert.sha256}`; const alertUuid = getAlertUuid(alertId); const indexedStartedAt = (_getAlertStartedDate = getAlertStartedDate(alertId)) !== null && _getAlertStartedDate !== void 0 ? _getAlertStartedDate : startedAt.toISOString(); const alertInstance = alertWithLifecycle({ id: alertId, fields: { 'tls.server.x509.subject.common_name': cert.common_name, 'tls.server.x509.issuer.common_name': cert.issuer, 'tls.server.x509.not_after': cert.not_after, 'tls.server.x509.not_before': cert.not_before, 'tls.server.hash.sha256': cert.sha256, [_ruleDataUtils.ALERT_REASON]: (0, _common2.generateAlertMessage)(_translations2.TlsTranslations.defaultActionMessage, summary), [_ruleDataUtils.ALERT_UUID]: alertUuid } }); alertInstance.replaceState({ ...(0, _common2.updateState)(state, foundCerts), ...summary }); alertInstance.scheduleActions(_uptime_alerts.TLS.id, { [_action_variables.ALERT_DETAILS_URL]: await (0, _common.getAlertUrl)(alertUuid, spaceId, indexedStartedAt, alertsLocator, basePath.publicBaseUrl), ...summary }); }); } await (0, _common2.setRecoveredAlertsContext)({ alertFactory, alertsLocator, basePath, defaultStartedAt: startedAt.toISOString(), getAlertStartedDate, getAlertUuid, spaceId }); return { state: (0, _common2.updateState)(state, foundCerts) }; }, alerts: _common2.UptimeRuleTypeAlertDefinition, getViewInAppRelativeUrl: ({ rule }) => _common.observabilityPaths.ruleDetails(rule.id) }); exports.tlsAlertFactory = tlsAlertFactory;