Пример #1
0
    def delete(self, ref_or_id, requester_user):
        """
            Delete an action alias.

            Handles requests:
                DELETE /actionalias/1
        """
        action_alias_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)
        LOG.debug('DELETE /actionalias/ lookup with id=%s found object: %s', ref_or_id,
                  action_alias_db)

        permission_type = PermissionType.ACTION_ALIAS_DELETE
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=action_alias_db,
                                                          permission_type=permission_type)

        try:
            ActionAlias.delete(action_alias_db)
        except Exception as e:
            LOG.exception('Database delete encountered exception during delete of id="%s".',
                          ref_or_id)
            abort(http_client.INTERNAL_SERVER_ERROR, six.text_type(e))
            return

        extra = {'action_alias_db': action_alias_db}
        LOG.audit('Action alias deleted. ActionAlias.id=%s.' % (action_alias_db.id), extra=extra)

        return Response(status=http_client.NO_CONTENT)
Пример #2
0
    def delete(self, ref_or_id, requester_user):
        """
            Delete an action alias.

            Handles requests:
                DELETE /actionalias/1
        """
        action_alias_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)
        LOG.debug('DELETE /actionalias/ lookup with id=%s found object: %s', ref_or_id,
                  action_alias_db)

        permission_type = PermissionType.ACTION_ALIAS_DELETE
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=action_alias_db,
                                                          permission_type=permission_type)

        try:
            ActionAlias.delete(action_alias_db)
        except Exception as e:
            LOG.exception('Database delete encountered exception during delete of id="%s".',
                          ref_or_id)
            abort(http_client.INTERNAL_SERVER_ERROR, six.text_type(e))
            return

        extra = {'action_alias_db': action_alias_db}
        LOG.audit('Action alias deleted. ActionAlias.id=%s.' % (action_alias_db.id), extra=extra)

        return Response(status=http_client.NO_CONTENT)
Пример #3
0
    def _register_action_alias(self, pack, action_alias):
        action_alias_db = self._get_action_alias_db(pack=pack,
                                                    action_alias=action_alias)

        try:
            action_alias_db.id = ActionAlias.get_by_name(
                action_alias_db.name).id
        except StackStormDBObjectNotFoundError:
            LOG.debug('ActionAlias %s not found. Creating new one.',
                      action_alias)

        action_ref = action_alias_db.action_ref

        action_db = Action.get_by_ref(action_ref)
        if not action_db:
            LOG.warning(
                'Action %s not found in DB. Did you forget to register the action?',
                action_ref)

        try:
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
            extra = {'action_alias_db': action_alias_db}
            LOG.audit('Action alias updated. Action alias %s from %s.',
                      action_alias_db,
                      action_alias,
                      extra=extra)
        except Exception:
            LOG.exception('Failed to create action alias %s.',
                          action_alias_db.name)
            raise
Пример #4
0
    def _register_action_alias(self, pack, action_alias):
        content = self._meta_loader.load(action_alias)
        pack_field = content.get('pack', None)
        if not pack_field:
            content['pack'] = pack
            pack_field = pack
        if pack_field != pack:
            raise Exception(
                'Model is in pack "%s" but field "pack" is different: %s' %
                (pack, pack_field))

        action_alias_api = ActionAliasAPI(**content)
        action_alias_api.validate()
        action_alias_db = ActionAliasAPI.to_model(action_alias_api)

        try:
            action_alias_db.id = ActionAlias.get_by_name(
                action_alias_api.name).id
        except ValueError:
            LOG.debug('ActionAlias %s not found. Creating new one.',
                      action_alias)

        try:
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
            extra = {'action_alias_db': action_alias_db}
            LOG.audit('Action alias updated. Action alias %s from %s.',
                      action_alias_db,
                      action_alias,
                      extra=extra)
        except Exception:
            LOG.exception('Failed to create action alias %s.',
                          action_alias_api.name)
            raise
Пример #5
0
    def _register_action_alias(self, pack, action_alias):
        content = self._meta_loader.load(action_alias)
        pack_field = content.get('pack', None)
        if not pack_field:
            content['pack'] = pack
            pack_field = pack
        if pack_field != pack:
            raise Exception('Model is in pack "%s" but field "pack" is different: %s' %
                            (pack, pack_field))

        action_alias_api = ActionAliasAPI(**content)
        action_alias_api.validate()
        action_alias_db = ActionAliasAPI.to_model(action_alias_api)

        try:
            action_alias_db.id = ActionAlias.get_by_name(action_alias_api.name).id
        except ValueError:
            LOG.info('ActionAlias %s not found. Creating new one.', action_alias)

        try:
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
            extra = {'action_alias_db': action_alias_db}
            LOG.audit('Action alias updated. Action alias %s from %s.', action_alias_db,
                      action_alias, extra=extra)
        except Exception:
            LOG.exception('Failed to create action alias %s.', action_alias_api.name)
            raise
