Skip to content

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

chore: github webhook (#11415)

Danny Xu582a3fd1328a
diff --git a/backend/api/gitops/github.go b/backend/api/gitops/github.go
new file mode 100644
index 0000000000..a9428019b9
--- /dev/null
+++ b/backend/api/gitops/github.go
@@ -0,0 +1,75 @@
+package gitops
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "path/filepath"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/plugin/vcs"
+ "github.com/bytebase/bytebase/backend/plugin/vcs/github"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+const (
+ closeAction = "closed"
+)
+
+func getGitHubPullRequestInfo(ctx context.Context, vcsProvider *store.VCSProviderMessage, vcsConnector *store.VCSConnectorMessage, body []byte) (*pullRequestInfo, error) {
+ var pushEvent github.PullRequestPushEvent
+ if err := json.Unmarshal(body, &pushEvent); err != nil {
+ return nil, errors.Errorf("failed to unmarshal push event, error %v", err)
+ }
+ fmt.Printf("Barny1: %+v\n", pushEvent)
+ if pushEvent.Action != closeAction {
+ return nil, errors.Errorf("invalid webhook event action, got %s, want closed", pushEvent.Action)
+ }
+
+ if pushEvent.PullRequest.Base.Ref != vcsConnector.Payload.Branch {
+ return nil, errors.Errorf("committed to branch %q, want branch %q", pushEvent.PullRequest.Base.Ref, vcsConnector.Payload.Branch)
+ }
+ oauthContext := &common.OauthContext{
+ AccessToken: vcsProvider.AccessToken,
+ }
+
+ mrFiles, err := vcs.Get(vcs.GitHub, vcs.ProviderConfig{}).ListPullRequestFile(ctx, oauthContext, vcsProvider.InstanceURL, vcsConnector.Payload.ExternalId, fmt.Sprintf("%d", pushEvent.Number))
+ if err != nil {
+ return nil, errors.Errorf("failed to list merge %q request files, error %v", pushEvent.PullRequest.URL, err)
+ }
+
+ prInfo := &pullRequestInfo{
+ // email. How do we determine the user for GitHub user?
+ url: pushEvent.PullRequest.URL,
+ title: pushEvent.PullRequest.Title,
+ description: pushEvent.PullRequest.Body,
+ }
+ for _, v := range mrFiles {
+ if v.IsDeleted {
+ continue
+ }
+ if filepath.Dir(v.Path) != vcsConnector.Payload.BaseDirectory {
+ continue
+ }
+ change, err := getFileChange(v.Path)
+ if err != nil {
+ slog.Error("failed to get file change info", slog.String("path", v.Path), log.BBError(err))
+ }
+ if change != nil {
+ change.path = v.Path
+ prInfo.changes = append(prInfo.changes, change)
+ }
+ }
+ for _, file := range prInfo.changes {
+ content, err := vcs.Get(vcs.GitHub, vcs.ProviderConfig{}).ReadFileContent(ctx, oauthContext, vcsProvider.InstanceURL, vcsConnector.Payload.ExternalId, file.path, vcs.RefInfo{RefType: vcs.RefTypeCommit, RefName: pushEvent.PullRequest.Head.SHA})
+ if err != nil {
+ return nil, errors.Errorf("failed read file content, merge request %q, file %q, error %v", pushEvent.PullRequest.URL, file.path, err)
+ }
+ file.content = content
+ }
+ return prInfo, nil
+}
diff --git a/backend/api/gitops/gitlab.go b/backend/api/gitops/gitlab.go
index 9eb29f7735..13b4a8079b 100644
--- a/backend/api/gitops/gitlab.go
+++ b/backend/api/gitops/gitlab.go
@@ -21,7 +21,7 @@ const (
mergeAction = "merge"
)
-func getMergeRequestChangeFileContent(ctx context.Context, vcsProvider *store.VCSProviderMessage, vcsConnector *store.VCSConnectorMessage, body []byte) (*pullRequestInfo, error) {
+func getGitLabPullRequestInfo(ctx context.Context, vcsProvider *store.VCSProviderMessage, vcsConnector *store.VCSConnectorMessage, body []byte) (*pullRequestInfo, error) {
var pushEvent gitlab.MergeRequestPushEvent
if err := json.Unmarshal(body, &pushEvent); err != nil {
return nil, errors.Errorf("failed to unmarshal push event, error %v", err)
diff --git a/backend/api/gitops/webhook.go b/backend/api/gitops/webhook.go
index eae9c2b4d4..e0488fd679 100644
--- a/backend/api/gitops/webhook.go
+++ b/backend/api/gitops/webhook.go
@@ -72,7 +72,7 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {
return c.String(http.StatusOK, fmt.Sprintf("failed to read body, error %v", err))
}
- // Validate webhook secret.
+ var prInfo *pullRequestInfo
switch vcsProvider.Type {
case vcs.GitHub:
secretToken := c.Request().Header.Get("X-Hub-Signature-256")
@@ -83,23 +83,38 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {
if !ok {
return c.String(http.StatusOK, fmt.Sprintf("invalid webhook secret token %q", secretToken))
}
+ eventType := c.Request().Header.Get("X-GitHub-Event")
+ // https://docs.github.com/en/developers/webhooks-and-events/webhooks/about-webhooks#ping-event
+ // When we create a new webhook, GitHub will send us a simple ping event to let us know we've set up the webhook correctly.
+ // We respond to this event so as not to mislead users.
+ switch eventType {
+ case "ping":
+ return c.String(http.StatusOK, "OK")
+ case "pull_request":
+ default:
+ return c.String(http.StatusOK, "OK")
+ }
+
+ prInfo, err = getGitHubPullRequestInfo(ctx, vcsProvider, vcsConnector, body)
+ if err != nil {
+ return c.String(http.StatusOK, fmt.Sprintf("failed to get pr info from pull request, error %v", err))
+ }
case vcs.GitLab:
secretToken := c.Request().Header.Get("X-Gitlab-Token")
if secretToken != vcsConnector.Payload.WebhookSecretToken {
return c.String(http.StatusOK, fmt.Sprintf("invalid webhook secret token %q", secretToken))
}
- }
- if vcsProvider.Type == vcs.GitLab {
- prInfo, err := getMergeRequestChangeFileContent(ctx, vcsProvider, vcsConnector, body)
+ prInfo, err = getGitLabPullRequestInfo(ctx, vcsProvider, vcsConnector, body)
if err != nil {
return c.String(http.StatusOK, fmt.Sprintf("failed to get pr info from pull request, error %v", err))
}
- if err := s.createIssueFromPRInfo(ctx, project, prInfo); err != nil {
- return c.String(http.StatusOK, fmt.Sprintf("failed to create issue from pull request %s, error %v", prInfo.url, err))
- }
+ default:
return nil
}
+ if err := s.createIssueFromPRInfo(ctx, project, prInfo); err != nil {
+ return c.String(http.StatusOK, fmt.Sprintf("failed to create issue from pull request %s, error %v", prInfo.url, err))
+ }
return nil
})
}
diff --git a/backend/plugin/vcs/github/webhook_events.go b/backend/plugin/vcs/github/webhook_events.go
new file mode 100644
index 0000000000..0098e20522
--- /dev/null
+++ b/backend/plugin/vcs/github/webhook_events.go
@@ -0,0 +1,24 @@
+package github
+
+// PullRequestPushEvent is the json message for pull request push event.
+type PullRequestPushEvent struct {
+ // opened, edited, closed.
+ Action string `json:"action"`
+ Number int `json:"number"`
+
+ PullRequest EventPullRequest `json:"pull_request"`
+}
+
+type EventPullRequest struct {
+ URL string `json:"url"`
+ Title string `json:"title"`
+ Body string `json:"body"`
+ Base EventBranch `json:"base"`
+ Head EventBranch `json:"head"`
+}
+
+type EventBranch struct {
+ // The branch name, e.g. main.
+ Ref string `json:"ref"`
+ SHA string `json:"sha"`
+}