Skip to content

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

chore: renovate gitlab webhook (#11411)

Danny Xu06be75186ffa
diff --git a/backend/api/gitops/common.go b/backend/api/gitops/common.go
new file mode 100644
index 0000000000..b6047b54bc
--- /dev/null
+++ b/backend/api/gitops/common.go
@@ -0,0 +1,64 @@
+package gitops
+
+import (
+ "path/filepath"
+ "regexp"
+ "strings"
+
+ v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
+)
+
+var (
+ versionRE = regexp.MustCompile(`^[0-9]+`)
+)
+
+type pullRequestInfo struct {
+ email string
+ title string
+ description string
+ url string
+ changes []*fileChange
+}
+
+type fileChange struct {
+ path string
+ version string
+ changeType v1pb.Plan_ChangeDatabaseConfig_Type
+ description string
+ content string
+}
+
+func getFileChange(path string) (*fileChange, error) {
+ filename := filepath.Base(path)
+ if filepath.Ext(filename) != ".sql" {
+ return nil, nil
+ }
+
+ matches := versionRE.FindAllString(filename, -1)
+ if len(matches) == 0 {
+ return nil, nil
+ }
+ version := matches[0]
+ description := strings.TrimPrefix(filename, version)
+ description = strings.TrimLeft(description, "_-#")
+ changeType := v1pb.Plan_ChangeDatabaseConfig_MIGRATE
+ switch {
+ case strings.HasPrefix(description, "ddl"):
+ description = strings.TrimPrefix(description, "ddl")
+ case strings.HasPrefix(description, "migrate"):
+ description = strings.TrimPrefix(description, "migrate")
+ case strings.HasPrefix(description, "dml"):
+ description = strings.TrimPrefix(description, "dml")
+ changeType = v1pb.Plan_ChangeDatabaseConfig_DATA
+ case strings.HasPrefix(description, "data"):
+ description = strings.TrimPrefix(description, "data")
+ changeType = v1pb.Plan_ChangeDatabaseConfig_DATA
+ }
+ description = strings.TrimLeft(description, "_-#")
+ return &fileChange{
+ path: path,
+ version: version,
+ changeType: changeType,
+ description: description,
+ }, nil
+}
diff --git a/backend/api/gitops/gitlab.go b/backend/api/gitops/gitlab.go
new file mode 100644
index 0000000000..ee5785c10c
--- /dev/null
+++ b/backend/api/gitops/gitlab.go
@@ -0,0 +1,77 @@
+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/gitlab"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+const (
+ mergeRequestObjectKind = "merge_request"
+ mergeAction = "merge"
+)
+
+func getMergeRequestChangeFileContent(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)
+ }
+ if pushEvent.ObjectKind != mergeRequestObjectKind {
+ return nil, errors.Errorf("invalid webhook event type, got %s, want push", pushEvent.ObjectKind)
+ }
+ if pushEvent.ObjectAttributes.Action != mergeAction {
+ return nil, errors.Errorf("invalid webhook event action, got %s, want merge", pushEvent.ObjectAttributes.Action)
+ }
+
+ if pushEvent.ObjectAttributes.TargetBranch != vcsConnector.Payload.Branch {
+ return nil, errors.Errorf("committed to branch %q, want branch %q", pushEvent.ObjectAttributes.TargetBranch, vcsConnector.Payload.Branch)
+ }
+ oauthContext := &common.OauthContext{
+ AccessToken: vcsProvider.AccessToken,
+ }
+
+ mrFiles, err := vcs.Get(vcs.GitLab, vcs.ProviderConfig{}).ListPullRequestFile(ctx, oauthContext, vcsProvider.InstanceURL, vcsConnector.Payload.ExternalId, fmt.Sprintf("%d", pushEvent.ObjectAttributes.IID))
+ if err != nil {
+ return nil, errors.Errorf("failed to list merge %q request files, error %v", pushEvent.ObjectAttributes.URL, err)
+ }
+
+ prInfo := &pullRequestInfo{
+ email: pushEvent.User.Email,
+ title: pushEvent.ObjectAttributes.Title,
+ url: pushEvent.ObjectAttributes.URL,
+ }
+ 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.GitLab, vcs.ProviderConfig{}).ReadFileContent(ctx, oauthContext, vcsProvider.InstanceURL, vcsConnector.Payload.ExternalId, file.path, vcs.RefInfo{RefType: vcs.RefTypeCommit, RefName: pushEvent.ObjectAttributes.LastCommit.ID})
+ if err != nil {
+ return nil, errors.Errorf("failed read file content, merge request %q, file %q, error %v", pushEvent.ObjectAttributes.URL, file.path, err)
+ }
+ file.content = content
+ }
+ return prInfo, nil
+}
diff --git a/backend/api/gitops/webhook.go b/backend/api/gitops/webhook.go
index c3025eb5b4..0e9b38190a 100644
--- a/backend/api/gitops/webhook.go
+++ b/backend/api/gitops/webhook.go
@@ -55,40 +55,40 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {
url := strings.TrimPrefix(c.Param("id"), "/")
workspaceID, projectID, vcsConnectorID, err := common.GetWorkspaceProjectVCSConnectorID(url)
if err != nil {
- return c.String(http.StatusBadRequest, fmt.Sprintf("invalid id %q", url))
+ return c.String(http.StatusOK, fmt.Sprintf("invalid id %q", url))
}
myWorkspaceID, err := s.store.GetWorkspaceID(ctx)
if err != nil {
- return c.String(http.StatusServiceUnavailable, fmt.Sprintf("failed to get workspace ID, error %v", err))
+ return c.String(http.StatusOK, fmt.Sprintf("failed to get workspace ID, error %v", err))
}
if myWorkspaceID != workspaceID {
- return c.String(http.StatusBadRequest, fmt.Sprintf("invalid workspace id %q, my ID %q", workspaceID, myWorkspaceID))
+ return c.String(http.StatusOK, fmt.Sprintf("invalid workspace id %q, my ID %q", workspaceID, myWorkspaceID))
}
project, err := s.store.GetProjectV2(ctx, &store.FindProjectMessage{ResourceID: &projectID})
if err != nil {
- return c.String(http.StatusServiceUnavailable, fmt.Sprintf("failed to get project %q, error %v", projectID, err))
+ return c.String(http.StatusOK, fmt.Sprintf("failed to get project %q, error %v", projectID, err))
}
if project == nil || project.Deleted {
- return c.String(http.StatusBadRequest, fmt.Sprintf("project %q does not exist or has been deleted", projectID))
+ return c.String(http.StatusOK, fmt.Sprintf("project %q does not exist or has been deleted", projectID))
}
vcsConnector, err := s.store.GetVCSConnector(ctx, &store.FindVCSConnectorMessage{ProjectID: &projectID, ResourceID: &vcsConnectorID})
if err != nil {
- return c.String(http.StatusServiceUnavailable, fmt.Sprintf("failed to get project %q VCS connector %q, error %v", projectID, vcsConnectorID, err))
+ return c.String(http.StatusOK, fmt.Sprintf("failed to get project %q VCS connector %q, error %v", projectID, vcsConnectorID, err))
}
if vcsConnector == nil {
- return c.String(http.StatusBadRequest, fmt.Sprintf("project %q VCS connector %q does not exist or has been deleted", projectID, vcsConnectorID))
+ return c.String(http.StatusOK, fmt.Sprintf("project %q VCS connector %q does not exist or has been deleted", projectID, vcsConnectorID))
}
vcsProvider, err := s.store.GetVCSProvider(ctx, &store.FindVCSProviderMessage{ResourceID: &vcsConnector.VCSResourceID})
if err != nil {
- return c.String(http.StatusServiceUnavailable, fmt.Sprintf("failed to get VCS provider %q, error %v", vcsConnector.VCSResourceID, err))
+ return c.String(http.StatusOK, fmt.Sprintf("failed to get VCS provider %q, error %v", vcsConnector.VCSResourceID, err))
}
if vcsProvider == nil {
- return c.String(http.StatusBadRequest, fmt.Sprintf("VCS provider %q does not exist or has been deleted", vcsConnector.VCSResourceID))
+ return c.String(http.StatusOK, fmt.Sprintf("VCS provider %q does not exist or has been deleted", vcsConnector.VCSResourceID))
}
body, err := io.ReadAll(c.Request().Body)
if err != nil {
- return c.String(http.StatusServiceUnavailable, fmt.Sprintf("failed to read body, error %v", err))
+ return c.String(http.StatusOK, fmt.Sprintf("failed to read body, error %v", err))
}
// Validate webhook secret.
@@ -97,15 +97,25 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {
secretToken := c.Request().Header.Get("X-Hub-Signature-256")
ok, err := validateGitHubWebhookSignature256(secretToken, vcsConnector.Payload.WebhookSecretToken, body)
if err != nil {
- return c.String(http.StatusBadRequest, fmt.Sprintf("failed to validate webhook signature %q, error %v", secretToken, err))
+ return c.String(http.StatusOK, fmt.Sprintf("failed to validate webhook signature %q, error %v", secretToken, err))
}
if !ok {
- return c.String(http.StatusBadRequest, fmt.Sprintf("invalid webhook secret token %q", secretToken))
+ return c.String(http.StatusOK, fmt.Sprintf("invalid webhook secret token %q", secretToken))
}
case vcs.GitLab:
secretToken := c.Request().Header.Get("X-Gitlab-Token")
if secretToken != vcsConnector.Payload.WebhookSecretToken {
- return c.String(http.StatusBadRequest, fmt.Sprintf("invalid webhook secret token %q", secretToken))
+ 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)
+ 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))
}
}
@@ -1089,3 +1099,130 @@ func patchTask(ctx context.Context, stores *store.Store, activityManager *activi
}
return nil
}
+
+func (s *Service) createIssueFromPRInfo(ctx context.Context, project *store.ProjectMessage, prInfo *pullRequestInfo) error {
+ creatorID := api.SystemBotID
+ user, err := s.store.GetUser(ctx, &store.FindUserMessage{Email: &prInfo.email})
+ if err != nil {
+ slog.Error("failed to find user by email", slog.String("email", prInfo.email), log.BBError(err))
+ }
+ if user != nil {
+ creatorID = user.ID
+ }
+
+ databases, err := s.store.ListDatabases(ctx, &store.FindDatabaseMessage{ProjectID: &project.ResourceID})
+ if err != nil {
+ return err
+ }
+ environments, err := s.store.ListEnvironmentV2(ctx, &store.FindEnvironmentMessage{})
+ if err != nil {
+ return err
+ }
+ environmentOrders := make(map[string]int32)
+ for _, environment := range environments {
+ environmentOrders[environment.ResourceID] = environment.Order
+ }
+ sort.Slice(databases, func(i, j int) bool {
+ return environmentOrders[databases[i].EffectiveEnvironmentID] < environmentOrders[databases[j].EffectiveEnvironmentID]
+ })
+
+ var sheets []int
+ for _, change := range prInfo.changes {
+ sheet, err := s.store.CreateSheet(ctx, &store.SheetMessage{
+ CreatorID: creatorID,
+ ProjectUID: project.UID,
+ Title: change.path,
+ Statement: change.content,
+ })
+ if err != nil {
+ return errors.Wrapf(err, "failed to create sheet for file %s", change.path)
+ }
+ sheets = append(sheets, sheet.UID)
+ }
+
+ var steps []*v1pb.Plan_Step
+ for i, database := range databases {
+ if i == 0 || databases[i].EffectiveEnvironmentID != databases[i-1].EffectiveEnvironmentID {
+ steps = append(steps, &v1pb.Plan_Step{})
+ }
+ step := steps[len(steps)-1]
+ for i, change := range prInfo.changes {
+ step.Specs = append(step.Specs, &v1pb.Plan_Spec{
+ Id: uuid.NewString(),
+ Config: &v1pb.Plan_Spec_ChangeDatabaseConfig{
+ ChangeDatabaseConfig: &v1pb.Plan_ChangeDatabaseConfig{
+ Type: change.changeType,
+ Target: common.FormatDatabase(database.InstanceID, database.DatabaseName),
+ Sheet: fmt.Sprintf("projects/%s/sheets/%d", project.ResourceID, sheets[i]),
+ SchemaVersion: change.version,
+ },
+ },
+ })
+ }
+ }
+
+ childCtx := context.WithValue(ctx, common.PrincipalIDContextKey, creatorID)
+ childCtx = context.WithValue(childCtx, common.UserContextKey, user)
+ childCtx = context.WithValue(childCtx, common.LoopbackContextKey, true)
+ plan, err := s.rolloutService.CreatePlan(childCtx, &v1pb.CreatePlanRequest{
+ Parent: fmt.Sprintf("projects/%s", project.ResourceID),
+ Plan: &v1pb.Plan{
+ Title: prInfo.title,
+ Steps: steps,
+ },
+ })
+ if err != nil {
+ return errors.Wrapf(err, "failed to create plan")
+ }
+ issue, err := s.issueService.CreateIssue(childCtx, &v1pb.CreateIssueRequest{
+ Parent: fmt.Sprintf("projects/%s", project.ResourceID),
+ Issue: &v1pb.Issue{
+ Title: prInfo.title,
+ Description: prInfo.description,
+ Type: v1pb.Issue_DATABASE_CHANGE,
+ Assignee: fmt.Sprintf("users/%s", api.SystemBotEmail),
+ Plan: plan.Name,
+ },
+ })
+ if err != nil {
+ return errors.Wrapf(err, "failed to create issue")
+ }
+ if _, err := s.rolloutService.CreateRollout(childCtx, &v1pb.CreateRolloutRequest{
+ Parent: fmt.Sprintf("projects/%s", project.ResourceID),
+ Rollout: &v1pb.Rollout{
+ Plan: plan.Name,
+ },
+ }); err != nil {
+ return errors.Wrapf(err, "failed to create rollout")
+ }
+
+ issueUID, err := strconv.Atoi(issue.Uid)
+ if err != nil {
+ return err
+ }
+ // Create a project activity after successfully creating the issue from the push event.
+ activityPayload, err := json.Marshal(
+ api.ActivityProjectRepositoryPushPayload{
+ // TODO(d): redefine VCS push event.
+ IssueID: issueUID,
+ IssueName: issue.Title,
+ },
+ )
+ if err != nil {
+ return errors.Wrapf(err, "failed to create activity payload")
+ }
+
+ activityCreate := &store.ActivityMessage{
+ CreatorUID: creatorID,
+ ResourceContainer: project.GetName(),
+ ContainerUID: project.UID,
+ Type: api.ActivityProjectRepositoryPush,
+ Level: api.ActivityInfo,
+ Comment: fmt.Sprintf("Created issue %q.", issue.Title),
+ Payload: string(activityPayload),
+ }
+ if _, err := s.activityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{}); err != nil {
+ return errors.Wrapf(err, "failed to activity after creating issue %d from push event", issueUID)
+ }
+ return nil
+}
diff --git a/backend/plugin/vcs/gitlab/gitlab.go b/backend/plugin/vcs/gitlab/gitlab.go
index 1fa9f0380d..bf392fe52d 100644
--- a/backend/plugin/vcs/gitlab/gitlab.go
+++ b/backend/plugin/vcs/gitlab/gitlab.go
@@ -512,6 +512,7 @@ type MergeRequestFile struct {
// ListPullRequestFile lists the changed files in the pull request.
//
+// TODO(d): migrate to diff API.
// Docs: https://docs.gitlab.com/ee/api/merge_requests.html#get-single-mr-changes
func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, pullRequestID string) ([]*vcs.PullRequestFile, error) {
url := fmt.Sprintf("%s/projects/%s/merge_requests/%s/changes", p.APIURL(instanceURL), repositoryID, pullRequestID)
diff --git a/backend/plugin/vcs/gitlab/webhook_events.go b/backend/plugin/vcs/gitlab/webhook_events.go
new file mode 100644
index 0000000000..74540c597b
--- /dev/null
+++ b/backend/plugin/vcs/gitlab/webhook_events.go
@@ -0,0 +1,27 @@
+package gitlab
+
+// MergeRequestPushEvent is the json message for merge request push event.
+type MergeRequestPushEvent struct {
+ ObjectKind string `json:"object_kind"`
+ User EventUser `json:"user"`
+ ObjectAttributes EventObjectAttributes `json:"object_attributes"`
+}
+
+type EventUser struct {
+ Email string `json:"email"`
+}
+
+type EventObjectAttributes struct {
+ IID int `json:"iid"`
+ URL string `json:"url"`
+ TargetBranch string `json:"target_branch"`
+ // open, merge.
+ Action string `json:"action"`
+ Title string `json:"title"`
+ Description string `json:"description"`
+ LastCommit LastCommit `json:"last_commit"`
+}
+
+type LastCommit struct {
+ ID string `json:"id"`
+}
diff --git a/backend/tests/schema_update_test.go b/backend/tests/schema_update_test.go
index 3b1b68c265..7d46541469 100644
--- a/backend/tests/schema_update_test.go
+++ b/backend/tests/schema_update_test.go
@@ -19,7 +19,6 @@ import (
"github.com/bytebase/bytebase/backend/plugin/vcs"
"github.com/bytebase/bytebase/backend/plugin/vcs/bitbucket"
"github.com/bytebase/bytebase/backend/plugin/vcs/github"
- "github.com/bytebase/bytebase/backend/plugin/vcs/gitlab"
"github.com/bytebase/bytebase/backend/resources/mysql"
"github.com/bytebase/bytebase/backend/resources/postgres"
"github.com/bytebase/bytebase/backend/tests/fake"
@@ -146,33 +145,6 @@ func TestSimpleVCS(t *testing.T) {
repositoryFullPath string
newWebhookPushEvent func(added, modified [][]string, beforeSHA, afterSHA string) any
}{
- {
- name: "GitLab",
- vcsProviderCreator: fake.NewGitLab,
- vcsType: v1pb.VCSProvider_GITLAB,
- externalID: "121",
- repositoryFullPath: "test/schemaUpdate",
- newWebhookPushEvent: func(added, modified [][]string, beforeSHA, afterSHA string) any {
- var commitList []gitlab.WebhookCommit
- for i := range added {
- commitList = append(commitList, gitlab.WebhookCommit{
- Timestamp: time.Now().Format(time.RFC3339),
- AddedList: added[i],
- ModifiedList: modified[i],
- })
- }
- return gitlab.WebhookPushEvent{
- ObjectKind: gitlab.WebhookPush,
- Ref: "refs/heads/feature/foo",
- Before: beforeSHA,
- After: afterSHA,
- Project: gitlab.WebhookProject{
- ID: 121,
- },
- CommitList: commitList,
- }
- },
- },
{
name: "GitHub",
vcsProviderCreator: fake.NewGitHub,