forked from carlos-jenkins/python-github-webhooks
-
Notifications
You must be signed in to change notification settings - Fork 1
/
webhooks.py
150 lines (122 loc) · 3.99 KB
/
webhooks.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
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Carlos Jenkins <carlos@jenkins.co.cr>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
from sys import stderr
logging.basicConfig(stream=stderr)
import hmac
from hashlib import sha1
from json import loads, dumps
from subprocess import Popen, PIPE
from tempfile import mkstemp
from os import access, X_OK, remove
from os.path import isfile, abspath, normpath, dirname, join, basename
import requests
from ipaddress import ip_address, ip_network
from flask import Flask, request, abort
application = Flask(__name__)
@application.route('/', methods=['GET', 'POST'])
def index():
"""
Main WSGI application entry.
"""
path = normpath(abspath(dirname(__file__)))
hooks = join(path, 'hooks')
# Only POST is implemented
if request.method != 'POST':
abort(501)
# Load config
with open(join(path, 'config.json'), 'r') as cfg:
config = loads(cfg.read())
# Allow Github IPs only
if config.get('github_ips_only', True):
src_ip = ip_address(
u'{}'.format(request.remote_addr) # Fix stupid ipaddress issue
)
whitelist = requests.get('https://api.github.com/meta').json()['hooks']
for valid_ip in whitelist:
if src_ip in ip_network(valid_ip):
break
else:
abort(403)
# Enforce secret
secret = config.get('enforce_secret', '')
if secret:
# Only SHA1 is supported
sha_name, signature = request.headers.get('X-Hub-Signature').split('=')
if sha_name != 'sha1':
abort(501)
# HMAC requires the key to be bytes, but data is string
mac = hmac.new(str(secret), msg=request.data, digestmod=sha1)
if not hmac.compare_digest(str(mac.hexdigest()), str(signature)):
abort(403)
# Implement ping
event = request.headers.get('X-GitHub-Event', 'ping')
if event == 'ping':
return dumps({'msg': 'pong'})
# Gather data
try:
payload = loads(request.data)
meta = {
'name': payload['repository']['name'],
'branch': payload['ref'].split('/')[2],
'event': event
}
except:
abort(400)
# Possible hooks
scripts = [
join(hooks, '{event}-{name}-{branch}'.format(**meta)),
join(hooks, '{event}-{name}'.format(**meta)),
join(hooks, '{event}'.format(**meta)),
join(hooks, 'all')
]
# Check permissions
scripts = [s for s in scripts if isfile(s) and access(s, X_OK)]
if not scripts:
return ''
# Save payload to temporal file
_, tmpfile = mkstemp()
with open(tmpfile, 'w') as pf:
pf.write(dumps(payload))
# Run scripts
ran = {}
for s in scripts:
proc = Popen(
[s, tmpfile, event],
stdout=PIPE, stderr=PIPE
)
stdout, stderr = proc.communicate()
ran[basename(s)] = {
'returncode': proc.returncode,
'stdout': stdout,
'stderr': stderr,
}
# Log errors if a hook failed
if proc.returncode != 0:
logging.error('{} : {} \n{}'.format(
s, proc.returncode, stderr
))
# Remove temporal file
remove(tmpfile)
info = config.get('return_scripts_info', False)
if not info:
return ''
output = dumps(ran, sort_keys=True, indent=4)
logging.info(output)
return output
if __name__ == '__main__':
application.run(debug=True, host='0.0.0.0')