Beispiel #1
0
    def _get_one(self, ref_or_id, requester_user, permission_type, exclude_fields=None,
                 include_fields=None, from_model_kwargs=None):
        try:
            instance = self._get_by_ref_or_id(ref_or_id=ref_or_id, exclude_fields=exclude_fields,
                                              include_fields=include_fields)
        except Exception as e:
            LOG.exception(six.text_type(e))
            abort(http_client.NOT_FOUND, six.text_type(e))
            return

        if permission_type:
            rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                              resource_db=instance,
                                                              permission_type=permission_type)

        # Perform resource isolation check (if supported)
        from_model_kwargs = from_model_kwargs or {}
        from_model_kwargs.update(self.from_model_kwargs)

        result = self.resource_model_filter(model=self.model, instance=instance,
                                            requester_user=requester_user,
                                            **from_model_kwargs)

        if not result:
            LOG.debug('Not returning the result because RBAC resource isolation is enabled and '
                      'current user doesn\'t match the resource user')
            raise ResourceAccessDeniedPermissionIsolationError(user_db=requester_user,
                                                               resource_api_or_db=instance,
                                                               permission_type=permission_type)

        return Response(json=result)
Beispiel #2
0
 def _get_action_by_id(id):
     try:
         return Action.get_by_id(id)
     except Exception as e:
         msg = 'Database lookup for id="%s" resulted in exception. %s' % (id, e)
         LOG.exception(msg)
         abort(http_client.NOT_FOUND, msg)
Beispiel #3
0
    def _get_one_by_id(self, id, requester_user, permission_type, exclude_fields=None,
                       from_model_kwargs=None):
        """Override ResourceController._get_one_by_id to contain scope of Inquiries UID hack

        :param exclude_fields: A list of object fields to exclude.
        :type exclude_fields: ``list``
        """

        instance = self._get_by_id(resource_id=id, exclude_fields=exclude_fields)

        # _get_by_id pulls the resource by ID directly off of the database. Since
        # Inquiries don't have their own DB model yet, this comes in the format
        # "execution:<id>". So, to allow RBAC to get a handle on inquiries specifically,
        # we're overriding the "get_uid" function to return one specific to Inquiries.
        #
        # TODO (mierdin): All of this should be removed once Inquiries get their own DB model
        if getattr(instance, 'runner', None) and instance.runner.get('runner_module') == 'inquirer':
            def get_uid():
                return "inquiry"
            instance.get_uid = get_uid

        if permission_type:
            rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                              resource_db=instance,
                                                              permission_type=permission_type)

        if not instance:
            msg = 'Unable to identify resource with id "%s".' % id
            abort(http_client.NOT_FOUND, msg)

        from_model_kwargs = from_model_kwargs or {}
        from_model_kwargs.update(self.from_model_kwargs)
        result = self.model.from_model(instance, **from_model_kwargs)

        return result
Beispiel #4
0
    def put(self, runner_type_api, name_or_id, requester_user):
        # Note: We only allow "enabled" attribute of the runner to be changed
        runner_type_db = self._get_by_name_or_id(name_or_id=name_or_id)

        permission_type = PermissionType.RUNNER_MODIFY
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=runner_type_db,
                                                          permission_type=permission_type)

        old_runner_type_db = runner_type_db
        LOG.debug('PUT /runnertypes/ lookup with id=%s found object: %s', name_or_id,
                  runner_type_db)

        try:
            if runner_type_api.id and runner_type_api.id != name_or_id:
                LOG.warning('Discarding mismatched id=%s found in payload and using uri_id=%s.',
                            runner_type_api.id, name_or_id)

            runner_type_db.enabled = runner_type_api.enabled
            runner_type_db = RunnerType.add_or_update(runner_type_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for runner type data=%s', runner_type_api)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        extra = {'old_runner_type_db': old_runner_type_db, 'new_runner_type_db': runner_type_db}
        LOG.audit('Runner Type updated. RunnerType.id=%s.' % (runner_type_db.id), extra=extra)
        runner_type_api = RunnerTypeAPI.from_model(runner_type_db)
        return runner_type_api
Beispiel #5
0
    def _get_one_by_name_or_id(self, name_or_id, requester_user, permission_type,
                               exclude_fields=None, include_fields=None, from_model_kwargs=None):
        """
        :param exclude_fields: A list of object fields to exclude.
        :type exclude_fields: ``list``
        :param include_fields: A list of object fields to include.
        :type include_fields: ``list``
        """

        instance = self._get_by_name_or_id(name_or_id=name_or_id, exclude_fields=exclude_fields,
                                           include_fields=include_fields)

        if permission_type:
            rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                              resource_db=instance,
                                                              permission_type=permission_type)

        if not instance:
            msg = 'Unable to identify resource with name_or_id "%s".' % (name_or_id)
            abort(http_client.NOT_FOUND, msg)

        from_model_kwargs = from_model_kwargs or {}
        from_model_kwargs.update(self.from_model_kwargs)
        result = self.model.from_model(instance, **from_model_kwargs)

        return result
Beispiel #6
0
    def put(self, triggertype, triggertype_ref_or_id):
        triggertype_db = self._get_by_ref_or_id(ref_or_id=triggertype_ref_or_id)
        triggertype_id = triggertype_db.id

        try:
            validate_not_part_of_system_pack(triggertype_db)
        except ValueValidationException as e:
            abort(http_client.BAD_REQUEST, six.text_type(e))

        try:
            triggertype_db = TriggerTypeAPI.to_model(triggertype)
            if triggertype.id is not None and len(triggertype.id) > 0 and \
               triggertype.id != triggertype_id:
                LOG.warning('Discarding mismatched id=%s found in payload and using uri_id=%s.',
                            triggertype.id, triggertype_id)
            triggertype_db.id = triggertype_id
            old_triggertype_db = triggertype_db
            triggertype_db = TriggerType.add_or_update(triggertype_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for triggertype data=%s', triggertype)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        extra = {'old_triggertype_db': old_triggertype_db, 'new_triggertype_db': triggertype_db}
        LOG.audit('TriggerType updated. TriggerType.id=%s' % (triggertype_db.id), extra=extra)

        triggertype_api = TriggerTypeAPI.from_model(triggertype_db)
        return triggertype_api
Beispiel #7
0
    def _get_one_by_id(self, id, requester_user, permission_type, exclude_fields=None,
                       from_model_kwargs=None):
        """
        :param exclude_fields: A list of object fields to exclude.
        :type exclude_fields: ``list``
        """

        instance = self._get_by_id(resource_id=id, exclude_fields=exclude_fields)

        if permission_type:
            rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                              resource_db=instance,
                                                              permission_type=permission_type)

        if not instance:
            msg = 'Unable to identify resource with id "%s".' % id
            abort(http_client.NOT_FOUND, msg)

        from_model_kwargs = from_model_kwargs or {}
        from_model_kwargs.update(self.from_model_kwargs)

        result = self.resource_model_filter(model=self.model, instance=instance,
                                            requester_user=requester_user,
                                            **from_model_kwargs)

        if not result:
            LOG.debug('Not returning the result because RBAC resource isolation is enabled and '
                      'current user doesn\'t match the resource user')
            raise ResourceAccessDeniedPermissionIsolationError(user_db=requester_user,
                                                               resource_api_or_db=instance,
                                                               permission_type=permission_type)

        return result
