|
| 1 | +from flask import Blueprint, request, Response, abort, Request |
| 2 | +from hashlib import sha256 |
| 3 | +from hmac import new as hmacNew |
| 4 | +from subprocess import run |
| 5 | +from unittest import TestSuite, TestResult |
| 6 | + |
| 7 | +def verifyGithubSignature(request: Request, token:str) -> bool: |
| 8 | + """Verify the GitHub signature of a webhook request""" |
| 9 | + signature = request.headers.get("X-Hub-Signature-256") |
| 10 | + if signature is None: |
| 11 | + return False |
| 12 | + hash_object = hmacNew(token.encode("utf-8"), msg=request.get_data(), digestmod=sha256) |
| 13 | + expected_signature = "sha256=" + hash_object.hexdigest() |
| 14 | + return signature == expected_signature |
| 15 | + |
| 16 | +class webhookBlueprint(Blueprint): |
| 17 | + """Wrapper over the flask blueprint that creates an endpoint for receiving and processing git webhooks. Overwrite the processWebhook method to process the webhook data.""" |
| 18 | + def __init__(self, webhookToken:str, tests:TestSuite=None, name:str="webhook", import_name:str=__name__, *args, **kwargs): |
| 19 | + super().__init__(name, import_name, *args, **kwargs) |
| 20 | + self.webhookToken = webhookToken |
| 21 | + self.tests = tests |
| 22 | + self.route("/", methods=["POST"])(self.receiveWebhook) |
| 23 | + def receiveWebhook(self) -> Response: |
| 24 | + """Receive webhook from GitHub and process it using the processWebhook method.""" |
| 25 | + if "X-Hub-Signature-256" in request.headers: |
| 26 | + if not verifyGithubSignature(request, self.webhookToken): |
| 27 | + abort(401) |
| 28 | + elif "X-Gitlab-Token": |
| 29 | + if request.headers.get("X-Gitlab-Token") != self.token: |
| 30 | + abort(401) |
| 31 | + else: |
| 32 | + abort(400, "Unsupported webhook source") |
| 33 | + #at this point the webhook is verified |
| 34 | + return self.processWebhook(request.json) |
| 35 | + def processWebhook(self, data:dict) -> tuple[int, str]: |
| 36 | + """Process the webhook. Return a tuple of (status code, message)""" |
| 37 | + process = run(["/usr/bin/git", "pull"], env=dict(GIT_SSH_COMMAND="/usr/bin/ssh")) |
| 38 | + if process.returncode != 0: |
| 39 | + return 500, process.stderr.decode("utf-8") |
| 40 | + if self.tests is not None: |
| 41 | + result:TestResult = self.tests.run() |
| 42 | + if result.wasSuccessful(): |
| 43 | + return 200, "Tests passed" |
| 44 | + else: |
| 45 | + abortProcess = run(["/usr/bin/git", "merge", "--abort"], env=dict(GIT_SSH_COMMAND="/usr/bin/ssh")) |
| 46 | + return 428, f"Tests did not pass, Errors: {result.errors}, Failures: {result.failures}. Merge abort status: {abortProcess.returncode}" |
| 47 | + else: |
| 48 | + return 200, "Webhook received successfully" |
| 49 | + |
| 50 | +if __name__ == "__main__": |
| 51 | + from flask import Flask |
| 52 | + app = Flask(__name__) |
| 53 | + app.register_blueprint(webhookBlueprint("token")) |
| 54 | + app.run() |
0 commit comments