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: auto-create the pipeline and policy for Azure DevOps SQL review (#7378)
ecmadao1421e9574264
diff --git a/backend/plugin/vcs/azure/azure.go b/backend/plugin/vcs/azure/azure.goindex e643fc8031..c6d7f4df2f 100644--- a/backend/plugin/vcs/azure/azure.go+++ b/backend/plugin/vcs/azure/azure.go@@ -222,6 +222,7 @@ func (p *Provider) ExchangeOAuthToken(ctx context.Context, _ string, oauthExchantype ChangesResponseChangeItem struct {GitObjectType string `json:"gitObjectType"`Path string `json:"path"`+ CommitID string `json:"commitId"`}// ChangesResponseChange represents a Azure DevOps changes response change.@@ -1155,79 +1156,18 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx common.Oautreturn nil, err}- return p.listChangedFilesInCommit(ctx, oauthCtx, repositoryID, res.LastMergeCommit.CommitID)-}--// listChangedFilesInCommit lists the changed files in the commit.-//-// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/commits/get-changes?view=azure-devops-rest-7.1&tabs=HTTP-func (p *Provider) listChangedFilesInCommit(ctx context.Context, oauthCtx common.OauthContext, repositoryID, commitID string) ([]*vcs.PullRequestFile, error) {- type changeItem struct {- GitObjectType string `json:"gitObjectType"`- Path string `json:"path"`- CommitID string `json:"commitId"`- }- type commitChange struct {- Item *changeItem `json:"item"`- ChangeType string `json:"changeType"`- }- type commitChangeResponse struct {- Changes []*commitChange `json:"changes"`- }-- apiURL, err := getRepositoryAPIURL(repositoryID)+ changeResponse, err := GetChangesByCommit(ctx, oauthCtx, repositoryID, res.LastMergeCommit.CommitID)if err != nil {return nil, err}-- urlParams := &url.Values{}- urlParams.Set("api-version", "7.0")- url := fmt.Sprintf("%s/commits/%s/changes?%s", apiURL, commitID, urlParams.Encode())-- code, _, resp, err := oauth.Get(- ctx,- p.client,- url,- &oauthCtx.AccessToken,- tokenRefresher(- oauthContext{- RefreshToken: oauthCtx.RefreshToken,- ClientSecret: oauthCtx.ClientSecret,- RedirectURL: oauthCtx.RedirectURL,- },- 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 create merge request from URL %s", url)- } else if code >= 300 {- return nil, errors.Errorf("failed to create merge request from URL %s, status code: %d, body: %s",- url,- code,- resp,- )- }-- var res commitChangeResponse- if err := json.Unmarshal([]byte(resp), &res); err != nil {- return nil, err- }-files := []*vcs.PullRequestFile{}- for _, change := range res.Changes {- if change.Item.GitObjectType != "blob" {- continue- }+ for _, change := range changeResponse.Changes {files = append(files, &vcs.PullRequestFile{Path: change.Item.Path,LastCommitID: change.Item.CommitID,IsDeleted: change.ChangeType == "delete",})}-return files, nil}diff --git a/backend/plugin/vcs/azure/sql_review.go b/backend/plugin/vcs/azure/sql_review.goindex a6eed0c949..78235edca8 100644--- a/backend/plugin/vcs/azure/sql_review.go+++ b/backend/plugin/vcs/azure/sql_review.go@@ -1,8 +1,19 @@package azureimport (+ "bytes"+ "context"_ "embed"+ "encoding/json""fmt"+ "net/http"+ "net/url"+ "strings"++ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/plugin/vcs/internal/oauth")// sqlReviewPipeline is the Azure pipeline for SQL review in VCS workflow.@@ -13,11 +24,204 @@ var sqlReviewPipeline stringconst (// SQLReviewPipelineFilePath is the SQL review pipeline file path.SQLReviewPipelineFilePath = ".pipelines/pipeline.bytebase-sql-review.yml"+ // sqlReviewPipelineName is the pipeline name for SQL review.+ sqlReviewPipelineName = "Bytebase SQL Review")// SetupSQLReviewCI will setup the SQL review CI content with SQL review endpoint.-// Users need to enable the branch policy to trigger pipeline in the pull request.-// https://learn.microsoft.com/en-us/azure/devops/pipelines/repos/azure-repos-git?view=azure-devops&tabs=yaml#pr-triggersfunc SetupSQLReviewCI(endpoint, branch, token string) string {return fmt.Sprintf(sqlReviewPipeline, endpoint, branch, token)}++type pipeline struct {+ ID int `jsno:"id"`+ Name string `jsno:"name"`+}++type pipelineCreate struct {+ Name string `json:"name"`+ Configuration *pipelineConfig `json:"configuration"`+}++type pipelineRepository struct {+ ID string `json:"id"`+ Type string `json:"type"`+}++type pipelineConfig struct {+ Type string `json:"type"`+ Path string `json:"path"`+ Repository *pipelineRepository `json:"repository"`+}++type branchPolicyCreate struct {+ IsBlocking bool `json:"isBlocking"`+ IsDeleted bool `json:"isDeleted"`+ IsEnabled bool `json:"isEnabled"`+ Settings *branchPolicySetting `json:"settings"`+ Type *policy `json:"type"`+}++type branchPolicySetting struct {+ // BuildDefinitionID is the pipeline ID.+ BuildDefinitionID int `json:"buildDefinitionId"`+ DisplayName string `json:"displayName"`+ ManualQueueOnly bool `json:"manualQueueOnly"`+ QueueOnSourceUpdateOnly bool `json:"queueOnSourceUpdateOnly"`+ Scope []*branchPolicyScope `json:"scope"`+ // ValidDuration is the expiration in hours for build artifacts.+ ValidDuration int `json:"validDuration"`+}++type branchPolicyScope struct {+ // MatchKind should always be "Exact"+ MatchKind string `json:"matchKind"`+ // RefName is the target branch name.+ RefName string `json:"refName"`+ RepositoryID string `json:"repositoryId"`+}++// policy is the API message for azure policy.+// It is hard code with specific id.+// We can check all the policies in docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/pipelines/pipelines/list?view=azure-devops-rest-7.1+// For branch validation policy, we will hardcode the id as "0609b952-1397-4640-95ec-e00a01b2c241".+type policy struct {+ ID string `json:"id"`+}++// EnableSQLReviewCI enables the SQL review pipeline and policy.+func EnableSQLReviewCI(ctx context.Context, oauthCtx common.OauthContext, repositoryID, branch string) error {+ pipeline, err := createSQLReviewPipeline(ctx, oauthCtx, repositoryID)+ if err != nil {+ return err+ }+ return createSQLReviewBranchPolicy(ctx, oauthCtx, repositoryID, branch, pipeline.ID)+}++// createSQLReviewPipeline creates the SQL Review pipeline.+//+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/pipelines/pipelines/create?view=azure-devops-rest-7.1+func createSQLReviewPipeline(ctx context.Context, oauthCtx common.OauthContext, repositoryID string) (*pipeline, error) {+ parts := strings.Split(repositoryID, "/")+ if len(parts) != 3 {+ return nil, errors.Errorf("invalid repository ID %q", repositoryID)+ }++ values := &url.Values{}+ values.Set("api-version", "7.1-preview.1")++ client := &http.Client{}+ apiURL := fmt.Sprintf("https://dev.azure.com/%s/%s/_apis/pipelines?%s", url.PathEscape(parts[0]), url.PathEscape(parts[1]), values.Encode())+ payload := &pipelineCreate{+ Name: sqlReviewPipelineName,+ Configuration: &pipelineConfig{+ Type: "yaml",+ Path: SQLReviewPipelineFilePath,+ Repository: &pipelineRepository{+ ID: parts[2],+ Type: "azureReposGit",+ },+ },+ }++ body, err := json.Marshal(payload)+ if err != nil {+ return nil, errors.Wrap(err, "marshal branch create")+ }++ code, _, resp, err := oauth.Post(+ ctx,+ client,+ apiURL,+ &oauthCtx.AccessToken,+ bytes.NewReader(body),+ tokenRefresher(+ oauthContext{+ RefreshToken: oauthCtx.RefreshToken,+ ClientSecret: oauthCtx.ClientSecret,+ RedirectURL: oauthCtx.RedirectURL,+ },+ oauthCtx.Refresher,+ ),+ )+ if err != nil {+ return nil, errors.Wrapf(err, "POST %s", apiURL)+ }+ if code != 200 {+ return nil, errors.Errorf("non-200 POST %s status code %d with body %q", apiURL, code, string(resp))+ }++ result := new(pipeline)+ if err := json.Unmarshal([]byte(resp), result); err != nil {+ return nil, errors.Wrapf(err, "failed to unmarshal response body")+ }++ return result, nil+}++// createSQLReviewPolicy creates the SQL Review policy.+//+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/policy/configurations/create?view=azure-devops-rest-7.0+func createSQLReviewBranchPolicy(ctx context.Context, oauthCtx common.OauthContext, repositoryID, branch string, pipelineID int) error {+ parts := strings.Split(repositoryID, "/")+ if len(parts) != 3 {+ return errors.Errorf("invalid repository ID %q", repositoryID)+ }++ values := &url.Values{}+ values.Set("api-version", "7.1-preview.1")++ client := &http.Client{}+ apiURL := fmt.Sprintf("https://dev.azure.com/%s/%s/_apis/policy/configurations?%s", url.PathEscape(parts[0]), url.PathEscape(parts[1]), values.Encode())+ payload := &branchPolicyCreate{+ IsBlocking: true,+ IsDeleted: false,+ IsEnabled: true,+ Settings: &branchPolicySetting{+ BuildDefinitionID: pipelineID,+ DisplayName: sqlReviewPipelineName,+ ManualQueueOnly: false,+ QueueOnSourceUpdateOnly: true,+ ValidDuration: 720,+ Scope: []*branchPolicyScope{+ {+ MatchKind: "Exact",+ RefName: fmt.Sprintf("refs/heads/%s", branch),+ RepositoryID: parts[2],+ },+ },+ },+ Type: &policy{+ ID: "0609b952-1397-4640-95ec-e00a01b2c241",+ },+ }++ body, err := json.Marshal(payload)+ if err != nil {+ return errors.Wrap(err, "marshal policy create")+ }++ code, _, resp, err := oauth.Post(+ ctx,+ client,+ apiURL,+ &oauthCtx.AccessToken,+ bytes.NewReader(body),+ tokenRefresher(+ oauthContext{+ RefreshToken: oauthCtx.RefreshToken,+ ClientSecret: oauthCtx.ClientSecret,+ RedirectURL: oauthCtx.RedirectURL,+ },+ oauthCtx.Refresher,+ ),+ )+ if err != nil {+ return errors.Wrapf(err, "POST %s", apiURL)+ }+ if code != 200 {+ return errors.Errorf("non-200 POST %s status code %d with body %q", apiURL, code, string(resp))+ }++ return nil+}diff --git a/frontend/src/components/VCSProviderOAuthPanel.vue b/frontend/src/components/VCSProviderOAuthPanel.vueindex 80f14b0d32..d042d8b7fd 100644--- a/frontend/src/components/VCSProviderOAuthPanel.vue+++ b/frontend/src/components/VCSProviderOAuthPanel.vue@@ -490,7 +490,8 @@</dt><!-- TODO: decide necessary scopes --><dd class="text-sm text-main">- Code (full), Identity (read), Project and team (read)+ Code (full), Identity (read), Project and team (read), Build+ (read and execute)</dd></div></dl>diff --git a/frontend/src/types/oauth.ts b/frontend/src/types/oauth.tsindex b9ad49c5c7..fab04e59c3 100644--- a/frontend/src/types/oauth.ts+++ b/frontend/src/types/oauth.ts@@ -76,7 +76,8 @@ export function openWindowForOAuth(// Scopes for Azure: https://learn.microsoft.com/zh-cn/azure/devops/integrate/get-started/authentication/oauth?view=azure-devops#scopes// We need full scopes in the application: https://stackoverflow.com/questions/56143321/azure-devops-oauth-enpoint-always-returns-error-invalidscope// TODO: decide necessary scopes- endpointQueryParams["scope"] = "vso.code_full vso.identity vso.project";+ endpointQueryParams["scope"] =+ "vso.code_full vso.identity vso.project vso.build_execute";endpointQueryParams["response_type"] = "Assertion";windowOpenOptions ="location=yes,left=200,top=200,height=640,width=720,scrollbars=yes,status=yes";