This repository has been archived by the owner on Nov 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple-webserver.py
53 lines (40 loc) · 1.55 KB
/
simple-webserver.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
import argparse
import hashlib
import hmac
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import pprint
import os
import sys
from subprocess import call
HOOK_SECRET_KEY = os.environb[b'HOOK_SECRET_KEY']
class GithubHookHandler(BaseHTTPRequestHandler):
"""Base class for webhook handlers.
Subclass it and implement 'handle_payload'.
"""
def _validate_signature(self, data):
sha_name, signature = self.headers['X-Hub-Signature'].split('=')
if sha_name != 'sha1':
return False
# HMAC requires its key to be bytes, but data is strings.
mac = hmac.new(HOOK_SECRET_KEY, msg=data, digestmod=hashlib.sha1)
return hmac.compare_digest(mac.hexdigest(), signature)
def do_POST(self):
data_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(data_length)
if not self._validate_signature(post_data):
self.send_response(401)
return
payload = json.loads(post_data.decode('utf-8'))
self.handle_payload(payload)
self.send_response(200)
class MyHandler(GithubHookHandler):
def handle_payload(self, json_payload):
"""Simple handler that pretty-prints the payload."""
call(["/build/build.sh"])
if __name__ == '__main__':
argparser = argparse.ArgumentParser(description='Github hook handler')
argparser.add_argument('port', type=int, help='TCP port to listen on')
args = argparser.parse_args()
server = HTTPServer(('', args.port), MyHandler)
server.serve_forever()