Skip to content

Commit 99378ec

Browse files
committed
Better secret initialization
1 parent a510e60 commit 99378ec

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

github_webhook/webhook.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,23 @@ class Webhook(object):
1818

1919
def __init__(self, app=None, endpoint="/postreceive", secret=None):
2020
self.app = app
21+
self.set_secret(secret)
2122
if app is not None:
2223
self.init_app(app, endpoint, secret)
2324

2425
def init_app(self, app, endpoint="/postreceive", secret=None):
2526
self._hooks = collections.defaultdict(list)
2627
self._logger = logging.getLogger("webhook")
28+
if secret is not None:
29+
# Do not override the secret if already has been set it the
30+
# constructor
31+
self.set_secret(secret)
32+
app.add_url_rule(rule=endpoint, endpoint=endpoint, view_func=self._postreceive, methods=["POST"])
33+
34+
def set_secret(self, secret=None):
2735
if secret is not None and not isinstance(secret, six.binary_type):
2836
secret = secret.encode("utf-8")
2937
self._secret = secret
30-
app.add_url_rule(rule=endpoint, endpoint=endpoint, view_func=self._postreceive, methods=["POST"])
3138

3239
def hook(self, event_type="push"):
3340
"""

tests/test_webhook.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,30 @@ def test_init_app_flow():
7979
)
8080

8181

82+
def test_init_app_flow_should_not_accidentally_override_secrets():
83+
# GIVEN
84+
app = mock.Mock()
85+
86+
# WHEN
87+
webhook = Webhook(secret="hello-world-of-secrecy")
88+
webhook.init_app(app)
89+
90+
# THEN
91+
assert webhook._secret is not None
92+
93+
94+
def test_init_app_flow_should_override_secrets():
95+
# GIVEN
96+
app = mock.Mock()
97+
98+
# WHEN
99+
webhook = Webhook(secret="hello-world-of-secrecy")
100+
webhook.init_app(app, secret="a-new-world-of-secrecy")
101+
102+
# THEN
103+
assert webhook._secret == "a-new-world-of-secrecy".encode("utf-8")
104+
105+
82106
def test_run_push_hook(webhook, handler, push_request):
83107
# WHEN
84108
webhook._postreceive()

0 commit comments

Comments
 (0)