Beispiel #1
0
 def send_report_request(self, workspace_name, report_json, user):
     logger.info("Send Report data to workspace [%s]", workspace_name)
     from faraday.server.web import app  # pylint:disable=import-outside-toplevel
     with app.app_context():
         ws = Workspace.query.filter_by(name=workspace_name).one()
         schema = BulkCreateSchema()
         data = schema.load(report_json)
         data = add_creator(data, user)
         bulk_create(ws, data, True)
Beispiel #2
0
def send_report_data(workspace_name: str, command_id: int, report_json: dict,
                     user_id: Optional[int], set_end_date: bool):
    logger.info("Send Report data to workspace [%s]", workspace_name)
    ws = Workspace.query.filter_by(name=workspace_name).one()
    command = Command.query.filter_by(id=command_id).one()
    schema = BulkCreateSchema()
    data = schema.load(report_json)
    if user_id:
        user = User.query.filter_by(id=user_id).one()
        data = add_creator(data, user)
    bulk_create(ws, command, data, True, set_end_date)
Beispiel #3
0
 def send_report_request(self, workspace_name: str, command_id: int,
                         report_json: dict, user_id: int):
     logger.info("Send Report data to workspace [%s]", workspace_name)
     from faraday.server.web import get_app  # pylint:disable=import-outside-toplevel
     with get_app().app_context():
         ws = Workspace.query.filter_by(name=workspace_name).one()
         command = Command.query.filter_by(id=command_id).one()
         user = User.query.filter_by(id=user_id).one()
         schema = BulkCreateSchema()
         data = schema.load(report_json)
         data = add_creator(data, user)
         bulk_create(ws, command, data, True, True)
Beispiel #4
0
    def post(self, workspace_name):
        """
        ---
          tags: ["Bulk"]
          description: Creates all faraday objects in bulk for a workspace
          requestBody:
            required: true
            content:
                application/json:
                    schema: BulkCreateSchema
          responses:
            201:tags:
              description: Created
              content:
                application/json:
                  schema: BulkCreateSchema
            403:
               description: Disabled workspace
            404:
               description: Workspace not found
        """
        data = self._parse_data(self._get_schema_instance({}), flask.request)

        if flask.g.user is None:
            agent = require_agent_token()
            workspace = agent.workspace

            if not workspace or workspace_name != workspace.name:
                flask.abort(404, "No such workspace: %s" % workspace_name)

            if "execution_id" not in data:
                flask.abort(400, "'execution_id' argument expected")

            execution_id = data["execution_id"]

            agent_execution = AgentExecution.query.filter(
                AgentExecution.id == execution_id).one_or_none()

            if agent_execution is None:
                logger.exception(
                    NoResultFound(
                        f"No row was found for agent executor id {execution_id}"
                    ))
                flask.abort(400,
                            "Can not find an agent execution with that id")

            if workspace_name != agent_execution.workspace.name:
                logger.exception(
                    ValueError(
                        f"The {agent.name} agent has permission to workspace {workspace_name} and ask to write "
                        f"to workspace {agent_execution.workspace.name}"))
                flask.abort(400, "Trying to write to the incorrect workspace")

            now = datetime.now()

            params_data = agent_execution.parameters_data
            params = ', '.join(
                [f'{key}={value}' for (key, value) in params_data.items()])

            data["command"] = {
                'tool':
                agent.name,  # Agent name
                'command':
                agent_execution.executor.name,
                'user':
                '',
                'hostname':
                '',
                'params':
                params,
                'import_source':
                'agent',
                'start_date': (data["command"].get("start_date") or now)
                if "command" in data else now,  #Now or when received run
                'end_date': (data["command"].get("start_date") or now)
                if "command" in data else now,  #Now or when received run
            }
        else:
            workspace = self._get_workspace(workspace_name)
            creator_user = flask.g.user
            data = add_creator(data, creator_user)

        bulk_create(workspace, data, True)
        return "Created", 201
Beispiel #5
0
    def post(self, workspace_name):
        """
        ---
          tags: ["Bulk"]
          description: Creates all faraday objects in bulk for a workspace
          requestBody:
            required: true
            content:
                application/json:
                    schema: BulkCreateSchema
          responses:
            201:tags:
              description: Created
              content:
                application/json:
                  schema: BulkCreateSchema
            401:
               $ref: "#/components/responses/UnauthorizedError"
            403:
               description: Disabled workspace
            404:
               description: Workspace not found
        """
        data = self._parse_data(self._get_schema_instance({}), flask.request)

        if flask.g.user is None:
            agent = require_agent_token()
            workspace = self._get_workspace(workspace_name)

            if not workspace or workspace not in agent.workspaces:
                flask.abort(404, f"No such workspace: {workspace_name}")

            if "execution_id" not in data:
                flask.abort(400, "'execution_id' argument expected")

            execution_id = data["execution_id"]

            agent_execution: AgentExecution = AgentExecution.query.filter(
                AgentExecution.id == execution_id).one_or_none()

            if agent_execution is None:
                logger.exception(
                    NoResultFound(
                        f"No row was found for agent executor id {execution_id}"
                    ))
                flask.abort(400,
                            "Can not find an agent execution with that id")

            if workspace_name != agent_execution.workspace.name:
                logger.exception(
                    ValueError(
                        f"The {agent.name} agent has permission to workspace {workspace_name} and ask to write "
                        f"to workspace {agent_execution.workspace.name}"))
                flask.abort(400, "Trying to write to the incorrect workspace")

            params_data = agent_execution.parameters_data
            params = ', '.join(
                [f'{key}={value}' for (key, value) in params_data.items()])

            start_date = (data["command"].get("start_date") or agent_execution.command.start_date) \
                if "command" in data else agent_execution.command.start_date

            end_date = data["command"].get("end_date",
                                           None) if "command" in data else None

            data["command"] = {
                'id': agent_execution.command.id,
                'tool': agent.name,  # Agent name
                'command': agent_execution.executor.name,
                'user': '',
                'hostname': '',
                'params': params,
                'import_source': 'agent',
                'start_date': start_date
            }

            if end_date is not None:
                data["command"]["end_date"] = end_date

            command = Command.query.filter(
                Command.id == agent_execution.command.id).one_or_none()
            if command is None:
                logger.exception(
                    ValueError(
                        f"There is no command with {agent_execution.command.id}"
                    ))
                flask.abort(400, "Trying to update a not existent command")

            _update_command(command, data['command'])
            db.session.flush()

        else:
            workspace = self._get_workspace(workspace_name)
            creator_user = flask.g.user
            data = add_creator(data, creator_user)

            if 'command' in data:
                command = Command(**(data['command']))
                command.workspace = workspace
                db.session.add(command)
                db.session.commit()
            else:
                # Here the data won't appear in the activity field
                command = None

        bulk_create(workspace, command, data, True, False)
        return flask.jsonify({
            "message":
            "Created",
            "command_id":
            None if command is None else command.id
        }), 201