Пример #6
0
    def test_run(self):
        pack = 'dummy_pack_1'
        # Verify all the resources are there

        pack_dbs = Pack.query(ref=pack)
        action_dbs = Action.query(pack=pack)
        alias_dbs = ActionAlias.query(pack=pack)
        rule_dbs = Rule.query(pack=pack)
        sensor_dbs = Sensor.query(pack=pack)
        trigger_type_dbs = TriggerType.query(pack=pack)
        policy_dbs = Policy.query(pack=pack)

        config_schema_dbs = ConfigSchema.query(pack=pack)
        config_dbs = Config.query(pack=pack)

        self.assertEqual(len(pack_dbs), 1)
        self.assertEqual(len(action_dbs), 1)
        self.assertEqual(len(alias_dbs), 3)
        self.assertEqual(len(rule_dbs), 1)
        self.assertEqual(len(sensor_dbs), 3)
        self.assertEqual(len(trigger_type_dbs), 4)
        self.assertEqual(len(policy_dbs), 2)

        self.assertEqual(len(config_schema_dbs), 1)
        self.assertEqual(len(config_dbs), 1)

        # Run action
        action = self.get_action_instance()
        action.run(packs=[pack])

        # Make sure all resources have been removed from the db
        pack_dbs = Pack.query(ref=pack)
        action_dbs = Action.query(pack=pack)
        alias_dbs = ActionAlias.query(pack=pack)
        rule_dbs = Rule.query(pack=pack)
        sensor_dbs = Sensor.query(pack=pack)
        trigger_type_dbs = TriggerType.query(pack=pack)
        policy_dbs = Policy.query(pack=pack)

        config_schema_dbs = ConfigSchema.query(pack=pack)
        config_dbs = Config.query(pack=pack)

        self.assertEqual(len(pack_dbs), 0)
        self.assertEqual(len(action_dbs), 0)
        self.assertEqual(len(alias_dbs), 0)
        self.assertEqual(len(rule_dbs), 0)
        self.assertEqual(len(sensor_dbs), 0)
        self.assertEqual(len(trigger_type_dbs), 0)
        self.assertEqual(len(policy_dbs), 0)

        self.assertEqual(len(config_schema_dbs), 0)
        self.assertEqual(len(config_dbs), 0)
Пример #7
0
    def test_run(self):
        pack = 'dummy_pack_1'
        # Verify all the resources are there

        pack_dbs = Pack.query(ref=pack)
        action_dbs = Action.query(pack=pack)
        alias_dbs = ActionAlias.query(pack=pack)
        rule_dbs = Rule.query(pack=pack)
        sensor_dbs = Sensor.query(pack=pack)
        trigger_type_dbs = TriggerType.query(pack=pack)
        policy_dbs = Policy.query(pack=pack)

        config_schema_dbs = ConfigSchema.query(pack=pack)
        config_dbs = Config.query(pack=pack)

        self.assertEqual(len(pack_dbs), 1)
        self.assertEqual(len(action_dbs), 1)
        self.assertEqual(len(alias_dbs), 2)
        self.assertEqual(len(rule_dbs), 1)
        self.assertEqual(len(sensor_dbs), 3)
        self.assertEqual(len(trigger_type_dbs), 4)
        self.assertEqual(len(policy_dbs), 2)

        self.assertEqual(len(config_schema_dbs), 1)
        self.assertEqual(len(config_dbs), 1)

        # Run action
        action = self.get_action_instance()
        action.run(packs=[pack])

        # Make sure all resources have been removed from the db
        pack_dbs = Pack.query(ref=pack)
        action_dbs = Action.query(pack=pack)
        alias_dbs = ActionAlias.query(pack=pack)
        rule_dbs = Rule.query(pack=pack)
        sensor_dbs = Sensor.query(pack=pack)
        trigger_type_dbs = TriggerType.query(pack=pack)
        policy_dbs = Policy.query(pack=pack)

        config_schema_dbs = ConfigSchema.query(pack=pack)
        config_dbs = Config.query(pack=pack)

        self.assertEqual(len(pack_dbs), 0)
        self.assertEqual(len(action_dbs), 0)
        self.assertEqual(len(alias_dbs), 0)
        self.assertEqual(len(rule_dbs), 0)
        self.assertEqual(len(sensor_dbs), 0)
        self.assertEqual(len(trigger_type_dbs), 0)
        self.assertEqual(len(policy_dbs), 0)

        self.assertEqual(len(config_schema_dbs), 0)
        self.assertEqual(len(config_dbs), 0)
Пример #8
0
    def _register_action_alias(self, pack, action_alias):
        action_alias_db = self._get_action_alias_db(pack=pack, action_alias=action_alias)

        try:
            action_alias_db.id = ActionAlias.get_by_name(action_alias_db.name).id
        except StackStormDBObjectNotFoundError:
            LOG.debug("ActionAlias %s not found. Creating new one.", action_alias)

        try:
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
            extra = {"action_alias_db": action_alias_db}
            LOG.audit("Action alias updated. Action alias %s from %s.", action_alias_db, action_alias, extra=extra)
        except Exception:
            LOG.exception("Failed to create action alias %s.", action_alias_db.name)
            raise
Пример #9
0
    def post(self, action_alias):
        """
            Create a new ActionAlias.

            Handles requests:
                POST /actionalias/
        """
        try:
            action_alias_db = ActionAliasAPI.to_model(action_alias)
            LOG.debug('/actionalias/ POST verified ActionAliasAPI and formulated ActionAliasDB=%s',
                      action_alias_db)
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
        except (ValidationError, ValueError, ValueValidationException) as e:
            LOG.exception('Validation failed for action alias data=%s.', action_alias)
            pecan.abort(http_client.BAD_REQUEST, str(e))
            return
        except StackStormDBObjectConflictError as e:
            LOG.warn('ActionAlias creation of %s failed with uniqueness conflict.', action_alias,
                     exc_info=True)
            pecan.abort(http_client.CONFLICT, str(e), body={'conflict-id': e.conflict_id})
            return

        extra = {'action_alias_db': action_alias_db}
        LOG.audit('Action alias created. ActionAlias.id=%s' % (action_alias_db.id), extra=extra)
        action_alias_api = ActionAliasAPI.from_model(action_alias_db)

        return action_alias_api
