Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: SQL review API for VCS workflow (#2966)
ecmadaoc5261f28f801
diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.goindex d842fe5ba2..fe28fd9b45 100644--- a/plugin/vcs/github/github.go+++ b/plugin/vcs/github/github.go@@ -19,8 +19,10 @@ import ("golang.org/x/crypto/nacl/box""github.com/pkg/errors"+ "go.uber.org/zap""github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/common/log""github.com/bytebase/bytebase/plugin/vcs""github.com/bytebase/bytebase/plugin/vcs/internal/oauth")@@ -783,6 +785,109 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, ireturn &file, nil}+type githubPullRequestFile struct {+ FileName string `json:"filename"`+ SHA string `json:"sha"`+ // The file status in GitHub PR.+ // Available values: "added", "removed", "modified", "renamed", "copied", "changed", "unchanged"+ Status string `json:"status"`+ // The file content API URL, which contains the ref value in the query.+ // Example: https://api.github.com/repos/octocat/Hello-World/contents/file1.txt?ref=6dcb09b5b57875f334f61aebed695e2e4193db5e+ ContentsURL string `json:"contents_url"`+}++// ListPullRequestFile lists the changed files in the pull request.+//+// Docs: https://docs.github.com/en/rest/pulls/pulls#list-pull-requests-files+func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, pullRequestID string) ([]*vcs.PullRequestFile, error) {+ var allPRFiles []githubPullRequestFile+ page := 1+ for {+ fileList, err := p.listPaginatedPullRequestFile(ctx, oauthCtx, instanceURL, repositoryID, pullRequestID, page)+ if err != nil {+ return nil, errors.Wrap(err, "Failed to list pull request file")+ }++ if len(fileList) == 0 {+ break+ }+ allPRFiles = append(allPRFiles, fileList...)+ page+++ }++ var res []*vcs.PullRequestFile+ for _, file := range allPRFiles {+ u, err := url.Parse(file.ContentsURL)+ if err != nil {+ log.Debug("Failed to parse content url for file",+ zap.String("content_url", file.ContentsURL),+ zap.String("file", file.FileName),+ zap.Error(err),+ )+ continue+ }+ m, _ := url.ParseQuery(u.RawQuery)+ if err != nil {+ log.Debug("Failed to parse query for file",+ zap.String("content_url", file.ContentsURL),+ zap.String("file", file.FileName),+ zap.Error(err),+ )+ continue+ }+ refs, ok := m["ref"]+ if !ok || len(refs) != 1 {+ continue+ }++ res = append(res, &vcs.PullRequestFile{+ Path: file.FileName,+ LastCommitID: refs[0],+ IsDeleted: file.Status == "removed",+ })+ }++ return res, nil+}++// listPaginatedPullRequestFile lists the changed files in the pull request with pagination.+func (p *Provider) listPaginatedPullRequestFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, pullRequestID string, page int) ([]githubPullRequestFile, error) {+ requestURL := fmt.Sprintf("%s/repos/%s/pulls/%s/files?per_page=%d&page=%d", p.APIURL(instanceURL), repositoryID, pullRequestID, apiPageSize, page)+ code, _, body, err := oauth.Get(+ ctx,+ p.client,+ requestURL,+ &oauthCtx.AccessToken,+ tokenRefresher(+ instanceURL,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),+ )+ if err != nil {+ return nil, errors.Wrapf(err, "GET %s", requestURL)+ }+ if code == http.StatusNotFound {+ return nil, common.Errorf(common.NotFound, "failed to list pull request file from URL %s", requestURL)+ } else if code >= 300 {+ return nil, errors.Errorf("failed to list pull request file from URL %s, status code: %d, body: %s",+ requestURL,+ code,+ body,+ )+ }++ var prFiles []githubPullRequestFile+ if err := json.Unmarshal([]byte(body), &prFiles); err != nil {+ return nil, err+ }+ return prFiles, nil+}+type githubBranchCreate struct {Ref string `json:"ref"`SHA string `json:"sha"`diff --git a/plugin/vcs/github/github_test.go b/plugin/vcs/github/github_test.goindex 785922ce7c..d4bdfbfe2f 100644--- a/plugin/vcs/github/github_test.go+++ b/plugin/vcs/github/github_test.go@@ -1380,3 +1380,55 @@ func TestProvider_UpsertEnvironmentVariable(t *testing.T) {err := p.UpsertEnvironmentVariable(ctx, common.OauthContext{}, githubComURL, "octocat/Hello-World", "1", "new value")require.NoError(t, err)}++func TestProvider_ListPullRequestFile(t *testing.T) {+ p := newProvider(+ vcs.ProviderConfig{+ Client: &http.Client{+ Transport: &common.MockRoundTripper{+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {+ assert.Equal(t, "/repos/octocat/Hello-World/pulls/1/files", r.URL.Path)+ if r.URL.Query().Get("page") == "2" {+ return &http.Response{+ StatusCode: http.StatusOK,+ Body: io.NopCloser(strings.NewReader(`[]`)),+ }, nil+ }+ return &http.Response{+ StatusCode: http.StatusOK,+ // Example response taken from https://docs.github.com/en/rest/pulls/pulls#list-pull-requests-files+ Body: io.NopCloser(strings.NewReader(`+[+ {+ "sha": "bbcd538c8e72b8c175046e27cc8f907076331401",+ "filename": "file1.txt",+ "status": "added",+ "additions": 103,+ "deletions": 21,+ "changes": 124,+ "blob_url": "https://github.com/octocat/Hello-World/blob/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt",+ "raw_url": "https://github.com/octocat/Hello-World/raw/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt",+ "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/file1.txt?ref=6dcb09b5b57875f334f61aebed695e2e4193db5e",+ "patch": "@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test"+ }+]+`)),+ }, nil+ },+ },+ },+ },+ )+ ctx := context.Background()+ got, err := p.ListPullRequestFile(ctx, common.OauthContext{}, githubComURL, "octocat/Hello-World", "1")+ require.NoError(t, err)++ want := []*vcs.PullRequestFile{+ {+ Path: "file1.txt",+ LastCommitID: "6dcb09b5b57875f334f61aebed695e2e4193db5e",+ IsDeleted: false,+ },+ }+ assert.Equal(t, want, got)+}diff --git a/plugin/vcs/github/sql-review.yml b/plugin/vcs/github/sql-review.ymlindex 0077687eba..f855ca951a 100644--- a/plugin/vcs/github/sql-review.yml+++ b/plugin/vcs/github/sql-review.yml@@ -6,14 +6,34 @@ jobs:steps:- name: SQL adviserun: |- pull_number=$(jq --raw-output .pull_request.number "$GITHUB_EVENT_PATH")- API="%s/pull/$pull_number"+ API="%s"+ TOKEN="${{ secrets.%s }}"echo "Start request $API"- response=$(curl -s --show-error -X GET "$API" -H "Content-type: application/json" -H "X-SQL-Review-Token: ${{ secrets.%s }}")- echo $response- status=$(echo $response | jq -r '.status')- content=$(echo $response | jq -r '.content')+ pull_number=$(jq --raw-output .pull_request.number "$GITHUB_EVENT_PATH")+ repository=`echo $GITHUB_REPOSITORY | tr '[:upper:]' '[:lower:]'`+ request_body=$(jq -n \+ --arg repositoryId "$repository" \+ --arg pullRequestId $pull_number \+ --arg webURL "$GITHUB_SERVER_URL" \+ '$ARGS.named')++ response=$(curl -s -w "%%{http_code}" -X POST $API \+ -H "X-SQL-Review-Token: $TOKEN" \+ -H "Content-Type: application/json" \+ -d "$request_body")+ echo "::debug::response $response"++ http_code=$(tail -n1 <<< "$response")+ body=$(sed '$ d' <<< "$response")++ if [ $http_code != 200 ]; then+ echo ":error::Failed to check SQL with response code $http_code and body $body"+ exit 1+ fi++ status=$(echo $body | jq -r '.status')+ content=$(echo $body | jq -r '.content')while read message; doecho $messagediff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.goindex 4f25f77e00..ae56881f01 100644--- a/plugin/vcs/gitlab/gitlab.go+++ b/plugin/vcs/gitlab/gitlab.go@@ -759,6 +759,68 @@ func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx common.OauthConreturn file.Content, nil}+type gitlabMergeRequestChange struct {+ SHA string `json:"sha"`+ Changes []gitlabMergeRequestFile `json:"changes"`+}++type gitlabMergeRequestFile struct {+ NewPath string `json:"new_path"`+ NewFile bool `json:"new_file"`+ RenamedFile bool `json:"renamed_file"`+ DeletedFile bool `json:"deleted_file"`+}++// ListPullRequestFile lists the changed files in the pull request.+//+// 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)+ code, _, body, err := oauth.Get(+ ctx,+ p.client,+ url,+ &oauthCtx.AccessToken,+ tokenRefresher(+ instanceURL,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),+ )+ if err != nil {+ return nil, errors.Wrapf(err, "GET %s", url)+ }+ if code == http.StatusNotFound {+ return nil, common.Errorf(common.NotFound, "failed to list merge request file from URL %s", url)+ } else if code >= 300 {+ return nil, errors.Errorf("failed to list merge request file from URL %s, status code: %d, body: %s",+ url,+ code,+ body,+ )+ }++ pr := new(gitlabMergeRequestChange)+ if err := json.Unmarshal([]byte(body), pr); err != nil {+ return nil, err+ }++ var res []*vcs.PullRequestFile+ for _, file := range pr.Changes {+ res = append(res, &vcs.PullRequestFile{+ Path: file.NewPath,+ LastCommitID: pr.SHA,+ IsDeleted: file.DeletedFile,+ })+ }++ return res, nil+}+type gitlabBranch struct {Name string `json:"name"`Commit Commit `json:"commit"`diff --git a/plugin/vcs/gitlab/gitlab_test.go b/plugin/vcs/gitlab/gitlab_test.goindex 71247b87d1..e13190e05b 100644--- a/plugin/vcs/gitlab/gitlab_test.go+++ b/plugin/vcs/gitlab/gitlab_test.go@@ -1088,3 +1088,70 @@ func TestProvider_UpsertEnvironmentVariable(t *testing.T) {err := p.UpsertEnvironmentVariable(ctx, common.OauthContext{}, "", "1", "1", "new value")require.NoError(t, err)}++func TestProvider_ListPullRequestFile(t *testing.T) {+ p := newProvider(+ vcs.ProviderConfig{+ Client: &http.Client{+ Transport: &common.MockRoundTripper{+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {+ assert.Equal(t, "/api/v4/projects/1/merge_requests/1/changes", r.URL.Path)+ return &http.Response{+ StatusCode: http.StatusOK,+ // Example response taken from https://docs.gitlab.com/ee/api/merge_requests.html#get-single-mr-changes+ Body: io.NopCloser(strings.NewReader(`+{+ "id": 21,+ "iid": 1,+ "project_id": 4,+ "title": "Blanditiis beatae suscipit hic assumenda et molestias nisi asperiores repellat et.",+ "state": "reopened",+ "created_at": "2015-02-02T19:49:39.159Z",+ "updated_at": "2015-02-02T20:08:49.959Z",+ "target_branch": "secret_token",+ "source_branch": "version-1-9",+ "source_project_id": 4,+ "target_project_id": 4,+ "labels": [ ],+ "description": "Qui voluptatibus placeat ipsa alias quasi. Deleniti rem ut sint. Optio velit qui distinctio.",+ "draft": false,+ "work_in_progress": false,+ "merge_when_pipeline_succeeds": true,+ "merge_status": "can_be_merged",+ "subscribed" : true,+ "sha": "8888888888888888888888888888888888888888",+ "merge_commit_sha": null,+ "squash_commit_sha": null,+ "changes": [+ {+ "old_path": "VERSION",+ "new_path": "VERSION",+ "a_mode": "100644",+ "b_mode": "100644",+ "new_file": false,+ "renamed_file": false,+ "deleted_file": false+ }+ ],+ "overflow": false+}+`)),+ }, nil+ },+ },+ },+ },+ )+ ctx := context.Background()+ got, err := p.ListPullRequestFile(ctx, common.OauthContext{}, "", "1", "1")+ require.NoError(t, err)++ want := []*vcs.PullRequestFile{+ {+ Path: "VERSION",+ LastCommitID: "8888888888888888888888888888888888888888",+ IsDeleted: false,+ },+ }+ assert.Equal(t, want, got)+}diff --git a/plugin/vcs/gitlab/sql-review.yml b/plugin/vcs/gitlab/sql-review.ymlindex aa9fe5973f..a57558e98e 100644--- a/plugin/vcs/gitlab/sql-review.yml+++ b/plugin/vcs/gitlab/sql-review.yml@@ -9,12 +9,16 @@ sql-review:- apk update && apk add curl- apk update && apk add jqscript:- - echo "Start request $API/pull/$CI_MERGE_REQUEST_IID"- - 'response=$(curl -s --show-error -X GET "$API/pull/$CI_MERGE_REQUEST_IID" -H "Content-type: application/json" -H "X-SQL-Review-Token: $%s")'+ - echo "Start request $API"+ - request_body=$(jq -n --arg repositoryId "$CI_PROJECT_ID" --arg pullRequestId $CI_MERGE_REQUEST_IID --arg webURL "$CI_SERVER_URL" '$ARGS.named')+ - 'response=$(curl -s --show-error -X POST "$API" -H "Content-type: application/json" -H "X-SQL-Review-Token: $%s" -d "$request_body")'- echo $response- content=$(echo $response | jq -r '.content')+ - len=$(echo $content | jq '. | length')+ - if [ $len == 0 ]; then exit 0; fi+ - msg=$(echo $content | jq -r '.[0]')+ - echo $msg >> sql-review.xml- status=$(echo $response | jq -r '.status')- - for msg in $(echo $content | jq -r '.[]'); do echo $msg >> sql-review.xml; done- if [ "$status" == "ERROR" ]; then exit 1; fiartifacts:when: alwaysdiff --git a/plugin/vcs/gitlab/sql_review.go b/plugin/vcs/gitlab/sql_review.goindex 39bcf6584d..1d0d3ac8bd 100644--- a/plugin/vcs/gitlab/sql_review.go+++ b/plugin/vcs/gitlab/sql_review.go@@ -14,6 +14,11 @@ const (CIFilePath = ".gitlab-ci.yml"// SQLReviewCIFilePath is the local path for SQL review CI in GitLab repo.SQLReviewCIFilePath = ".gitlab/sql-review.yml"+ // sqlReviewCIFileRelativePathInGitLabCI is the keyword for relative path for SQL review CI file in .gitlab-ci.yml.+ sqlReviewCIFileRelativePathKeywordInGitLabCI = "local"+ // gitlabCIIncludeKeyword is the keyword for "include" in .gitlab-ci.yml+ // Docs for GitLab include syntax: https://docs.gitlab.com/ee/ci/yaml/includes.html+ gitlabCIIncludeKeyword = "include")// sqlReviewCI is the GitLab CI for SQL review in VCS workflow.@@ -28,21 +33,21 @@ func SetupSQLReviewCI(endpoint string) string {// SetupGitLabCI will update the GitLab CI content to add or update the SQL review CI.func SetupGitLabCI(gitlabCI map[string]interface{}) (string, error) {- if gitlabCI["sql-review"] == nil {- // Add include for SQL review CI- var includeList []interface{}- // Docs for GitLab include syntax: https://docs.gitlab.com/ee/ci/yaml/includes.html- switch include := gitlabCI["include"].(type) {- case []interface{}:- includeList = append(includeList, include...)- case string, interface{}:- includeList = append(includeList, include)- }+ // Add include for SQL review CI+ var includeList []interface{}+ // Docs for GitLab include syntax: https://docs.gitlab.com/ee/ci/yaml/includes.html+ switch include := gitlabCI[gitlabCIIncludeKeyword].(type) {+ case []interface{}:+ includeList = append(includeList, include...)+ case string, interface{}:+ includeList = append(includeList, include)+ }- includeList = append(includeList, map[string]string{"local": SQLReviewCIFilePath})- gitlabCI["include"] = includeList+ if _, ok := findSQLReviewCI(includeList); !ok {+ includeList = append(includeList, map[string]string{sqlReviewCIFileRelativePathKeywordInGitLabCI: SQLReviewCIFilePath})}+ gitlabCI[gitlabCIIncludeKeyword] = includeListnewContent, err := yaml.Marshal(gitlabCI)if err != nil {return "", err@@ -50,3 +55,15 @@ func SetupGitLabCI(gitlabCI map[string]interface{}) (string, error) {return string(newContent), nil}++func findSQLReviewCI(include []interface{}) (map[string]interface{}, bool) {+ for _, data := range include {+ if val, ok := data.(map[string]interface{}); ok {+ if val[sqlReviewCIFileRelativePathKeywordInGitLabCI] == SQLReviewCIFilePath {+ return val, true+ }+ }+ }++ return nil, false+}diff --git a/plugin/vcs/gitlab/sql_review_test.go b/plugin/vcs/gitlab/sql_review_test.goindex 1a29fb217b..790ddb460b 100644--- a/plugin/vcs/gitlab/sql_review_test.go+++ b/plugin/vcs/gitlab/sql_review_test.go@@ -40,18 +40,7 @@ func Test_SetupGitLabCI(t *testing.T) {include, ok := content["include"].([]interface{})assert.Equal(t, ok, true)- sqlReviewCI := findSQLReviewCI(include)+ sqlReviewCI, ok := findSQLReviewCI(include)+ assert.Equal(t, ok, true)assert.NotNil(t, sqlReviewCI)}--func findSQLReviewCI(include []interface{}) map[string]interface{} {- for _, data := range include {- if val, ok := data.(map[string]interface{}); ok {- if val["local"] == SQLReviewCIFilePath {- return val- }- }- }-- return nil-}diff --git a/plugin/vcs/vcs.go b/plugin/vcs/vcs.goindex 416f54eb8a..7fd2ccd6e2 100644--- a/plugin/vcs/vcs.go+++ b/plugin/vcs/vcs.go@@ -139,6 +139,13 @@ type Repository struct {WebURL string `json:"webUrl"`}+// PullRequestFile is the API message for file in the pull request.+type PullRequestFile struct {+ Path string+ LastCommitID string+ IsDeleted bool+}+// BranchInfo is the API message for repository branch.type BranchInfo struct {Name string@@ -254,6 +261,8 @@ type Provider interface {// oauthCtx: OAuth context to create the webhook// instanceURL: VCS instance URL// repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)+ // pullRequestID: the pull request id+ ListPullRequestFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, pullRequestID string) ([]*PullRequestFile, error)// pullRequestCreate: the new pull request infoCreatePullRequest(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, pullRequestCreate *PullRequestCreate) error// UpsertEnvironmentVariable creates or updates the environment variable in the repository.diff --git a/server/project.go b/server/project.goindex b9a588df22..8bfa23b8a1 100644--- a/server/project.go+++ b/server/project.go@@ -613,13 +613,15 @@ func (s *Server) setupVCSSQLReviewCI(ctx context.Context, repository *api.Reposireturn err}+ sqlReviewEndpoint := fmt.Sprintf("%s/hook/sql-review/%s", s.profile.ExternalURL, repository.WebhookEndpointID)+switch repository.VCS.Type {case vcsPlugin.GitHubCom:- if err := s.setupVCSSQLReviewCIForGitHub(ctx, repository, branch); err != nil {+ if err := s.setupVCSSQLReviewCIForGitHub(ctx, repository, branch, sqlReviewEndpoint); err != nil {return err}case vcsPlugin.GitLabSelfHost:- if err := s.setupVCSSQLReviewCIForGitLab(ctx, repository, branch); err != nil {+ if err := s.setupVCSSQLReviewCIForGitLab(ctx, repository, branch, sqlReviewEndpoint); err != nil {return err}}@@ -689,8 +691,7 @@ func (s *Server) setupVCSSQLReviewBranch(ctx context.Context, repository *api.Re}// setupVCSSQLReviewCIForGitHub will create the pull request in GitHub to setup SQL review action.-func (s *Server) setupVCSSQLReviewCIForGitHub(ctx context.Context, repository *api.Repository, branch *vcsPlugin.BranchInfo) error {- sqlReviewEndpoint := fmt.Sprintf("%s/hook/sql-review/%d", s.profile.ExternalURL, repository.ProjectID)+func (s *Server) setupVCSSQLReviewCIForGitHub(ctx context.Context, repository *api.Repository, branch *vcsPlugin.BranchInfo, sqlReviewEndpoint string) error {sqlReviewConfig := github.SetupSQLReviewCI(sqlReviewEndpoint)fileLastCommitID := ""@@ -742,7 +743,7 @@ func (s *Server) setupVCSSQLReviewCIForGitHub(ctx context.Context, repository *a}// setupVCSSQLReviewCIForGitLab will create or update SQL review related files in GitLab to setup SQL review CI.-func (s *Server) setupVCSSQLReviewCIForGitLab(ctx context.Context, repository *api.Repository, branch *vcsPlugin.BranchInfo) error {+func (s *Server) setupVCSSQLReviewCIForGitLab(ctx context.Context, repository *api.Repository, branch *vcsPlugin.BranchInfo, sqlReviewEndpoint string) error {// create or update the .gitlab-ci.ymlif err := s.createOrUpdateVCSSQLReviewFileForGitLab(ctx, repository, branch, gitlab.CIFilePath, func(fileMeta *vcsPlugin.FileMeta) (string, error) {content := make(map[string]interface{})@@ -782,7 +783,6 @@ func (s *Server) setupVCSSQLReviewCIForGitLab(ctx context.Context, repository *a// create or update the SQL review CI.return s.createOrUpdateVCSSQLReviewFileForGitLab(ctx, repository, branch, gitlab.SQLReviewCIFilePath, func(_ *vcsPlugin.FileMeta) (string, error) {- sqlReviewEndpoint := fmt.Sprintf("%s/hook/sql-review/%d", s.profile.ExternalURL, repository.ProjectID)return gitlab.SetupSQLReviewCI(sqlReviewEndpoint), nil})}