"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ActionsClient = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _uuid = require("uuid");
var _boom = _interopRequireDefault(require("@hapi/boom"));
var _url = _interopRequireDefault(require("url"));
var _i18n = require("@kbn/i18n");
var _lodash = require("lodash");
var _server = require("@kbn/core/server");
var _get_all = require("../application/connector/methods/get_all");
var _list_types = require("../application/connector/methods/list_types");
var _lib = require("../lib");
var _preconfigured_action_disabled_modification = require("../lib/errors/preconfigured_action_disabled_modification");
var _get_authorization_mode_by_source = require("../authorization/get_authorization_mode_by_source");
var _audit_events = require("../lib/audit_events");
var _track_legacy_rbac_exemption = require("../lib/track_legacy_rbac_exemption");
var _get_oauth_jwt_access_token = require("../lib/get_oauth_jwt_access_token");
var _get_oauth_client_credentials_access_token = require("../lib/get_oauth_client_credentials_access_token");
var _get_execution_log_aggregation = require("../lib/get_execution_log_aggregation");
var _lib2 = require("../application/connector/lib");
/*
 * 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.
 */

class ActionsClient {
  constructor({
    logger,
    actionTypeRegistry,
    kibanaIndices,
    scopedClusterClient,
    unsecuredSavedObjectsClient,
    inMemoryConnectors,
    actionExecutor,
    ephemeralExecutionEnqueuer,
    bulkExecutionEnqueuer,
    request,
    authorization,
    auditLogger,
    usageCounter,
    connectorTokenClient,
    getEventLogClient
  }) {
    (0, _defineProperty2.default)(this, "context", void 0);
    this.context = {
      logger,
      actionTypeRegistry,
      unsecuredSavedObjectsClient,
      scopedClusterClient,
      kibanaIndices,
      inMemoryConnectors,
      actionExecutor,
      ephemeralExecutionEnqueuer,
      bulkExecutionEnqueuer,
      request,
      authorization,
      auditLogger,
      usageCounter,
      connectorTokenClient,
      getEventLogClient
    };
  }

  /**
   * Create an action
   */
  async create({
    action: {
      actionTypeId,
      name,
      config,
      secrets
    },
    options
  }) {
    var _actionType$validate, _this$context$auditLo2;
    const id = (options === null || options === void 0 ? void 0 : options.id) || _server.SavedObjectsUtils.generateId();
    try {
      await this.context.authorization.ensureAuthorized({
        operation: 'create',
        actionTypeId
      });
    } catch (error) {
      var _this$context$auditLo;
      (_this$context$auditLo = this.context.auditLogger) === null || _this$context$auditLo === void 0 ? void 0 : _this$context$auditLo.log((0, _audit_events.connectorAuditEvent)({
        action: _audit_events.ConnectorAuditAction.CREATE,
        savedObject: {
          type: 'action',
          id
        },
        error
      }));
      throw error;
    }
    const foundInMemoryConnector = this.context.inMemoryConnectors.find(connector => connector.id === id);
    if (this.context.actionTypeRegistry.isSystemActionType(actionTypeId) || foundInMemoryConnector !== null && foundInMemoryConnector !== void 0 && foundInMemoryConnector.isSystemAction) {
      throw _boom.default.badRequest(_i18n.i18n.translate('xpack.actions.serverSideErrors.systemActionCreationForbidden', {
        defaultMessage: 'System action creation is forbidden. Action type: {actionTypeId}.',
        values: {
          actionTypeId
        }
      }));
    }
    if (foundInMemoryConnector !== null && foundInMemoryConnector !== void 0 && foundInMemoryConnector.isPreconfigured) {
      throw _boom.default.badRequest(_i18n.i18n.translate('xpack.actions.serverSideErrors.predefinedIdConnectorAlreadyExists', {
        defaultMessage: 'This {id} already exists in a preconfigured action.',
        values: {
          id
        }
      }));
    }
    const actionType = this.context.actionTypeRegistry.get(actionTypeId);
    const configurationUtilities = this.context.actionTypeRegistry.getUtils();
    const validatedActionTypeConfig = (0, _lib.validateConfig)(actionType, config, {
      configurationUtilities
    });
    const validatedActionTypeSecrets = (0, _lib.validateSecrets)(actionType, secrets, {
      configurationUtilities
    });
    if ((_actionType$validate = actionType.validate) !== null && _actionType$validate !== void 0 && _actionType$validate.connector) {
      (0, _lib.validateConnector)(actionType, {
        config,
        secrets
      });
    }
    this.context.actionTypeRegistry.ensureActionTypeEnabled(actionTypeId);
    (_this$context$auditLo2 = this.context.auditLogger) === null || _this$context$auditLo2 === void 0 ? void 0 : _this$context$auditLo2.log((0, _audit_events.connectorAuditEvent)({
      action: _audit_events.ConnectorAuditAction.CREATE,
      savedObject: {
        type: 'action',
        id
      },
      outcome: 'unknown'
    }));
    const result = await this.context.unsecuredSavedObjectsClient.create('action', {
      actionTypeId,
      name,
      isMissingSecrets: false,
      config: validatedActionTypeConfig,
      secrets: validatedActionTypeSecrets
    }, {
      id
    });
    return {
      id: result.id,
      actionTypeId: result.attributes.actionTypeId,
      isMissingSecrets: result.attributes.isMissingSecrets,
      name: result.attributes.name,
      config: result.attributes.config,
      isPreconfigured: false,
      isSystemAction: false,
      isDeprecated: (0, _lib2.isConnectorDeprecated)(result.attributes)
    };
  }

