Skip to content

Commit

Permalink
gh webhook signature unit test (#82)
Browse files Browse the repository at this point in the history
  • Loading branch information
wojpo authored May 27, 2024
1 parent 7fa6e71 commit eafe625
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
8 changes: 6 additions & 2 deletions core/gh_webhook_handling.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,13 @@ def handle_issue(payload, action):
return action


def verify_secret(secret, payload, signature_header):
def generate_signature(secret, payload):
hash_object = hmac.new(
secret.encode("utf-8"), msg=payload, digestmod=hashlib.sha256
)
expected_signature = f"sha256={hash_object.hexdigest()}"
return f"sha256={hash_object.hexdigest()}"


def verify_secret(secret, payload, signature_header):
expected_signature = generate_signature(secret, payload)
return hmac.compare_digest(expected_signature, signature_header)
27 changes: 26 additions & 1 deletion core/tests.py
Original file line number Diff line number Diff line change
@@ -1 +1,26 @@
# Create your tests here.
import json
from django.test import TestCase

from core.gh_webhook_handling import verify_secret, generate_signature


class GHWebhookTestCase(TestCase):
def setUp(self):
self.secret = "UwU"
self.payload = {
"sender": {"login": "test_user"},
"action": "opened",
"pull_request": {"merged": False},
"issue": {"state_reason": "completed"},
}
self.payload_bytes = json.dumps(self.payload).encode("utf-8")
self.signature = generate_signature(self.secret, self.payload_bytes)

def test_valid_signature(self):
self.assertTrue(verify_secret(self.secret, self.payload_bytes, self.signature))

def test_invalid_signature(self):
wrong_signature = "silly:3"
self.assertFalse(
verify_secret(self.secret, self.payload_bytes, wrong_signature)
)

0 comments on commit eafe625

Please sign in to comment.