Пример #10
0
    def post(self, payload):
        action_alias_name = payload.name if payload else None

        if not action_alias_name:
            pecan.abort(http_client.BAD_REQUEST, 'Alias execution "name" is required')

        format = payload.format or ''
        command = payload.command or ''

        try:
            action_alias_db = ActionAlias.get_by_name(action_alias_name)
        except ValueError:
            action_alias_db = None

        if not action_alias_db:
            msg = 'Unable to identify action alias with name "%s".' % (action_alias_name)
            pecan.abort(http_client.NOT_FOUND, msg)
            return

        if not action_alias_db.enabled:
            msg = 'Action alias with name "%s" is disabled.' % (action_alias_name)
            pecan.abort(http_client.BAD_REQUEST, msg)
            return

        execution_parameters = self._extract_parameters(action_alias_db=action_alias_db,
                                                        format=format,
                                                        param_stream=command)
        notify = self._get_notify_field(payload)
        execution = self._schedule_execution(action_alias_db=action_alias_db,
                                             params=execution_parameters,
                                             notify=notify)

        return str(execution.id)
Пример #11
0
    def _register_action_alias(self, pack, action_alias):
        action_alias_db = self._get_action_alias_db(pack=pack, action_alias=action_alias)

        try:
            action_alias_db.id = ActionAlias.get_by_name(action_alias_db.name).id
        except ValueError:
            LOG.debug('ActionAlias %s not found. Creating new one.', action_alias)

        try:
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
            extra = {'action_alias_db': action_alias_db}
            LOG.audit('Action alias updated. Action alias %s from %s.', action_alias_db,
                      action_alias, extra=extra)
        except Exception:
            LOG.exception('Failed to create action alias %s.', action_alias_db.name)
            raise
Пример #12
0
    def post(self, action_alias, requester_user):
        """
            Create a new ActionAlias.

            Handles requests:
                POST /actionalias/
        """

        permission_type = PermissionType.ACTION_ALIAS_CREATE
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_api_permission(user_db=requester_user,
                                                           resource_api=action_alias,
                                                           permission_type=permission_type)

        try:
            action_alias_db = ActionAliasAPI.to_model(action_alias)
            LOG.debug('/actionalias/ POST verified ActionAliasAPI and formulated ActionAliasDB=%s',
                      action_alias_db)
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
        except (ValidationError, ValueError, ValueValidationException) as e:
            LOG.exception('Validation failed for action alias data=%s.', action_alias)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        extra = {'action_alias_db': action_alias_db}
        LOG.audit('Action alias created. ActionAlias.id=%s' % (action_alias_db.id), extra=extra)
        action_alias_api = ActionAliasAPI.from_model(action_alias_db)

        return Response(json=action_alias_api, status=http_client.CREATED)
Пример #13
0
    def put(self, action_alias_ref_or_id, action_alias):
        action_alias_db = self._get_by_ref_or_id(
            ref_or_id=action_alias_ref_or_id)
        LOG.debug('PUT /actionalias/ lookup with id=%s found object: %s',
                  action_alias_ref_or_id, action_alias_db)

        try:
            if action_alias.id is not None and action_alias.id is not '' and \
               action_alias.id != action_alias_ref_or_id:
                LOG.warning(
                    'Discarding mismatched id=%s found in payload and using uri_id=%s.',
                    action_alias.id, action_alias_ref_or_id)
            old_action_alias_db = action_alias_db
            action_alias_db = ActionAliasAPI.to_model(action_alias)
            action_alias_db.id = action_alias_ref_or_id
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for action alias data=%s',
                          action_alias)
            pecan.abort(http_client.BAD_REQUEST, str(e))
            return

        extra = {
            'old_action_alias_db': old_action_alias_db,
            'new_action_alias_db': action_alias_db
        }
        LOG.audit('Action alias updated. ActionAlias.id=%s.' %
                  (action_alias_db.id),
                  extra=extra)
        action_alias_api = ActionAliasAPI.from_model(action_alias_db)

        return action_alias_api
Пример #14
0
    def post(self, action_alias):
        """
            Create a new ActionAlias.

            Handles requests:
                POST /actionalias/
        """
        try:
            action_alias_db = ActionAliasAPI.to_model(action_alias)
            LOG.debug(
                '/actionalias/ POST verified ActionAliasAPI and formulated ActionAliasDB=%s',
                action_alias_db)
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
        except (ValidationError, ValueError, ValueValidationException) as e:
            LOG.exception('Validation failed for action alias data=%s.',
                          action_alias)
            pecan.abort(http_client.BAD_REQUEST, str(e))
            return

        extra = {'action_alias_db': action_alias_db}
        LOG.audit('Action alias created. ActionAlias.id=%s' %
                  (action_alias_db.id),
                  extra=extra)
        action_alias_api = ActionAliasAPI.from_model(action_alias_db)

        return action_alias_api