  /**
   * Update action
   */
  async update({
    id,
    action
  }) {
    var _actionType$validate2, _this$context$auditLo4;
    try {
      await this.context.authorization.ensureAuthorized({
        operation: 'update'
      });
      const foundInMemoryConnector = this.context.inMemoryConnectors.find(connector => connector.id === id);
      if (foundInMemoryConnector !== null && foundInMemoryConnector !== void 0 && foundInMemoryConnector.isSystemAction) {
        throw _boom.default.badRequest(_i18n.i18n.translate('xpack.actions.serverSideErrors.systemActionUpdateForbidden', {
          defaultMessage: 'System action {id} can not be updated.',
          values: {
            id
          }
        }));
      }
      if (foundInMemoryConnector !== null && foundInMemoryConnector !== void 0 && foundInMemoryConnector.isPreconfigured) {
        throw new _preconfigured_action_disabled_modification.PreconfiguredActionDisabledModificationError(_i18n.i18n.translate('xpack.actions.serverSideErrors.predefinedActionUpdateDisabled', {
          defaultMessage: 'Preconfigured action {id} can not be updated.',
          values: {
            id
          }
        }), 'update');
      }
    } catch (error) {
      var _this$context$auditLo3;
      (_this$context$auditLo3 = this.context.auditLogger) === null || _this$context$auditLo3 === void 0 ? void 0 : _this$context$auditLo3.log((0, _audit_events.connectorAuditEvent)({
        action: _audit_events.ConnectorAuditAction.UPDATE,
        savedObject: {
          type: 'action',
          id
        },
        error
      }));
      throw error;
    }
    const {
      attributes,
      references,
      version
    } = await this.context.unsecuredSavedObjectsClient.get('action', id);
    const {
      actionTypeId
    } = attributes;
    const {
      name,
      config,
      secrets
    } = action;
    const actionType = this.context.actionTypeRegistry.get(actionTypeId);
    const configurationUtilities = this.context.actionTypeRegistry.getUtils();
    const validatedActionTypeConfig = (0, _lib.validateConfig)(actionType, config, {
      configurationUtilities
    });
    const validatedActionTypeSecrets = (0, _lib.validateSecrets)(actionType, secrets, {
      configurationUtilities
    });
    if ((_actionType$validate2 = actionType.validate) !== null && _actionType$validate2 !== void 0 && _actionType$validate2.connector) {
      (0, _lib.validateConnector)(actionType, {
        config,
        secrets
      });
    }
    this.context.actionTypeRegistry.ensureActionTypeEnabled(actionTypeId);
    (_this$context$auditLo4 = this.context.auditLogger) === null || _this$context$auditLo4 === void 0 ? void 0 : _this$context$auditLo4.log((0, _audit_events.connectorAuditEvent)({
      action: _audit_events.ConnectorAuditAction.UPDATE,
      savedObject: {
        type: 'action',
        id
      },
      outcome: 'unknown'
    }));
    const result = await this.context.unsecuredSavedObjectsClient.create('action', {
      ...attributes,
      actionTypeId,
      name,
      isMissingSecrets: false,
      config: validatedActionTypeConfig,
      secrets: validatedActionTypeSecrets
    }, (0, _lodash.omitBy)({
      id,
      overwrite: true,
      references,
      version
    }, _lodash.isUndefined));
    try {
      await this.context.connectorTokenClient.deleteConnectorTokens({
        connectorId: id
      });
    } catch (e) {
      this.context.logger.error(`Failed to delete auth tokens for connector "${id}" after update: ${e.message}`);
    }
    return {
      id,
      actionTypeId: result.attributes.actionTypeId,
      isMissingSecrets: result.attributes.isMissingSecrets,
      name: result.attributes.name,
      config: result.attributes.config,
      isPreconfigured: false,
      isSystemAction: false,
      isDeprecated: (0, _lib2.isConnectorDeprecated)(result.attributes)
    };
  }

