Update securing-your-webhooks.md#24635
Conversation
add python example
|
Thanks for opening this pull request! A GitHub docs team member should be by to give feedback soon. In the meantime, please check out the contributing guidelines. |
Automatically generated comment ℹ️This comment is automatically generated and will be overwritten every time changes are committed to this branch. The table contains an overview of files in the Content directory changesYou may find it useful to copy this table into the pull request summary. There you can edit it to share links to important articles or changes and to give a high-level overview of how the changes in your pull request support the overall goals of the pull request.
fpt: Free, Pro, Team |
|
@beliaev-maksim Thanks so much for opening a PR! I'll get this triaged for review ⚡ |
skedwards88
left a comment
There was a problem hiding this comment.
Thanks for adding this example! I'd like to to reorganize the content a bit so that we can display the examples side-by-side, which will help readers focus on the example that is relevant to them + make space for examples in other languages. However, I don't have permission to push to your branch. Can you either:
Replace everything following the Validating payloads from GitHub header with this content:
Click to expand
## Validating payloads from GitHub
When your secret token is set, {% data variables.product.product_name %} uses it to create a hash signature with each payload. This hash signature is included with the headers of each request as `x-hub-signature-256`.
{% ifversion fpt or ghes or ghec %}
{% note %}
**Note:** For backward-compatibility, we also include the `x-hub-signature` header that is generated using the SHA-1 hash function. If possible, we recommend that you use the `x-hub-signature-256` header for improved security. The examples below demonstrate using the `x-hub-signature-256` header.
{% endnote %}
{% endif %}
You should calculate a hash using your `SECRET_TOKEN`, and ensure that the result matches the hash from {% data variables.product.product_name %}. {% data variables.product.product_name %} uses an HMAC hex digest to compute the hash.
{% note %}
**Note:** Webhook payloads can contain unicode characters. If your language and server implementation specifies a character encoding, ensure that you handle the payload as UTF-8.
{% endnote %}
Your language and server implementations may differ from the following examples. However, there are a number of very important things to point out:
* No matter which implementation you use, the hash signature starts with `sha256=`, using the key of your secret token and your payload body.
* Using a plain `==` operator is **not advised**. A method like [`secure_compare`][secure_compare] performs a "constant time" string comparison, which helps mitigate certain timing attacks against regular equality operators.
### Ruby example
For example, you can define the following `verify_signature` function:
``` ruby
def verify_signature(payload_body)
signature = 'sha256=' + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), ENV['SECRET_TOKEN'], payload_body)
return halt 500, "Signatures didn't match!" unless Rack::Utils.secure_compare(signature, request.env['HTTP_X_HUB_SIGNATURE_256'])
end
```
Then you can call it when you receive a webhook payload:
``` ruby
post '/payload' do
request.body.rewind
payload_body = request.body.read
verify_signature(payload_body)
push = JSON.parse(payload_body)
"I got some JSON: #{push.inspect}"
end
```
### Python example
For example, you can define the following `verify_signature` function and call it when you receive a webhook payload:
```python
import hashlib
import hmac
def verify_signature(payload_body, secret_token, signature_header):
"""Verify that the payload was sent from GitHub by validating SHA256.
Raise and return 403 if not authorized.
Args:
payload_body: original request body to verify (request.body())
secret_token: GitHub app webhook token (WEBHOOK_SECRET)
signature_header: header received from GitHub (x-hub-signature-256)
"""
if not signature_header:
raise HTTPException(status_code=403, detail="x-hub-signature-256 header is missing!")
hash_object = hmac.new(secret_token.encode('utf-8'), msg=payload_body, digestmod=hashlib.sha256)
expected_signature = "sha256=" + hash_object.hexdigest()
if not hmac.compare_digest(expected_signature, signature_header):
raise HTTPException(status_code=403, detail="Request signatures didn't match!")
```
[secure_compare]: https://rubydoc.info/github/rack/rack/main/Rack/Utils:secure_compare
Or, enable the checkbox to allow maintainer edits? Then I'll be able to (I think) push this change. https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/allowing-changes-to-a-pull-request-branch-created-from-a-fork
|
Hello @skedwards88, I think I have edits enabled (default?) but I pushed the update that you requested |
skedwards88
left a comment
There was a problem hiding this comment.
Thanks for making these changes! We'll get this merged down for you.
|
Thanks very much for contributing! Your pull request has been merged 🎉 You should see your changes appear on the site in approximately 24 hours. If you're looking for your next contribution, check out our help wanted issues ⚡ |



What's being changed (if available, include any code snippets, screenshots, or gifs):
Added example of webhook signature validation in Python language
Why:
Python is one of the most popular languages, it might be helpful to have example in another language to remove barriers to make apps more secure ;)
Check off the following: