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 `FetchRepositoryActiveMemberList` (#1775)
Joe Chenedb907e3bf7c
diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.goindex ab0841ff76..a2ea1f49be 100644--- a/plugin/vcs/github/github.go+++ b/plugin/vcs/github/github.go@@ -46,6 +46,25 @@ func (p *Provider) APIURL(string) string {return apiURL}+// RepositoryRole is the role of the repository collaborator.+type RepositoryRole string++// The list of GitHub roles.+const (+ RepositoryRoleAdmin RepositoryRole = "admin"+ RepositoryRoleMaintain RepositoryRole = "maintain"+ RepositoryRoleWrite RepositoryRole = "write"+ RepositoryRoleTriage RepositoryRole = "triage"+ RepositoryRoleRead RepositoryRole = "read"+)++// RepositoryCollaborator represents a GitHub API response for a repository+// collaborator.+type RepositoryCollaborator struct {+ Login string `json:"login"`+ RoleName string `json:"role_name"`+}+// User represents a GitHub API response for a user.type User struct {Name string `json:"name"`@@ -155,9 +174,106 @@ func (p *Provider) FetchUserInfo(ctx context.Context, oauthCtx common.OauthContereturn p.fetchUserInfo(ctx, oauthCtx, fmt.Sprintf("users/%s", username))}+func getRoleAndMappedRole(roleName string) (githubRole RepositoryRole, bytebaseRole common.ProjectRole) {+ // Please refer to https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#repository-roles-for-organizations+ // for the detailed role descriptions of GitHub.+ switch roleName {+ case "admin":+ return RepositoryRoleAdmin, common.ProjectOwner+ case "maintain":+ return RepositoryRoleMaintain, common.ProjectOwner+ case "write":+ return RepositoryRoleWrite, common.ProjectOwner+ case "triage":+ return RepositoryRoleTriage, common.ProjectDeveloper+ case "read":+ return RepositoryRoleRead, common.ProjectDeveloper+ }+ return "", ""+}+// FetchRepositoryActiveMemberList fetch all active members of a repository-func (p *Provider) FetchRepositoryActiveMemberList(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string) ([]*vcs.RepositoryMember, error) {- return nil, errors.New("not implemented yet") // TODO: https://github.com/bytebase/bytebase/issues/928+func (p *Provider) FetchRepositoryActiveMemberList(ctx context.Context, oauthCtx common.OauthContext, _, repositoryID string) ([]*vcs.RepositoryMember, error) {+ var allCollaborators []RepositoryCollaborator+ page := 1+ for {+ collaborators, hasNextPage, err := p.fetchPaginatedRepositoryCollaborators(ctx, oauthCtx, repositoryID, page)+ if err != nil {+ return nil, errors.Wrap(err, "fetch paginated list")+ }+ allCollaborators = append(allCollaborators, collaborators...)++ if !hasNextPage {+ break+ }+ page+++ }++ var allMembers []*vcs.RepositoryMember+ for _, c := range allCollaborators {+ userInfo, err := p.FetchUserInfo(ctx, oauthCtx, "", c.Login)+ if err != nil {+ return nil, errors.Wrapf(err, "fetch user info, login: %s", c.Login)+ }++ githubRole, bytebaseRole := getRoleAndMappedRole(c.RoleName)+ allMembers = append(allMembers,+ &vcs.RepositoryMember{+ Name: userInfo.Name,+ Email: userInfo.PublicEmail,+ Role: bytebaseRole,+ VCSRole: string(githubRole),+ State: vcs.StateActive,+ RoleProvider: vcs.GitHubCom,+ },+ )+ }+ return allMembers, nil+}++// fetchPaginatedRepositoryCollaborators fetches collaborators of a repository+// 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)+ 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 collaborators from URL %s", url))+ } else if code >= 300 {+ return nil, false,+ fmt.Errorf("failed to read repository collaborators from URL %s, status code: %d, body: %s",+ url,+ code,+ body,+ )+ }++ if err := json.Unmarshal([]byte(body), &collaborators); err != nil {+ return nil, false, errors.Wrap(err, "unmarshal body")+ }++ // 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 collaborators, len(collaborators) >= 100, nil}// oauthResponse is a GitHub OAuth response.diff --git a/plugin/vcs/github/github_test.go b/plugin/vcs/github/github_test.goindex 0f3b9e27b5..7b2b024f43 100644--- a/plugin/vcs/github/github_test.go+++ b/plugin/vcs/github/github_test.go@@ -7,6 +7,7 @@ import ("strings""testing"+ "github.com/pkg/errors""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"@@ -91,6 +92,128 @@ func TestProvider_FetchUserInfo(t *testing.T) {assert.Equal(t, want, got)}+func TestProvider_FetchRepositoryActiveMemberList(t *testing.T) {+ p := newProvider(+ vcs.ProviderConfig{+ Client: &http.Client{+ Transport: &common.MockRoundTripper{+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {+ switch r.URL.Path {+ case "/repos/octocat/Hello-World/collaborators":+ return &http.Response{+ StatusCode: http.StatusOK,+ // Example response taken from https://docs.github.com/en/rest/collaborators/collaborators#list-repository-collaborators+ Body: io.NopCloser(strings.NewReader(`+[+ {+ "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,+ "permissions": {+ "pull": true,+ "triage": true,+ "push": true,+ "maintain": false,+ "admin": false+ },+ "role_name": "write"+ }+]+`)),+ }, nil+ case "/users/octocat":+ return &http.Response{+ StatusCode: http.StatusOK,+ // Example response taken from https://docs.github.com/en/rest/reference/users#get-a-user+ Body: io.NopCloser(strings.NewReader(`+{+ "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,+ "name": "monalisa octocat",+ "company": "GitHub",+ "blog": "https://github.com/blog",+ "location": "San Francisco",+ "email": "[email protected]",+ "hireable": false,+ "bio": "There once was...",+ "twitter_username": "monatheoctocat",+ "public_repos": 2,+ "public_gists": 1,+ "followers": 20,+ "following": 0,+ "created_at": "2008-01-14T04:33:35Z",+ "updated_at": "2008-01-14T04:33:35Z",+ "private_gists": 81,+ "total_private_repos": 100,+ "owned_private_repos": 100,+ "disk_usage": 10000,+ "collaborators": 8,+ "two_factor_authentication": true,+ "plan": {+ "name": "Medium",+ "space": 400,+ "private_repos": 20,+ "collaborators": 0+ }+}+`)),+ }, nil+ }+ return nil, errors.Errorf("unexpected request path: %s", r.URL.Path)+ },+ },+ },+ },+ )++ ctx := context.Background()+ got, err := p.FetchRepositoryActiveMemberList(ctx, common.OauthContext{}, "", "octocat/Hello-World")+ require.NoError(t, err)++ want := []*vcs.RepositoryMember{+ {+ Email: "[email protected]",+ Name: "monalisa octocat",+ State: vcs.StateActive,+ Role: common.ProjectOwner,+ VCSRole: string(RepositoryRoleWrite),+ RoleProvider: vcs.GitHubCom,+ },+ }+ assert.Equal(t, want, got)+}+func TestProvider_FetchCommitByID(t *testing.T) {p := newProvider(vcs.ProviderConfig{diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.goindex 2f0cacf71e..f8b46addc0 100644--- a/plugin/vcs/gitlab/gitlab.go+++ b/plugin/vcs/gitlab/gitlab.go@@ -131,10 +131,10 @@ type File struct {LastCommitID string `json:"last_commit_id"`}-// ProjectRole is the role of the project member+// ProjectRole is the role of the project member.type ProjectRole string-// Gitlab Role type+// The list of GitLab roles.const (ProjectRoleOwner ProjectRole = "Owner"ProjectRoleMaintainer ProjectRole = "Maintainer"@@ -426,7 +426,7 @@ func (p *Provider) FetchUserInfo(ctx context.Context, oauthCtx common.OauthConte}func getRoleAndMappedRole(accessLevel int32) (gitLabRole ProjectRole, bytebaseRole common.ProjectRole) {- // see https://docs.gitlab.com/ee/api/members.html for the detailed role type at GitLab+ // Please refer to https://docs.gitlab.com/ee/api/members.html for the detailed role descriptions of GitLab.switch accessLevel {case 50 /* Owner */ :return ProjectRoleOwner, common.ProjectOwner