Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: gitops sql review support azure (#13050)
ecmadao61590ae2261c
diff --git a/backend/api/gitops/azure.go b/backend/api/gitops/azure.goindex 309077220e..4e9b85f09f 100644--- a/backend/api/gitops/azure.go+++ b/backend/api/gitops/azure.go@@ -19,11 +19,20 @@ func getAzurePullRequestInfo(ctx context.Context, vcsProvider *store.VCSProviderreturn nil, errors.Errorf("failed to unmarshal push event, error %v", err)}- if strings.ToLower(pushEvent.Resource.Status) != "completed" {- return nil, errors.Errorf("invalid pull request status: %v", pushEvent.Resource.Status)- }- if strings.ToLower(pushEvent.Resource.MergeStatus) != "succeeded" {- return nil, errors.Errorf("invalid pull request merge status: %v", pushEvent.Resource.MergeStatus)+ var actionType webhookAction+ switch pushEvent.EventType {+ case azure.PullRequestEventCreated, azure.PullRequestEventUpdated:+ actionType = webhookActionSQLReview+ case azure.PullRequestEventMerged:+ if strings.ToLower(pushEvent.Resource.Status) != "completed" {+ return nil, errors.Errorf("invalid pull request status: %v", pushEvent.Resource.Status)+ }+ if strings.ToLower(pushEvent.Resource.MergeStatus) != "succeeded" {+ return nil, errors.Errorf("invalid pull request merge status: %v", pushEvent.Resource.MergeStatus)+ }+ actionType = webhookActionCreateIssue+ default:+ return nil, errors.Errorf(`skip webhook event action "%v"`, pushEvent.EventType)}targetBranch, err := vcs.Branch(pushEvent.Resource.TargetRefName)@@ -35,20 +44,26 @@ func getAzurePullRequestInfo(ctx context.Context, vcsProvider *store.VCSProviderreturn nil, errors.Errorf("committed to branch %q, want branch %q", targetBranch, vcsConnector.Payload.Branch)}- mrFiles, err := vcs.Get(+ azurePlugin, ok := vcs.Get(storepb.VCSType_AZURE_DEVOPS,vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken},- ).ListPullRequestFile(+ ).(*azure.Provider)+ if !ok {+ return nil, errors.Errorf("failed to get azure plugin")+ }++ mrFiles, err := azurePlugin.ListPullRequestFileInCommit(ctx,vcsConnector.Payload.ExternalId,pushEvent.Resource.LastMergeCommit.CommitID,+ pushEvent.Resource.PullRequestID,)if err != nil {return nil, errors.Errorf("failed to list merge request files by commit %v, error %v", pushEvent.Resource.LastMergeCommit.CommitID, err)}prInfo := &pullRequestInfo{- action: webhookActionCreateIssue,+ action: actionType,// TODO(ed): get the email.url: pushEvent.Resource.Links.Web.Href,title: pushEvent.Resource.Title,@@ -57,10 +72,7 @@ func getAzurePullRequestInfo(ctx context.Context, vcsProvider *store.VCSProvider}for _, file := range prInfo.changes {- content, err := vcs.Get(- storepb.VCSType_AZURE_DEVOPS,- vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken},- ).ReadFileContent(+ content, err := azurePlugin.ReadFileContent(ctx,vcsConnector.Payload.ExternalId,file.path,diff --git a/backend/api/gitops/common.go b/backend/api/gitops/common.goindex e34032cfe2..e4f6ec6f4a 100644--- a/backend/api/gitops/common.go+++ b/backend/api/gitops/common.go@@ -56,21 +56,19 @@ func getChangesByFileList(files []*vcs.PullRequestFile, rootDir string) []*fileCif filepath.Dir(prFilePath) != rootDir {continue}- change, err := getFileChange(v.Path)+ change, err := getFileChange(v)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- change.webURL = v.WebURLchanges = append(changes, change)}}return changes}-func getFileChange(path string) (*fileChange, error) {- filename := filepath.Base(path)+func getFileChange(file *vcs.PullRequestFile) (*fileChange, error) {+ filename := filepath.Base(file.Path)if filepath.Ext(filename) != ".sql" {return nil, nil}@@ -96,10 +94,11 @@ func getFileChange(path string) (*fileChange, error) {}description = strings.TrimLeft(description, "_")return &fileChange{- path: path,+ path: file.Path,version: version,changeType: changeType,description: description,+ webURL: file.WebURL,}, nil}diff --git a/backend/api/gitops/webhook.go b/backend/api/gitops/webhook.goindex 2571c95c10..290e72f03f 100644--- a/backend/api/gitops/webhook.go+++ b/backend/api/gitops/webhook.go@@ -23,6 +23,7 @@ import ("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/bitbucket""github.com/bytebase/bytebase/backend/store"storepb "github.com/bytebase/bytebase/proto/generated-go/store"@@ -120,10 +121,10 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {case storepb.VCSType_BITBUCKET:eventType := c.Request().Header.Get("X-Event-Key")var action webhookAction- switch eventType {- case "pullrequest:created", "pullrequest:updated":+ switch bitbucket.PullRequestEventType(eventType) {+ case bitbucket.PullRequestEventCreated, bitbucket.PullRequestEventUpdated:action = webhookActionSQLReview- case "pullrequest:fulfilled":+ case bitbucket.PullRequestEventFulfilled:action = webhookActionCreateIssuedefault:return c.String(http.StatusOK, fmt.Sprintf(`skip webhook event "%v"`, eventType))@@ -135,7 +136,6 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {}prInfo.action = actioncase storepb.VCSType_AZURE_DEVOPS:- // TODO(ed): support pr update/create event.secretToken := c.Request().Header.Get("X-Azure-Token")if secretToken != vcsConnector.Payload.WebhookSecretToken {return c.String(http.StatusOK, fmt.Sprintf("invalid webhook secret token %q", secretToken))@@ -366,7 +366,7 @@ func (s *Service) createIssueFromPRInfo(ctx context.Context, project *store.ProjResponse: "",Status: nil,}); err != nil {- slog.Warn("failed to create audit log after creating issue from push event", "issueUID", issueUID)+ slog.Error("failed to create audit log after creating issue from push event", slog.Int("issue", issueUID), log.BBError(err))}return issue, nildiff --git a/backend/api/v1/vcs_connector_service.go b/backend/api/v1/vcs_connector_service.goindex 6491e0190e..b77ef3d916 100644--- a/backend/api/v1/vcs_connector_service.go+++ b/backend/api/v1/vcs_connector_service.go@@ -358,15 +358,19 @@ func (s *VCSConnectorService) DeleteVCSConnector(ctx context.Context, request *v}// Delete the webhook, and fail-open.- if err = vcs.Get(+ webhookIDs := strings.Split(vcsConnector.Payload.ExternalWebhookId, ",")+ vcsPlugin := vcs.Get(vcsProvider.Type,vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken},- ).DeleteWebhook(- ctx,- vcsConnector.Payload.ExternalId,- vcsConnector.Payload.ExternalWebhookId,- ); err != nil {- slog.Error("failed to delete webhook for VCS connector", slog.String("project", projectID), slog.String("VCS connector", vcsConnector.ResourceID), log.BBError(err))+ )+ for _, webhookID := range webhookIDs {+ if err = vcsPlugin.DeleteWebhook(+ ctx,+ vcsConnector.Payload.ExternalId,+ webhookID,+ ); err != nil {+ slog.Error("failed to delete webhook for VCS connector", slog.String("project", projectID), slog.String("VCS connector", vcsConnector.ResourceID), log.BBError(err))+ }}return &emptypb.Empty{}, nil@@ -421,8 +425,7 @@ func checkBranchExistence(ctx context.Context, vcsProvider *store.VCSProviderMesfunc createVCSWebhook(ctx context.Context, vcsProvider *store.VCSProviderMessage, webhookEndpointID, webhookSecretToken, externalRepoID, bytebaseEndpointURL string) (string, error) {// Create a new webhook and retrieve the created webhook ID- var webhookCreatePayload []byte- var err error+ var webhookCreatePayloads [][]byteswitch vcsProvider.Type {case storepb.VCSType_GITLAB:// https://docs.gitlab.com/ee/user/project/integrations/webhook_events.html#push-events@@ -433,10 +436,11 @@ func createVCSWebhook(ctx context.Context, vcsProvider *store.VCSProviderMessageNoteEvents: true,EnableSSLVerification: false,}- webhookCreatePayload, err = json.Marshal(webhookCreate)+ createPayload, err := json.Marshal(webhookCreate)if err != nil {return "", errors.Wrap(err, "failed to marshal request body for creating webhook")}+ webhookCreatePayloads = append(webhookCreatePayloads, createPayload)case storepb.VCSType_GITHUB:webhookPost := github.WebhookCreateOrUpdate{Config: github.WebhookConfig{@@ -448,22 +452,29 @@ func createVCSWebhook(ctx context.Context, vcsProvider *store.VCSProviderMessage// https://docs.github.com/en/webhooks/webhook-events-and-payloadsEvents: []string{"pull_request", "pull_request_review_comment"},}- webhookCreatePayload, err = json.Marshal(webhookPost)+ createPayload, err := json.Marshal(webhookPost)if err != nil {return "", errors.Wrap(err, "failed to marshal request body for creating webhook")}+ webhookCreatePayloads = append(webhookCreatePayloads, createPayload)case storepb.VCSType_BITBUCKET:webhookPost := bitbucket.WebhookCreateOrUpdate{Description: "Bytebase GitOps",URL: fmt.Sprintf("%s/hook/%s", bytebaseEndpointURL, webhookEndpointID),Active: true,// https://support.atlassian.com/bitbucket-cloud/docs/event-payloads- Events: []string{"pullrequest:created", "pullrequest:updated", "pullrequest:fulfilled", "pullrequest:comment_created"},+ Events: []string{+ string(bitbucket.PullRequestEventCreated),+ string(bitbucket.PullRequestEventUpdated),+ string(bitbucket.PullRequestEventFulfilled),+ "pullrequest:comment_created",+ },}- webhookCreatePayload, err = json.Marshal(webhookPost)+ createPayload, err := json.Marshal(webhookPost)if err != nil {return "", errors.Wrap(err, "failed to marshal request body for creating webhook")}+ webhookCreatePayloads = append(webhookCreatePayloads, createPayload)case storepb.VCSType_AZURE_DEVOPS:part := strings.Split(externalRepoID, "/")if len(part) != 3 {@@ -472,39 +483,55 @@ func createVCSWebhook(ctx context.Context, vcsProvider *store.VCSProviderMessageprojectID, repositoryID := part[1], part[2]// https://learn.microsoft.com/en-us/azure/devops/service-hooks/events?view=azure-devops- // TODO(ed): Azure doesn't support multiply events in a single webhook, but we need:+ // Azure doesn't support multiply events in a single webhook, but we need:// - git.pullrequest.merged: A merge commit was created on a pull request.// - git.pullrequest.created: A pull request is created in a Git repository.// - git.pullrequest.updated: A pull request is updated; status, review list, reviewer vote changed, or the source branch is updated with a push.- webhookPost := azure.WebhookCreateOrUpdate{- ConsumerActionID: "httpRequest",- ConsumerID: "webHooks",- ConsumerInputs: azure.WebhookCreateConsumerInputs{- URL: fmt.Sprintf("%s/hook/%s", bytebaseEndpointURL, webhookEndpointID),- AcceptUntrustedCerts: true,- HTTPHeaders: fmt.Sprintf("X-Azure-Token: %s", webhookSecretToken),- },- EventType: "git.pullrequest.merged",- PublisherID: "tfs",- PublisherInputs: azure.WebhookCreatePublisherInputs{- Repository: repositoryID,- Branch: "", /* Any branches */- MergeResult: azure.WebhookMergeResultSucceeded,- ProjectID: projectID,- },+ events := []azure.PullRequestEventType{+ azure.PullRequestEventCreated,+ azure.PullRequestEventUpdated,+ azure.PullRequestEventMerged,}- webhookCreatePayload, err = json.Marshal(webhookPost)- if err != nil {- return "", errors.Wrap(err, "failed to marshal request body for creating webhook")+ for _, event := range events {+ publisherInputs := azure.WebhookCreatePublisherInputs{+ Repository: repositoryID,+ Branch: "", /* Any branches */+ ProjectID: projectID,+ }+ if event == azure.PullRequestEventMerged {+ publisherInputs.MergeResult = azure.WebhookMergeResultSucceeded+ }+ webhookPost := azure.WebhookCreateOrUpdate{+ ConsumerActionID: "httpRequest",+ ConsumerID: "webHooks",+ ConsumerInputs: azure.WebhookCreateConsumerInputs{+ URL: fmt.Sprintf("%s/hook/%s", bytebaseEndpointURL, webhookEndpointID),+ AcceptUntrustedCerts: true,+ HTTPHeaders: fmt.Sprintf("X-Azure-Token: %s", webhookSecretToken),+ },+ EventType: string(event),+ PublisherID: "tfs",+ PublisherInputs: publisherInputs,+ }+ createPayload, err := json.Marshal(webhookPost)+ if err != nil {+ return "", errors.Wrap(err, "failed to marshal request body for creating webhook")+ }+ webhookCreatePayloads = append(webhookCreatePayloads, createPayload)}}- webhookID, err := vcs.Get(vcsProvider.Type, vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken}).CreateWebhook(- ctx,- externalRepoID,- webhookCreatePayload,- )- if err != nil {- return "", errors.Wrap(err, "failed to create webhook")++ var webhookIDs []string+ for _, webhookCreatePayload := range webhookCreatePayloads {+ webhookID, err := vcs.Get(vcsProvider.Type, vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken}).CreateWebhook(+ ctx,+ externalRepoID,+ webhookCreatePayload,+ )+ if err != nil {+ return "", errors.Wrap(err, "failed to create webhook")+ }+ webhookIDs = append(webhookIDs, webhookID)}- return webhookID, nil+ return strings.Join(webhookIDs, ","), nil}diff --git a/backend/plugin/vcs/azure/azure.go b/backend/plugin/vcs/azure/azure.goindex 1df899dc15..1eff9ad7bb 100644--- a/backend/plugin/vcs/azure/azure.go+++ b/backend/plugin/vcs/azure/azure.go@@ -362,23 +362,44 @@ func (p *Provider) GetBranch(ctx context.Context, repositoryID, branchName strin}, nil}-// ListPullRequestFile lists the changed files by last merge commit id.-func (p *Provider) ListPullRequestFile(ctx context.Context, repositoryID, lastMergeCommitID string) ([]*vcs.PullRequestFile, error) {+// ListPullRequestFileInCommit lists the changed files by last merge commit id.+func (p *Provider) ListPullRequestFileInCommit(ctx context.Context, repositoryID, lastMergeCommitID string, pullRequestID int) ([]*vcs.PullRequestFile, error) {+ organizationName, projectName, repoID, err := getAzureRepositoryIDs(repositoryID)+ if err != nil {+ return nil, err+ }++ var prURL string+ if pullRequestID != 0 {+ prURL = fmt.Sprintf("%s/%s/%s/_git/%s/pullrequest/%d", p.instanceURL, organizationName, projectName, repoID, pullRequestID)+ }changeResponse, err := p.getChangesByCommit(ctx, repositoryID, lastMergeCommitID)if err != nil {return nil, err}files := []*vcs.PullRequestFile{}for _, change := range changeResponse.Changes {+ var webURL string+ if prURL != "" {+ // Web URL for file in PR:+ // {PR web URL}?_a=files&path={file path}+ webURL = fmt.Sprintf("%s?_a=files&path=%s", webURL, url.QueryEscape(change.Item.Path))+ }files = append(files, &vcs.PullRequestFile{Path: change.Item.Path,LastCommitID: change.Item.CommitID,IsDeleted: change.ChangeType == "delete",+ WebURL: webURL,})}return files, nil}+// ListPullRequestFile lists the changed files by last merge commit id.+func (p *Provider) ListPullRequestFile(ctx context.Context, repositoryID, lastMergeCommitID string) ([]*vcs.PullRequestFile, error) {+ return p.ListPullRequestFileInCommit(ctx, repositoryID, lastMergeCommitID, 0)+}+type Comment struct {Content string `json:"content"`CommentType string `json:"commentType"`@@ -449,13 +470,15 @@ func (p *Provider) ListPullRequestComments(ctx context.Context, repositoryID, pureturn nil, errors.Errorf("failed to list thread, code: %v, body: %s", code, string(body))}- var threads []PullRequestThread- if err := json.Unmarshal([]byte(body), &threads); err != nil {+ var resp struct {+ Value []*PullRequestThread `json:"value"`+ }+ if err := json.Unmarshal([]byte(body), &resp); err != nil {return nil, err}var res []*vcs.PullRequestComment- for _, thread := range threads {+ for _, thread := range resp.Value {if len(thread.Comments) != 1 {continue}@@ -561,13 +584,21 @@ func (p *Provider) DeleteWebhook(ctx context.Context, _, webhookID string) errorreturn nil}-func (p *Provider) getRepositoryAPIURL(repositoryID string) (string, error) {+func getAzureRepositoryIDs(repositoryID string) (string, string, string, error) {// By design, we encode the repository ID as <organization>/<projectID>/<repositoryID> for Azure DevOps.parts := strings.Split(repositoryID, "/")if len(parts) != 3 {- return "", errors.Errorf("invalid repository ID %q", repositoryID)+ return "", "", "", errors.Errorf("invalid repository ID %q", repositoryID)}organizationName, projectName, repositoryID := parts[0], parts[1], parts[2]+ return organizationName, projectName, repositoryID, nil+}++func (p *Provider) getRepositoryAPIURL(repositoryID string) (string, error) {+ organizationName, projectName, repositoryID, err := getAzureRepositoryIDs(repositoryID)+ if err != nil {+ return "", err+ }return fmt.Sprintf("%s/%s/%s/_apis/git/repositories/%s", p.APIURL(p.instanceURL), url.PathEscape(organizationName), url.PathEscape(projectName), url.PathEscape(repositoryID)), nil}diff --git a/backend/plugin/vcs/azure/webhook_events.go b/backend/plugin/vcs/azure/webhook_events.goindex b98aa9f993..c942042a1e 100644--- a/backend/plugin/vcs/azure/webhook_events.go+++ b/backend/plugin/vcs/azure/webhook_events.go@@ -36,14 +36,24 @@ type PullRequestResource struct {CreatedBy *PullRequestCreatedBy `json:"createdBy"`}+type PullRequestEventType string++const (+ // A pull request is created in a Git repository.+ PullRequestEventCreated PullRequestEventType = "git.pullrequest.created"+ // A pull request is updated; status, review list, reviewer vote changed, or the source branch is updated with a push.+ PullRequestEventUpdated PullRequestEventType = "git.pullrequest.updated"+ // A merge commit was created on a pull request.+ PullRequestEventMerged PullRequestEventType = "git.pullrequest.merged"+)+// PullRequestEvent is the API message for pull request webhook event.//// Docs: https://learn.microsoft.com/en-us/azure/devops/service-hooks/events?view=azure-devops#pull-request-merge-commit-createdtype PullRequestEvent struct {// ID is the webhook message id.- ID string `json:"id"`- // EventType should be "git.pullrequest.merged".- EventType string `json:"eventType"`+ ID string `json:"id"`+ EventType PullRequestEventType `json:"eventType"`Resource *PullRequestResource `json:"resource"`}@@ -66,7 +76,7 @@ type WebhookCreatePublisherInputs struct {// The target branch for PR without "refs/heads/" prefix.Branch string `json:"branch"`// The merge result for PR, we only need the "Succeeded".- MergeResult WebhookMergeResult `json:"mergeResult"`+ MergeResult WebhookMergeResult `json:"mergeResult,omitempty"`ProjectID string `json:"projectId"`}diff --git a/backend/plugin/vcs/bitbucket/bitbucket.go b/backend/plugin/vcs/bitbucket/bitbucket.goindex 120e5fdd3f..7a461b59e3 100644--- a/backend/plugin/vcs/bitbucket/bitbucket.go+++ b/backend/plugin/vcs/bitbucket/bitbucket.go@@ -310,7 +310,11 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, repositoryID, pullRePath: d.New.Path,LastCommitID: extractCommitIDFromLinkSelf(d.New.Links.Self.Href),IsDeleted: d.Status == "removed",- WebURL: fmt.Sprintf("%s/diff#L%s", prURL, d.New.Path),+ // Web URL for file in PR:+ // {PR web URL}/diff#chg-{file path}+ // Web URL for file with a specific line in PR:+ // {PR web URL}/diff#L{file path}T{line}+ WebURL: fmt.Sprintf("%s/diff#L%s", prURL, d.New.Path),}files = append(files, file)}diff --git a/backend/plugin/vcs/bitbucket/webhook_events.go b/backend/plugin/vcs/bitbucket/webhook_events.goindex 92eb90c14d..2cd6b65061 100644--- a/backend/plugin/vcs/bitbucket/webhook_events.go+++ b/backend/plugin/vcs/bitbucket/webhook_events.go@@ -1,6 +1,18 @@package bitbucket// Header X-Event-Key: pullrequest:created, pullrequest:updated, pullrequest:fulfilled.+//+// https://support.atlassian.com/bitbucket-cloud/docs/event-payloads+type PullRequestEventType string++const (+ // A pull request is created in a Git repository.+ PullRequestEventCreated PullRequestEventType = "pullrequest:created"+ // A pull request is updated.+ PullRequestEventUpdated PullRequestEventType = "pullrequest:updated"+ // A pull request is merged.+ PullRequestEventFulfilled PullRequestEventType = "pullrequest:fulfilled"+)// PullRequestPushEvent is the json message for pull request push event.type PullRequestPushEvent struct {diff --git a/backend/plugin/vcs/github/github.go b/backend/plugin/vcs/github/github.goindex 94ac1b5e65..fdab3e3cf1 100644--- a/backend/plugin/vcs/github/github.go+++ b/backend/plugin/vcs/github/github.go@@ -310,7 +310,11 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, repositoryID, pullRePath: file.FileName,LastCommitID: refs[0],IsDeleted: file.Status == "removed",- WebURL: fmt.Sprintf("%s/files#diff-%s", prURL, fileHash),+ // Web URL for file in PR:+ // {PR web URL}/files#diff-{sha256 for file path}+ // Web URL for file with a specific line in PR:+ // {PR web URL}/files#diff-{sha256 for file path}R{line}+ WebURL: fmt.Sprintf("%s/files#diff-%s", prURL, fileHash),})}diff --git a/backend/plugin/vcs/gitlab/gitlab.go b/backend/plugin/vcs/gitlab/gitlab.goindex bb83ba72a2..8934620a96 100644--- a/backend/plugin/vcs/gitlab/gitlab.go+++ b/backend/plugin/vcs/gitlab/gitlab.go@@ -294,7 +294,11 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, repositoryID, pullRePath: file.NewPath,LastCommitID: pr.SHA,IsDeleted: file.DeletedFile,- WebURL: fmt.Sprintf("%s/diffs#%s", pr.WebURL, fileHash),+ // Web URL for file in PR:+ // {PR web URL}/diffs#diff-content-{sha1 for file path}+ // Web URL for file with a specific line in PR:+ // {PR web URL}/diffs#{sha1 for file path}_0_{line}+ WebURL: fmt.Sprintf("%s/diffs#%s", pr.WebURL, fileHash),})}