-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathhandler.py
More file actions
372 lines (314 loc) · 12.6 KB
/
handler.py
File metadata and controls
372 lines (314 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import json
import os
import http.client
import hmac
import time
import uuid
import boto3
from time import perf_counter as pc
from urllib.parse import urlparse
import ssl
from io import StringIO
import gzip
import re
import hashlib
class Config:
"""Lambda function runtime configuration"""
ENDPOINT = 'ENDPOINT'
METHOD = 'METHOD'
PAYLOAD = 'PAYLOAD'
TIMEOUT = 'TIMEOUT'
HEADERS = 'HEADERS'
USER_AGENT = 'USER_AGENT'
COMPRESSED = 'COMPRESSED'
REPORT_RESPONSE_BODY = 'REPORT_RESPONSE_BODY'
REPORT_AS_CW_METRICS = 'REPORT_AS_CW_METRICS'
CW_METRICS_NAMESPACE = 'CW_METRICS_NAMESPACE'
CW_METRICS_METRIC_NAME = 'CW_METRICS_METRIC_NAME'
BODY_REGEX_MATCH = 'BODY_REGEX_MATCH'
STATUS_CODE_MATCH = 'STATUS_CODE_MATCH'
FAIL_ON_STATUS_CODE_MISMATCH = 'FAIL_ON_STATUS_CODE_MISMATCH'
HMAC_SECRET_SSM = 'HMAC_SECRET_SSM'
HMAC_KEY_ID = 'HMAC_KEY_ID'
HMAC_HEADER_PREFIX = 'HMAC_HEADER_PREFIX'
def __init__(self, event):
self.event = event
self.defaults = {
self.ENDPOINT: 'https://google.com.au',
self.METHOD: 'GET',
self.PAYLOAD: None,
self.TIMEOUT: 120,
self.REPORT_RESPONSE_BODY: '0',
self.REPORT_AS_CW_METRICS: '1',
self.CW_METRICS_NAMESPACE: 'HttpCheck',
self.USER_AGENT: '',
self.HEADERS: '',
self.COMPRESSED: '0',
self.BODY_REGEX_MATCH: None,
self.STATUS_CODE_MATCH: None,
self.FAIL_ON_STATUS_CODE_MISMATCH: None,
self.HMAC_SECRET_SSM: None,
self.HMAC_KEY_ID: 'default',
self.HMAC_HEADER_PREFIX: 'X-Health',
}
def __get_property(self, property_name):
if property_name in self.event:
return self.event[property_name]
if property_name in os.environ:
return os.environ[property_name]
if property_name in self.defaults:
return self.defaults[property_name]
return None
@property
def endpoint(self):
return self.__get_property(self.ENDPOINT)
@property
def method(self):
return self.__get_property(self.METHOD)
@property
def payload(self):
payload = self.__get_property(self.PAYLOAD)
if payload is not None:
return payload.encode('utf-8')
return payload
@property
def timeout(self):
return self.__get_property(self.TIMEOUT)
@property
def reportbody(self):
return self.__get_property(self.REPORT_RESPONSE_BODY)
@property
def headers(self):
header_dict = {}
headers = self.__get_property(self.HEADERS)
user_agent = self.__get_property(self.USER_AGENT)
if user_agent != '':
header_dict['User-Agent'] = user_agent
if headers == '':
return header_dict
else:
try:
for u in headers.split(' '):
key = u.split("=")[0]
val = u.split("=")[1].replace('%20',' ')
header_dict[key] = val
return header_dict
except:
print(f"Could not decode headers: {header_dict}")
return header_dict
@property
def bodyregexmatch(self):
return self.__get_property(self.BODY_REGEX_MATCH)
@property
def statuscodematch(self):
return self.__get_property(self.STATUS_CODE_MATCH)
@property
def fail_on_statuscode_mismatch(self):
return self.__get_property(self.FAIL_ON_STATUS_CODE_MISMATCH)
@property
def hmac_secret_ssm(self):
return self.__get_property(self.HMAC_SECRET_SSM)
@property
def hmac_key_id(self):
return self.__get_property(self.HMAC_KEY_ID)
@property
def hmac_header_prefix(self):
return self.__get_property(self.HMAC_HEADER_PREFIX)
@property
def cwoptions(self):
return {
'enabled': self.__get_property(self.REPORT_AS_CW_METRICS),
'namespace': self.__get_property(self.CW_METRICS_NAMESPACE),
}
@property
def compressed(self):
return self.__get_property(self.COMPRESSED)
# Module-level SSM secret cache: {ssm_path: (secret_value, fetched_at)}
# Cached values are reused across warm Lambda invocations for up to SSM_CACHE_TTL seconds.
_SSM_CACHE = {}
_SSM_CACHE_TTL = 600 # 10 minutes
class HmacSigner:
"""Generates HMAC signed request headers using a secret fetched from SSM Parameter Store.
The canonical string used for signing is:
METHOD\nPATH\nTIMESTAMP\nNONCE\nQUERY\nBODY_HASH
Four headers are added to the request:
{prefix}-Signature — HMAC-SHA256 hex digest of the canonical string
{prefix}-Key-Id — identifier for the signing key
{prefix}-Timestamp — Unix epoch timestamp (seconds)
{prefix}-Nonce — random UUID hex used to prevent replay attacks
"""
def __init__(self, config):
self.secret_ssm = config.hmac_secret_ssm
self.key_id = config.hmac_key_id
self.header_prefix = config.hmac_header_prefix
def _fetch_secret(self):
now = time.time()
cached = _SSM_CACHE.get(self.secret_ssm)
if cached and (now - cached[1]) < _SSM_CACHE_TTL:
return cached[0]
ssm = boto3.client('ssm')
response = ssm.get_parameter(Name=self.secret_ssm, WithDecryption=True)
secret = response['Parameter']['Value']
_SSM_CACHE[self.secret_ssm] = (secret, now)
return secret
def sign(self, method, path, query, body):
secret = self._fetch_secret()
timestamp = str(int(time.time()))
nonce = uuid.uuid4().hex
body_hash = hashlib.sha256(body if body else b'').hexdigest()
canonical = '\n'.join([method, path, timestamp, nonce, query or '', body_hash])
signature = hmac.new(
secret.encode('utf-8'),
canonical.encode('utf-8'),
hashlib.sha256
).hexdigest()
prefix = self.header_prefix
if 'HTTP_DEBUG' in os.environ and os.environ['HTTP_DEBUG'] == '1':
print(f"HMAC canonical string: {repr(canonical)}")
return {
f'{prefix}-Signature': signature,
f'{prefix}-Key-Id': self.key_id,
f'{prefix}-Timestamp': timestamp,
f'{prefix}-Nonce': nonce,
}
class HttpCheck:
"""Execution of HTTP(s) request"""
def __init__(self, config):
self.method = config.method
self.endpoint = config.endpoint
self.timeout = config.timeout
self.payload = config.payload
self.headers = config.headers
self.compressed = config.compressed
self.bodyregexmatch = config.bodyregexmatch
self.statuscodematch = config.statuscodematch
self.fail_on_statuscode_mismatch = config.fail_on_statuscode_mismatch
self.hmac_signer = HmacSigner(config) if config.hmac_secret_ssm else None
def execute(self):
url = urlparse(self.endpoint)
location = url.netloc
if url.scheme == 'http':
request = http.client.HTTPConnection(location, timeout=int(self.timeout))
if url.scheme == 'https':
request = http.client.HTTPSConnection(location, timeout=int(self.timeout), context=ssl._create_unverified_context())
if 'HTTP_DEBUG' in os.environ and os.environ['HTTP_DEBUG'] == '1':
request.set_debuglevel(1)
path = url.path
if path == '':
path = '/'
if url.query is not None:
path = path + "?" + url.query
if self.hmac_signer:
hmac_headers = self.hmac_signer.sign(
self.method,
url.path if url.path else '/',
url.query or '',
self.payload,
)
self.headers.update(hmac_headers)
if self.compressed == '1':
self.headers['Accept-Encoding'] = 'deflate, gzip'
try:
t0 = pc()
# perform request
request.request(self.method, path, self.payload, self.headers)
# read response
response_data = request.getresponse()
# stop the stopwatch
t1 = pc()
print(f"Request headers: {self.headers}")
print(f"Headers: {response_data.getheaders()}")
if response_data.getheader('Content-Encoding') == 'gzip':
data = gzip.decompress(response_data.read())
response_body = str(data,'utf-8')
elif response_data.getheader('Content-Type') and response_data.getheader('Content-Type').startswith('image/'):
response_body = hashlib.md5(response_data.read()).hexdigest()
print(response_body)
else:
response_body = str(response_data.read().decode('utf-8','replace'))
result = {
'Reason': response_data.reason,
'ResponseBody': response_body,
'StatusCode': response_data.status,
'TimeTaken': int((t1 - t0) * 1000),
'Available': '1'
}
if self.bodyregexmatch is not None:
regex = re.compile(self.bodyregexmatch)
value = 1 if regex.search(response_body) else 0
result['ResponseBodyRegexMatch'] = value
if self.statuscodematch is not None:
result['StatusCodeMatch'] = int(int(response_data.status) == int(self.statuscodematch))
if not result['StatusCodeMatch'] and self.fail_on_statuscode_mismatch:
result['Available'] = '0'
# return structure with data
return result
except Exception as e:
print(f"Failed to connect to {self.endpoint}\n{e}")
return {'Available': 0, 'Reason': str(e)}
class ResultReporter:
"""Reporting results to CloudWatch"""
def __init__(self, config, context):
self.options = config.cwoptions
self.endpoint = config.endpoint
def report(self, result):
if self.options['enabled'] == '1':
try:
cloudwatch = boto3.client('cloudwatch')
metric_data = [{
'MetricName': 'Available',
'Dimensions': [
{'Name': 'Endpoint', 'Value': self.endpoint}
],
'Unit': 'None',
'Value': int(result['Available'])
}]
if result['Available'] == '1':
metric_data.append({
'MetricName': 'TimeTaken',
'Dimensions': [
{'Name': 'Endpoint', 'Value': self.endpoint}
],
'Unit': 'Milliseconds',
'Value': int(result['TimeTaken'])
})
metric_data.append({
'MetricName': 'StatusCode',
'Dimensions': [
{'Name': 'Endpoint', 'Value': self.endpoint}
],
'Unit': 'None',
'Value': int(result['StatusCode'])
})
for additional_metric in ['ResponseBodyRegexMatch', 'StatusCodeMatch']:
if additional_metric in result:
metric_data.append({
'MetricName': additional_metric,
'Dimensions': [
{'Name': 'Endpoint', 'Value': self.endpoint}
],
'Unit': 'None',
'Value': int(result[additional_metric])
})
result = cloudwatch.put_metric_data(
MetricData=metric_data,
Namespace=self.options['namespace']
)
print(f"Sent data to CloudWatch requestId=:{result['ResponseMetadata']['RequestId']}")
except Exception as e:
print(f"Failed to publish metrics to CloudWatch:{e}")
def http_check(event, context):
"""Lambda function handler"""
config = Config(event)
http_check = HttpCheck(config)
result = http_check.execute()
# report results
ResultReporter(config, result).report(result)
# Remove body if not required
if (config.reportbody != '1') and ('ResponseBody' in result):
del result['ResponseBody']
result_json = json.dumps(result, indent=4)
# log results
print(f"Result of checking {config.method} {config.endpoint}\n{result_json}")
# return to caller
return result