Skip to content

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

fix: should parse branch name from GitHub webhook (#2323)

h3n4l3e2a48b20fef
diff --git a/server/webhook.go b/server/webhook.go
index 397554411e..8c30f59972 100644
--- a/server/webhook.go
+++ b/server/webhook.go
@@ -166,6 +166,12 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformed push event").SetInternal(err)
}
+ if branch, err := parseBranchNameFromGitHubRefs(pushEvent.Ref); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Invalid ref").SetInternal(err)
+ } else if branch != repo.BranchFilter {
+ return c.String(http.StatusOK, "")
+ }
+
if pushEvent.Repository.FullName != repo.ExternalID {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project mismatch, got %s, want %s", pushEvent.Repository.FullName, repo.ExternalID))
}
@@ -246,6 +252,18 @@ func validateGitHubWebhookSignature256(signature, key string, body []byte) (bool
return subtle.ConstantTimeCompare([]byte(signature), []byte(got)) == 1, nil
}
+// parseBranchNameFromGitHubRefs is for GitHub.
+// GitLab webhook has the option to listen to push events to a certain branch while GitHub doesn't. So we need to manually parse the branch name from the refs field in the request.
+// https://docs.github.com/en/rest/git/refs
+func parseBranchNameFromGitHubRefs(ref string) (string, error) {
+ expectedPrefix := "refs/heads/"
+ if !strings.HasPrefix(ref, expectedPrefix) || len(expectedPrefix) == len(ref) {
+ log.Debug("ref is not prefix with expected prefix", zap.String("escaped ref", common.EscapeForLogging(ref)), zap.String("expected prefix", expectedPrefix))
+ return ref, errors.Errorf("unexpected ref name %q without prefix %q", ref, expectedPrefix)
+ }
+ return ref[len(expectedPrefix):], nil
+}
+
// 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 95a4394334..589b07aaba 100644
--- a/server/webhook_test.go
+++ b/server/webhook_test.go
@@ -320,3 +320,40 @@ func TestValidateGitHubWebhookSignature256(t *testing.T) {
assert.NoError(t, err)
})
}
+
+func TestParseBranchNameFromGitHubRefs(t *testing.T) {
+ tests := []struct {
+ refs string
+ expect string
+ err bool
+ }{
+ {
+ refs: "refs/heads/main",
+ expect: "main",
+ err: false,
+ },
+ {
+ refs: "refs/heads/feat/heads",
+ expect: "feat/heads",
+ err: false,
+ },
+ // Broken
+ {
+ refs: "ref",
+ err: true,
+ },
+ {
+ refs: "refs/heads/",
+ expect: "",
+ err: true,
+ },
+ }
+ for _, test := range tests {
+ branch, err := parseBranchNameFromGitHubRefs(test.refs)
+ if test.err {
+ assert.Error(t, err)
+ } else {
+ assert.Equal(t, test.expect, branch)
+ }
+ }
+}