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(github): implement `FetchAllRepositoryList` (#1827)
Joe Chen3020b3e95d40
diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.goindex d2a9cac238..772873fc11 100644--- a/plugin/vcs/github/github.go+++ b/plugin/vcs/github/github.go@@ -19,7 +19,12 @@ import ("github.com/bytebase/bytebase/plugin/vcs/internal/oauth")-const apiURL = "https://api.github.com"+const (+ // apiURL is the API URL.+ apiURL = "https://api.github.com"+ // apiPageSize is the default page size when making API requests.+ apiPageSize = 100+)func init() {vcs.Register(vcs.GitHubCom, newProvider)@@ -71,6 +76,14 @@ type User struct {Email string `json:"email"`}+// Repository represents a GitHub API response for a repository.+type Repository struct {+ ID int64 `json:"id"`+ Name string `json:"name"`+ FullName string `json:"full_name"`+ HTMLURL string `json:"html_url"`+}+// fetchUserInfo fetches user information from the given resourceURI, which// should be either "user" or "users/{username}".func (p *Provider) fetchUserInfo(ctx context.Context, oauthCtx common.OauthContext, resourceURI string) (*vcs.UserInfo, error) {@@ -193,6 +206,8 @@ func getRoleAndMappedRole(roleName string) (githubRole RepositoryRole, bytebaseR}// FetchRepositoryActiveMemberList fetch all active members of a repository+//+// Docs: https://docs.github.com/en/rest/collaborators/collaborators#list-repository-collaboratorsfunc (p *Provider) FetchRepositoryActiveMemberList(ctx context.Context, oauthCtx common.OauthContext, _, repositoryID string) ([]*vcs.RepositoryMember, error) {var allCollaborators []RepositoryCollaboratorpage := 1@@ -246,7 +261,7 @@ func (p *Provider) FetchRepositoryActiveMemberList(ctx context.Context, oauthCtx// in given page. It return the paginated results along with a boolean// indicating whether the next page exists.func (p *Provider) fetchPaginatedRepositoryCollaborators(ctx context.Context, oauthCtx common.OauthContext, repositoryID string, page int) (collaborators []RepositoryCollaborator, hasNextPage bool, err error) {- url := fmt.Sprintf("%s/repos/%s/collaborators?page=%d&per_page=100", apiURL, repositoryID, page)+ url := fmt.Sprintf("%s/repos/%s/collaborators?page=%d&per_page=%d", apiURL, repositoryID, page, apiPageSize)code, body, err := oauth.Get(ctx,p.client,@@ -344,9 +359,85 @@ func (p *Provider) ExchangeOAuthToken(ctx context.Context, _ string, oauthExchanreturn oauthResp.toVCSOAuthToken(), nil}-// FetchAllRepositoryList fetches all repositories where the authenticated user has a maintainer role.-func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx common.OauthContext, instanceURL string) ([]*vcs.Repository, error) {- return nil, errors.New("not implemented yet")+// FetchAllRepositoryList fetches all repositories where the authenticated user+// has a owner role, which is required to create webhook in the repository.+//+// Docs: https://docs.github.com/en/rest/repos/repos#list-repositories-for-the-authenticated-user+func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx common.OauthContext, _ string) ([]*vcs.Repository, error) {+ var githubRepos []Repository+ page := 1+ for {+ repos, hasNextPage, err := p.fetchPaginatedRepositoryList(ctx, oauthCtx, page)+ if err != nil {+ return nil, errors.Wrap(err, "fetch paginated list")+ }+ githubRepos = append(githubRepos, repos...)++ if !hasNextPage {+ break+ }+ page+++ }++ var allRepos []*vcs.Repository+ for _, r := range githubRepos {+ allRepos = append(allRepos,+ &vcs.Repository{+ ID: r.ID,+ Name: r.Name,+ FullPath: r.FullName,+ WebURL: r.HTMLURL,+ },+ )+ }+ return allRepos, nil+}++// fetchPaginatedRepositoryList fetches repositories where the authenticated+// user has a owner 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, oauthCtx common.OauthContext, 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/user/repos?affiliation=owner&page=%d&per_page=%d", apiURL, page, apiPageSize)+ code, body, err := oauth.Get(+ ctx,+ p.client,+ url,+ &oauthCtx.AccessToken,+ tokenRefresher(+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),+ )+ if err != nil {+ return nil, false, errors.Wrapf(err, "GET %s", url)+ }++ if code == http.StatusNotFound {+ return nil, false, common.Errorf(common.NotFound, fmt.Errorf("failed to fetch repository list from URL %s", url))+ } else if code >= 300 {+ return nil, false,+ fmt.Errorf("failed to fetch repository list from URL %s, status code: %d, body: %s",+ url,+ code,+ body,+ )+ }++ if err := json.Unmarshal([]byte(body), &repos); err != nil {+ return nil, false, errors.Wrap(err, "unmarshal")+ }++ // NOTE: We deliberately choose to not use the Link header for checking the next+ // page to avoid introducing a new dependency, see+ // https://github.com/bytebase/bytebase/pull/1423#discussion_r884278534 for the+ // discussion.+ return repos, len(repos) >= 100, nil}// FetchRepositoryFileList fetch the files from repository treediff --git a/plugin/vcs/github/github_test.go b/plugin/vcs/github/github_test.goindex 2f6ffd3aef..372430e962 100644--- a/plugin/vcs/github/github_test.go+++ b/plugin/vcs/github/github_test.go@@ -433,6 +433,165 @@ func TestProvider_ExchangeOAuthToken(t *testing.T) {assert.Equal(t, want, got)}+func TestProvider_FetchAllRepositoryList(t *testing.T) {+ p := newProvider(+ vcs.ProviderConfig{+ Client: &http.Client{+ Transport: &common.MockRoundTripper{+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {+ assert.Equal(t, "/user/repos", r.URL.Path)+ return &http.Response{+ StatusCode: http.StatusOK,+ // Example response taken from https://docs.github.com/en/rest/repos/repos#list-repositories-for-the-authenticated-user+ Body: io.NopCloser(strings.NewReader(`+[+ {+ "id": 1296269,+ "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5",+ "name": "Hello-World",+ "full_name": "octocat/Hello-World",+ "owner": {+ "login": "octocat",+ "id": 1,+ "node_id": "MDQ6VXNlcjE=",+ "avatar_url": "https://github.com/images/error/octocat_happy.gif",+ "gravatar_id": "",+ "url": "https://api.github.com/users/octocat",+ "html_url": "https://github.com/octocat",+ "followers_url": "https://api.github.com/users/octocat/followers",+ "following_url": "https://api.github.com/users/octocat/following{/other_user}",+ "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",+ "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",+ "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",+ "organizations_url": "https://api.github.com/users/octocat/orgs",+ "repos_url": "https://api.github.com/users/octocat/repos",+ "events_url": "https://api.github.com/users/octocat/events{/privacy}",+ "received_events_url": "https://api.github.com/users/octocat/received_events",+ "type": "User",+ "site_admin": false+ },+ "private": false,+ "html_url": "https://github.com/octocat/Hello-World",+ "description": "This your first repo!",+ "fork": false,+ "url": "https://api.github.com/repos/octocat/Hello-World",+ "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}",+ "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}",+ "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}",+ "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}",+ "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}",+ "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}",+ "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}",+ "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}",+ "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}",+ "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors",+ "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments",+ "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads",+ "events_url": "https://api.github.com/repos/octocat/Hello-World/events",+ "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks",+ "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}",+ "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}",+ "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}",+ "git_url": "git:github.com/octocat/Hello-World.git",+ "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}",+ "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}",+ "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}",+ "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}",+ "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}",+ "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages",+ "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges",+ "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}",+ "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}",+ "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}",+ "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}",+ "ssh_url": "[email protected]:octocat/Hello-World.git",+ "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers",+ "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}",+ "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers",+ "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription",+ "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags",+ "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams",+ "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}",+ "clone_url": "https://github.com/octocat/Hello-World.git",+ "mirror_url": "git:git.example.com/octocat/Hello-World",+ "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks",+ "svn_url": "https://svn.github.com/octocat/Hello-World",+ "homepage": "https://github.com",+ "language": null,+ "forks_count": 9,+ "stargazers_count": 80,+ "watchers_count": 80,+ "size": 108,+ "default_branch": "master",+ "open_issues_count": 0,+ "is_template": true,+ "topics": [+ "octocat",+ "atom",+ "electron",+ "api"+ ],+ "has_issues": true,+ "has_projects": true,+ "has_wiki": true,+ "has_pages": false,+ "has_downloads": true,+ "archived": false,+ "disabled": false,+ "visibility": "public",+ "pushed_at": "2011-01-26T19:06:43Z",+ "created_at": "2011-01-26T19:01:12Z",+ "updated_at": "2011-01-26T19:14:43Z",+ "permissions": {+ "admin": false,+ "push": false,+ "pull": true+ },+ "allow_rebase_merge": true,+ "template_repository": null,+ "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O",+ "allow_squash_merge": true,+ "allow_auto_merge": false,+ "delete_branch_on_merge": true,+ "allow_merge_commit": true,+ "subscribers_count": 42,+ "network_count": 0,+ "license": {+ "key": "mit",+ "name": "MIT License",+ "url": "https://api.github.com/licenses/mit",+ "spdx_id": "MIT",+ "node_id": "MDc6TGljZW5zZW1pdA==",+ "html_url": "https://github.com/licenses/mit"+ },+ "forks": 1,+ "open_issues": 1,+ "watchers": 1+ }+]+`)),+ }, nil+ },+ },+ },+ },+ )++ ctx := context.Background()+ got, err := p.FetchAllRepositoryList(ctx, common.OauthContext{}, "")+ require.NoError(t, err)++ want := []*vcs.Repository{+ {+ ID: 1296269,+ Name: "Hello-World",+ FullPath: "octocat/Hello-World",+ WebURL: "https://github.com/octocat/Hello-World",+ },+ }+ assert.Equal(t, want, got)+}+func TestOAuth_RefreshToken(t *testing.T) {ctx := context.Background()client := &http.Client{diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.goindex 123758059f..99634e5508 100644--- a/plugin/vcs/gitlab/gitlab.go+++ b/plugin/vcs/gitlab/gitlab.go@@ -26,6 +26,8 @@ const (// apiPath is the API path.apiPath = "api/v4"+ // apiPageSize is the default page size when making API requests.+ apiPageSize = 100)var _ vcs.Provider = (*Provider)(nil)@@ -154,7 +156,7 @@ type RepositoryMember struct {AccessLevel int32 `json:"access_level"`}-// gitLabRepository is the API message for repository in GitLab+// gitLabRepository represents a GitLab API response for a repository.type gitLabRepository struct {ID int64 `json:"id"`Name string `json:"name"`@@ -251,37 +253,47 @@ func (p *Provider) ExchangeOAuthToken(ctx context.Context, instanceURL string, oreturn oauthResp.toVCSOAuthToken(), nil}-// FetchAllRepositoryList fetches all repositories where the authenticated user has a maintainer role.-// The maintainer role is required to create webhook in the project.+// FetchAllRepositoryList fetches all repositories where the authenticated user+// has a maintainer role, which is required to create webhook in the project.+//+// Docs: https://docs.gitlab.com/ee/api/projects.html#list-all-projectsfunc (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx common.OauthContext, instanceURL string) ([]*vcs.Repository, error) {- repoList := []*vcs.Repository{}- // page is the current requesting page index, starts from 1.- // perPage is the number of items to list per page (default: 20, max: 100).- // refer: https://docs.gitlab.com/ee/api/#offset-based-pagination+ var gitlabRepos []gitLabRepositorypage := 1- perPage := 40-for {- temp, err := p.fetchOffsetRepositoryList(ctx, oauthCtx, instanceURL, page, perPage)+ repos, hasNextPage, err := p.fetchPaginatedRepositoryList(ctx, oauthCtx, instanceURL, page)if err != nil {- return nil, err+ return nil, errors.Wrap(err, "fetch paginated list")}+ gitlabRepos = append(gitlabRepos, repos...)- repoList = append(repoList, temp...)- if len(temp) < perPage {+ if !hasNextPage {break}page++}- return repoList, nil+ var allRepos []*vcs.Repository+ for _, r := range gitlabRepos {+ allRepos = append(allRepos,+ &vcs.Repository{+ ID: r.ID,+ Name: r.Name,+ FullPath: r.PathWithNamespace,+ WebURL: r.WebURL,+ },+ )+ }+ return allRepos, nil}-// fetchOffsetRepositoryList fetches repositories at page `page` with `perPage` items per page.-func (p *Provider) fetchOffsetRepositoryList(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, page, perPage int) ([]*vcs.Repository, error) {+// 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, oauthCtx common.OauthContext, instanceURL string, page int) (repos []gitLabRepository, 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(instanceURL), page, perPage)+ url := fmt.Sprintf("%s/projects?membership=true&simple=true&min_access_level=40&page=%d&per_page=%d", p.APIURL(instanceURL), page, apiPageSize)code, body, err := oauth.Get(ctx,p.client,@@ -298,35 +310,29 @@ func (p *Provider) fetchOffsetRepositoryList(ctx context.Context, oauthCtx commo),)if err != nil {- return nil, errors.Wrap(err, "GET")+ return nil, false, errors.Wrapf(err, "GET %s", url)}if code == http.StatusNotFound {- return nil, common.Errorf(common.NotFound, fmt.Errorf("repository list for GitLab instance %s not found", instanceURL))+ return nil, false, common.Errorf(common.NotFound, fmt.Errorf("failed to fetch repository list from URL %s", url))} else if code >= 300 {- return nil, fmt.Errorf("failed to read repository list from GitLab instance %s, status code: %d",- instanceURL,- code,- )- }-- var gitlabRepos []gitLabRepository- if err := json.Unmarshal([]byte(body), &gitlabRepos); err != nil {- return nil, errors.Wrap(err, "unmarshal")+ return nil, false,+ fmt.Errorf("failed to fetch repository list from URL %s, status code: %d, body: %s",+ url,+ code,+ body,+ )}- var repos []*vcs.Repository- for _, r := range gitlabRepos {- repo := &vcs.Repository{- ID: r.ID,- Name: r.Name,- FullPath: r.PathWithNamespace,- WebURL: r.WebURL,- }- repos = append(repos, repo)+ if err := json.Unmarshal([]byte(body), &repos); err != nil {+ return nil, false, errors.Wrap(err, "unmarshal")}- return repos, nil+ // NOTE: We deliberately choose to not use the Link header for checking the next+ // page to avoid introducing a new dependency, see+ // https://github.com/bytebase/bytebase/pull/1423#discussion_r884278534 for the+ // discussion.+ return repos, len(repos) >= 100, nil}// fetchUserInfo fetches user information from the given resourceURI, which@@ -520,7 +526,7 @@ func (p *Provider) FetchRepositoryActiveMemberList(ctx context.Context, oauthCtxfunc (p *Provider) fetchPaginatedRepositoryActiveMemberList(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, page int) (members []RepositoryMember, hasNextPage bool, err error) {// The "state" filter only available in GitLab Premium self-managed, GitLab// Premium SaaS, and higher tiers, but worth a try for less abandoned results.- url := fmt.Sprintf("%s/projects/%s/members/all?state=active&page=%d&per_page=100", p.APIURL(instanceURL), repositoryID, page)+ url := fmt.Sprintf("%s/projects/%s/members/all?state=active&page=%d&per_page=%d", p.APIURL(instanceURL), repositoryID, page, apiPageSize)code, body, err := oauth.Get(ctx,p.client,@@ -544,7 +550,7 @@ func (p *Provider) fetchPaginatedRepositoryActiveMemberList(ctx context.Context,return nil, false, common.Errorf(common.NotFound, fmt.Errorf("failed to fetch repository members from URL %s", url))} else if code >= 300 {return nil, false,- fmt.Errorf("failed to read repository members from URL %s, status code: %d, body: %s",+ fmt.Errorf("failed to fetch repository members from URL %s, status code: %d, body: %s",url,code,body,diff --git a/plugin/vcs/gitlab/gitlab_test.go b/plugin/vcs/gitlab/gitlab_test.goindex d410e53d8f..921542a433 100644--- a/plugin/vcs/gitlab/gitlab_test.go+++ b/plugin/vcs/gitlab/gitlab_test.go@@ -250,7 +250,6 @@ func TestProvider_FetchRepositoryActiveMemberList(t *testing.T) {got, err := p.FetchRepositoryActiveMemberList(ctx, common.OauthContext{}, "", "1")require.NoError(t, err)- // Non-active member should be excludedwant := []*vcs.RepositoryMember{{Email: "[email protected]",@@ -372,6 +371,69 @@ func TestProvider_ExchangeOAuthToken(t *testing.T) {assert.Equal(t, want, got)}+func TestProvider_FetchAllRepositoryList(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", r.URL.Path)+ return &http.Response{+ StatusCode: http.StatusOK,+ // Example response taken from https://docs.gitlab.com/ee/api/projects.html#list-all-projects+ Body: io.NopCloser(strings.NewReader(`+[+ {+ "id": 4,+ "description": null,+ "default_branch": "master",+ "ssh_url_to_repo": "[email protected]:diaspora/diaspora-client.git",+ "http_url_to_repo": "http://example.com/diaspora/diaspora-client.git",+ "web_url": "http://example.com/diaspora/diaspora-client",+ "readme_url": "http://example.com/diaspora/diaspora-client/blob/master/README.md",+ "tag_list": [+ "example",+ "disapora client"+ ],+ "topics": [+ "example",+ "disapora client"+ ],+ "name": "Diaspora Client",+ "name_with_namespace": "Diaspora / Diaspora Client",+ "path": "diaspora-client",+ "path_with_namespace": "diaspora/diaspora-client",+ "created_at": "2013-09-30T13:46:02Z",+ "last_activity_at": "2013-09-30T13:46:02Z",+ "forks_count": 0,+ "avatar_url": "http://example.com/uploads/project/avatar/4/uploads/avatar.png",+ "star_count": 0+ }+]+`)),+ }, nil+ },+ },+ },+ },+ )++ ctx := context.Background()+ got, err := p.FetchAllRepositoryList(ctx, common.OauthContext{}, "")+ require.NoError(t, err)++ // Non-active member should be excluded+ want := []*vcs.Repository{+ {+ ID: 4,+ Name: "Diaspora Client",+ FullPath: "diaspora/diaspora-client",+ WebURL: "http://example.com/diaspora/diaspora-client",+ },+ }+ assert.Equal(t, want, got)+}+func TestOAuth_RefreshToken(t *testing.T) {ctx := context.Background()client := &http.Client{