Beispiel #8
0
    def delete(self, triggertype_ref_or_id):
        """
            Delete a triggertype.

            Handles requests:
                DELETE /triggertypes/1
                DELETE /triggertypes/pack.name
        """
        LOG.info('DELETE /triggertypes/ with ref_or_id=%s',
                 triggertype_ref_or_id)

        triggertype_db = self._get_by_ref_or_id(ref_or_id=triggertype_ref_or_id)
        triggertype_id = triggertype_db.id

        try:
            validate_not_part_of_system_pack(triggertype_db)
        except ValueValidationException as e:
            abort(http_client.BAD_REQUEST, six.text_type(e))

        try:
            TriggerType.delete(triggertype_db)
        except Exception as e:
            LOG.exception('Database delete encountered exception during delete of id="%s". ',
                          triggertype_id)
            abort(http_client.INTERNAL_SERVER_ERROR, six.text_type(e))
            return
        else:
            extra = {'triggertype': triggertype_db}
            LOG.audit('TriggerType deleted. TriggerType.id=%s' % (triggertype_db.id), extra=extra)
            if not triggertype_db.parameters_schema:
                TriggerTypeController._delete_shadow_trigger(triggertype_db)

        return Response(status=http_client.NO_CONTENT)
Beispiel #9
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)
Beispiel #10
0
    def post(self, trigger_instance_id):
        """
        Re-send the provided trigger instance optionally specifying override parameters.

        Handles requests:

            POST /triggerinstance/<id>/re_emit
            POST /triggerinstance/<id>/re_send
        """
        # Note: We only really need parameters here
        existing_trigger_instance = self._get_one_by_id(id=trigger_instance_id,
                                                        permission_type=None,
                                                        requester_user=None)

        new_payload = copy.deepcopy(existing_trigger_instance.payload)
        new_payload['__context'] = {
            'original_id': trigger_instance_id
        }

        try:
            self.trigger_dispatcher.dispatch(existing_trigger_instance.trigger,
                                             new_payload)
            return {
                'message': 'Trigger instance %s succesfully re-sent.' % trigger_instance_id,
                'payload': new_payload
            }
        except Exception as e:
            abort(http_client.INTERNAL_SERVER_ERROR, six.text_type(e))
Beispiel #11
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)
Beispiel #12
0
 def _get_runner_by_name(name):
     try:
         return RunnerType.get_by_name(name)
     except (ValueError, ValidationError) as e:
         msg = 'Database lookup for name="%s" resulted in exception. %s' % (id, e)
         LOG.exception(msg)
         abort(http_client.NOT_FOUND, msg)
Beispiel #13
0
    def get_one(self, api_key_id_or_key, requester_user, show_secrets=None):
        """
            List api keys.

            Handle:
                GET /apikeys/1
        """
        api_key_db = None
        try:
            api_key_db = ApiKey.get_by_key_or_id(api_key_id_or_key)
        except ApiKeyNotFoundError:
            msg = ('ApiKey matching %s for reference and id not found.' % (api_key_id_or_key))
            LOG.exception(msg)
            abort(http_client.NOT_FOUND, msg)

        permission_type = PermissionType.API_KEY_VIEW
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=api_key_db,
                                                          permission_type=permission_type)

        try:
            mask_secrets = self._get_mask_secrets(show_secrets=show_secrets,
                                                  requester_user=requester_user)
            return ApiKeyAPI.from_model(api_key_db, mask_secrets=mask_secrets)
        except (ValidationError, ValueError) as e:
            LOG.exception('Failed to serialize API key.')
            abort(http_client.INTERNAL_SERVER_ERROR, six.text_type(e))
Beispiel #14
0
    def delete(self, rule_ref_or_id, requester_user):
        """
            Delete a rule.

            Handles requests:
                DELETE /rules/1
        """
        rule_db = self._get_by_ref_or_id(ref_or_id=rule_ref_or_id)

        permission_type = PermissionType.RULE_DELETE
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=rule_db,
                                                          permission_type=permission_type)

        LOG.debug('DELETE /rules/ lookup with id=%s found object: %s', rule_ref_or_id, rule_db)
        try:
            Rule.delete(rule_db)
        except Exception as e:
            LOG.exception('Database delete encountered exception during delete of id="%s".',
                          rule_ref_or_id)
            abort(http_client.INTERNAL_SERVER_ERROR, six.text_type(e))
            return

        # use old_rule_db for cleanup.
        cleanup_trigger_db_for_rule(rule_db)

        extra = {'rule_db': rule_db}
        LOG.audit('Rule deleted. Rule.id=%s.' % (rule_db.id), extra=extra)

        return Response(status=http_client.NO_CONTENT)
Beispiel #15
0
 def __get_by_id(id):
     try:
         return RuleType.get_by_id(id)
     except (ValueError, ValidationError) as e:
         msg = 'Database lookup for id="%s" resulted in exception. %s' % (id, e)
         LOG.exception(msg)
         abort(http_client.NOT_FOUND, msg)
Beispiel #16
0
    def put(self, rule, rule_ref_or_id, requester_user):
        rule_db = self._get_by_ref_or_id(rule_ref_or_id)

        rbac_utils = get_rbac_backend().get_utils_class()
        permission_type = PermissionType.RULE_MODIFY
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=rule,
                                                          permission_type=permission_type)

        LOG.debug('PUT /rules/ lookup with id=%s found object: %s', rule_ref_or_id, rule_db)

        if not requester_user:
            requester_user = UserDB(cfg.CONF.system_user.user)
        # Validate that the authenticated user is admin if user query param is provided
        user = requester_user.name
        rbac_utils.assert_user_is_admin_if_user_query_param_is_provided(user_db=requester_user,
                                                                        user=user)

        if not hasattr(rule, 'context'):
            rule.context = dict()
        rule.context['user'] = user

        try:
            if rule.id is not None and rule.id != '' and rule.id != rule_ref_or_id:
                LOG.warning('Discarding mismatched id=%s found in payload and using uri_id=%s.',
                            rule.id, rule_ref_or_id)
            old_rule_db = rule_db

            try:
                rule_db = RuleAPI.to_model(rule)
            except TriggerDoesNotExistException as e:
                abort(http_client.BAD_REQUEST, six.text_type(e))
                return

            # Check referenced trigger and action permissions
            # Note: This needs to happen after "to_model" call since to_model performs some
            # validation (trigger exists, etc.)
            rbac_utils.assert_user_has_rule_trigger_and_action_permission(user_db=requester_user,
                                                                          rule_api=rule)

            rule_db.id = rule_ref_or_id
            rule_db = Rule.add_or_update(rule_db)
            # After the rule has been added modify the ref_count. This way a failure to add
            # the rule due to violated constraints will have no impact on ref_count.
            increment_trigger_ref_count(rule_api=rule)
        except (ValueValidationException, jsonschema.ValidationError, ValueError) as e:
            LOG.exception('Validation failed for rule data=%s', rule)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        # use old_rule_db for cleanup.
        cleanup_trigger_db_for_rule(old_rule_db)

        extra = {'old_rule_db': old_rule_db, 'new_rule_db': rule_db}
        LOG.audit('Rule updated. Rule.id=%s.' % (rule_db.id), extra=extra)
        rule_api = RuleAPI.from_model(rule_db)

        return rule_api
Beispiel #17
0
    def get_all(self, timer_type=None):
        if timer_type and timer_type not in self._allowed_timer_types:
            msg = 'Timer type %s not in supported types - %s.' % (timer_type,
                                                                  self._allowed_timer_types)
            abort(http_client.BAD_REQUEST, msg)

        t_all = self._timers.get_all(timer_type=timer_type)
        LOG.debug('Got timers: %s', t_all)
        return t_all