Пример #15
0
    def put(self, action_alias_ref_or_id, action_alias):
        action_alias_db = self._get_by_ref_or_id(ref_or_id=action_alias_ref_or_id)
        LOG.debug("PUT /actionalias/ lookup with id=%s found object: %s", action_alias_ref_or_id, action_alias_db)

        try:
            if action_alias.id is not None and action_alias.id is not "" and action_alias.id != action_alias_ref_or_id:
                LOG.warning(
                    "Discarding mismatched id=%s found in payload and using uri_id=%s.",
                    action_alias.id,
                    action_alias_ref_or_id,
                )
            old_action_alias_db = action_alias_db
            action_alias_db = ActionAliasAPI.to_model(action_alias)
            action_alias_db.id = action_alias_ref_or_id
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
        except (ValidationError, ValueError) as e:
            LOG.exception("Validation failed for action alias data=%s", action_alias)
            pecan.abort(http_client.BAD_REQUEST, str(e))
            return

        extra = {"old_action_alias_db": old_action_alias_db, "new_action_alias_db": action_alias_db}
        LOG.audit("Action alias updated. ActionAlias.id=%s." % (action_alias_db.id), extra=extra)
        action_alias_api = ActionAliasAPI.from_model(action_alias_db)

        return action_alias_api
Пример #16
0
    def post(self, action_alias, requester_user):
        """
            Create a new ActionAlias.

            Handles requests:
                POST /actionalias/
        """

        permission_type = PermissionType.ACTION_ALIAS_CREATE
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_api_permission(user_db=requester_user,
                                                           resource_api=action_alias,
                                                           permission_type=permission_type)

        try:
            action_alias_db = ActionAliasAPI.to_model(action_alias)
            LOG.debug('/actionalias/ POST verified ActionAliasAPI and formulated ActionAliasDB=%s',
                      action_alias_db)
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
        except (ValidationError, ValueError, ValueValidationException) as e:
            LOG.exception('Validation failed for action alias data=%s.', action_alias)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        extra = {'action_alias_db': action_alias_db}
        LOG.audit('Action alias created. ActionAlias.id=%s' % (action_alias_db.id), extra=extra)
        action_alias_api = ActionAliasAPI.from_model(action_alias_db)

        return Response(json=action_alias_api, status=http_client.CREATED)
Пример #17
0
    def post(self, payload):
        action_alias_name = payload.name if payload else None

        if not action_alias_name:
            pecan.abort(http_client.BAD_REQUEST,
                        'Alias execution "name" is required')

        format_str = payload.format or ''
        command = payload.command or ''

        try:
            action_alias_db = ActionAlias.get_by_name(action_alias_name)
        except ValueError:
            action_alias_db = None

        if not action_alias_db:
            msg = 'Unable to identify action alias with name "%s".' % (
                action_alias_name)
            pecan.abort(http_client.NOT_FOUND, msg)
            return

        if not action_alias_db.enabled:
            msg = 'Action alias with name "%s" is disabled.' % (
                action_alias_name)
            pecan.abort(http_client.BAD_REQUEST, msg)
            return

        execution_parameters = self._extract_parameters(
            action_alias_db=action_alias_db,
            format_str=format_str,
            param_stream=command)
        notify = self._get_notify_field(payload)

        context = {
            'action_alias_ref': reference.get_ref_from_model(action_alias_db),
            'api_user': payload.user,
            'user': get_requester(),
            'source_channel': payload.source_channel
        }

        execution = self._schedule_execution(action_alias_db=action_alias_db,
                                             params=execution_parameters,
                                             notify=notify,
                                             context=context)

        result = {
            'execution': execution,
            'actionalias': ActionAliasAPI.from_model(action_alias_db)
        }

        if action_alias_db.ack and 'format' in action_alias_db.ack:
            result.update({
                'message':
                render({'alias': action_alias_db.ack['format']},
                       result)['alias']
            })

        return result
Пример #18
0
    def post(self, payload):
        action_alias_name = payload.name if payload else None

        if not action_alias_name:
            pecan.abort(http_client.BAD_REQUEST, 'Alias execution "name" is required')

        format_str = payload.format or ''
        command = payload.command or ''

        try:
            action_alias_db = ActionAlias.get_by_name(action_alias_name)
        except ValueError:
            action_alias_db = None

        if not action_alias_db:
            msg = 'Unable to identify action alias with name "%s".' % (action_alias_name)
            pecan.abort(http_client.NOT_FOUND, msg)
            return

        if not action_alias_db.enabled:
            msg = 'Action alias with name "%s" is disabled.' % (action_alias_name)
            pecan.abort(http_client.BAD_REQUEST, msg)
            return

        execution_parameters = extract_parameters_for_action_alias_db(
            action_alias_db=action_alias_db,
            format_str=format_str,
            param_stream=command)
        notify = self._get_notify_field(payload)

        context = {
            'action_alias_ref': reference.get_ref_from_model(action_alias_db),
            'api_user': payload.user,
            'user': get_requester(),
            'source_channel': payload.source_channel
        }

        execution = self._schedule_execution(action_alias_db=action_alias_db,
                                             params=execution_parameters,
                                             notify=notify,
                                             context=context)

        result = {
            'execution': execution,
            'actionalias': ActionAliasAPI.from_model(action_alias_db)
        }

        if action_alias_db.ack:
            if 'format' in action_alias_db.ack:
                result.update({
                    'message': render({'alias': action_alias_db.ack['format']}, result)['alias']
                })
            if 'extra' in action_alias_db.ack:
                result.update({
                    'extra': render(action_alias_db.ack['extra'], result)
                })

        return result
