Exemplo n.º 1
0
    def handle_lambda_event(self, event):
        #log_to_elk("in Lambda_Graph.handle_lambda_event :{0}".format(event))
        data    = event.get('data')
        if data:
            channel = data.get('channel')
            team_id = data.get('team_id')
        else:
            channel = None
            team_id = None
        params  = event.get('params')

        if params is None or len(params) == 0:
            params = ['help']

        from osbot_jira.api.graph.Lambda_Graph_Commands import Lambda_Graph_Commands # can only do this here to avoid circular dependencies
        try:
            method_name  = params.pop(0)
            method       = getattr(Lambda_Graph_Commands, method_name)
        except Exception:
            method = Lambda_Graph_Commands.help
        try:
            return method(team_id, channel, params, data)
        except Exception as error:
            message = ':red_circle: Error processing params `{0}`: _{1}_'.format(params, pprint.pformat(error))
            slack_message(message, [], channel)
            log_to_elk("Error in Lambda_Graph.handle_lambda_event :{0}".format(error), level = 'error')
            return message
Exemplo n.º 2
0
    def handle_dialog_submission(self, event):

        channel = event['channel']['id']
        team_id = event['team']['id']
        #user         = "******".format(data['user']['name'],data['user']['id'])
        data    = {
                      'channel'      : event.get('channel'     ),
                      'team_id'      : event.get('team'        ),
                      'user'         : event.get('user'        ),
                      'callback_id'  : event.get('callback_id' ),
                      'submission'   : event.get('submission'  ),
                      'action_ts'    : event.get('action_ts'   ),
                      'response_url' : event.get('response_url'),

                   }

        log_to_elk('Slack_Actions.handle_dialog_submission', data=data, index='slack_interaction', category='OSBot-jira')



        payload =  { "channel": channel,
                     "team_id": team_id,
                     "data"   : data  }
        Lambda('osbot_jira.lambdas.slack_jira_actions').invoke_async(payload) # calling lambda that handles submissions

        return {}
Exemplo n.º 3
0
def run(event, context):
    load_dependency('pydot')
    channel = event.get('channel')
    data = event.get('dot')

    #slack_message("in dot to svg: {0}".format(event), [], channel)
    log_to_elk("in dot to svg: {0}".format(event))

    import dot_parser

    try:
        (fd, tmp_file) = tempfile.mkstemp('dot)')
        dot_static = '/tmp/lambdas-dependencies/pydot/dot_static'
        Process.run("chmod", ['+x', dot_static])
        data = data.replace('&lt;', '<').replace(
            '&gt;', '>'
        )  # this solved a really nasty bug caused by the fact that Slack will html encode the < and >

        # graph          = pydot.graph_from_dot_data(data).pop()
        # <from pydot>  use code below (instead of above) to get a better error message from dot parser
        graphparser = dot_parser.graph_definition()
        graphparser.parseWithTabs()
        tokens = graphparser.parseString(data)
        graph = list(tokens).pop()
        # </from pydot>
        graph.write_svg(tmp_file, prog=dot_static)
        svg_raw = Files.contents(tmp_file)
        return base64.b64encode(svg_raw.encode()).decode()
    except Exception as error:
        slack_message("[dot_to_svg] Error: {0} ".format(error), [], channel)
        return None
Exemplo n.º 4
0
    def handle_lambda_event(self, event):

        channel = event.get('channel' )
        params  = event.get("params"  )
        user    = event.get('user'    )
        team_id  = event.get('team_id')
        log_to_elk('[Elk_to_Slack.handle_lambda_event]: {0}'.format(event))
        try:
            if params:
                command = params.pop(0)
                if command == 'search'      : return self.cmd_search      (params, user, team_id, channel)
                #if command == 'search-graph': return self.cmd_search_graph(params, user, team_id, channel)

                #return slack_message(":point_right: in handle_lambda_event with params: {0}".format(event), [], channel)
            slack_message(":red_circle: in ELK_to_Slack, un-supported command :`{0}`. Data received was: {1}".format(command,event), [], channel)
        except Exception as error:
            message = ":red_circle: error in ELK_to_Slack:`{0}`. Data received was: {1}".format(error,event)
            log_to_elk(message, level = 'error')
            slack_message(message , [], channel)

    # def save_search_in_elk(self, message):
    #     index   = 'slack_interaction'
    #     item    = { 'data': message,
    #                 'date': datetime.datetime.utcnow() }
    #     elastic = Log_To_Elk().setup(index)
    #     return elastic.add(item)