Beispiel #18
0
    def post(self, hook, webhook_body_api, headers, requester_user):
        body = webhook_body_api.data

        permission_type = PermissionType.WEBHOOK_SEND
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=WebhookDB(name=hook),
                                                          permission_type=permission_type)

        headers = self._get_headers_as_dict(headers)

        # If webhook contains a trace-tag use that else create create a unique trace-tag.
        trace_context = self._create_trace_context(trace_tag=headers.pop(TRACE_TAG_HEADER, None),
                                                   hook=hook)

        if hook == 'st2' or hook == 'st2/':
            # When using st2 or system webhook, body needs to always be a dict
            if not isinstance(body, dict):
                type_string = get_json_type_for_python_value(body)
                msg = ('Webhook body needs to be an object, got: %s' % (type_string))
                raise ValueError(msg)

            trigger = body.get('trigger', None)
            payload = body.get('payload', None)

            if not trigger:
                msg = 'Trigger not specified.'
                return abort(http_client.BAD_REQUEST, msg)

            self._trigger_dispatcher_service.dispatch_with_context(trigger=trigger,
                   payload=payload,
                   trace_context=trace_context,
                   throw_on_validation_error=True)
        else:
            if not self._is_valid_hook(hook):
                self._log_request('Invalid hook.', headers, body)
                msg = 'Webhook %s not registered with st2' % hook
                return abort(http_client.NOT_FOUND, msg)

            triggers = self._hooks.get_triggers_for_hook(hook)
            payload = {}

            payload['headers'] = headers
            payload['body'] = body

            # Dispatch trigger instance for each of the trigger found
            for trigger_dict in triggers:
                # TODO: Instead of dispatching the whole dict we should just
                # dispatch TriggerDB.ref or similar
                self._trigger_dispatcher_service.dispatch_with_context(trigger=trigger_dict,
                   payload=payload,
                   trace_context=trace_context,
                   throw_on_validation_error=True)

        return Response(json=body, status=http_client.ACCEPTED)
Beispiel #19
0
    def delete(self, name, requester_user, scope=FULL_SYSTEM_SCOPE, user=None):
        """
            Delete the key value pair.

            Handles requests:
                DELETE /keys/1
        """
        if not scope:
            scope = FULL_SYSTEM_SCOPE

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

        scope = get_datastore_full_scope(scope)
        self._validate_scope(scope=scope)

        user = user or requester_user.name

        # Validate that the authenticated user is admin if user query param is provided
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_is_admin_if_user_query_param_is_provided(user_db=requester_user,
                                                                        user=user,
                                                                        require_rbac=True)

        key_ref = get_key_reference(scope=scope, name=name, user=user)
        lock_name = self._get_lock_name_for_key(name=key_ref, scope=scope)

        # Note: We use lock to avoid a race
        with self._coordinator.get_lock(lock_name):
            from_model_kwargs = {'mask_secrets': True}
            kvp_api = self._get_one_by_scope_and_name(
                name=key_ref,
                scope=scope,
                from_model_kwargs=from_model_kwargs
            )

            kvp_db = KeyValuePairAPI.to_model(kvp_api)

            LOG.debug('DELETE /keys/ lookup with scope=%s name=%s found object: %s',
                      scope, name, kvp_db)

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

        extra = {'kvp_db': kvp_db}
        LOG.audit('KeyValuePair deleted. KeyValuePair.id=%s' % (kvp_db.id), extra=extra)

        return Response(status=http_client.NO_CONTENT)
Beispiel #20
0
    def post(self, def_yaml):
        if not mistral:
            abort(http_client.NOT_FOUND)
            return

        result = self.validator.validate(def_yaml)

        for error in result:
            if not error.get('path', None):
                error['path'] = ''

        return Response(json=result)