Пример #19
0
    def delete(self, action_alias_ref_or_id):
        """
            Delete an action alias.

            Handles requests:
                DELETE /actionalias/1
        """
        action_alias_db = self._get_by_ref_or_id(ref_or_id=action_alias_ref_or_id)
        LOG.debug("DELETE /actionalias/ lookup with id=%s found object: %s", action_alias_ref_or_id, action_alias_db)
        try:
            ActionAlias.delete(action_alias_db)
        except Exception as e:
            LOG.exception('Database delete encountered exception during delete of id="%s".', action_alias_ref_or_id)
            pecan.abort(http_client.INTERNAL_SERVER_ERROR, str(e))
            return

        extra = {"action_alias_db": action_alias_db}
        LOG.audit("Action alias deleted. ActionAlias.id=%s." % (action_alias_db.id), extra=extra)
Пример #20
0
    def put(self, action_alias, ref_or_id, requester_user):
        """
        Update an action alias.

        Handles requests:
            PUT /actionalias/1
        """
        action_alias_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)
        LOG.debug(
            "PUT /actionalias/ lookup with id=%s found object: %s",
            ref_or_id,
            action_alias_db,
        )

        permission_type = PermissionType.ACTION_ALIAS_MODIFY
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(
            user_db=requester_user,
            resource_db=action_alias_db,
            permission_type=permission_type,
        )

        if not hasattr(action_alias, "id"):
            action_alias.id = None

        try:
            if (
                action_alias.id is not None
                and action_alias.id != ""
                and action_alias.id != ref_or_id
            ):
                LOG.warning(
                    "Discarding mismatched id=%s found in payload and using uri_id=%s.",
                    action_alias.id,
                    ref_or_id,
                )
            old_action_alias_db = action_alias_db
            action_alias_db = ActionAliasAPI.to_model(action_alias)
            action_alias_db.id = ref_or_id
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
        except (ValidationError, ValueError) as e:
            LOG.exception("Validation failed for action alias data=%s", action_alias)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        extra = {
            "old_action_alias_db": old_action_alias_db,
            "new_action_alias_db": action_alias_db,
        }
        LOG.audit(
            "Action alias updated. ActionAlias.id=%s." % (action_alias_db.id),
            extra=extra,
        )
        action_alias_api = ActionAliasAPI.from_model(action_alias_db)

        return action_alias_api
Пример #21
0
def get_matching_alias(command):
    """
    Find a matching ActionAliasDB object (if any) for the provided command.
    """
    # 1. Get aliases
    action_alias_dbs = ActionAlias.query(Q(formats__match_multiple=None)
                                         | Q(formats__match_multiple=False),
                                         enabled=True)

    # 2. Match alias(es) to command
    matches = match_command_to_alias(command=command, aliases=action_alias_dbs)

    if len(matches) > 1:
        raise ActionAliasAmbiguityException(
            "Command '%s' matched more than 1 pattern" % command,
            matches=matches,
            command=command,
        )
    elif len(matches) == 0:
        match_multiple_action_alias_dbs = ActionAlias.query(
            formats__match_multiple=True, enabled=True)

        matches = match_command_to_alias(
            command=command,
            aliases=match_multiple_action_alias_dbs,
            match_multiple=True,
        )

        if len(matches) > 1:
            raise ActionAliasAmbiguityException(
                "Command '%s' matched more than 1 (multi) pattern" % command,
                matches=matches,
                command=command,
            )

        if len(matches) == 0:
            raise ActionAliasAmbiguityException(
                "Command '%s' matched no patterns" % command,
                matches=[],
                command=command,
            )

    return matches[0]
Пример #22
0
    def delete(self, action_alias_ref_or_id):
        """
            Delete an action alias.

            Handles requests:
                DELETE /actionalias/1
        """
        action_alias_db = self._get_by_ref_or_id(ref_or_id=action_alias_ref_or_id)
        LOG.debug('DELETE /actionalias/ lookup with id=%s found object: %s', action_alias_ref_or_id,
                  action_alias_db)
        try:
            ActionAlias.delete(action_alias_db)
        except Exception as e:
            LOG.exception('Database delete encountered exception during delete of id="%s".',
                          action_alias_ref_or_id)
            pecan.abort(http_client.INTERNAL_SERVER_ERROR, str(e))
            return

        extra = {'action_alias_db': action_alias_db}
        LOG.audit('Action alias deleted. ActionAlias.id=%s.' % (action_alias_db.id), extra=extra)
Пример #23
0
    def _register_action_alias(self, pack, action_alias):
        action_alias_db = self._get_action_alias_db(pack=pack,
                                                    action_alias=action_alias)

        try:
            action_alias_db.id = ActionAlias.get_by_name(
                action_alias_db.name).id
        except ValueError:
            LOG.debug('ActionAlias %s not found. Creating new one.',
                      action_alias)

        try:
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
            extra = {'action_alias_db': action_alias_db}
            LOG.audit('Action alias updated. Action alias %s from %s.',
                      action_alias_db,
                      action_alias,
                      extra=extra)
        except Exception:
            LOG.exception('Failed to create action alias %s.',
                          action_alias_db.name)
            raise