  /**
   * Get an action
   */
  async get({
    id,
    throwIfSystemAction = true
  }) {
    var _this$context$auditLo7;
    try {
      await this.context.authorization.ensureAuthorized({
        operation: 'get'
      });
    } catch (error) {
      var _this$context$auditLo5;
      (_this$context$auditLo5 = this.context.auditLogger) === null || _this$context$auditLo5 === void 0 ? void 0 : _this$context$auditLo5.log((0, _audit_events.connectorAuditEvent)({
        action: _audit_events.ConnectorAuditAction.GET,
        savedObject: {
          type: 'action',
          id
        },
        error
      }));
      throw error;
    }
    const foundInMemoryConnector = this.context.inMemoryConnectors.find(connector => connector.id === id);

    /**
     * Getting system connector is not allowed
     * if throwIfSystemAction is set to true.
     * Default behavior is to throw
     */
    if (foundInMemoryConnector !== undefined && foundInMemoryConnector.isSystemAction && throwIfSystemAction) {
      throw _boom.default.notFound(`Connector ${id} not found`);
    }
    if (foundInMemoryConnector !== undefined) {
      var _this$context$auditLo6;
      (_this$context$auditLo6 = this.context.auditLogger) === null || _this$context$auditLo6 === void 0 ? void 0 : _this$context$auditLo6.log((0, _audit_events.connectorAuditEvent)({
        action: _audit_events.ConnectorAuditAction.GET,
        savedObject: {
          type: 'action',
          id
        }
      }));
      return {
        id,
        actionTypeId: foundInMemoryConnector.actionTypeId,
        name: foundInMemoryConnector.name,
        isPreconfigured: foundInMemoryConnector.isPreconfigured,
        isSystemAction: foundInMemoryConnector.isSystemAction,
        isDeprecated: (0, _lib2.isConnectorDeprecated)(foundInMemoryConnector)
      };
    }
    const result = await this.context.unsecuredSavedObjectsClient.get('action', id);
    (_this$context$auditLo7 = this.context.auditLogger) === null || _this$context$auditLo7 === void 0 ? void 0 : _this$context$auditLo7.log((0, _audit_events.connectorAuditEvent)({
      action: _audit_events.ConnectorAuditAction.GET,
      savedObject: {
        type: 'action',
        id
      }
    }));
    return {
      id,
      actionTypeId: result.attributes.actionTypeId,
      isMissingSecrets: result.attributes.isMissingSecrets,
      name: result.attributes.name,
      config: result.attributes.config,
      isPreconfigured: false,
      isSystemAction: false,
      isDeprecated: (0, _lib2.isConnectorDeprecated)(result.attributes)
    };
  }