Exemplo n.º 5
0
    def invoke(self, team_id, channel, params):
        attachments = []
        if len(params) == 0:
            (text, attachments) = self.help()
        else:
            command = params.pop(0)  # extract first element from the array
            if command in self.available_methods():
                method = getattr(self.target, command)
                try:
                    if self.with_slack_support:
                        return method(team_id, channel, params)
                    else:
                        text, attachments = method(params)
                except Exception as error:
                    text = ':red_circle: Error processing params `{0}`: _{1}_'.format(
                        params, pprint.pformat(error))
                    log_to_elk(
                        "Error in Lambda_Graph.handle_lambda_event :{0}".
                        format(error),
                        level='error')
            else:
                (text, attachments) = self.help(
                    ':red_circle: command not found `{0}`\n\n'.format(command))

        return slack_message(text, attachments, channel, team_id)
Exemplo n.º 6
0
    def cmd_create(self, params, team_id=None, channel=None):
        try:
            if len(params) < 3:
                text = ":exclamation: To create an issue you need to provide the `issue type` and `summary`. For example `jira create task abc"
                return {"text": text, "attachments": []}
            else:
                params.pop(0)  # the create command
                issue_type = params.pop(
                    0)  #.title() # todo: find a better solution for this
                project = issue_type.upper(
                )  # todo: and to address the mapping of issue types to projects
                summary = ' '.join(params)
                slack_message(
                    ':point_right: Going to create an `{0}` issue, in project `{1}` with summary `{2}`'
                    .format(issue_type, project,
                            summary), [], channel, team_id)

                #to do, move this feature to a separate lambda (which can be called to create issues
                from osbot_aws.Dependencies import load_dependency
                load_dependency('jira')
                from osbot_jira.api.jira_server.API_Jira import API_Jira

                # create issue
                result = API_Jira().issue_create(project, summary, '',
                                                 issue_type)
                issue_id = "{0}".format(result)

                # show issue screenshot
                # payload = {'issue_id': issue_id,'channel': channel,'team_id': team_id, }
                # Lambda('osbot_browser.lambdas.jira_web').invoke_async(payload)

                # show issue UI
                payload = {'params': ['issue', issue_id], "channel": channel}
                Lambda('osbot_jira.lambdas.jira').invoke_async(payload)

                # show link of new issue to user
                jira_link = "https://glasswall.atlassian.net/browse/{0}".format(
                    issue_id)
                text = ':point_right: New issue created with id <{0}|{1}>'.format(
                    jira_link, issue_id)
            return {"text": text, "attachments": []}
        except Exception as error:
            log_to_elk('jira create error', f'{error}')
            return {
                'text':
                f':red_circle: Issue could not be created, please make sure that: \n - issue type exists\n - issue type = project type\n - Issue type CamelCase is correctly entered (you want `Task` and not `task`)',
                "attachments": []
            }
def upload_png_file(team_id, channel_id, file):
    import requests
    from osbot_aws.helpers.Lambda_Helpers import log_to_elk
    log_to_elk("[upload_png_file]: {0} {1} {2}".format(team_id,channel_id,file))
    bot_token = resolve_bot_token(team_id)
    my_file = {
        'file': ('/tmp/myfile.png', open(file, 'rb'), 'png')
    }

    payload = {
        "filename"  : 'image.png',
        "token"     : bot_token,
        "channels"  : [channel_id],
    }
    requests.post("https://slack.com/api/files.upload", params=payload, files=my_file)

    return 'image sent .... '
Exemplo n.º 8
0
def run(event, context):
    try:
        data = event.get('data')
        type = event.get('type')
        if type == 'jira_slash_command':
            return API_Jira_Dialog().handle_jira_slash_command(data)
        if type == 'dialog_submission':
            return API_Jira_Dialog().handle_dialog_submission(data)
        if type == 'jira_dialog_action':
            return API_Jira_Dialog().handle_jira_dialog_action(data)
        if type == 'button_dialog_test':
            return API_Jira_Dialog().handle_button_dialog_test(data)
        return {
            "text": 'Unrecognised command: {0}'.format(type),
            "attachments": [],
            'replace_original': False
        }
    except Exception as error:
        error_message = 'Error in jira_dialog Lambda: {0}'.format(error)
        log_to_elk(error_message, level='error')
        return {"text": error_message, "attachments": []}