Пример #24
0
def get_matching_alias(command):
    """
    Find a matching ActionAliasDB object (if any) for the provided command.
    """
    # 1. Get aliases
    action_alias_dbs = ActionAlias.query(
        Q(formats__match_multiple=None) | Q(formats__match_multiple=False),
        enabled=True)

    # 2. Match alias(es) to command
    matches = match_command_to_alias(command=command, aliases=action_alias_dbs)

    if len(matches) > 1:
        raise ActionAliasAmbiguityException("Command '%s' matched more than 1 pattern" %
                                            command,
                                            matches=matches,
                                            command=command)
    elif len(matches) == 0:
        match_multiple_action_alias_dbs = ActionAlias.query(
            formats__match_multiple=True,
            enabled=True)

        matches = match_command_to_alias(command=command, aliases=match_multiple_action_alias_dbs,
                                         match_multiple=True)

        if len(matches) > 1:
            raise ActionAliasAmbiguityException("Command '%s' matched more than 1 (multi) pattern" %
                                                command,
                                                matches=matches,
                                                command=command)

        if len(matches) == 0:
            raise ActionAliasAmbiguityException("Command '%s' matched no patterns" %
                                                command,
                                                matches=[],
                                                command=command)

    return matches[0]
Пример #25
0
    def _register_action_alias(self, pack, action_alias):
        action_alias_db = self._get_action_alias_db(pack=pack,
                                                    action_alias=action_alias)

        try:
            action_alias_db.id = ActionAlias.get_by_name(action_alias_db.name).id
        except StackStormDBObjectNotFoundError:
            LOG.debug('ActionAlias %s not found. Creating new one.', action_alias)

        action_ref = action_alias_db.action_ref

        action_db = Action.get_by_ref(action_ref)
        if not action_db:
            LOG.warning('Action %s not found in DB. Did you forget to register the action?',
                        action_ref)

        try:
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
            extra = {'action_alias_db': action_alias_db}
            LOG.audit('Action alias updated. Action alias %s from %s.', action_alias_db,
                      action_alias, extra=extra)
        except Exception:
            LOG.exception('Failed to create action alias %s.', action_alias_db.name)
            raise
Пример #26
0
    def put(self, action_alias, ref_or_id, requester_user):
        """
            Update an action alias.

            Handles requests:
                PUT /actionalias/1
        """
        action_alias_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)
        LOG.debug('PUT /actionalias/ lookup with id=%s found object: %s',
                  ref_or_id, action_alias_db)

        permission_type = PermissionType.ACTION_ALIAS_MODIFY
        rbac_utils.assert_user_has_resource_db_permission(
            user_db=requester_user,
            resource_db=action_alias_db,
            permission_type=permission_type)

        if not hasattr(action_alias, 'id'):
            action_alias.id = None

        try:
            if action_alias.id is not None and action_alias.id is not '' and \
               action_alias.id != ref_or_id:
                LOG.warning(
                    'Discarding mismatched id=%s found in payload and using uri_id=%s.',
                    action_alias.id, ref_or_id)
            old_action_alias_db = action_alias_db
            action_alias_db = ActionAliasAPI.to_model(action_alias)
            action_alias_db.id = ref_or_id
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for action alias data=%s',
                          action_alias)
            abort(http_client.BAD_REQUEST, str(e))
            return

        extra = {
            'old_action_alias_db': old_action_alias_db,
            'new_action_alias_db': action_alias_db
        }
        LOG.audit('Action alias updated. ActionAlias.id=%s.' %
                  (action_alias_db.id),
                  extra=extra)
        action_alias_api = ActionAliasAPI.from_model(action_alias_db)

        return action_alias_api
Пример #27
0
    def post(self, payload):
        action_alias_name = payload.name if payload else None

        if not action_alias_name:
            pecan.abort(http_client.BAD_REQUEST, 'Alias execution "name" is required')

        format_str = payload.format or ''
        command = payload.command or ''

        try:
            action_alias_db = ActionAlias.get_by_name(action_alias_name)
        except ValueError:
            action_alias_db = None

        if not action_alias_db:
            msg = 'Unable to identify action alias with name "%s".' % (action_alias_name)
            pecan.abort(http_client.NOT_FOUND, msg)
            return

        if not action_alias_db.enabled:
            msg = 'Action alias with name "%s" is disabled.' % (action_alias_name)
            pecan.abort(http_client.BAD_REQUEST, msg)
            return

        execution_parameters = self._extract_parameters(action_alias_db=action_alias_db,
                                                        format_str=format_str,
                                                        param_stream=command)
        notify = self._get_notify_field(payload)

        context = {
            'action_alias_ref': reference.get_ref_from_model(action_alias_db),
            'api_user': payload.user,
            'user': get_system_username(),
            'source_channel': payload.source_channel
        }

        execution = self._schedule_execution(action_alias_db=action_alias_db,
                                             params=execution_parameters,
                                             notify=notify,
                                             context=context)

        return str(execution.id)