  /**
   * Get all connectors with in-memory connectors
   */
  async getAll({
    includeSystemActions = false
  } = {}) {
    return (0, _get_all.getAll)({
      context: this.context,
      includeSystemActions
    });
  }

  /**
   * Get bulk actions with in-memory list
   */
  async getBulk({
    ids,
    throwIfSystemAction = true
  }) {
    try {
      await this.context.authorization.ensureAuthorized({
        operation: 'get'
      });
    } catch (error) {
      ids.forEach(id => {
        var _this$context$auditLo8;
        return (_this$context$auditLo8 = this.context.auditLogger) === null || _this$context$auditLo8 === void 0 ? void 0 : _this$context$auditLo8.log((0, _audit_events.connectorAuditEvent)({
          action: _audit_events.ConnectorAuditAction.GET,
          savedObject: {
            type: 'action',
            id
          },
          error
        }));
      });
      throw error;
    }
    const actionResults = new Array();
    for (const actionId of ids) {
      const action = this.context.inMemoryConnectors.find(inMemoryConnector => inMemoryConnector.id === actionId);

      /**
       * Getting system connector is not allowed
       * if throwIfSystemAction is set to true.
       * Default behavior is to throw
       */
      if (action !== undefined && action.isSystemAction && throwIfSystemAction) {
        throw _boom.default.notFound(`Connector ${action.id} not found`);
      }
      if (action !== undefined) {
        actionResults.push(action);
      }
    }

    // Fetch action objects in bulk
    // Excluding in-memory actions to avoid an not found error, which is already added
    const actionSavedObjectsIds = [...new Set(ids.filter(actionId => !actionResults.find(actionResult => actionResult.id === actionId)))];
    const bulkGetOpts = actionSavedObjectsIds.map(id => ({
      id,
      type: 'action'
    }));
    const bulkGetResult = await this.context.unsecuredSavedObjectsClient.bulkGet(bulkGetOpts);
    bulkGetResult.saved_objects.forEach(({
      id,
      error
    }) => {
      if (!error && this.context.auditLogger) {
        this.context.auditLogger.log((0, _audit_events.connectorAuditEvent)({
          action: _audit_events.ConnectorAuditAction.GET,
          savedObject: {
            type: 'action',
            id
          }
        }));
      }
    });
    for (const action of bulkGetResult.saved_objects) {
      if (action.error) {
        throw _boom.default.badRequest(`Failed to load action ${action.id} (${action.error.statusCode}): ${action.error.message}`);
      }
      actionResults.push((0, _lib2.connectorFromSavedObject)(action, (0, _lib2.isConnectorDeprecated)(action.attributes)));
    }
    return actionResults;
  }
  async getOAuthAccessToken({
    type,
    options
  }, configurationUtilities) {
    // Verify that user has edit access
    await this.context.authorization.ensureAuthorized({
      operation: 'update'
    });

    // Verify that token url is allowed by allowed hosts config
    try {
      configurationUtilities.ensureUriAllowed(options.tokenUrl);
    } catch (err) {
      throw _boom.default.badRequest(err.message);
    }

    // Verify that token url contains a hostname and uses https
    const parsedUrl = _url.default.parse(options.tokenUrl, false /* parseQueryString */, true /* slashesDenoteHost */);

    if (!parsedUrl.hostname) {
      throw _boom.default.badRequest(`Token URL must contain hostname`);
    }
    if (parsedUrl.protocol !== 'https:' && parsedUrl.protocol !== 'http:') {
      throw _boom.default.badRequest(`Token URL must use http or https`);
    }
    let accessToken = null;
    if (type === 'jwt') {
      const tokenOpts = options;
      try {
        accessToken = await (0, _get_oauth_jwt_access_token.getOAuthJwtAccessToken)({
          logger: this.context.logger,
          configurationUtilities,
          credentials: {
            config: tokenOpts.config,
            secrets: tokenOpts.secrets
          },
          tokenUrl: tokenOpts.tokenUrl
        });
        this.context.logger.debug(`Successfully retrieved access token using JWT OAuth with tokenUrl ${tokenOpts.tokenUrl} and config ${JSON.stringify(tokenOpts.config)}`);
      } catch (err) {
        this.context.logger.debug(`Failed to retrieve access token using JWT OAuth with tokenUrl ${tokenOpts.tokenUrl} and config ${JSON.stringify(tokenOpts.config)} - ${err.message}`);
        throw _boom.default.badRequest(`Failed to retrieve access token`);
      }
    } else if (type === 'client') {
      const tokenOpts = options;
      try {
        accessToken = await (0, _get_oauth_client_credentials_access_token.getOAuthClientCredentialsAccessToken)({
          logger: this.context.logger,
          configurationUtilities,
          credentials: {
            config: tokenOpts.config,
            secrets: tokenOpts.secrets
          },
          tokenUrl: tokenOpts.tokenUrl,
          oAuthScope: tokenOpts.scope
        });
        this.context.logger.debug(`Successfully retrieved access token using Client Credentials OAuth with tokenUrl ${tokenOpts.tokenUrl}, scope ${tokenOpts.scope} and config ${JSON.stringify(tokenOpts.config)}`);
      } catch (err) {
        this.context.logger.debug(`Failed to retrieved access token using Client Credentials OAuth with tokenUrl ${tokenOpts.tokenUrl}, scope ${tokenOpts.scope} and config ${JSON.stringify(tokenOpts.config)} - ${err.message}`);
        throw _boom.default.badRequest(`Failed to retrieve access token`);
      }
    }
    return {
      accessToken
    };
  }

