Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(github): support validating webhook signature (#1995)

Joe Chencf2fa2609cfb
diff --git a/server/webhook.go b/server/webhook.go
index bef2a38c34..3455203d09 100644
--- a/server/webhook.go
+++ b/server/webhook.go
@@ -2,6 +2,10 @@ package server
import (
"context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/hex"
"encoding/json"
"fmt"
"io"
@@ -120,10 +124,6 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
})
g.POST("/github/:id", func(c echo.Context) error {
ctx := c.Request().Context()
- body, err := io.ReadAll(c.Request().Body)
- if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, "Failed to read webhook request").SetInternal(err)
- }
// This shouldn't happen as we only setup webhook to receive push event, just in case.
eventType := github.WebhookType(c.Request().Header.Get("X-GitHub-Event"))
@@ -131,11 +131,6 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid webhook event type, got %s, want %s", eventType, github.WebhookPush))
}
- var pushEvent github.WebhookPushEvent
- if err := json.Unmarshal(body, &pushEvent); err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, "Malformed push event").SetInternal(err)
- }
-
webhookEndpointID := c.Param("id")
repo, err := s.store.GetRepository(ctx, &api.RepositoryFind{WebhookEndpointID: &webhookEndpointID})
if err != nil {
@@ -150,8 +145,21 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, err).SetInternal(err)
}
- //nolint:misspell
- // TODO(unknwon): Validate webhook signature, https://linear.app/bbteam/issue/BYT-935
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Failed to read webhook request").SetInternal(err)
+ }
+
+ // Validate the request body first because there is no point in unmarshalling
+ // the request body if the signature doesn't match.
+ if !validateGitHubWebhookSignature256(c.Request().Header.Get("X-Hub-Signature-256"), repo.WebhookSecretToken, body) {
+ return echo.NewHTTPError(http.StatusBadRequest, "Mismatched payload signature")
+ }
+
+ var pushEvent github.WebhookPushEvent
+ if err := json.Unmarshal(body, &pushEvent); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformed push event").SetInternal(err)
+ }
if pushEvent.Repository.FullName != repo.ExternalID {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project mismatch, got %s, want %s", pushEvent.Repository.FullName, repo.ExternalID))
@@ -217,6 +225,20 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
})
}
+// validateGitHubWebhookSignature256 returns true if the signature matches the
+// HMAC hex digested SHA256 hash of the body using the given key.
+func validateGitHubWebhookSignature256(signature, key string, body []byte) bool {
+ signature = strings.TrimPrefix(signature, "sha256=")
+ m := hmac.New(sha256.New, []byte(key))
+ m.Write(body)
+ got := hex.EncodeToString(m.Sum(nil))
+
+ // NOTE: Use constant time string comparison helps mitigate certain timing
+ // attacks against regular equality operators, see
+ // https://docs.github.com/en/developers/webhooks-and-events/webhooks/securing-your-webhooks#validating-payloads-from-github
+ return subtle.ConstantTimeCompare([]byte(signature), []byte(got)) == 1
+}
+
// We are observing the push webhook event so that we will receive the event either when:
// 1. A commit is directly pushed to a branch.
// 2. One or more commits are merged to a branch.
diff --git a/server/webhook_test.go b/server/webhook_test.go
index 9d9d94cf77..89081f25b1 100644
--- a/server/webhook_test.go
+++ b/server/webhook_test.go
@@ -4,8 +4,9 @@ import (
"testing"
"time"
- "github.com/bytebase/bytebase/plugin/vcs/gitlab"
"github.com/stretchr/testify/assert"
+
+ "github.com/bytebase/bytebase/plugin/vcs/gitlab"
)
func TestDedupMigrationFiles(t *testing.T) {
@@ -284,3 +285,35 @@ func TestDedupMigrationFiles(t *testing.T) {
})
}
}
+
+func TestValidateGitHubWebhookSignature256(t *testing.T) {
+ //nolint:misspell
+ const payload = `{"ref":"refs/heads/main","before":"07da1e122bdbb81da8499b6d82c6b6302581a5a7","after":"5a96148ac5ef11a53b838b8cc0d9c929420657f3","repository":{"id":470746482,"node_id":"R_kgDOHA8Fcg","name":"bytebase-test","full_name":"unknwon/bytebase-test","private":true,"owner":{"name":"unknwon","email":"[email protected]","login":"unknwon","id":2946214,"node_id":"MDQ6VXNlcjI5NDYyMTQ=","avatar_url":"https://avatars.githubusercontent.com/u/2946214?v=4","gravatar_id":"","url":"https://api.github.com/users/unknwon","html_url":"https://github.com/unknwon","followers_url":"https://api.github.com/users/unknwon/followers","following_url":"https://api.github.com/users/unknwon/following{/other_user}","gists_url":"https://api.github.com/users/unknwon/gists{/gist_id}","starred_url":"https://api.github.com/users/unknwon/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/unknwon/subscriptions","organizations_url":"https://api.github.com/users/unknwon/orgs","repos_url":"https://api.github.com/users/unknwon/repos","events_url":"https://api.github.com/users/unknwon/events{/privacy}","received_events_url":"https://api.github.com/users/unknwon/received_events","type":"User","site_admin":false},"html_url":"https://github.com/unknwon/bytebase-test","description":null,"fork":false,"url":"https://github.com/unknwon/bytebase-test","forks_url":"https://api.github.com/repos/unknwon/bytebase-test/forks","keys_url":"https://api.github.com/repos/unknwon/bytebase-test/keys{/key_id}","collaborators_url":"https://api.github.com/repos/unknwon/bytebase-test/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/unknwon/bytebase-test/teams","hooks_url":"https://api.github.com/repos/unknwon/bytebase-test/hooks","issue_events_url":"https://api.github.com/repos/unknwon/bytebase-test/issues/events{/number}","events_url":"https://api.github.com/repos/unknwon/bytebase-test/events","assignees_url":"https://api.github.com/repos/unknwon/bytebase-test/assignees{/user}","branches_url":"https://api.github.com/repos/unknwon/bytebase-test/branches{/branch}","tags_url":"https://api.github.com/repos/unknwon/bytebase-test/tags","blobs_url":"https://api.github.com/repos/unknwon/bytebase-test/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/unknwon/bytebase-test/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/unknwon/bytebase-test/git/refs{/sha}","trees_url":"https://api.github.com/repos/unknwon/bytebase-test/git/trees{/sha}","statuses_url":"https://api.github.com/repos/unknwon/bytebase-test/statuses/{sha}","languages_url":"https://api.github.com/repos/unknwon/bytebase-test/languages","stargazers_url":"https://api.github.com/repos/unknwon/bytebase-test/stargazers","contributors_url":"https://api.github.com/repos/unknwon/bytebase-test/contributors","subscribers_url":"https://api.github.com/repos/unknwon/bytebase-test/subscribers","subscription_url":"https://api.github.com/repos/unknwon/bytebase-test/subscription","commits_url":"https://api.github.com/repos/unknwon/bytebase-test/commits{/sha}","git_commits_url":"https://api.github.com/repos/unknwon/bytebase-test/git/commits{/sha}","comments_url":"https://api.github.com/repos/unknwon/bytebase-test/comments{/number}","issue_comment_url":"https://api.github.com/repos/unknwon/bytebase-test/issues/comments{/number}","contents_url":"https://api.github.com/repos/unknwon/bytebase-test/contents/{+path}","compare_url":"https://api.github.com/repos/unknwon/bytebase-test/compare/{base}...{head}","merges_url":"https://api.github.com/repos/unknwon/bytebase-test/merges","archive_url":"https://api.github.com/repos/unknwon/bytebase-test/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/unknwon/bytebase-test/downloads","issues_url":"https://api.github.com/repos/unknwon/bytebase-test/issues{/number}","pulls_url":"https://api.github.com/repos/unknwon/bytebase-test/pulls{/number}","milestones_url":"https://api.github.com/repos/unknwon/bytebase-test/milestones{/number}","notifications_url":"https://api.github.com/repos/unknwon/bytebase-test/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/unknwon/bytebase-test/labels{/name}","releases_url":"https://api.github.com/repos/unknwon/bytebase-test/releases{/id}","deployments_url":"https://api.github.com/repos/unknwon/bytebase-test/deployments","created_at":1647463607,"updated_at":"2022-03-16T20:46:47Z","pushed_at":1658671596,"git_url":"git://github.com/unknwon/bytebase-test.git","ssh_url":"[email protected]:unknwon/bytebase-test.git","clone_url":"https://github.com/unknwon/bytebase-test.git","svn_url":"https://github.com/unknwon/bytebase-test","homepage":null,"size":20,"stargazers_count":0,"watchers_count":0,"language":null,"has_issues":true,"has_projects":true,"has_downloads":true,"has_wiki":true,"has_pages":false,"forks_count":0,"mirror_url":null,"archived":false,"disabled":false,"open_issues_count":0,"license":{"key":"apache-2.0","name":"Apache License 2.0","spdx_id":"Apache-2.0","url":"https://api.github.com/licenses/apache-2.0","node_id":"MDc6TGljZW5zZTI="},"allow_forking":true,"is_template":false,"web_commit_signoff_required":false,"topics":[],"visibility":"private","forks":0,"open_issues":0,"watchers":0,"default_branch":"main","stargazers":0,"master_branch":"main"},"pusher":{"name":"unknwon","email":"[email protected]"},"sender":{"login":"unknwon","id":2946214,"node_id":"MDQ6VXNlcjI5NDYyMTQ=","avatar_url":"https://avatars.githubusercontent.com/u/2946214?v=4","gravatar_id":"","url":"https://api.github.com/users/unknwon","html_url":"https://github.com/unknwon","followers_url":"https://api.github.com/users/unknwon/followers","following_url":"https://api.github.com/users/unknwon/following{/other_user}","gists_url":"https://api.github.com/users/unknwon/gists{/gist_id}","starred_url":"https://api.github.com/users/unknwon/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/unknwon/subscriptions","organizations_url":"https://api.github.com/users/unknwon/orgs","repos_url":"https://api.github.com/users/unknwon/repos","events_url":"https://api.github.com/users/unknwon/events{/privacy}","received_events_url":"https://api.github.com/users/unknwon/received_events","type":"User","site_admin":false},"created":false,"deleted":false,"forced":false,"base_ref":null,"compare":"https://github.com/unknwon/bytebase-test/compare/07da1e122bdb...5a96148ac5ef","commits":[{"id":"5a96148ac5ef11a53b838b8cc0d9c929420657f3","tree_id":"8a842b23b62886d2ee12c152eda741cf39b1ceef","distinct":true,"message":"Create testdb_dev__202101131000__baseline__create_tablefoo_for_bar.sql","timestamp":"2022-07-24T22:06:36+08:00","url":"https://github.com/unknwon/bytebase-test/commit/5a96148ac5ef11a53b838b8cc0d9c929420657f3","author":{"name":"Joe Chen","email":"[email protected]","username":"unknwon"},"committer":{"name":"GitHub","email":"[email protected]","username":"web-flow"},"added":["Dev/testdb_dev__202101131000__baseline__create_tablefoo_for_bar.sql"],"removed":[],"modified":[]}],"head_commit":{"id":"5a96148ac5ef11a53b838b8cc0d9c929420657f3","tree_id":"8a842b23b62886d2ee12c152eda741cf39b1ceef","distinct":true,"message":"Create testdb_dev__202101131000__baseline__create_tablefoo_for_bar.sql","timestamp":"2022-07-24T22:06:36+08:00","url":"https://github.com/unknwon/bytebase-test/commit/5a96148ac5ef11a53b838b8cc0d9c929420657f3","author":{"name":"Joe Chen","email":"[email protected]","username":"unknwon"},"committer":{"name":"GitHub","email":"[email protected]","username":"web-flow"},"added":["Dev/testdb_dev__202101131000__baseline__create_tablefoo_for_bar.sql"],"removed":[],"modified":[]}}`
+
+ t.Run("wrong key", func(t *testing.T) {
+ got := validateGitHubWebhookSignature256(
+ "sha256=6bf313c917fd04a3c6c85270bab6c2a6ae40b7ab37767107bf80ad5c6a0a0deb",
+ "abadkey",
+ []byte(payload),
+ )
+ assert.False(t, got)
+ })
+
+ t.Run("wrong signature", func(t *testing.T) {
+ got := validateGitHubWebhookSignature256(
+ "sha256=8335bc69262e94b20753316d844e155ae4d7826a6c89f12e98083ed0dce8d057",
+ "bZovosSKsJ8QKCG9",
+ []byte(payload),
+ )
+ assert.False(t, got)
+ })
+
+ t.Run("success", func(t *testing.T) {
+ got := validateGitHubWebhookSignature256(
+ "sha256=6bf313c917fd04a3c6c85270bab6c2a6ae40b7ab37767107bf80ad5c6a0a0deb",
+ "bZovosSKsJ8QKCG9",
+ []byte(payload),
+ )
+ assert.True(t, got)
+ })
+}