Visitar URL original
Update securing-your-webhooks.md by beliaev-maksim · Pull Request #24635 · github/docs · GitHub
The Wayback Machine - https://web.archive.org/web/20260603154819/https://github.com/github/docs/pull/24635
Skip to content

Update securing-your-webhooks.md#24635

Merged
cmwilson21 merged 6 commits into
github:mainfrom
beliaev-maksim:patch-1
Apr 3, 2023
Merged

Update securing-your-webhooks.md#24635
cmwilson21 merged 6 commits into
github:mainfrom
beliaev-maksim:patch-1

Conversation

@beliaev-maksim
Copy link
Copy Markdown
Contributor

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:

  • I have reviewed my changes in staging (look for the "Automatically generated comment" and click the links in the "Preview" column to view your latest changes).
  • For content changes, I have completed the self-review checklist.

@welcome
Copy link
Copy Markdown

welcome Bot commented Mar 23, 2023

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.

@github-actions github-actions Bot added the triage Do not begin working on this issue until triaged by the team label Mar 23, 2023
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Mar 23, 2023 •

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 that have been changed in this pull request. It's provided to make it easy to review your changes on the staging site. Please note that changes to the data directory will not show up in this table.


Content directory changes

You 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.

Source Preview Production What Changed
webhooks-and-events/webhooks/securing-your-webhooks.md fpt
ghec
ghes@ 3.8 3.7 3.6 3.5 3.4
ghae
fpt
ghec
ghes@ 3.8 3.7 3.6 3.5 3.4
ghae

fpt: Free, Pro, Team
ghec: GitHub Enterprise Cloud
ghes: GitHub Enterprise Server
ghae: GitHub AE

@cmwilson21
Copy link
Copy Markdown
Contributor

@beliaev-maksim Thanks so much for opening a PR! I'll get this triaged for review ⚡

@cmwilson21 cmwilson21 added content This issue or pull request belongs to the Docs Content team waiting for review Issue/PR is waiting for a writer's review webhooks Content related to webhooks and removed triage Do not begin working on this issue until triaged by the team labels Mar 27, 2023
Copy link
Copy Markdown
Contributor

@skedwards88 skedwards88 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@beliaev-maksim
Copy link
Copy Markdown
Contributor Author

Hello @skedwards88,
thanks for the review!

I think I have edits enabled (default?)
image

but I pushed the update that you requested

Copy link
Copy Markdown
Contributor

@skedwards88 skedwards88 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for making these changes! We'll get this merged down for you.

@skedwards88 skedwards88 added the ready to merge This pull request is ready to merge label Apr 3, 2023
@cmwilson21 cmwilson21 added this pull request to the merge queue Apr 3, 2023
Merged via the queue into github:main with commit 3aa60a1 Apr 3, 2023
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Apr 3, 2023

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 ⚡

@beliaev-maksim beliaev-maksim deleted the patch-1 branch April 3, 2023 19:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

content This issue or pull request belongs to the Docs Content team ready to merge This pull request is ready to merge waiting for review Issue/PR is waiting for a writer's review webhooks Content related to webhooks

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants