]> git.cworth.org Git - turbot/blob - turbot_lambda/turbot_lambda.py
Correct the code storing the picked base64 token
[turbot] / turbot_lambda / turbot_lambda.py
1 from urllib.parse import parse_qs
2 from slack import WebClient
3 import base64
4 import boto3
5 import requests
6 import json
7 import os
8 import pickle
9 from types import SimpleNamespace
10 from google.auth.transport.requests import Request
11 from googleapiclient.discovery import build
12
13 import turbot.actions
14 import turbot.commands
15 import turbot.events
16
17 ssm = boto3.client('ssm')
18
19 response = ssm.get_parameter(Name='SLACK_SIGNING_SECRET', WithDecryption=True)
20 slack_signing_secret = response['Parameter']['Value']
21 os.environ['SLACK_SIGNING_SECRET'] = slack_signing_secret
22
23 # Note: Late import here to have the environment variable above available
24 from turbot.slack import slack_is_valid_request # noqa
25
26 response = ssm.get_parameter(Name='SLACK_BOT_TOKEN', WithDecryption=True)
27 slack_bot_token = response['Parameter']['Value']
28 slack_client = WebClient(slack_bot_token)
29
30 response = ssm.get_parameter(Name='GSHEETS_PICKLE_BASE64', WithDecryption=True)
31 gsheets_pickle_base64 = response['Parameter']['Value']
32 gsheets_pickle = base64.b64decode(gsheets_pickle_base64)
33 gsheets_creds = pickle.loads(gsheets_pickle)
34 if gsheets_creds:
35     if gsheets_creds.valid:
36         print("Loaded valid GSheets credentials from SSM")
37     else:
38         gsheets_creds.refresh(Request())
39         gsheets_pickle = pickle.dumps(gsheets_creds)
40         gsheets_pickle_base64_bytes = base64.b64encode(gsheets_pickle)
41         gsheets_pickle_base64 = gsheets_pickle_base64_bytes.decode('us-ascii')
42         print("Storing refreshed GSheets credentials into SSM")
43         ssm.put_parameter(Name='GSHEETS_PICKLE_BASE64',
44                           Type='SecureString',
45                           Value=gsheets_pickle_base64,
46                           Overwrite=True)
47 service = build('sheets',
48                 'v4',
49                 credentials=gsheets_creds,
50                 cache_discovery=False)
51 sheets = service.spreadsheets()
52
53 db = boto3.resource('dynamodb')
54
55 turb = SimpleNamespace()
56 turb.slack_client = slack_client
57 turb.db = db
58 turb.sheets = sheets
59
60 def error(message):
61     """Generate an error response for a Slack request
62
63     This will print the error message (so that it appears in CloudWatch
64     logs) and will then return a dictionary suitable for returning
65     as an error response."""
66
67     print("Error: {}.".format(message))
68
69     return {
70         'statusCode': 400,
71         'body': ''
72     }
73
74 def turbot_lambda(event, context):
75     """Top-level entry point for our lambda function.
76
77     This function first verifies that the request actually came from
78     Slack, (by means of the SLACK_SIGNING_SECRET SSM parameter), and
79     refuses to do anything if not.
80
81     Then this defers to either turbot_event_handler or
82     turbot_slash_command to do any real work.
83     """
84
85     headers = requests.structures.CaseInsensitiveDict(event['headers'])
86
87     signature = headers['X-Slack-Signature']
88     timestamp = headers['X-Slack-Request-Timestamp']
89
90     if not slack_is_valid_request(signature, timestamp, event['body']):
91         return error("Invalid Slack signature")
92
93     # It's a bit cheesy, but we'll just use the content-type header to
94     # determine if we're being called from a Slack event or from a
95     # slash command or other interactivity. (The more typical way to
96     # do this would be to have different URLs for each Slack entry
97     # point, but it's simpler to have our Slack app implemented as a
98     # single AWS Lambda, (which can only have a single entry point).
99     content_type = headers['content-type']
100
101     if (content_type == "application/json"):
102         return turbot_event_handler(turb, event, context)
103     if (content_type == "application/x-www-form-urlencoded"):
104         return turbot_interactive_or_slash_command(turb, event, context)
105     return error("Unknown content-type: {}".format(content_type))
106
107 def turbot_event_handler(turb, event, context):
108     """Handler for all subscribed Slack events"""
109
110     body = json.loads(event['body'])
111
112     type = body['type']
113
114     if type == 'url_verification':
115         return url_verification_handler(turb, body)
116     if type == 'event_callback':
117         return event_callback_handler(turb, body)
118     return error("Unknown event type: {}".format(type))
119
120 def url_verification_handler(turb, body):
121
122     # First, we have to properly respond to url_verification
123     # challenges or else Slack won't let us configure our URL as an
124     # event handler.
125     challenge = body['challenge']
126
127     return {
128         'statusCode': 200,
129         'body': challenge
130     }
131
132 def event_callback_handler(turb, body):
133     type = body['event']['type']
134
135     if type in turbot.events.events:
136         return turbot.events.events[type](turb, body)
137     return error("Unknown event type: {}".format(type))
138
139 def turbot_interactive_or_slash_command(turb, event, context):
140     """Handler for Slack interactive things (buttons, shortcuts, etc.)
141     as well as slash commands.
142
143     This function simply makes a quiuck determination of what we're looking
144     at and then defers to either turbot_interactive or turbot_slash_command."""
145
146     # Both interactives and slash commands have a urlencoded body
147     body = parse_qs(event['body'])
148
149     # The difference is that an interactive thingy has a 'payload'
150     # while a slash command has a 'command'
151     if 'payload' in body:
152         return turbot_interactive(turb, json.loads(body['payload'][0]))
153     if 'command' in body:
154         return turbot_slash_command(turb, body)
155     return error("Unrecognized event (neither interactive nor slash command)")
156
157 def turbot_interactive(turb, payload):
158     """Handler for Slack interactive requests
159
160     These are the things that come from a user interacting with a button
161     a shortcut or some other interactive element that our app has made
162     available to the user."""
163
164     type = payload['type']
165
166     if type == 'block_actions':
167         return turbot_block_action(turb, payload)
168     if type == 'view_submission':
169         return turbot.actions.view_submission(turb, payload)
170     return error("Unrecognized interactive type: {}".format(type))
171
172 def turbot_block_action(turb, payload):
173     """Handler for Slack interactive block actions
174
175     Specifically, those that have a payload type of 'block_actions'"""
176
177     actions = payload['actions']
178
179     if len(actions) != 1:
180         return error("No support for multiple actions ({}) in a single request"
181                      .format(len(actions)))
182
183     action = actions[0]
184
185     atype = action['type']
186     avalue = action['value']
187
188     if (
189             atype in turbot.actions.actions
190             and avalue in turbot.actions.actions[atype]
191     ):
192         return turbot.actions.actions[atype][avalue](turb, payload)
193     return error("Unknown action of type/value: {}/{}".format(atype, avalue))
194
195 def turbot_slash_command(turb, body):
196     """Implementation for Slack slash commands.
197
198     This parses the request and arguments and farms out to
199     supporting functions to implement all supported slash commands.
200     """
201
202     command = body['command'][0]
203     args = body['text'][0]
204
205     if command in turbot.commands.commands:
206         return turbot.commands.commands[command](turb, body, args)
207
208     return error("Command {} not implemented".format(command))