-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
106 lines (79 loc) · 3.33 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
import base64
from flask import abort
import hmac
from http import HTTPStatus
from gitsup import update_git_submodules
import googleapiclient.discovery
import os
import sys
def autoupdate(request):
"""
Execute auto-update if the request contains the correct `X-Hub-Signature`,
depending on the shared secret key.
See https://developer.github.com/webhooks/creating/.
"""
github_api_token, github_webhook_secret = _read_secrets()
_check_signature(github_webhook_secret, request)
request_json = request.get_json()
try:
trigger_name = request_json["repository"]["name"]
print(f"Update triggered by repository '{trigger_name}'")
except KeyError:
print(f"Failed to get source repository name from request: {request_json}",
file=sys.stderr)
try:
update_git_submodules(token=github_api_token)
except ConnectionError as e:
print(f"{e}", file=sys.stderr)
abort(HTTPStatus.SERVICE_UNAVAILABLE)
except (PermissionError, RuntimeError) as e:
print(f"{e}", file=sys.stderr)
abort(HTTPStatus.INTERNAL_SERVER_ERROR)
return "ok"
def _read_secrets():
"""
Get the secrets from the environment. They are stored encrypted, so
we need to use the Google Key Management Service (KMS) to decrypt
them.
"""
print("Decrypting secrets")
crypto_key_id = os.environ["KMS_CRYPTO_KEY_ID"]
encrypted_github_api_token = os.environ["GITHUB_API_TOKEN"]
encrypted_github_webhook_secret = os.environ["GITHUB_WEBHOOK_SECRET"]
kms_client = googleapiclient.discovery.build("cloudkms",
"v1",
cache_discovery=False)
github_api_token = _decrypt(kms_client,
crypto_key_id,
encrypted_github_api_token)
github_webhook_secret = _decrypt(kms_client,
crypto_key_id,
encrypted_github_webhook_secret)
print("Successfully decrypted secrets")
return github_api_token, github_webhook_secret
def _decrypt(client, crypto_key_id, encrypted_secret):
""" Decrypt a secret using the Google Key Management Service. """
response = client \
.projects() \
.locations() \
.keyRings() \
.cryptoKeys() \
.decrypt(name=crypto_key_id, body={"ciphertext": encrypted_secret}) \
.execute()
return base64.b64decode(response["plaintext"]).decode("utf-8").strip()
def _check_signature(secret, request):
""" Check if we received the correct signature. """
print("Check signature")
header_signature = request.headers.get("X-Hub-Signature")
if not header_signature:
print("Header signature missing in request", file=sys.stderr)
abort(HTTPStatus.FORBIDDEN)
sha_name, signature = header_signature.split("=")
if sha_name != "sha1":
print(f"Signature has invalid digest type: {sha_name}", file=sys.stderr)
abort(HTTPStatus.NOT_IMPLEMENTED)
mac = hmac.new(secret.encode("UTF-8"), msg=request.data, digestmod="sha1")
if not hmac.compare_digest(str(mac.hexdigest()), str(signature)):
print("Invalid header signature in request", file=sys.stderr)
abort(HTTPStatus.FORBIDDEN)
print("Signature is valid")