Beispiel #21
0
    def delete(self, id, requester_user, show_secrets=False):
        """
        Stops a single execution.

        Handles requests:
            DELETE /executions/<id>

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

        from_model_kwargs = {
            'mask_secrets': self._get_mask_secrets(requester_user, show_secrets=show_secrets)
        }
        execution_api = self._get_one_by_id(id=id, requester_user=requester_user,
                                            from_model_kwargs=from_model_kwargs,
                                            permission_type=PermissionType.EXECUTION_STOP)

        if not execution_api:
            abort(http_client.NOT_FOUND, 'Execution with id %s not found.' % id)

        liveaction_id = execution_api.liveaction['id']
        if not liveaction_id:
            abort(http_client.INTERNAL_SERVER_ERROR,
                  'Execution object missing link to liveaction %s.' % liveaction_id)

        try:
            liveaction_db = LiveAction.get_by_id(liveaction_id)
        except:
            abort(http_client.INTERNAL_SERVER_ERROR,
                  'Execution object missing link to liveaction %s.' % liveaction_id)

        if liveaction_db.status == action_constants.LIVEACTION_STATUS_CANCELED:
            LOG.info(
                'Action %s already in "canceled" state; \
                returning execution object.' % liveaction_db.id
            )
            return execution_api

        if liveaction_db.status not in action_constants.LIVEACTION_CANCELABLE_STATES:
            abort(http_client.OK, 'Action cannot be canceled. State = %s.' % liveaction_db.status)

        try:
            (liveaction_db, execution_db) = action_service.request_cancellation(
                liveaction_db, requester_user.name or cfg.CONF.system_user.user)
        except:
            LOG.exception('Failed requesting cancellation for liveaction %s.', liveaction_db.id)
            abort(http_client.INTERNAL_SERVER_ERROR, 'Failed canceling execution.')

        return ActionExecutionAPI.from_model(execution_db,
                                             mask_secrets=from_model_kwargs['mask_secrets'])
Beispiel #22
0
    def post(self, api_key_api, requester_user):
        """
        Create a new entry.
        """

        permission_type = PermissionType.API_KEY_CREATE
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_api_permission(user_db=requester_user,
                                                           resource_api=api_key_api,
                                                           permission_type=permission_type)

        api_key_db = None
        api_key = None
        try:
            if not getattr(api_key_api, 'user', None):
                if requester_user:
                    api_key_api.user = requester_user.name
                else:
                    api_key_api.user = cfg.CONF.system_user.user

            try:
                User.get_by_name(api_key_api.user)
            except StackStormDBObjectNotFoundError:
                user_db = UserDB(name=api_key_api.user)
                User.add_or_update(user_db)

                extra = {'username': api_key_api.user, 'user': user_db}
                LOG.audit('Registered new user "%s".' % (api_key_api.user), extra=extra)

            # If key_hash is provided use that and do not create a new key. The assumption
            # is user already has the original api-key
            if not getattr(api_key_api, 'key_hash', None):
                api_key, api_key_hash = auth_util.generate_api_key_and_hash()
                # store key_hash in DB
                api_key_api.key_hash = api_key_hash
            api_key_db = ApiKey.add_or_update(ApiKeyAPI.to_model(api_key_api))
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for api_key data=%s.', api_key_api)
            abort(http_client.BAD_REQUEST, six.text_type(e))

        extra = {'api_key_db': api_key_db}
        LOG.audit('ApiKey created. ApiKey.id=%s' % (api_key_db.id), extra=extra)

        api_key_create_response_api = ApiKeyCreateResponseAPI.from_model(api_key_db)
        # Return real api_key back to user. A one-way hash of the api_key is stored in the DB
        # only the real value only returned at create time. Also, no masking of key here since
        # the user needs to see this value atleast once.
        api_key_create_response_api.key = api_key

        return Response(json=api_key_create_response_api, status=http_client.CREATED)
Beispiel #23
0
    def get_one(self, inquiry_id, requester_user=None):
        """Retrieve a single Inquiry

            Handles requests:
                GET /inquiries/<inquiry id>
        """

        # Retrieve the inquiry by id.
        # (Passing permission_type here leverages inquiry service built-in RBAC assertions)
        try:
            inquiry = self._get_one_by_id(
                id=inquiry_id,
                requester_user=requester_user,
                permission_type=rbac_types.PermissionType.INQUIRY_VIEW
            )
        except db_exceptions.StackStormDBObjectNotFoundError as e:
            LOG.exception('Unable to identify inquiry with id "%s".' % inquiry_id)
            api_router.abort(http_client.NOT_FOUND, six.text_type(e))
        except rbac_exceptions.ResourceAccessDeniedError as e:
            LOG.exception('User is denied access to inquiry "%s".' % inquiry_id)
            api_router.abort(http_client.FORBIDDEN, six.text_type(e))
        except Exception as e:
            LOG.exception('Unable to get record for inquiry "%s".' % inquiry_id)
            api_router.abort(http_client.INTERNAL_SERVER_ERROR, six.text_type(e))

        try:
            inquiry_service.check_inquiry(inquiry)
        except Exception as e:
            api_router.abort(http_client.BAD_REQUEST, six.text_type(e))

        return inqy_api_models.InquiryResponseAPI.from_inquiry_api(inquiry)
Beispiel #24
0
    def get_one(self, url, requester_user):
        triggers = self._hooks.get_triggers_for_hook(url)

        if not triggers:
            abort(http_client.NOT_FOUND)
            return

        permission_type = PermissionType.WEBHOOK_VIEW
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=WebhookDB(name=url),
                                                          permission_type=permission_type)

        # For demonstration purpose return 1st
        return triggers[0]
Beispiel #25
0
    def _get_one_by_pack_ref(self, pack_ref, exclude_fields=None, include_fields=None,
                             from_model_kwargs=None):
        instance = self._get_by_pack_ref(pack_ref=pack_ref, exclude_fields=exclude_fields,
                                         include_fields=include_fields)

        if not instance:
            msg = 'Unable to identify resource with pack_ref "%s".' % (pack_ref)
            abort(http_client.NOT_FOUND, msg)

        from_model_kwargs = from_model_kwargs or {}
        from_model_kwargs.update(self.from_model_kwargs)
        result = self.model.from_model(instance, **from_model_kwargs)

        return result
Beispiel #26
0
    def _get_one_by_ref_or_id(self, ref_or_id, requester_user, exclude_fields=None):
        instance = self._get_by_ref_or_id(ref_or_id=ref_or_id, exclude_fields=exclude_fields)

        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=instance,
                                                          permission_type=PermissionType.PACK_VIEW)

        if not instance:
            msg = 'Unable to identify resource with ref_or_id "%s".' % (ref_or_id)
            abort(http_client.NOT_FOUND, msg)
            return

        result = self.model.from_model(instance, **self.from_model_kwargs)

        return result
Beispiel #27
0
    def _handle_schedule_execution(self, liveaction_api, requester_user, context_string=None,
                                   show_secrets=False):
        """
        :param liveaction: LiveActionAPI object.
        :type liveaction: :class:`LiveActionAPI`
        """
        if not requester_user:
            requester_user = UserDB(cfg.CONF.system_user.user)

        # Assert action ref is valid
        action_ref = liveaction_api.action
        action_db = action_utils.get_action_by_ref(action_ref)

        if not action_db:
            message = 'Action "%s" cannot be found.' % (action_ref)
            LOG.warning(message)
            abort(http_client.BAD_REQUEST, message)

        # Assert the permissions
        assert_user_has_resource_db_permission(user_db=requester_user, resource_db=action_db,
                                               permission_type=PermissionType.ACTION_EXECUTE)

        # Validate that the authenticated user is admin if user query param is provided
        user = liveaction_api.user or requester_user.name
        assert_user_is_admin_if_user_query_param_is_provided(user_db=requester_user,
                                                             user=user)

        try:
            return self._schedule_execution(liveaction=liveaction_api,
                                            requester_user=requester_user,
                                            user=user,
                                            context_string=context_string,
                                            show_secrets=show_secrets,
                                            action_db=action_db)
        except ValueError as e:
            LOG.exception('Unable to execute action.')
            abort(http_client.BAD_REQUEST, six.text_type(e))
        except jsonschema.ValidationError as e:
            LOG.exception('Unable to execute action. Parameter validation failed.')
            abort(http_client.BAD_REQUEST, re.sub("u'([^']*)'", r"'\1'",
                                                  getattr(e, 'message', six.text_type(e))))
        except trace_exc.TraceNotFoundException as e:
            abort(http_client.BAD_REQUEST, six.text_type(e))
        except validation_exc.ValueValidationException as e:
            raise e
        except Exception as e:
            LOG.exception('Unable to execute action. Unexpected error encountered.')
            abort(http_client.INTERNAL_SERVER_ERROR, six.text_type(e))
Beispiel #28
0
    def post(self, action, requester_user):
        """
            Create a new action.

            Handles requests:
                POST /actions/
        """

        permission_type = PermissionType.ACTION_CREATE
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_api_permission(user_db=requester_user,
                                                           resource_api=action,
                                                           permission_type=permission_type)

        try:
            # Perform validation
            validate_not_part_of_system_pack(action)
            action_validator.validate_action(action)
        except (ValidationError, ValueError,
                ValueValidationException, InvalidActionParameterException) as e:
            LOG.exception('Unable to create action data=%s', action)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        # Write pack data files to disk (if any are provided)
        data_files = getattr(action, 'data_files', [])
        written_data_files = []
        if data_files:
            written_data_files = self._handle_data_files(pack_ref=action.pack,
                                                         data_files=data_files)

        action_model = ActionAPI.to_model(action)

        LOG.debug('/actions/ POST verified ActionAPI object=%s', action)
        action_db = Action.add_or_update(action_model)
        LOG.debug('/actions/ POST saved ActionDB object=%s', action_db)

        # Dispatch an internal trigger for each written data file. This way user
        # automate comitting this files to git using StackStorm rule
        if written_data_files:
            self._dispatch_trigger_for_written_data_files(action_db=action_db,
                                                          written_data_files=written_data_files)

        extra = {'acion_db': action_db}
        LOG.audit('Action created. Action.id=%s' % (action_db.id), extra=extra)
        action_api = ActionAPI.from_model(action_db)

        return Response(json=action_api, status=http_client.CREATED)
Beispiel #29
0
    def get_one(self, ref_or_id, requester_user):
        try:
            trigger_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)
        except Exception as e:
            LOG.exception(six.text_type(e))
            abort(http_client.NOT_FOUND, six.text_type(e))
            return

        permission_type = PermissionType.TIMER_VIEW
        resource_db = TimerDB(pack=trigger_db.pack, name=trigger_db.name)
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=resource_db,
                                                          permission_type=permission_type)

        result = self.model.from_model(trigger_db)
        return result
Beispiel #30
0
    def put(self, action, ref_or_id, requester_user):
        action_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)

        # Assert permissions
        permission_type = PermissionType.ACTION_MODIFY
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=action_db,
                                                          permission_type=permission_type)

        action_id = action_db.id

        if not getattr(action, 'pack', None):
            action.pack = action_db.pack

        # Perform validation
        validate_not_part_of_system_pack(action)
        action_validator.validate_action(action)

        # Write pack data files to disk (if any are provided)
        data_files = getattr(action, 'data_files', [])
        written_data_files = []
        if data_files:
            written_data_files = self._handle_data_files(pack_ref=action.pack,
                                                         data_files=data_files)

        try:
            action_db = ActionAPI.to_model(action)
            LOG.debug('/actions/ PUT incoming action: %s', action_db)
            action_db.id = action_id
            action_db = Action.add_or_update(action_db)
            LOG.debug('/actions/ PUT after add_or_update: %s', action_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Unable to update action data=%s', action)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        # Dispatch an internal trigger for each written data file. This way user
        # automate committing this files to git using StackStorm rule
        if written_data_files:
            self._dispatch_trigger_for_written_data_files(action_db=action_db,
                                                          written_data_files=written_data_files)

        action_api = ActionAPI.from_model(action_db)
        LOG.debug('PUT /actions/ client_result=%s', action_api)

        return action_api
Beispiel #31
0
    def post(self, trigger):
        """
            Create a new trigger.

            Handles requests:
                POST /triggers/
        """
        try:
            trigger_db = TriggerService.create_trigger_db(trigger)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for trigger data=%s.', trigger)
            abort(http_client.BAD_REQUEST, str(e))
            return

        extra = {'trigger': trigger_db}
        LOG.audit('Trigger created. Trigger.id=%s' % (trigger_db.id),
                  extra=extra)
        trigger_api = TriggerAPI.from_model(trigger_db)

        return Response(json=trigger_api, status=http_client.CREATED)
Beispiel #32
0
    def put(self, trigger, trigger_id):
        trigger_db = TriggerController.__get_by_id(trigger_id)
        try:
            if trigger.id is not None and trigger.id is not '' and trigger.id != trigger_id:
                LOG.warning(
                    'Discarding mismatched id=%s found in payload and using uri_id=%s.',
                    trigger.id, trigger_id)
            trigger_db = TriggerAPI.to_model(trigger)
            trigger_db.id = trigger_id
            trigger_db = Trigger.add_or_update(trigger_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for trigger data=%s', trigger)
            abort(http_client.BAD_REQUEST, str(e))
            return

        extra = {'old_trigger_db': trigger, 'new_trigger_db': trigger_db}
        LOG.audit('Trigger updated. Trigger.id=%s' % (trigger.id), extra=extra)
        trigger_api = TriggerAPI.from_model(trigger_db)

        return trigger_api
Beispiel #33
0
    def get_one(self, ref_or_id, requester_user):
        try:
            trigger_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)
        except Exception as e:
            LOG.exception(six.text_type(e))
            abort(http_client.NOT_FOUND, six.text_type(e))
            return

        permission_type = PermissionType.TIMER_VIEW
        resource_db = TimerDB(pack=trigger_db.pack, name=trigger_db.name)

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

        result = self.model.from_model(trigger_db)
        return result
Beispiel #34
0
    def put(self, sensor_type, ref_or_id, requester_user):
        # Note: Right now this function only supports updating of "enabled"
        # attribute on the SensorType model.
        # The reason for that is that SensorTypeAPI.to_model right now only
        # knows how to work with sensor type definitions from YAML files.

        sensor_type_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)

        permission_type = PermissionType.SENSOR_MODIFY
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=sensor_type_db,
                                                          permission_type=permission_type)

        sensor_type_id = sensor_type_db.id

        try:
            validate_not_part_of_system_pack(sensor_type_db)
        except ValueValidationException as e:
            abort(http_client.BAD_REQUEST, str(e))
            return

        if not getattr(sensor_type, 'pack', None):
            sensor_type.pack = sensor_type_db.pack
        try:
            old_sensor_type_db = sensor_type_db
            sensor_type_db.id = sensor_type_id
            sensor_type_db.enabled = getattr(sensor_type, 'enabled', False)
            sensor_type_db = SensorType.add_or_update(sensor_type_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Unable to update sensor_type data=%s', sensor_type)
            abort(http_client.BAD_REQUEST, str(e))
            return

        extra = {
            'old_sensor_type_db': old_sensor_type_db,
            'new_sensor_type_db': sensor_type_db
        }
        LOG.audit('Sensor updated. Sensor.id=%s.' % (sensor_type_db.id), extra=extra)
        sensor_type_api = SensorTypeAPI.from_model(sensor_type_db)

        return sensor_type_api
Beispiel #35
0
    def _get_one_by_ref_or_id(self,
                              ref_or_id,
                              requester_user,
                              exclude_fields=None):
        instance = self._get_by_ref_or_id(ref_or_id=ref_or_id,
                                          exclude_fields=exclude_fields)

        rbac_utils.assert_user_has_resource_db_permission(
            user_db=requester_user,
            resource_db=instance,
            permission_type=PermissionType.PACK_VIEW)

        if not instance:
            msg = 'Unable to identify resource with ref_or_id "%s".' % (
                ref_or_id)
            abort(http_client.NOT_FOUND, msg)
            return

        result = self.model.from_model(instance, **self.from_model_kwargs)

        return result
Beispiel #36
0
    def _get_one_by_pack_ref(self,
                             pack_ref,
                             exclude_fields=None,
                             include_fields=None,
                             from_model_kwargs=None):
        instance = self._get_by_pack_ref(
            pack_ref=pack_ref,
            exclude_fields=exclude_fields,
            include_fields=include_fields,
        )

        if not instance:
            msg = 'Unable to identify resource with pack_ref "%s".' % (
                pack_ref)
            abort(http_client.NOT_FOUND, msg)

        from_model_kwargs = from_model_kwargs or {}
        from_model_kwargs.update(self.from_model_kwargs)
        result = self.model.from_model(instance, **from_model_kwargs)

        return result
Beispiel #37
0
    def get_one(self, pack_ref, requester_user):
        """
        Retrieve config for a particular pack.

        Handles requests:
            GET /configs/<pack_ref>
        """
        # TODO: Make sure secret values are masked
        try:
            instance = packs_service.get_pack_by_ref(pack_ref=pack_ref)
        except StackStormDBObjectNotFoundError:
            msg = 'Unable to identify resource with pack_ref "%s".' % (
                pack_ref)
            abort(http_client.NOT_FOUND, msg)

        rbac_utils.assert_user_has_resource_db_permission(
            user_db=requester_user,
            resource_db=instance,
            permission_type=PermissionType.PACK_VIEW)

        return self._get_one_by_pack_ref(pack_ref=pack_ref)
Beispiel #38
0
    def delete(self, trigger_id):
        """
            Delete a trigger.

            Handles requests:
                DELETE /triggers/1
        """
        LOG.info('DELETE /triggers/ with id=%s', trigger_id)
        trigger_db = TriggerController.__get_by_id(trigger_id)
        try:
            Trigger.delete(trigger_db)
        except Exception as e:
            LOG.exception('Database delete encountered exception during delete of id="%s". ',
                          trigger_id)
            abort(http_client.INTERNAL_SERVER_ERROR, str(e))
            return

        extra = {'trigger_db': trigger_db}
        LOG.audit('Trigger deleted. Trigger.id=%s' % (trigger_db.id), extra=extra)

        return Response(status=http_client.NO_CONTENT)
Beispiel #39
0
    def get_one(self, inquiry_id, requester_user=None):
        """Retrieve a single Inquiry

            Handles requests:
                GET /inquiries/<inquiry id>
        """

        # Retrieve the desired inquiry
        #
        # (Passing permission_type here leverages _get_one_by_id's built-in
        # RBAC assertions)
        inquiry = self._get_one_by_id(
            id=inquiry_id,
            requester_user=requester_user,
            permission_type=PermissionType.INQUIRY_VIEW)

        sanity_result, msg = self._inquiry_sanity_check(inquiry)
        if not sanity_result:
            abort(http_client.BAD_REQUEST, msg)

        return InquiryResponseAPI.from_inquiry_api(inquiry)
Beispiel #40
0
    def _get_one_by_name_or_id(
        self,
        name_or_id,
        requester_user,
        permission_type,
        exclude_fields=None,
        include_fields=None,
        from_model_kwargs=None,
    ):
        """
        :param exclude_fields: A list of object fields to exclude.
        :type exclude_fields: ``list``
        :param include_fields: A list of object fields to include.
        :type include_fields: ``list``
        """

        instance = self._get_by_name_or_id(
            name_or_id=name_or_id,
            exclude_fields=exclude_fields,
            include_fields=include_fields,
        )

        if permission_type:
            rbac_utils = get_rbac_backend().get_utils_class()
            rbac_utils.assert_user_has_resource_db_permission(
                user_db=requester_user,
                resource_db=instance,
                permission_type=permission_type,
            )

        if not instance:
            msg = 'Unable to identify resource with name_or_id "%s".' % (
                name_or_id)
            abort(http_client.NOT_FOUND, msg)

        from_model_kwargs = from_model_kwargs or {}
        from_model_kwargs.update(self.from_model_kwargs)
        result = self.model.from_model(instance, **from_model_kwargs)

        return result
Beispiel #41
0
    def put(self, instance, ref_or_id, requester_user):
        op = 'PUT /policies/%s/' % ref_or_id

        db_model = self._get_by_ref_or_id(ref_or_id=ref_or_id)
        LOG.debug('%s found object: %s', op, db_model)

        permission_type = PermissionType.POLICY_MODIFY
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(
            user_db=requester_user,
            resource_db=db_model,
            permission_type=permission_type)

        db_model_id = db_model.id

        try:
            validate_not_part_of_system_pack(db_model)
        except ValueValidationException as e:
            LOG.exception('%s unable to update object from system pack.', op)
            abort(http_client.BAD_REQUEST, six.text_type(e))

        if not getattr(instance, 'pack', None):
            instance.pack = db_model.pack

        try:
            db_model = self.model.to_model(instance)
            db_model.id = db_model_id
            db_model = self.access.add_or_update(db_model)
        except (ValidationError, ValueError) as e:
            LOG.exception('%s unable to update object: %s', op, db_model)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        LOG.debug('%s updated object: %s', op, db_model)
        LOG.audit('Policy updated. Policy.id=%s' % (db_model.id),
                  extra={'policy_db': db_model})

        exec_result = self.model.from_model(db_model)

        return Response(json=exec_result, status=http_client.OK)
    def _schedule_execution(self, action_alias_db, params, notify, context, requester_user,
                            show_secrets):
        action_ref = action_alias_db.action_ref
        action_db = action_utils.get_action_by_ref(action_ref)

        if not action_db:
            raise StackStormDBObjectNotFoundError('Action with ref "%s" not found ' % (action_ref))

        assert_user_has_resource_db_permission(user_db=requester_user, resource_db=action_db,
                                               permission_type=PermissionType.ACTION_EXECUTE)

        try:
            # prior to shipping off the params cast them to the right type.
            params = action_param_utils.cast_params(action_ref=action_alias_db.action_ref,
                                                    params=params,
                                                    cast_overrides=CAST_OVERRIDES)
            if not context:
                context = {
                    'action_alias_ref': reference.get_ref_from_model(action_alias_db),
                    'user': get_system_username()
                }
            liveaction = LiveActionDB(action=action_alias_db.action_ref, context=context,
                                      parameters=params, notify=notify)
            _, action_execution_db = action_service.request(liveaction)
            mask_secrets = self._get_mask_secrets(requester_user, show_secrets=show_secrets)
            return ActionExecutionAPI.from_model(action_execution_db, mask_secrets=mask_secrets)
        except ValueError as e:
            LOG.exception('Unable to execute action.')
            abort(http_client.BAD_REQUEST, str(e))
        except jsonschema.ValidationError as e:
            LOG.exception('Unable to execute action. Parameter validation failed.')
            abort(http_client.BAD_REQUEST, str(e))
        except Exception as e:
            LOG.exception('Unable to execute action. Unexpected error encountered.')
            abort(http_client.INTERNAL_SERVER_ERROR, str(e))
Beispiel #43
0
    def put(self, triggertype, triggertype_ref_or_id):
        triggertype_db = self._get_by_ref_or_id(ref_or_id=triggertype_ref_or_id)
        triggertype_id = triggertype_db.id

        try:
            validate_not_part_of_system_pack(triggertype_db)
        except ValueValidationException as e:
            abort(http_client.BAD_REQUEST, six.text_type(e))

        try:
            triggertype_db = TriggerTypeAPI.to_model(triggertype)

            if (
                triggertype.id is not None
                and len(triggertype.id) > 0
                and triggertype.id != triggertype_id
            ):
                LOG.warning(
                    "Discarding mismatched id=%s found in payload and using uri_id=%s.",
                    triggertype.id,
                    triggertype_id,
                )
            triggertype_db.id = triggertype_id
            old_triggertype_db = triggertype_db
            triggertype_db = TriggerType.add_or_update(triggertype_db)
        except (ValidationError, ValueError) as e:
            LOG.exception("Validation failed for triggertype data=%s", triggertype)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        extra = {
            "old_triggertype_db": old_triggertype_db,
            "new_triggertype_db": triggertype_db,
        }
        LOG.audit(
            "TriggerType updated. TriggerType.id=%s" % (triggertype_db.id), extra=extra
        )

        triggertype_api = TriggerTypeAPI.from_model(triggertype_db)
        return triggertype_api
Beispiel #44
0
    def post(self, rule, requester_user):
        """
            Create a new rule.

            Handles requests:
                POST /rules/
        """

        permission_type = PermissionType.RULE_CREATE
        rbac_utils.assert_user_has_resource_api_permission(user_db=requester_user,
                                                           resource_api=rule,
                                                           permission_type=permission_type)

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

        # Validate that the authenticated user is admin if user query param is provided
        user = requester_user.name
        assert_user_is_admin_if_user_query_param_is_provided(user_db=requester_user,
                                                             user=user)

        if not hasattr(rule, 'context'):
            rule.context = dict()

        rule.context['user'] = user

        try:
            rule_db = RuleAPI.to_model(rule)
            LOG.debug('/rules/ POST verified RuleAPI and formulated RuleDB=%s', rule_db)

            # Check referenced trigger and action permissions
            # Note: This needs to happen after "to_model" call since to_model performs some
            # validation (trigger exists, etc.)
            assert_user_has_rule_trigger_and_action_permission(user_db=requester_user,
                                                               rule_api=rule)

            rule_db = Rule.add_or_update(rule_db)
            # After the rule has been added modify the ref_count. This way a failure to add
            # the rule due to violated constraints will have no impact on ref_count.
            increment_trigger_ref_count(rule_api=rule)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for rule data=%s.', rule)
            abort(http_client.BAD_REQUEST, str(e))
            return
        except (ValueValidationException, jsonschema.ValidationError) as e:
            LOG.exception('Validation failed for rule data=%s.', rule)
            abort(http_client.BAD_REQUEST, str(e))
            return
        except TriggerDoesNotExistException as e:
            msg = ('Trigger "%s" defined in the rule does not exist in system or it\'s missing '
                   'required "parameters" attribute' % (rule.trigger['type']))
            LOG.exception(msg)
            abort(http_client.BAD_REQUEST, msg)
            return

        extra = {'rule_db': rule_db}
        LOG.audit('Rule created. Rule.id=%s' % (rule_db.id), extra=extra)
        rule_api = RuleAPI.from_model(rule_db)

        return Response(json=rule_api, status=exc.HTTPCreated.code)
Beispiel #45
0
    def delete(self, triggertype_ref_or_id):
        """
        Delete a triggertype.

        Handles requests:
            DELETE /triggertypes/1
            DELETE /triggertypes/pack.name
        """
        LOG.info("DELETE /triggertypes/ with ref_or_id=%s",
                 triggertype_ref_or_id)

        triggertype_db = self._get_by_ref_or_id(
            ref_or_id=triggertype_ref_or_id)
        triggertype_id = triggertype_db.id

        try:
            validate_not_part_of_system_pack(triggertype_db)
        except ValueValidationException as e:
            abort(http_client.BAD_REQUEST, six.text_type(e))

        try:
            TriggerType.delete(triggertype_db)
        except Exception as e:
            LOG.exception(
                'Database delete encountered exception during delete of id="%s". ',
                triggertype_id,
            )
            abort(http_client.INTERNAL_SERVER_ERROR, six.text_type(e))
            return
        else:
            extra = {"triggertype": triggertype_db}
            LOG.audit(
                "TriggerType deleted. TriggerType.id=%s" % (triggertype_db.id),
                extra=extra,
            )
            if not triggertype_db.parameters_schema:
                TriggerTypeController._delete_shadow_trigger(triggertype_db)

        return Response(status=http_client.NO_CONTENT)
Beispiel #46
0
    def delete(self, ref_or_id, requester_user):
        """
            Delete a policy.
            Handles requests:
                POST /policies/1?_method=delete
                DELETE /policies/1
                DELETE /policies/mypack.mypolicy
        """
        op = 'DELETE /policies/%s/' % ref_or_id

        db_model = self._get_by_ref_or_id(ref_or_id=ref_or_id)
        LOG.debug('%s found object: %s', op, db_model)

        permission_type = PermissionType.POLICY_DELETE
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(
            user_db=requester_user,
            resource_db=db_model,
            permission_type=permission_type)

        try:
            validate_not_part_of_system_pack(db_model)
        except ValueValidationException as e:
            LOG.exception('%s unable to delete object from system pack.', op)
            abort(http_client.BAD_REQUEST, six.text_type(e))

        try:
            self.access.delete(db_model)
        except Exception as e:
            LOG.exception('%s unable to delete object: %s', op, db_model)
            abort(http_client.INTERNAL_SERVER_ERROR, six.text_type(e))
            return

        LOG.debug('%s deleted object: %s', op, db_model)
        LOG.audit('Policy deleted. Policy.id=%s' % (db_model.id),
                  extra={'policy_db': db_model})

        # return None
        return Response(status=http_client.NO_CONTENT)
Beispiel #47
0
    def _handle_schedule_execution(self,
                                   liveaction_api,
                                   requester_user,
                                   context_string=None,
                                   show_secrets=False):
        """
        :param liveaction: LiveActionAPI object.
        :type liveaction: :class:`LiveActionAPI`
        """

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

        # Assert the permissions
        action_ref = liveaction_api.action
        action_db = action_utils.get_action_by_ref(action_ref)
        user = liveaction_api.user or requester_user.name

        assert_user_has_resource_db_permission(
            user_db=requester_user,
            resource_db=action_db,
            permission_type=PermissionType.ACTION_EXECUTE)

        # Validate that the authenticated user is admin if user query param is provided
        assert_user_is_admin_if_user_query_param_is_provided(
            user_db=requester_user, user=user)

        try:
            return self._schedule_execution(liveaction=liveaction_api,
                                            requester_user=requester_user,
                                            user=user,
                                            context_string=context_string,
                                            show_secrets=show_secrets)
        except ValueError as e:
            LOG.exception('Unable to execute action.')
            abort(http_client.BAD_REQUEST, str(e))
        except jsonschema.ValidationError as e:
            LOG.exception(
                'Unable to execute action. Parameter validation failed.')
            abort(http_client.BAD_REQUEST,
                  re.sub("u'([^']*)'", r"'\1'", e.message))
        except TraceNotFoundException as e:
            abort(http_client.BAD_REQUEST, str(e))
        except ValueValidationException as e:
            raise e
        except Exception as e:
            LOG.exception(
                'Unable to execute action. Unexpected error encountered.')
            abort(http_client.INTERNAL_SERVER_ERROR, str(e))
Beispiel #48
0
    def delete(self, ref_or_id, requester_user):
        """
            Delete an action.

            Handles requests:
                POST /actions/1?_method=delete
                DELETE /actions/1
                DELETE /actions/mypack.myaction
        """
        action_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)
        action_id = action_db.id

        permission_type = PermissionType.ACTION_DELETE
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(
            user_db=requester_user,
            resource_db=action_db,
            permission_type=permission_type)

        try:
            validate_not_part_of_system_pack(action_db)
        except ValueValidationException as e:
            abort(http_client.BAD_REQUEST, six.text_type(e))

        LOG.debug('DELETE /actions/ lookup with ref_or_id=%s found object: %s',
                  ref_or_id, action_db)

        try:
            Action.delete(action_db)
        except Exception as e:
            LOG.error(
                'Database delete encountered exception during delete of id="%s". '
                'Exception was %s', action_id, e)
            abort(http_client.INTERNAL_SERVER_ERROR, six.text_type(e))
            return

        extra = {'action_db': action_db}
        LOG.audit('Action deleted. Action.id=%s' % (action_db.id), extra=extra)
        return Response(status=http_client.NO_CONTENT)
Beispiel #49
0
    def get_one(self, pack_ref, requester_user, show_secrets=False):
        """
        Retrieve config for a particular pack.

        Handles requests:
            GET /configs/<pack_ref>
        """
        from_model_kwargs = {
            'mask_secrets': self._get_mask_secrets(requester_user, show_secrets=show_secrets)
        }
        try:
            instance = packs_service.get_pack_by_ref(pack_ref=pack_ref)
        except StackStormDBObjectNotFoundError:
            msg = 'Unable to identify resource with pack_ref "%s".' % (pack_ref)
            abort(http_client.NOT_FOUND, msg)

        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=instance,
                                                          permission_type=PermissionType.PACK_VIEW)

        return self._get_one_by_pack_ref(pack_ref=pack_ref, from_model_kwargs=from_model_kwargs)
Beispiel #50
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
Beispiel #51
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)
Beispiel #52
0
    def put(self, runner_type_api, name_or_id, requester_user):
        # Note: We only allow "enabled" attribute of the runner to be changed
        runner_type_db = self._get_by_name_or_id(name_or_id=name_or_id)

        permission_type = PermissionType.RUNNER_MODIFY
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(
            user_db=requester_user,
            resource_db=runner_type_db,
            permission_type=permission_type)

        old_runner_type_db = runner_type_db
        LOG.debug('PUT /runnertypes/ lookup with id=%s found object: %s',
                  name_or_id, runner_type_db)

        try:
            if runner_type_api.id and runner_type_api.id != name_or_id:
                LOG.warning(
                    'Discarding mismatched id=%s found in payload and using uri_id=%s.',
                    runner_type_api.id, name_or_id)

            runner_type_db.enabled = runner_type_api.enabled
            runner_type_db = RunnerType.add_or_update(runner_type_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for runner type data=%s',
                          runner_type_api)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        extra = {
            'old_runner_type_db': old_runner_type_db,
            'new_runner_type_db': runner_type_db
        }
        LOG.audit('Runner Type updated. RunnerType.id=%s.' %
                  (runner_type_db.id),
                  extra=extra)
        runner_type_api = RunnerTypeAPI.from_model(runner_type_db)
        return runner_type_api
Beispiel #53
0
    def _get_one(self, ref_or_id, requester_user, permission_type, exclude_fields=None,
                 from_model_kwargs=None):
        try:
            instance = self._get_by_ref_or_id(ref_or_id=ref_or_id, exclude_fields=exclude_fields)
        except Exception as e:
            LOG.exception(e.message)
            abort(http_client.NOT_FOUND, e.message)
            return

        if permission_type:
            rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                              resource_db=instance,
                                                              permission_type=permission_type)

        from_model_kwargs = from_model_kwargs or {}
        from_model_kwargs.update(self.from_model_kwargs)
        result = self.model.from_model(instance, **from_model_kwargs)
        if result and self.include_reference:
            pack = getattr(result, 'pack', None)
            name = getattr(result, 'name', None)
            result.ref = ResourceReference(pack=pack, name=name).ref

        return Response(json=result)
Beispiel #54
0
    def _get_one_by_id(self, id, requester_user, permission_type, exclude_fields=None,
                       from_model_kwargs=None):
        """
        :param exclude_fields: A list of object fields to exclude.
        :type exclude_fields: ``list``
        """

        instance = self._get_by_id(resource_id=id, exclude_fields=exclude_fields)

        if permission_type:
            rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                              resource_db=instance,
                                                              permission_type=permission_type)

        if not instance:
            msg = 'Unable to identify resource with id "%s".' % id
            abort(http_client.NOT_FOUND, msg)

        from_model_kwargs = from_model_kwargs or {}
        from_model_kwargs.update(self.from_model_kwargs)
        result = self.model.from_model(instance, **from_model_kwargs)

        return result
Beispiel #55
0
    def help(self, filter, pack, limit, offset, **kwargs):
        """
            Get available help strings for action aliases.

            Handles requests:
                GET /actionalias/help
        """
        try:
            aliases_resp = super(ActionAliasController, self)._get_all(**kwargs)
            aliases = [ActionAliasAPI(**alias) for alias in aliases_resp.json]
            return generate_helpstring_result(aliases, filter, pack, int(limit), int(offset))
        except (TypeError) as e:
            LOG.exception('Helpstring request contains an invalid data type: %s.', six.text_type(e))
            return abort(http_client.BAD_REQUEST, six.text_type(e))
Beispiel #56
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)
Beispiel #57
0
    def post(self, triggertype):
        """
            Create a new triggertype.

            Handles requests:
                POST /triggertypes/
        """

        try:
            triggertype_db = TriggerTypeAPI.to_model(triggertype)
            triggertype_db = TriggerType.add_or_update(triggertype_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for triggertype data=%s.', triggertype)
            abort(http_client.BAD_REQUEST, str(e))
            return
        else:
            extra = {'triggertype_db': triggertype_db}
            LOG.audit('TriggerType created. TriggerType.id=%s' % (triggertype_db.id), extra=extra)
            if not triggertype_db.parameters_schema:
                TriggerTypeController._create_shadow_trigger(triggertype_db)

        triggertype_api = TriggerTypeAPI.from_model(triggertype_db)

        return Response(json=triggertype_api, status=http_client.CREATED)
Beispiel #58
0
    def _get_one(self, ref_or_id, requester_user, permission_type, exclude_fields=None,
                 include_fields=None, from_model_kwargs=None):
        try:
            instance = self._get_by_ref_or_id(ref_or_id=ref_or_id, exclude_fields=exclude_fields,
                                              include_fields=include_fields)
        except Exception as e:
            LOG.exception(str(e))
            abort(http_client.NOT_FOUND, str(e))
            return

        if permission_type:
            rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                              resource_db=instance,
                                                              permission_type=permission_type)

        # Perform resource isolation check (if supported)
        from_model_kwargs = from_model_kwargs or {}
        from_model_kwargs.update(self.from_model_kwargs)

        result = self.resource_model_filter(model=self.model, instance=instance,
                                            requester_user=requester_user,
                                            **from_model_kwargs)

        if not result:
            LOG.debug('Not returning the result because RBAC resource isolation is enabled and '
                      'current user doesn\'t match the resource user')
            raise ResourceAccessDeniedPermissionIsolationError(user_db=requester_user,
                                                               resource_api_or_db=instance,
                                                               permission_type=permission_type)

        if result and self.include_reference:
            pack = getattr(result, 'pack', None)
            name = getattr(result, 'name', None)
            result.ref = ResourceReference(pack=pack, name=name).ref

        return Response(json=result)
Beispiel #59
0
    def _get_one_by_id(self, id, requester_user, permission_type, exclude_fields=None,
                       include_fields=None, from_model_kwargs=None):
        """
        :param exclude_fields: A list of object fields to exclude.
        :type exclude_fields: ``list``
        :param include_fields: A list of object fields to include.
        :type include_fields: ``list``
        """

        instance = self._get_by_id(resource_id=id, exclude_fields=exclude_fields,
                                   include_fields=include_fields)

        if permission_type:
            rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                              resource_db=instance,
                                                              permission_type=permission_type)

        if not instance:
            msg = 'Unable to identify resource with id "%s".' % id
            abort(http_client.NOT_FOUND, msg)

        from_model_kwargs = from_model_kwargs or {}
        from_model_kwargs.update(self.from_model_kwargs)

        result = self.resource_model_filter(model=self.model, instance=instance,
                                            requester_user=requester_user,
                                            **from_model_kwargs)

        if not result:
            LOG.debug('Not returning the result because RBAC resource isolation is enabled and '
                      'current user doesn\'t match the resource user')
            raise ResourceAccessDeniedPermissionIsolationError(user_db=requester_user,
                                                               resource_api_or_db=instance,
                                                               permission_type=permission_type)

        return result
Beispiel #60
0
    def match_and_execute(self, input_api, requester_user, show_secrets=False):
        """
        Try to find a matching alias and if one is found, schedule a new
        execution by parsing parameters from the provided command against
        the matched alias.

        Handles requests:
            POST /aliasexecution/match_and_execute
        """
        command = input_api.command

        try:
            format_ = get_matching_alias(command=command)
        except ActionAliasAmbiguityException as e:
            LOG.exception('Command "%s" matched (%s) patterns.', e.command,
                          len(e.matches))
            return abort(http_client.BAD_REQUEST, six.text_type(e))

        action_alias_db = format_["alias"]
        representation = format_["representation"]

        params = {
            "name": action_alias_db.name,
            "format": representation,
            "command": command,
            "user": input_api.user,
            "source_channel": input_api.source_channel,
        }

        # Add in any additional parameters provided by the user
        if input_api.notification_channel:
            params["notification_channel"] = input_api.notification_channel

        if input_api.notification_route:
            params["notification_route"] = input_api.notification_route

        alias_execution_api = AliasMatchAndExecuteInputAPI(**params)
        results = self._post(
            payload=alias_execution_api,
            requester_user=requester_user,
            show_secrets=show_secrets,
            match_multiple=format_["match_multiple"],
        )
        return Response(json={"results": results}, status=http_client.CREATED)