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(vcs): GitOps workflow setup/update should verify if the branch exists (#3396)
ZhengX807c700146f6
diff --git a/server/project.go b/server/project.goindex 5ecf41b646..f6764cca09 100644--- a/server/project.go+++ b/server/project.go@@ -235,7 +235,9 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {if repositoryCreate.BranchFilter == "" {return echo.NewHTTPError(http.StatusBadRequest, "Branch must be specified.")}- if strings.Contains(repositoryCreate.BranchFilter, "*") && repositoryCreate.SchemaPathTemplate != "" {++ hasWildcard := strings.Contains(repositoryCreate.BranchFilter, "*")+ if hasWildcard && repositoryCreate.SchemaPathTemplate != "" {return echo.NewHTTPError(http.StatusBadRequest, "Schema path template is supported only if branch doesn't have wildcard.")}@@ -269,6 +271,15 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("VCS not found with ID: %d", repositoryCreate.VCSID))}+ // When the branch names doesn't contain wildcards, we should make sure the branch exists in the repo.+ if !hasWildcard {+ if notFound, err := isBranchNotFound(ctx, vcs, repositoryCreate.AccessToken, repositoryCreate.RefreshToken, repositoryCreate.ExternalID, repositoryCreate.BranchFilter); notFound {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Branch %q not found in repository %s.", repositoryCreate.BranchFilter, repositoryCreate.Name)).SetInternal(err)+ } else if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get branch %q", repositoryCreate.BranchFilter)).SetInternal(err)+ }+ }+// For a particular VCS repo, all Bytebase projects share the same webhook.repositories, err := s.store.FindRepository(ctx, &api.RepositoryFind{WebURL: &repositoryCreate.WebURL,@@ -476,10 +487,29 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {if newBranchFilter == "" {return echo.NewHTTPError(http.StatusBadRequest, "Branch must be specified.")}- if strings.Contains(newBranchFilter, "*") && newSchemaPathTemplate != "" {++ hasWildcard := strings.Contains(newBranchFilter, "*")+ if hasWildcard && newSchemaPathTemplate != "" {return echo.NewHTTPError(http.StatusBadRequest, "Schema path template is supported only if branch doesn't have wildcard.")}+ vcs, err := s.store.GetVCSByID(ctx, repo.VCSID)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find VCS for creating repository: %d", repo.VCSID)).SetInternal(err)+ }+ if vcs == nil {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("VCS not found with ID: %d", repo.VCSID))+ }++ // When the branch names doesn't contain wildcards, we should make sure the branch exists in the repo.+ if !hasWildcard {+ if notFound, err := isBranchNotFound(ctx, vcs, repo.AccessToken, repo.RefreshToken, repo.ExternalID, newBranchFilter); notFound {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Branch %q not found in repository %s.", newBranchFilter, repo.Name)).SetInternal(err)+ } else if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get branch %q", newBranchFilter)).SetInternal(err)+ }+ }+// We need to check the FilePathTemplate in create repository request.// This avoids to a certain extent that the creation succeeds but does not work.newBaseDirectory, newFilePathTemplate := repo.BaseDirectory, repo.FilePathTemplate@@ -1207,3 +1237,20 @@ func refreshTokenNoop() common.TokenRefresher {return nil}}++func isBranchNotFound(ctx context.Context, vcs *api.VCS, accessToken, refreshToken, externalID, branch string) (bool, error) {+ _, err := vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{}).GetBranch(ctx,+ common.OauthContext{+ ClientID: vcs.ApplicationID,+ ClientSecret: vcs.Secret,+ AccessToken: accessToken,+ RefreshToken: refreshToken,+ Refresher: nil,+ },+ vcs.InstanceURL, externalID, branch)++ if common.ErrorCode(err) == common.NotFound {+ return true, nil+ }+ return false, err+}diff --git a/tests/schema_update_test.go b/tests/schema_update_test.goindex 7bfaf7782f..2e66df901d 100644--- a/tests/schema_update_test.go+++ b/tests/schema_update_test.go@@ -396,6 +396,11 @@ func TestVCS(t *testing.T) {// Create a repository.ctl.vcsProvider.CreateRepository(test.externalID)++ // Create the branch+ err = ctl.vcsProvider.CreateBranch(test.externalID, "feature/foo")+ a.NoError(err)+_, err = ctl.createRepository(api.RepositoryCreate{VCSID: apiVCS.ID,@@ -1639,6 +1644,192 @@ func TestVCS_SQL_Review(t *testing.T) {}}+func TestBranchNameInVCSSetupAndUpdate(t *testing.T) {+ type testCase struct {+ name string+ existedBranchList []string+ branchFilter string+ want bool+ }+ type vcsTestCase struct {+ vcsType vcs.Type+ vcsProviderCreator fake.VCSProviderCreator+ externalID string+ repoFullPath string+ caseList []testCase+ }++ tests := []vcsTestCase{+ {+ vcsType: vcs.GitLabSelfHost,+ vcsProviderCreator: fake.NewGitLab,+ externalID: "1234",+ repoFullPath: "1234",+ caseList: []testCase{+ {+ name: "mainBranchWithGitLab",+ existedBranchList: []string{+ "main",+ "test/branch",+ },+ branchFilter: "main",+ want: false,+ }, {+ name: "customBranchWithGitLab",+ existedBranchList: []string{+ "main",+ "test/branch",+ },+ branchFilter: "test/branch",+ want: false,+ }, {+ name: "nonExistedBranchWithGitLab",+ existedBranchList: []string{+ "main",+ "test/branch",+ },+ branchFilter: "non_existed_branch",+ want: true,+ }, {+ name: "wildcardBranchWithGitLab",+ existedBranchList: []string{+ "main",+ },+ branchFilter: "main*",+ want: false,+ },+ },+ },+ {+ vcsType: vcs.GitHubCom,+ vcsProviderCreator: fake.NewGitHub,+ externalID: "test/branch",+ repoFullPath: "test/branch",+ caseList: []testCase{+ {+ name: "mainBranchWithGitHub",+ existedBranchList: []string{+ "main",+ "test/branch",+ },+ branchFilter: "main",+ want: false,+ }, {+ name: "customBranchWithGitHub",+ existedBranchList: []string{+ "main",+ "test/branch",+ },+ branchFilter: "test/branch",+ want: false,+ }, {+ name: "nonExistedBranchWithGitHub",+ existedBranchList: []string{+ "main",+ "test/branch",+ },+ branchFilter: "non_existed_branch",+ want: true,+ }, {+ name: "wildcardBranchWithGitHub",+ existedBranchList: []string{+ "main",+ },+ branchFilter: "main*",+ want: false,+ },+ },+ },+ }++ for _, vcsTest := range tests {+ // Wrap the defer statement in an anonymous func to make it work properly.+ (func() {+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}++ // Create a server.+ err := ctl.StartServer(ctx, &config{+ dataDir: t.TempDir(),+ vcsProviderCreator: vcsTest.vcsProviderCreator,+ })+ a.NoError(err)++ defer func() {+ _ = ctl.Close(ctx)+ }()++ err = ctl.Login()+ a.NoError(err)+ err = ctl.setLicense()+ a.NoError(err)++ // Create a VCS.+ apiVCS, err := ctl.createVCS(+ api.VCSCreate{+ Name: "testName",+ Type: vcsTest.vcsType,+ InstanceURL: ctl.vcsURL,+ APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),+ ApplicationID: "testID",+ Secret: "testSecret",+ },+ )+ a.NoError(err)++ // Create a project.+ project, err := ctl.createProject(+ api.ProjectCreate{+ Name: "Test VSC Project",+ Key: "TVP",+ },+ )+ a.NoError(err)++ for _, test := range vcsTest.caseList {+ test := test+ t.Run(test.name, func(t *testing.T) {+ // Create a repository in the fake vsc provider.+ ctl.vcsProvider.CreateRepository(vcsTest.externalID)++ // Create existed branches.+ for _, existedBranch := range test.existedBranchList {+ err := ctl.vcsProvider.CreateBranch(vcsTest.externalID, existedBranch)+ a.NoError(err)+ }++ // Create a repository.+ _, err = ctl.createRepository(+ api.RepositoryCreate{+ VCSID: apiVCS.ID,+ ProjectID: project.ID,+ Name: "Test Repository",+ FullPath: vcsTest.repoFullPath,+ WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, vcsTest.repoFullPath),+ BranchFilter: test.branchFilter,+ BaseDirectory: "",+ FilePathTemplate: "{{ENV_NAME}}/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",+ SchemaPathTemplate: "",+ ExternalID: vcsTest.externalID,+ AccessToken: "accessToken1",+ RefreshToken: "refreshToken1",+ },+ )++ if test.want {+ a.Error(err)+ } else {+ a.NoError(err)+ err = ctl.unlinkRepository(project.ID)+ a.NoError(err)+ }+ })+ }+ })()+ }+}+// postVCSSQLReview will create the VCS SQL review and get the response.func postVCSSQLReview(ctl *controller, repo *api.Repository, request *api.VCSSQLReviewRequest) (*api.VCSSQLReviewResult, error) {url := fmt.Sprintf("%s/hook/sql-review/%s", ctl.rootURL, repo.WebhookEndpointID)diff --git a/tests/sheet_vcs_test.go b/tests/sheet_vcs_test.goindex 0d7aad8ef4..143e72aafa 100644--- a/tests/sheet_vcs_test.go+++ b/tests/sheet_vcs_test.go@@ -83,6 +83,11 @@ func TestSheetVCS(t *testing.T) {// Create a repository.ctl.vcsProvider.CreateRepository(test.externalID)++ // Create the branch+ err = ctl.vcsProvider.CreateBranch(test.externalID, "feature/foo")+ a.NoError(err)+_, err = ctl.createRepository(api.RepositoryCreate{VCSID: vcs.ID,diff --git a/tests/tenant_test.go b/tests/tenant_test.goindex 2256dc67cd..f7938eb7a0 100644--- a/tests/tenant_test.go+++ b/tests/tenant_test.go@@ -328,6 +328,11 @@ func TestTenantVCS(t *testing.T) {// Create a repository.ctl.vcsProvider.CreateRepository(test.externalID)++ // Create the branch+ err = ctl.vcsProvider.CreateBranch(test.externalID, "feature/foo")+ a.NoError(err)+_, err = ctl.createRepository(api.RepositoryCreate{VCSID: apiVCS.ID,@@ -794,6 +799,11 @@ func TestTenantVCSDatabaseNameTemplate(t *testing.T) {// Create a repository.ctl.vcsProvider.CreateRepository(test.externalID)++ // Create the branch+ err = ctl.vcsProvider.CreateBranch(test.externalID, "feature/foo")+ a.NoError(err)+_, err = ctl.createRepository(api.RepositoryCreate{VCSID: apiVCS.ID,@@ -1132,6 +1142,11 @@ func TestTenantVCSDatabaseNameTemplate_Empty(t *testing.T) {// Create a repository.ctl.vcsProvider.CreateRepository(test.externalID)++ // Create the branch+ err = ctl.vcsProvider.CreateBranch(test.externalID, "feature/foo")+ a.NoError(err)+_, err = ctl.createRepository(api.RepositoryCreate{VCSID: apiVCS.ID,@@ -1413,6 +1428,11 @@ func TestTenantVCS_YAML(t *testing.T) {// Create a repository.ctl.vcsProvider.CreateRepository(test.externalID)++ // Create the branch+ err = ctl.vcsProvider.CreateBranch(test.externalID, "feature/foo")+ require.NoError(t, err)+_, err = ctl.createRepository(api.RepositoryCreate{VCSID: apiVCS.ID,diff --git a/tests/tests.go b/tests/tests.goindex 4b7d691da1..1dda5729c0 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -1035,7 +1035,7 @@ func (ctl *controller) createVCS(vcsCreate api.VCSCreate) (*api.VCS, error) {return vcs, nil}-// createRepository creates a repository.+// createRepository links the repository with the project.func (ctl *controller) createRepository(repositoryCreate api.RepositoryCreate) (*api.Repository, error) {buf := new(bytes.Buffer)if err := jsonapi.MarshalPayload(buf, &repositoryCreate); err != nil {@@ -1054,6 +1054,15 @@ func (ctl *controller) createRepository(repositoryCreate api.RepositoryCreate) (return repository, nil}+// unlinkRepository unlinks the repository from the project by projectID.+func (ctl *controller) unlinkRepository(projectID int) error {+ _, err := ctl.delete(fmt.Sprintf("/project/%d/repository", projectID), nil)+ if err != nil {+ return err+ }+ return nil+}+// listRepository gets the repository list.func (ctl *controller) listRepository(projectID int) ([]*api.Repository, error) {body, err := ctl.get(fmt.Sprintf("/project/%d/repository", projectID), nil)