Skip to content

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

chore: update vcs test (#11502)

ecmadaof633b7a54175
diff --git a/backend/api/v1/vcs_provider_service.go b/backend/api/v1/vcs_provider_service.go
index 10b827228d..6f8c2f5c08 100644
--- a/backend/api/v1/vcs_provider_service.go
+++ b/backend/api/v1/vcs_provider_service.go
@@ -11,7 +11,6 @@ import (
"google.golang.org/protobuf/types/known/emptypb"
"github.com/bytebase/bytebase/backend/common"
- "github.com/bytebase/bytebase/backend/component/config"
"github.com/bytebase/bytebase/backend/plugin/vcs"
"github.com/bytebase/bytebase/backend/store"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
@@ -21,13 +20,12 @@ import (
// VCSProviderService represents a service for managing vcs provider.
type VCSProviderService struct {
v1pb.UnimplementedVCSProviderServiceServer
- store *store.Store
- profile *config.Profile
+ store *store.Store
}
// NewVCSProviderService returns a new instance of VCSProviderService.
-func NewVCSProviderService(store *store.Store, profile *config.Profile) *VCSProviderService {
- return &VCSProviderService{store: store, profile: profile}
+func NewVCSProviderService(store *store.Store) *VCSProviderService {
+ return &VCSProviderService{store: store}
}
// GetVCSProvider get a single vcs provider.
@@ -66,14 +64,8 @@ func (s *VCSProviderService) CreateVCSProvider(ctx context.Context, request *v1p
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, err.Error())
}
- // TODO(ed): add test and remove this
- if s.profile.Mode != common.ReleaseModeDev {
- if _, err := vcs.Get(
- vcsProvider.Type,
- vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken},
- ).FetchRepositoryList(ctx, false); err != nil {
- return nil, status.Errorf(codes.InvalidArgument, "failed to fetch repositories, please check if the token has right permissions: %v", err)
- }
+ if err := checkAccessTokenPermission(ctx, vcsProvider.Type, vcsProvider.InstanceURL, vcsProvider.AccessToken); err != nil {
+ return nil, err
}
principalID, ok := ctx.Value(common.PrincipalIDContextKey).(int)
@@ -110,15 +102,8 @@ func (s *VCSProviderService) UpdateVCSProvider(ctx context.Context, request *v1p
return nil, status.Errorf(codes.InvalidArgument, "secret should not be empty")
}
update.AccessToken = &request.VcsProvider.AccessToken
- // TODO(ed): add test and remove this
- if s.profile.Mode != common.ReleaseModeDev {
- vcsProvider.AccessToken = request.VcsProvider.AccessToken
- if _, err := vcs.Get(
- vcsProvider.Type,
- vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken},
- ).FetchRepositoryList(ctx, false); err != nil {
- return nil, status.Errorf(codes.InvalidArgument, "failed to fetch repositories, please check if the token has right permissions: %v", err)
- }
+ if err := checkAccessTokenPermission(ctx, vcsProvider.Type, vcsProvider.InstanceURL, request.VcsProvider.AccessToken); err != nil {
+ return nil, err
}
}
}
@@ -216,6 +201,16 @@ func (s *VCSProviderService) getVCS(ctx context.Context, name string) (*store.VC
return vcsProvider, nil
}
+func checkAccessTokenPermission(ctx context.Context, vcsType storepb.VCSType, instanceURL, token string) error {
+ if _, err := vcs.Get(
+ vcsType,
+ vcs.ProviderConfig{InstanceURL: instanceURL, AuthToken: token},
+ ).FetchRepositoryList(ctx, false); err != nil {
+ return status.Errorf(codes.InvalidArgument, "failed to fetch repositories, please check if the token has right permissions: %v", err)
+ }
+ return nil
+}
+
func convertToVCSProviders(vcsProviders []*store.VCSProviderMessage) []*v1pb.VCSProvider {
var res []*v1pb.VCSProvider
for _, vcsProvider := range vcsProviders {
diff --git a/backend/plugin/vcs/bitbucket/bitbucket.go b/backend/plugin/vcs/bitbucket/bitbucket.go
index 95b7626741..59dec1b57c 100644
--- a/backend/plugin/vcs/bitbucket/bitbucket.go
+++ b/backend/plugin/vcs/bitbucket/bitbucket.go
@@ -130,7 +130,7 @@ type Repository struct {
// RepositoryPermission represents a Bitbucket Cloud API response for a
// repository permission.
type RepositoryPermission struct {
- Repository Repository `json:"repository"`
+ Repository *Repository `json:"repository"`
}
// FetchRepositoryList fetches all repositories where the authenticated user
diff --git a/backend/plugin/vcs/gitlab/gitlab.go b/backend/plugin/vcs/gitlab/gitlab.go
index a8f7688b32..fd42edc9d3 100644
--- a/backend/plugin/vcs/gitlab/gitlab.go
+++ b/backend/plugin/vcs/gitlab/gitlab.go
@@ -136,8 +136,8 @@ type CommitsDiff struct {
FileDiffList []MergeRequestFile `json:"diffs"`
}
-// gitLabRepository represents a GitLab API response for a repository.
-type gitLabRepository struct {
+// Repository represents a GitLab API response for a repository.
+type Repository struct {
ID int64 `json:"id"`
Name string `json:"name"`
PathWithNamespace string `json:"path_with_namespace"`
@@ -169,7 +169,7 @@ func (*Provider) APIURL(instanceURL string) string {
//
// Docs: https://docs.gitlab.com/ee/api/projects.html#list-all-projects
func (p *Provider) FetchRepositoryList(ctx context.Context, listAll bool) ([]*vcs.Repository, error) {
- var gitlabRepos []gitLabRepository
+ var gitlabRepos []Repository
page := 1
for {
repos, hasNextPage, err := p.fetchPaginatedRepositoryList(ctx, page)
@@ -201,7 +201,7 @@ func (p *Provider) FetchRepositoryList(ctx context.Context, listAll bool) ([]*vc
// fetchPaginatedRepositoryList fetches repositories where the authenticated
// user has a maintainer role in given page. It return the paginated results
// along with a boolean indicating whether the next page exists.
-func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, page int) (repos []gitLabRepository, hasNextPage bool, err error) {
+func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, page int) (repos []Repository, hasNextPage bool, err error) {
// We will use user's token to create webhook in the project, which requires the
// token owner to be at least the project maintainer(40).
url := fmt.Sprintf("%s/projects?membership=true&simple=true&min_access_level=40&page=%d&per_page=%d", p.APIURL(p.instanceURL), page, apiPageSize)
diff --git a/backend/server/grpc_routes.go b/backend/server/grpc_routes.go
index 7399c6a300..31862621e8 100644
--- a/backend/server/grpc_routes.go
+++ b/backend/server/grpc_routes.go
@@ -75,7 +75,7 @@ func configureGrpcRouters(
v1pb.RegisterSettingServiceServer(grpcServer, apiv1.NewSettingService(stores, profile, licenseService, stateCfg))
v1pb.RegisterAnomalyServiceServer(grpcServer, apiv1.NewAnomalyService(stores))
v1pb.RegisterSQLServiceServer(grpcServer, apiv1.NewSQLService(stores, schemaSyncer, dbFactory, activityManager, licenseService, profile, iamManager))
- v1pb.RegisterVCSProviderServiceServer(grpcServer, apiv1.NewVCSProviderService(stores, profile))
+ v1pb.RegisterVCSProviderServiceServer(grpcServer, apiv1.NewVCSProviderService(stores))
v1pb.RegisterRiskServiceServer(grpcServer, apiv1.NewRiskService(stores, licenseService))
issueService := apiv1.NewIssueService(stores, activityManager, relayRunner, stateCfg, licenseService, profile, iamManager, metricReporter)
v1pb.RegisterIssueServiceServer(grpcServer, issueService)
diff --git a/backend/tests/fake/bitbucket.go b/backend/tests/fake/bitbucket.go
index 1b6ff2ad0f..ef2cdb7a2b 100644
--- a/backend/tests/fake/bitbucket.go
+++ b/backend/tests/fake/bitbucket.go
@@ -30,7 +30,8 @@ type Bitbucket struct {
}
type bitbucketRepositoryData struct {
- webhooks []*bitbucket.WebhookCreateOrUpdate
+ repository *bitbucket.Repository
+ webhooks []*bitbucket.WebhookCreateOrUpdate
// files is a map that the full file path is the key and the file content is the
// value.
files map[string]string
@@ -59,6 +60,7 @@ func NewBitbucket(port int) VCSProvider {
}
g := e.Group("/2.0")
+ g.GET("/user/permissions/repositories", bb.listRepositories)
g.POST("/repositories/:owner/:repo/hooks", bb.createRepositoryWebhook)
g.GET("/repositories/:owner/:repo/commit/:commitID", bb.getRepositoryCommit)
g.GET("/repositories/:owner/:repo/src/:ref/:filepath", bb.getRepositoryContent)
@@ -70,6 +72,24 @@ func NewBitbucket(port int) VCSProvider {
return bb
}
+func (bb *Bitbucket) listRepositories(c echo.Context) error {
+ var resp struct {
+ Values []*bitbucket.RepositoryPermission `json:"values"`
+ Next string `json:"next"`
+ }
+
+ for _, repoData := range bb.repositories {
+ resp.Values = append(resp.Values, &bitbucket.RepositoryPermission{
+ Repository: repoData.repository,
+ })
+ }
+ buf, err := json.Marshal(resp)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for list repository: %v", err))
+ }
+ return c.String(http.StatusOK, string(buf))
+}
+
func (bb *Bitbucket) createRepositoryWebhook(c echo.Context) error {
r, err := bb.validRepository(c)
if err != nil {
@@ -223,8 +243,13 @@ func (*Bitbucket) APIURL(string) string {
}
// CreateRepository creates a Bitbucket repository with given ID.
-func (bb *Bitbucket) CreateRepository(id string) {
- bb.repositories[id] = &bitbucketRepositoryData{
+func (bb *Bitbucket) CreateRepository(repository *vcs.Repository) error {
+ bb.repositories[repository.ID] = &bitbucketRepositoryData{
+ repository: &bitbucket.Repository{
+ UUID: repository.ID,
+ Name: repository.Name,
+ FullName: repository.FullPath,
+ },
files: make(map[string]string),
refs: map[string]*bitbucket.Branch{},
diffStats: map[string][]*bitbucket.CommitDiffStat{},
@@ -232,6 +257,7 @@ func (bb *Bitbucket) CreateRepository(id string) {
Files []*bitbucket.CommitDiffStat
}{},
}
+ return nil
}
// CreateBranch creates a new branch with the given name.
diff --git a/backend/tests/fake/github.go b/backend/tests/fake/github.go
index 954369f6f9..cc69994b38 100644
--- a/backend/tests/fake/github.go
+++ b/backend/tests/fake/github.go
@@ -34,7 +34,8 @@ type GitHub struct {
}
type githubRepositoryData struct {
- webhooks []*github.WebhookCreateOrUpdate
+ repository *github.Repository
+ webhooks []*github.WebhookCreateOrUpdate
// files is a map that the full file path is the key and the file content is the
// value.
files map[string]string
@@ -64,6 +65,7 @@ func NewGitHub(port int) VCSProvider {
}
g := e.Group("/api/v3")
+ g.GET("/user/repos", gh.listRepositories)
g.POST("/repos/:owner/:repo/hooks", gh.createRepositoryWebhook)
g.GET("/repos/:owner/:repo/git/commits/:commitID", gh.getRepositoryCommit)
g.GET("/repos/:owner/:repo/contents/:filePath", gh.readRepositoryFile)
@@ -75,6 +77,18 @@ func NewGitHub(port int) VCSProvider {
return gh
}
+func (gh *GitHub) listRepositories(c echo.Context) error {
+ repoList := []*github.Repository{}
+ for _, repoData := range gh.repositories {
+ repoList = append(repoList, repoData.repository)
+ }
+ buf, err := json.Marshal(repoList)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for list repository: %v", err))
+ }
+ return c.String(http.StatusOK, string(buf))
+}
+
func (gh *GitHub) createRepositoryWebhook(c echo.Context) error {
r, err := gh.validRepository(c)
if err != nil {
@@ -280,8 +294,13 @@ func (*GitHub) APIURL(instanceURL string) string {
}
// CreateRepository creates a GitHub repository with given ID.
-func (gh *GitHub) CreateRepository(id string) {
- gh.repositories[id] = &githubRepositoryData{
+func (gh *GitHub) CreateRepository(repository *vcs.Repository) error {
+ gh.repositories[repository.FullPath] = &githubRepositoryData{
+ repository: &github.Repository{
+ ID: int64(len(gh.repositories) + 1),
+ Name: repository.Name,
+ FullName: repository.FullPath,
+ },
files: make(map[string]string),
refs: map[string]*github.Branch{},
pullRequests: map[int]struct {
@@ -290,6 +309,7 @@ func (gh *GitHub) CreateRepository(id string) {
}{},
commitsDiff: map[string]*github.CommitsDiff{},
}
+ return nil
}
// CreateBranch creates a new branch with the given name.
diff --git a/backend/tests/fake/gitlab.go b/backend/tests/fake/gitlab.go
index eb83d6e080..95d4bc7898 100644
--- a/backend/tests/fake/gitlab.go
+++ b/backend/tests/fake/gitlab.go
@@ -31,7 +31,8 @@ type GitLab struct {
}
type projectData struct {
- webhooks []*gitlab.WebhookCreate
+ repository *gitlab.Repository
+ webhooks []*gitlab.WebhookCreate
// files is a map that the full file path is the key and the file content is the
// value.
files map[string]string
@@ -62,6 +63,7 @@ func NewGitLab(port int) VCSProvider {
// Routes
projectGroup := e.Group("/api/v4")
+ projectGroup.GET("/projects", gl.listRepositories)
projectGroup.POST("/projects/:id/hooks", gl.createProjectHook)
projectGroup.GET("/projects/:id/repository/commits/:commitID", gl.getFakeCommit)
projectGroup.GET("/projects/:id/repository/files/:filePath/raw", gl.readProjectFile)
@@ -98,8 +100,18 @@ func (*GitLab) APIURL(instanceURL string) string {
}
// CreateRepository creates a GitLab project with given ID.
-func (gl *GitLab) CreateRepository(id string) {
- gl.projects[id] = &projectData{
+func (gl *GitLab) CreateRepository(repository *vcs.Repository) error {
+ // GitLab repo id should be int64.
+ id, err := strconv.ParseInt(repository.ID, 10, 64)
+ if err != nil {
+ return err
+ }
+ gl.projects[repository.ID] = &projectData{
+ repository: &gitlab.Repository{
+ ID: id,
+ Name: repository.Name,
+ PathWithNamespace: repository.FullPath,
+ },
files: map[string]string{},
branches: map[string]*gitlab.Branch{},
mergeRequests: map[int]struct {
@@ -108,6 +120,7 @@ func (gl *GitLab) CreateRepository(id string) {
}{},
commitsDiff: map[string]*gitlab.CommitsDiff{},
}
+ return nil
}
// CreateBranch creates a new branch with the given name.
@@ -132,6 +145,18 @@ func (gl *GitLab) CreateBranch(id, branchName string) error {
return nil
}
+func (gl *GitLab) listRepositories(c echo.Context) error {
+ repoList := []*gitlab.Repository{}
+ for _, repoData := range gl.projects {
+ repoList = append(repoList, repoData.repository)
+ }
+ buf, err := json.Marshal(repoList)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for list repository: %v", err))
+ }
+ return c.String(http.StatusOK, string(buf))
+}
+
// createProjectHook creates a project webhook.
func (gl *GitLab) createProjectHook(c echo.Context) error {
pd, err := gl.validProject(c)
diff --git a/backend/tests/fake/provider.go b/backend/tests/fake/provider.go
index ac2b098a3b..25cd52a3b5 100644
--- a/backend/tests/fake/provider.go
+++ b/backend/tests/fake/provider.go
@@ -18,7 +18,7 @@ type VCSProvider interface {
APIURL(instanceURL string) string
// CreateRepository creates a new repository with given ID.
- CreateRepository(id string)
+ CreateRepository(repository *vcs.Repository) error
// CreateBranch creates a new branch in the repository with given ID.
CreateBranch(id, branchName string) error
// SendWebhookPush sends out a webhook for a push event for the repository using
diff --git a/backend/tests/vcs_test.go b/backend/tests/vcs_test.go
index a23b4e9686..eef1e7f653 100644
--- a/backend/tests/vcs_test.go
+++ b/backend/tests/vcs_test.go
@@ -36,16 +36,18 @@ func TestVCS(t *testing.T) {
name string
vcsProviderCreator fake.VCSProviderCreator
vcsType v1pb.VCSType
- externalID string
- repositoryFullPath string
+ repository *vcs.Repository
webhookPushEvent any
}{
{
name: "GitLab",
vcsProviderCreator: fake.NewGitLab,
vcsType: v1pb.VCSType_GITLAB,
- externalID: "121",
- repositoryFullPath: "test/vcs",
+ repository: &vcs.Repository{
+ ID: "121",
+ Name: "test/vcs",
+ FullPath: "test/vcs",
+ },
webhookPushEvent: gitlab.MergeRequestPushEvent{
ObjectKind: "merge_request",
ObjectAttributes: gitlab.EventObjectAttributes{
@@ -65,8 +67,11 @@ func TestVCS(t *testing.T) {
name: "GitHub",
vcsProviderCreator: fake.NewGitHub,
vcsType: v1pb.VCSType_GITHUB,
- externalID: "octocat/Hello-World",
- repositoryFullPath: "octocat/Hello-World",
+ repository: &vcs.Repository{
+ ID: "octocat/Hello-World",
+ Name: "octocat/Hello-World",
+ FullPath: "octocat/Hello-World",
+ },
webhookPushEvent: github.PullRequestPushEvent{
Action: "closed",
Number: pullRequestID,
@@ -89,8 +94,11 @@ func TestVCS(t *testing.T) {
name: "Bitbucket",
vcsProviderCreator: fake.NewBitbucket,
vcsType: v1pb.VCSType_BITBUCKET,
- externalID: "octocat/Hello-World",
- repositoryFullPath: "octocat/Hello-World",
+ repository: &vcs.Repository{
+ ID: "octocat/Hello-World",
+ Name: "octocat/Hello-World",
+ FullPath: "octocat/Hello-World",
+ },
webhookPushEvent: bitbucket.PullRequestPushEvent{
PullRequest: bitbucket.EventPullRequest{
ID: pullRequestID,
@@ -125,6 +133,9 @@ func TestVCS(t *testing.T) {
_ = ctl.Close(ctx)
}()
+ err = ctl.vcsProvider.CreateRepository(test.repository)
+ a.NoError(err)
+
evcs, err := ctl.evcsClient.CreateVCSProvider(ctx, &v1pb.CreateVCSProviderRequest{
VcsProvider: &v1pb.VCSProvider{
Title: t.Name(),
@@ -135,8 +146,7 @@ func TestVCS(t *testing.T) {
VcsProviderId: strings.ToLower(test.vcsType.String()),
})
a.NoError(err)
- ctl.vcsProvider.CreateRepository(test.externalID)
- err = ctl.vcsProvider.CreateBranch(test.externalID, branchName)
+ err = ctl.vcsProvider.CreateBranch(test.repository.ID, branchName)
a.NoError(err)
oldVcsConnector, err := ctl.vcsConnectorServiceClient.CreateVCSConnector(ctx, &v1pb.CreateVCSConnectorRequest{
@@ -144,11 +154,11 @@ func TestVCS(t *testing.T) {
VcsConnector: &v1pb.VCSConnector{
VcsProvider: evcs.Name,
Title: "Test VCS Connector",
- FullPath: test.repositoryFullPath,
- WebUrl: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),
+ FullPath: test.repository.FullPath,
+ WebUrl: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repository.FullPath),
Branch: branchName,
BaseDirectory: baseDirectory + "+invalid",
- ExternalId: test.externalID,
+ ExternalId: test.repository.ID,
},
VcsConnectorId: "default",
})
@@ -187,14 +197,14 @@ func TestVCS(t *testing.T) {
})
a.NoError(err)
- err = ctl.vcsProvider.AddPullRequest(test.externalID, pullRequestID, pullRequestFiles)
+ err = ctl.vcsProvider.AddPullRequest(test.repository.ID, pullRequestID, pullRequestFiles)
a.NoError(err)
- err = ctl.vcsProvider.AddFiles(test.externalID, fileContentMap)
+ err = ctl.vcsProvider.AddFiles(test.repository.ID, fileContentMap)
a.NoError(err)
payload, err := json.Marshal(test.webhookPushEvent)
a.NoError(err)
- err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)
+ err = ctl.vcsProvider.SendWebhookPush(test.repository.ID, payload)
a.NoError(err)
// Get schema update issue.