Пример #28
0
    def post(self, action_alias):
        """
            Create a new ActionAlias.

            Handles requests:
                POST /actionalias/
        """
        try:
            action_alias_db = ActionAliasAPI.to_model(action_alias)
            LOG.debug("/actionalias/ POST verified ActionAliasAPI and formulated ActionAliasDB=%s", action_alias_db)
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
        except (ValidationError, ValueError, ValueValidationException) as e:
            LOG.exception("Validation failed for action alias data=%s.", action_alias)
            pecan.abort(http_client.BAD_REQUEST, str(e))
            return

        extra = {"action_alias_db": action_alias_db}
        LOG.audit("Action alias created. ActionAlias.id=%s" % (action_alias_db.id), extra=extra)
        action_alias_api = ActionAliasAPI.from_model(action_alias_db)

        return action_alias_api
Пример #29
0
    def put(self, action_alias, ref_or_id, requester_user):
        """
            Update an action alias.

            Handles requests:
                PUT /actionalias/1
        """
        action_alias_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)
        LOG.debug('PUT /actionalias/ lookup with id=%s found object: %s', ref_or_id,
                  action_alias_db)

        permission_type = PermissionType.ACTION_ALIAS_MODIFY
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=action_alias_db,
                                                          permission_type=permission_type)

        if not hasattr(action_alias, 'id'):
            action_alias.id = None

        try:
            if action_alias.id is not None and action_alias.id != '' and \
               action_alias.id != ref_or_id:
                LOG.warning('Discarding mismatched id=%s found in payload and using uri_id=%s.',
                            action_alias.id, ref_or_id)
            old_action_alias_db = action_alias_db
            action_alias_db = ActionAliasAPI.to_model(action_alias)
            action_alias_db.id = ref_or_id
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for action alias data=%s', action_alias)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        extra = {'old_action_alias_db': old_action_alias_db, 'new_action_alias_db': action_alias_db}
        LOG.audit('Action alias updated. ActionAlias.id=%s.' % (action_alias_db.id), extra=extra)
        action_alias_api = ActionAliasAPI.from_model(action_alias_db)

        return action_alias_api
Пример #30
0
    def post(self, payload):
        action_alias_name = payload.name if payload else None

        if not action_alias_name:
            pecan.abort(http_client.BAD_REQUEST,
                        'Alias execution "name" is required')

        format = payload.format or ''
        command = payload.command or ''

        try:
            action_alias_db = ActionAlias.get_by_name(action_alias_name)
        except ValueError:
            action_alias_db = None

        if not action_alias_db:
            msg = 'Unable to identify action alias with name "%s".' % (
                action_alias_name)
            pecan.abort(http_client.NOT_FOUND, msg)
            return

        if not action_alias_db.enabled:
            msg = 'Action alias with name "%s" is disabled.' % (
                action_alias_name)
            pecan.abort(http_client.BAD_REQUEST, msg)
            return

        execution_parameters = self._extract_parameters(
            action_alias_db=action_alias_db,
            format=format,
            param_stream=command)
        notify = self._get_notify_field(payload)
        execution = self._schedule_execution(action_alias_db=action_alias_db,
                                             params=execution_parameters,
                                             notify=notify)

        return str(execution.id)
Пример #31
0
    def _post(self, payload, requester_user, show_secrets=False, match_multiple=False):
        action_alias_name = payload.name if payload else None

        if not action_alias_name:
            abort(http_client.BAD_REQUEST, 'Alias execution "name" is required')
            return

        if not requester_user:
            requester_user = UserDB(cfg.CONF.system_user.user)

        format_str = payload.format or ''
        command = payload.command or ''

        try:
            action_alias_db = ActionAlias.get_by_name(action_alias_name)
        except ValueError:
            action_alias_db = None

        if not action_alias_db:
            msg = 'Unable to identify action alias with name "%s".' % (action_alias_name)
            abort(http_client.NOT_FOUND, msg)
            return

        if not action_alias_db.enabled:
            msg = 'Action alias with name "%s" is disabled.' % (action_alias_name)
            abort(http_client.BAD_REQUEST, msg)
            return

        if match_multiple:
            multiple_execution_parameters = extract_parameters_for_action_alias_db(
                action_alias_db=action_alias_db,
                format_str=format_str,
                param_stream=command,
                match_multiple=match_multiple)
        else:
            multiple_execution_parameters = [
                extract_parameters_for_action_alias_db(
                    action_alias_db=action_alias_db,
                    format_str=format_str,
                    param_stream=command,
                    match_multiple=match_multiple)
            ]

        notify = self._get_notify_field(payload)

        context = {
            'action_alias_ref': reference.get_ref_from_model(action_alias_db),
            'api_user': payload.user,
            'user': requester_user.name,
            'source_channel': payload.source_channel
        }

        results = []
        for execution_parameters in multiple_execution_parameters:
            execution = self._schedule_execution(action_alias_db=action_alias_db,
                                                 params=execution_parameters,
                                                 notify=notify,
                                                 context=context,
                                                 show_secrets=show_secrets,
                                                 requester_user=requester_user)

            result = {
                'execution': execution,
                'actionalias': ActionAliasAPI.from_model(action_alias_db)
            }

            if action_alias_db.ack:
                try:
                    if 'format' in action_alias_db.ack:
                        message = render({'alias': action_alias_db.ack['format']}, result)['alias']

                        result.update({
                            'message': message
                        })
                except UndefinedError as e:
                    result.update({
                        'message': ('Cannot render "format" in field "ack" for alias. ' +
                                    six.text_type(e))
                    })

                try:
                    if 'extra' in action_alias_db.ack:
                        result.update({
                            'extra': render(action_alias_db.ack['extra'], result)
                        })
                except UndefinedError as e:
                    result.update({
                        'extra': ('Cannot render "extra" in field "ack" for alias. ' +
                                  six.text_type(e))
                    })

            results.append(result)

        return results
