-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
214 lines (172 loc) · 6.87 KB
/
main.py
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
import json
import os
import functions_framework
import logging
import hmac
import hashlib
import google.cloud.logging
from google.cloud import workflows_v1
from google.cloud.workflows import executions_v1
from google.cloud.workflows.executions_v1 import Execution
from google.cloud.workflows.executions_v1.types import executions
# Setup google cloud logging and ignore errors
if "DISABLE_GOOGLE_LOGGING" not in os.environ:
try:
client = google.cloud.logging.Client()
client.setup_logging()
except google.auth.exceptions.DefaultCredentialsError:
pass
if "TFC_ORG" in os.environ:
TFC_ORG = os.environ["TFC_ORG"]
else:
TFC_ORG = False
if "WORKSPACE_PREFIX" in os.environ:
WORKSPACE_PREFIX = os.environ["WORKSPACE_PREFIX"]
else:
WORKSPACE_PREFIX = False
if "HMAC_KEY" in os.environ:
HMAC_KEY = os.environ["HMAC_KEY"]
else:
HMAC_KEY = False
if "TFC_API_SECRET_NAME" in os.environ:
TFC_API_SECRET_NAME = os.environ["TFC_API_SECRET_NAME"]
else:
TFC_API_SECRET_NAME = False
if "GOOGLE_PROJECT" in os.environ:
GOOGLE_PROJECT = os.environ["GOOGLE_PROJECT"]
else:
GOOGLE_PROJECT = False
if "GOOGLE_REGION" in os.environ:
GOOGLE_REGION = os.environ["GOOGLE_REGION"]
else:
GOOGLE_REGION = False
if "NOTIFICATION_WORKFLOW" in os.environ:
NOTIFICATION_WORKFLOW = os.environ["NOTIFICATION_WORKFLOW"]
else:
NOTIFICATION_WORKFLOW = False
if "LOG_LEVEL" in os.environ:
logging.getLogger().setLevel(os.environ["LOG_LEVEL"])
logging.info("LOG_LEVEL set to %s" % logging.getLogger().getEffectiveLevel())
@functions_framework.http
def request_handler(request):
try:
logging.info("headers: " + str(request.headers))
logging.info("payload: " + str(request.get_data()))
request_headers = request.headers
request_payload = request.get_json(silent=True)
http_code = 422
if not HMAC_KEY:
http_message = "HMAC_KEY key environment variable missing on server"
http_code = 500
logging.error(http_message)
elif not TFC_API_SECRET_NAME:
http_message = (
"TFC_API_SECRET_NAME key environment variable missing on server"
)
http_code = 500
logging.error(http_message)
elif not GOOGLE_PROJECT:
http_message = "Project environment variable missing on server"
http_code = 500
logging.error(http_message)
elif not GOOGLE_REGION:
http_message = "Region environment variable missing on server"
http_code = 500
logging.error(http_message)
elif not NOTIFICATION_WORKFLOW:
http_message = "Workflow name environment variable missing on server"
http_code = 500
logging.error(http_message)
elif request_payload:
result, message = validate_request(request_headers, request_payload)
if result:
# Check HMAC signature
signature = request_headers["x-tfe-notification-signature"]
# Need to use request.get_data() for hmac digest
if validate_hmac(HMAC_KEY, request.get_data(), signature):
try:
request_payload["tfc_api_secret_name"] = TFC_API_SECRET_NAME
execute_workflow(request_payload)
http_message = "OK"
http_code = 200
except Exception as e:
http_code = 500
http_message = "Workflow execution error"
logging.error(f"{http_code} - {http_message}: {e}")
else:
http_message = "HMAC signature invalid"
logging.warning(message)
else:
http_code = 200
http_message = "Payload missing in request"
logging.info(f"{http_code} - {http_message}")
return http_message, http_code
except Exception as e:
logging.exception("Terraform Cloud notification Request error: {}".format(e))
http_message = "Internal notification API error occurred"
http_code = 500
logging.warning(f"{http_code} - {http_message}: {e}")
return http_message, http_code
def validate_request(headers, payload) -> (bool, str):
"""Validate request values"""
if headers is None:
message = "Headers missing in request"
logging.warning(message)
return False, message
if payload is None:
message = "Payload missing in request"
logging.warning(message)
return False, message
if "x-tfe-notification-signature" not in headers:
message = "Terraform notification signature missing"
logging.warning(message)
return False, message
if "organization_name" not in payload.keys():
message = "Terraform payload missing : organization_name"
logging.warning(message)
return False, message
if "workspace_name" not in payload.keys():
message = "Terraform payload missing : workspace_name"
logging.warning(message)
return False, message
if TFC_ORG and payload.get("organization_name") != TFC_ORG:
message = "Terraform Org verification failed : {}".format(
payload.get("organization_name")
)
logging.warning(message)
return False, message
return True, "OK"
def validate_hmac(key: str, payload: str, signature: str) -> bool:
"""Returns true if the x-tfe-notification-signature header matches the SHA512 digest of the payload"""
digest = hmac.new(
bytes(key, "utf-8"), msg=payload, digestmod=hashlib.sha512
).hexdigest()
result = hmac.compare_digest(digest, signature)
if not result:
logging.warning(f"HMAC mismatch, digest: {digest}, signature: {signature}")
return result
def execute_workflow(
payload: dict,
project: str = GOOGLE_PROJECT,
location: str = GOOGLE_REGION,
workflow: str = NOTIFICATION_WORKFLOW,
) -> Execution:
"""
Execute a workflow and print the execution results
:param project: The Google Cloud project id which contains the workflow to execute.
:param location: The location for the workflow
:param workflow: The ID of the workflow to execute.
:return:
"""
arguments = payload
execution = Execution(argument=json.dumps(arguments))
# Set up API clients.
execution_client = executions_v1.ExecutionsClient()
workflows_client = workflows_v1.WorkflowsClient()
# Construct the fully qualified location path.
parent = workflows_client.workflow_path(project, location, workflow)
# Execute the workflow.
response = execution_client.create_execution(parent=parent, execution=execution)
logging.info(f"Created execution: {response.name}")
execution = execution_client.get_execution(request={"name": response.name})
return execution