  /**
   * Delete action
   */
  async delete({
    id
  }) {
    var _this$context$auditLo10;
    try {
      await this.context.authorization.ensureAuthorized({
        operation: 'delete'
      });
      const foundInMemoryConnector = this.context.inMemoryConnectors.find(connector => connector.id === id);
      if (foundInMemoryConnector !== null && foundInMemoryConnector !== void 0 && foundInMemoryConnector.isSystemAction) {
        throw _boom.default.badRequest(_i18n.i18n.translate('xpack.actions.serverSideErrors.systemActionDeletionForbidden', {
          defaultMessage: 'System action {id} is not allowed to delete.',
          values: {
            id
          }
        }));
      }
      if (foundInMemoryConnector !== null && foundInMemoryConnector !== void 0 && foundInMemoryConnector.isPreconfigured) {
        throw new _preconfigured_action_disabled_modification.PreconfiguredActionDisabledModificationError(_i18n.i18n.translate('xpack.actions.serverSideErrors.predefinedActionDeleteDisabled', {
          defaultMessage: 'Preconfigured action {id} is not allowed to delete.',
          values: {
            id
          }
        }), 'delete');
      }
    } catch (error) {
      var _this$context$auditLo9;
      (_this$context$auditLo9 = this.context.auditLogger) === null || _this$context$auditLo9 === void 0 ? void 0 : _this$context$auditLo9.log((0, _audit_events.connectorAuditEvent)({
        action: _audit_events.ConnectorAuditAction.DELETE,
        savedObject: {
          type: 'action',
          id
        },
        error
      }));
      throw error;
    }
    (_this$context$auditLo10 = this.context.auditLogger) === null || _this$context$auditLo10 === void 0 ? void 0 : _this$context$auditLo10.log((0, _audit_events.connectorAuditEvent)({
      action: _audit_events.ConnectorAuditAction.DELETE,
      outcome: 'unknown',
      savedObject: {
        type: 'action',
        id
      }
    }));
    try {
      await this.context.connectorTokenClient.deleteConnectorTokens({
        connectorId: id
      });
    } catch (e) {
      this.context.logger.error(`Failed to delete auth tokens for connector "${id}" after delete: ${e.message}`);
    }
    return await this.context.unsecuredSavedObjectsClient.delete('action', id);
  }
  getSystemActionKibanaPrivileges(connectorId, params) {
    const inMemoryConnector = this.context.inMemoryConnectors.find(connector => connector.id === connectorId);
    const additionalPrivileges = inMemoryConnector !== null && inMemoryConnector !== void 0 && inMemoryConnector.isSystemAction ? this.context.actionTypeRegistry.getSystemActionKibanaPrivileges(inMemoryConnector.actionTypeId, params) : [];
    return additionalPrivileges;
  }
  async execute({
    actionId,
    params,
    source,
    relatedSavedObjects
  }) {
    if ((await (0, _get_authorization_mode_by_source.getAuthorizationModeBySource)(this.context.unsecuredSavedObjectsClient, source)) === _get_authorization_mode_by_source.AuthorizationMode.RBAC) {
      const additionalPrivileges = this.getSystemActionKibanaPrivileges(actionId, params);
      await this.context.authorization.ensureAuthorized({
        operation: 'execute',
        additionalPrivileges
      });
    } else {
      (0, _track_legacy_rbac_exemption.trackLegacyRBACExemption)('execute', this.context.usageCounter);
    }
    return this.context.actionExecutor.execute({
      actionId,
      params,
      source,
      request: this.context.request,
      relatedSavedObjects,
      actionExecutionId: (0, _uuid.v4)()
    });
  }
  async bulkEnqueueExecution(options) {
    const sources = (0, _lodash.compact)((options !== null && options !== void 0 ? options : []).map(option => option.source));
    const authModes = await (0, _get_authorization_mode_by_source.bulkGetAuthorizationModeBySource)(this.context.logger, this.context.unsecuredSavedObjectsClient, sources);
    if (authModes[_get_authorization_mode_by_source.AuthorizationMode.RBAC] > 0) {
      /**
       * For scheduled executions the additional authorization check
       * for system actions (kibana privileges) will be performed
       * inside the ActionExecutor at execution time
       */
      await this.context.authorization.ensureAuthorized({
        operation: 'execute'
      });
    }
    if (authModes[_get_authorization_mode_by_source.AuthorizationMode.Legacy] > 0) {
      (0, _track_legacy_rbac_exemption.trackLegacyRBACExemption)('bulkEnqueueExecution', this.context.usageCounter, authModes[_get_authorization_mode_by_source.AuthorizationMode.Legacy]);
    }
    return this.context.bulkExecutionEnqueuer(this.context.unsecuredSavedObjectsClient, options);
  }
  async ephemeralEnqueuedExecution(options) {
    const {
      source
    } = options;
    if ((await (0, _get_authorization_mode_by_source.getAuthorizationModeBySource)(this.context.unsecuredSavedObjectsClient, source)) === _get_authorization_mode_by_source.AuthorizationMode.RBAC) {
      await this.context.authorization.ensureAuthorized({
        operation: 'execute'
      });
    } else {
      (0, _track_legacy_rbac_exemption.trackLegacyRBACExemption)('ephemeralEnqueuedExecution', this.context.usageCounter);
    }
    return this.context.ephemeralExecutionEnqueuer(this.context.unsecuredSavedObjectsClient, options);
  }
  async listTypes({
    featureId,
    includeSystemActionTypes = false
  } = {}) {
    return (0, _list_types.listTypes)(this.context, {
      featureId,
      includeSystemActionTypes
    });
  }
  isActionTypeEnabled(actionTypeId, options = {
    notifyUsage: false
  }) {
    return this.context.actionTypeRegistry.isActionTypeEnabled(actionTypeId, options);
  }
  isPreconfigured(connectorId) {
    return !!this.context.inMemoryConnectors.find(connector => connector.isPreconfigured && connector.id === connectorId);
  }
  isSystemAction(connectorId) {
    return !!this.context.inMemoryConnectors.find(connector => connector.isSystemAction && connector.id === connectorId);
  }
  async getGlobalExecutionLogWithAuth({
    dateStart,
    dateEnd,
    filter,
    page,
    perPage,
    sort,
    namespaces
  }) {
    var _this$context$auditLo12;
    this.context.logger.debug(`getGlobalExecutionLogWithAuth(): getting global execution log`);
    const authorizationTuple = {};
    try {
      await this.context.authorization.ensureAuthorized({
        operation: 'get'
      });
    } catch (error) {
      var _this$context$auditLo11;
      (_this$context$auditLo11 = this.context.auditLogger) === null || _this$context$auditLo11 === void 0 ? void 0 : _this$context$auditLo11.log((0, _audit_events.connectorAuditEvent)({
        action: _audit_events.ConnectorAuditAction.GET_GLOBAL_EXECUTION_LOG,
        error
      }));
      throw error;
    }
    (_this$context$auditLo12 = this.context.auditLogger) === null || _this$context$auditLo12 === void 0 ? void 0 : _this$context$auditLo12.log((0, _audit_events.connectorAuditEvent)({
      action: _audit_events.ConnectorAuditAction.GET_GLOBAL_EXECUTION_LOG
    }));
    const dateNow = new Date();
    const parsedDateStart = (0, _lib.parseDate)(dateStart, 'dateStart', dateNow);
    const parsedDateEnd = (0, _lib.parseDate)(dateEnd, 'dateEnd', dateNow);
    const eventLogClient = await this.context.getEventLogClient();
    try {
      const aggResult = await eventLogClient.aggregateEventsWithAuthFilter('action', authorizationTuple, {
        start: parsedDateStart.toISOString(),
        end: parsedDateEnd.toISOString(),
        aggs: (0, _get_execution_log_aggregation.getExecutionLogAggregation)({
          filter: filter ? `${filter} AND (${_get_execution_log_aggregation.ACTION_FILTER})` : _get_execution_log_aggregation.ACTION_FILTER,
          page,
          perPage,
          sort
        })
      }, namespaces, true);
      return (0, _get_execution_log_aggregation.formatExecutionLogResult)(aggResult);
    } catch (err) {
      this.context.logger.debug(`actionsClient.getGlobalExecutionLogWithAuth(): error searching global event log: ${err.message}`);
      throw err;
    }
  }
  async getGlobalExecutionKpiWithAuth({
    dateStart,
    dateEnd,
    filter,
    namespaces
  }) {
    var _this$context$auditLo14;
    this.context.logger.debug(`getGlobalExecutionKpiWithAuth(): getting global execution KPI`);
    const authorizationTuple = {};
    try {
      await this.context.authorization.ensureAuthorized({
        operation: 'get'
      });
    } catch (error) {
      var _this$context$auditLo13;
      (_this$context$auditLo13 = this.context.auditLogger) === null || _this$context$auditLo13 === void 0 ? void 0 : _this$context$auditLo13.log((0, _audit_events.connectorAuditEvent)({
        action: _audit_events.ConnectorAuditAction.GET_GLOBAL_EXECUTION_KPI,
        error
      }));
      throw error;
    }
    (_this$context$auditLo14 = this.context.auditLogger) === null || _this$context$auditLo14 === void 0 ? void 0 : _this$context$auditLo14.log((0, _audit_events.connectorAuditEvent)({
      action: _audit_events.ConnectorAuditAction.GET_GLOBAL_EXECUTION_KPI
    }));
    const dateNow = new Date();
    const parsedDateStart = (0, _lib.parseDate)(dateStart, 'dateStart', dateNow);
    const parsedDateEnd = (0, _lib.parseDate)(dateEnd, 'dateEnd', dateNow);
    const eventLogClient = await this.context.getEventLogClient();
    try {
      const aggResult = await eventLogClient.aggregateEventsWithAuthFilter('action', authorizationTuple, {
        start: parsedDateStart.toISOString(),
        end: parsedDateEnd.toISOString(),
        aggs: (0, _get_execution_log_aggregation.getExecutionKPIAggregation)(filter ? `${filter} AND (${_get_execution_log_aggregation.ACTION_FILTER})` : _get_execution_log_aggregation.ACTION_FILTER)
      }, namespaces, true);
      return (0, _get_execution_log_aggregation.formatExecutionKPIResult)(aggResult);
    } catch (err) {
      this.context.logger.debug(`actionsClient.getGlobalExecutionKpiWithAuth(): error searching global execution KPI: ${err.message}`);
      throw err;
    }
  }
}
exports.ActionsClient = ActionsClient;