Пример #32
0
    def _post(self,
              payload,
              requester_user,
              show_secrets=False,
              match_multiple=False):
        action_alias_name = payload.name if payload else None

        if not action_alias_name:
            abort(http_client.BAD_REQUEST,
                  'Alias execution "name" is required')
            return

        if not requester_user:
            requester_user = UserDB(cfg.CONF.system_user.user)

        format_str = payload.format or ''
        command = payload.command or ''

        try:
            action_alias_db = ActionAlias.get_by_name(action_alias_name)
        except ValueError:
            action_alias_db = None

        if not action_alias_db:
            msg = 'Unable to identify action alias with name "%s".' % (
                action_alias_name)
            abort(http_client.NOT_FOUND, msg)
            return

        if not action_alias_db.enabled:
            msg = 'Action alias with name "%s" is disabled.' % (
                action_alias_name)
            abort(http_client.BAD_REQUEST, msg)
            return

        if match_multiple:
            multiple_execution_parameters = extract_parameters_for_action_alias_db(
                action_alias_db=action_alias_db,
                format_str=format_str,
                param_stream=command,
                match_multiple=match_multiple)
        else:
            multiple_execution_parameters = [
                extract_parameters_for_action_alias_db(
                    action_alias_db=action_alias_db,
                    format_str=format_str,
                    param_stream=command,
                    match_multiple=match_multiple)
            ]

        notify = self._get_notify_field(payload)

        context = {
            'action_alias_ref': reference.get_ref_from_model(action_alias_db),
            'api_user': payload.user,
            'user': requester_user.name,
            'source_channel': payload.source_channel,
        }

        inject_immutable_parameters(
            action_alias_db=action_alias_db,
            multiple_execution_parameters=multiple_execution_parameters,
            action_context=context)

        results = []
        for execution_parameters in multiple_execution_parameters:
            execution = self._schedule_execution(
                action_alias_db=action_alias_db,
                params=execution_parameters,
                notify=notify,
                context=context,
                show_secrets=show_secrets,
                requester_user=requester_user)

            result = {
                'execution': execution,
                'actionalias': ActionAliasAPI.from_model(action_alias_db)
            }

            if action_alias_db.ack:
                try:
                    if 'format' in action_alias_db.ack:
                        message = render(
                            {'alias': action_alias_db.ack['format']},
                            result)['alias']

                        result.update({'message': message})
                except UndefinedError as e:
                    result.update({
                        'message':
                        ('Cannot render "format" in field "ack" for alias. ' +
                         six.text_type(e))
                    })

                try:
                    if 'extra' in action_alias_db.ack:
                        result.update({
                            'extra':
                            render(action_alias_db.ack['extra'], result)
                        })
                except UndefinedError as e:
                    result.update({
                        'extra':
                        ('Cannot render "extra" in field "ack" for alias. ' +
                         six.text_type(e))
                    })

            results.append(result)

        return results
Пример #33
0
    def post(self, payload, requester_user=None, show_secrets=False):
        action_alias_name = payload.name if payload else None

        if not action_alias_name:
            abort(http_client.BAD_REQUEST,
                  'Alias execution "name" is required')
            return

        if not requester_user:
            requester_user = UserDB(cfg.CONF.system_user.user)

        format_str = payload.format or ''
        command = payload.command or ''

        try:
            action_alias_db = ActionAlias.get_by_name(action_alias_name)
        except ValueError:
            action_alias_db = None

        if not action_alias_db:
            msg = 'Unable to identify action alias with name "%s".' % (
                action_alias_name)
            abort(http_client.NOT_FOUND, msg)
            return

        if not action_alias_db.enabled:
            msg = 'Action alias with name "%s" is disabled.' % (
                action_alias_name)
            abort(http_client.BAD_REQUEST, msg)
            return

        execution_parameters = extract_parameters_for_action_alias_db(
            action_alias_db=action_alias_db,
            format_str=format_str,
            param_stream=command)
        notify = self._get_notify_field(payload)

        context = {
            'action_alias_ref': reference.get_ref_from_model(action_alias_db),
            'api_user': payload.user,
            'user': requester_user.name,
            'source_channel': payload.source_channel
        }

        execution = self._schedule_execution(action_alias_db=action_alias_db,
                                             params=execution_parameters,
                                             notify=notify,
                                             context=context,
                                             show_secrets=show_secrets,
                                             requester_user=requester_user)

        result = {
            'execution': execution,
            'actionalias': ActionAliasAPI.from_model(action_alias_db)
        }

        if action_alias_db.ack:
            try:
                if 'format' in action_alias_db.ack:
                    result.update({
                        'message':
                        render({'alias': action_alias_db.ack['format']},
                               result)['alias']
                    })
            except UndefinedError as e:
                result.update({
                    'message':
                    'Cannot render "format" in field "ack" for alias. ' +
                    e.message
                })

            try:
                if 'extra' in action_alias_db.ack:
                    result.update({
                        'extra':
                        render(action_alias_db.ack['extra'], result)
                    })
            except UndefinedError as e:
                result.update({
                    'extra':
                    'Cannot render "extra" in field "ack" for alias. ' +
                    e.message
                })

        return Response(json=result, status=http_client.CREATED)