Exemplo n.º 9
0
def run(event, context):
    load_dependencies('requests,elastic')
    from osbot_aws.helpers.Lambda_Helpers import log_to_elk
    from osbot_jira.api.jira_server.API_Jira_To_Elastic import API_Jira_To_Elastic
    try:
        data       = json.loads(event.get('body'))
        event_type = data.get('webhookEvent')
        user_id    = event.get('queryStringParameters').get('user_id')
        message    = API_Jira_To_Elastic().handle_event(event_type, user_id, data)
        status_code = 200
    except Exception as error:
        message = f'error in on_jira_change: {error}'
        log_to_elk(message, f"{event.get('body')}", index='elastic_logs', level='error')
        status_code = 200                                                   # don't return error 500 or Jira will keep sending it


    return {
                "isBase64Encoded": False      ,
                "statusCode"     : status_code,
                "headers"        : {}         ,
                "body"           : f'{message}'
           }
Exemplo n.º 10
0
    def handle_callback_issue_search_dialog(self, data):
        channel     = data['channel']['id']
        key         = data.get('submission').get('key')
        if key is None:
            key     = data.get('submission').get('key_direct')
        view_type   = data.get('submission').get('view-type')
        view_engine = data.get('submission').get('view-engine')

        user_id     = data['user']['id']

        if view_type == 'table':
            slack_message("Generating table for key: {0}".format(key), [], channel)
            Lambda('pbx_gs_python_utils.lambdas.gs.elastic_jira').invoke_async({"params": ["issue", key], "user": user_id, "channel": channel})
            #slack_message(result.get('text'), result.get('attachments'), channel)

        elif view_type == 'issue-links-vuln-path':
            path          = 'is parent of, supports RISK, creates R3, creates R2, creates R1, has Stakeholder'
            view_engine   = view_engine
            self.call_lambda_jira_view_issue_links(data, key, path, view_engine, channel)

        elif view_type == 'issue-links-stakeholder-path':
            path          = 'is Stakeholder,is created by R3, is created by R2, is created by R1'
            view_engine   = view_engine
            self.call_lambda_jira_view_issue_links(data, key, path, view_engine, channel)

        elif view_engine == 'issue-links-all-depth-1':
            view_engine = view_engine
            self.call_lambda_jira_view_issue_links(data, key, "", view_engine, channel)

        # elif view_type == 'issue-links-view-all':
        #     path          = 'is parent of, supports RISK, creates R3, creates R2, creates R1, has Stakeholder'
        #     view_engine   = view_engine
        #     self.call_lambda_jira_view_issue_links(data, key, path, view_engine, channel)

            #Lambdas('pbx_gs_python_utils.lambdas.gs.elastic_jira').invoke_async({"params": ["issue-links", key], "channel": channel})
        else:
            log_to_elk("Error: un-supported view engine `{0}` for key `{1}`".format(view_type,key),level= 'error')
Exemplo n.º 11
0
    def handle_event(self, event_type, user_id, data):
        log_message = 'API_Jira_To_Elastic.handle_event'
        if event_type == 'issuelink_deleted':  # link deleted
            log_data = self.handle_link_event(data, 'link_deleted')
        elif event_type == 'issuelink_created':  # link created
            log_data = self.handle_link_event(data, 'link_created')
        elif event_type == 'jira:issue_created':
            log_data = self.handle_issue_created(data)
        elif event_type == 'jira:issue_deleted':  # issue deleted
            log_data = self.handle_issue_deleted(data)
        elif event_type == 'jira:issue_updated':  # issue updated
            log_data = self.handle_issue_updated(data)
        else:
            log_data = {
                'event_type': f'unsupported event_type: {event_type}',
                'event_user': '******',
                'event_key': 'NA',
                'raw_data': f'{data}'
            }

        log_data['user_id'] = user_id

        return log_to_elk(log_message, log_data, index='elastic_logs')