Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: merge common methods of GitHub and GitLab VCS providers (#982)
Joe Chen13437d52d7cc
diff --git a/common/mock.go b/common/mock.gonew file mode 100644index 0000000000..d1bd236c40--- /dev/null+++ b/common/mock.go@@ -0,0 +1,14 @@+package common++import (+ "net/http"+)++// MockRoundTripper is a helper to mock http.RoundTripper.+type MockRoundTripper struct {+ MockRoundTrip func(r *http.Request) (*http.Response, error)+}++func (m *MockRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {+ return m.MockRoundTrip(r)+}diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.goindex 5852aac0ab..0a71cb1ce3 100644--- a/plugin/vcs/github/github.go+++ b/plugin/vcs/github/github.go@@ -15,13 +15,10 @@ import ("github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/vcs"+ "github.com/bytebase/bytebase/plugin/vcs/internal/oauth")-const (- maxRetries = 3-- apiURL = "https://api.github.com"-)+const apiURL = "https://api.github.com"func init() {vcs.Register(vcs.GitHubCom, newProvider)@@ -58,17 +55,20 @@ type User struct {// 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) {- code, body, err := httpGet(+ url := fmt.Sprintf("%s/%s", apiURL, resourceURI)+ code, body, err := oauth.Get(ctx,p.client,- resourceURI,+ url,&oauthCtx.AccessToken,- oauthContext{- ClientID: oauthCtx.ClientID,- ClientSecret: oauthCtx.ClientSecret,- RefreshToken: oauthCtx.RefreshToken,- },- oauthCtx.Refresher,+ tokenRefresher(+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),)if err != nil {return nil, errors.Wrap(err, "GET")@@ -78,7 +78,7 @@ func (p *Provider) fetchUserInfo(ctx context.Context, oauthCtx common.OauthConteerrInfo := []string{"failed to fetch user info from GitHub.com"}resourceURISplit := strings.Split(resourceURI, "/")if len(resourceURI) > 1 {- errInfo = append(errInfo, fmt.Sprintf("UserID: %v", resourceURISplit[1]))+ errInfo = append(errInfo, fmt.Sprintf("Username: %s", resourceURISplit[1]))}return nil, common.Errorf(common.NotFound, fmt.Errorf(strings.Join(errInfo, ", ")))} else if code >= 300 {@@ -147,91 +147,6 @@ func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthContereturn errors.New("not implemented yet") // TODO: https://github.com/bytebase/bytebase/issues/928}-func httpGet(ctx context.Context, client *http.Client, resourcePath string, token *string, oauthCtx oauthContext, refresher common.TokenRefresher) (code int, respBody string, err error) {- return retry(ctx, client, token, oauthCtx, refresher,- func() (*http.Response, error) {- url := fmt.Sprintf("%s/%s", apiURL, resourcePath)- req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)- if err != nil {- return nil, errors.Wrapf(err, "construct GET %s", url)- }-- req.Header.Set("Content-Type", "application/json")- req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", *token))- resp, err := client.Do(req)- if err != nil {- return nil, errors.Wrapf(err, "GET %s", url)- }- return resp, nil- },- )-}--func retry(ctx context.Context, client *http.Client, token *string, oauthCtx oauthContext, refresher common.TokenRefresher, f func() (*http.Response, error)) (code int, respBody string, err error) {- var resp *http.Response- var body []byte- for retries := 0; retries < maxRetries; retries++ {- select {- case <-ctx.Done():- return 0, "", ctx.Err()- default:- }-- resp, err = f()- if err != nil {- return 0, "", err- }-- body, err := io.ReadAll(resp.Body)- if err != nil {- return 0, "", errors.Wrapf(err, "read response body with status code %d", resp.StatusCode)- }-- if err = getOAuthErrorDetails(resp.StatusCode, string(body)); err != nil {- if _, ok := err.(*oauthError); ok {- // Refresh and store the token.- if err := refreshToken(ctx, client, token, oauthCtx, refresher); err != nil {- return 0, "", err- }- continue- }- return 0, "", errors.Errorf("want oauthError but got %T", err)- }- return resp.StatusCode, string(body), nil- }- return 0, "", errors.Errorf("retries exceeded for oauth refresher with status code %d and body %q", resp.StatusCode, string(body))-}--type oauthError struct {- Err string `json:"error"`- ErrorDescription string `json:"error_description"`-}--func (e oauthError) Error() string {- return fmt.Sprintf("GitHub oauth response error %q description %q", e.Err, e.ErrorDescription)-}--// getOAuthErrorDetails only returns error if it's an OAuth error. For other-// errors like 404 we don't return error. We do this because this method is only-// intended to be used by oauth to refresh access token on expiration.-func getOAuthErrorDetails(code int, body string) error {- if 200 <= code && code < 300 {- return nil- }-- var oe oauthError- if err := json.Unmarshal([]byte(body), &oe); err != nil {- // If we failed to unmarshal body with oauth error, it's not oauthError and we should return nil.- return nil- }- // https://www.oauth.com/oauth2-servers/access-tokens/access-token-response/- // {"error":"invalid_token","error_description":"Token is expired. You can either do re-authorization or token refresh."}- if oe.Err == "invalid_token" && strings.Contains(oe.ErrorDescription, "expired") {- return &oe- }- return nil-}-// oauthContext is the request context for refreshing oauth token.type oauthContext struct {ClientID string `json:"client_id"`@@ -248,50 +163,52 @@ type refreshOAuthResponse struct {// token_type, scope are not used.}-func refreshToken(ctx context.Context, client *http.Client, oldToken *string, oauthContext oauthContext, refresher common.TokenRefresher) error {- url := fmt.Sprintf("%s/login/oauth/access_token", apiURL)- oauthContext.GrantType = "refresh_token"- body, err := json.Marshal(oauthContext)- if err != nil {- return err- }+func tokenRefresher(oauthCtx oauthContext, refresher common.TokenRefresher) oauth.TokenRefresher {+ return func(ctx context.Context, client *http.Client, oldToken *string) error {+ url := fmt.Sprintf("%s/login/oauth/access_token", apiURL)+ oauthCtx.GrantType = "refresh_token"+ body, err := json.Marshal(oauthCtx)+ if err != nil {+ return err+ }- req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(body))- if err != nil {- return errors.Wrapf(err, "construct POST %s", url)- }+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))+ if err != nil {+ return errors.Wrapf(err, "construct POST %s", url)+ }- req.Header.Set("Content-Type", "application/json")- resp, err := client.Do(req)- if err != nil {- return errors.Wrapf(err, "POST %s", url)- }+ req.Header.Set("Content-Type", "application/json")+ resp, err := client.Do(req)+ if err != nil {+ return errors.Wrapf(err, "POST %s", url)+ }- body, err = io.ReadAll(resp.Body)- if err != nil {- return errors.Wrapf(err, "read body of POST %s", url)- }+ body, err = io.ReadAll(resp.Body)+ if err != nil {+ return errors.Wrapf(err, "read body of POST %s", url)+ }- if resp.StatusCode != http.StatusOK {- return errors.Errorf("non-200 status code %d with body %q", resp.StatusCode, body)- }+ if resp.StatusCode != http.StatusOK {+ return errors.Errorf("non-200 status code %d with body %q", resp.StatusCode, body)+ }- var r refreshOAuthResponse- if err = json.Unmarshal(body, &r); err != nil {- return errors.Wrapf(err, "unmarshal body from POST %s", url)- }+ var r refreshOAuthResponse+ if err = json.Unmarshal(body, &r); err != nil {+ return errors.Wrapf(err, "unmarshal body from POST %s", url)+ }- // Update the old token to new value for retries.- *oldToken = r.AccessToken+ // Update the old token to new value for retries.+ *oldToken = r.AccessToken- // OAuth token never expires for traditional GitHub OAuth (i.e. not a GitHub App)- var expireAt int64- if r.ExpiresIn != "" {- expiresIn, _ := strconv.ParseInt(r.ExpiresIn, 10, 64)- expireAt = r.CreatedAt + expiresIn- }- if err = refresher(r.AccessToken, r.RefreshToken, expireAt); err != nil {- return err+ // OAuth token never expires for traditional GitHub OAuth (i.e. not a GitHub App)+ var expireAt int64+ if r.ExpiresIn != "" {+ expiresIn, _ := strconv.ParseInt(r.ExpiresIn, 10, 64)+ expireAt = r.CreatedAt + expiresIn+ }+ if err = refresher(r.AccessToken, r.RefreshToken, expireAt); err != nil {+ return err+ }+ return nil}- return nil}diff --git a/plugin/vcs/github/github_test.go b/plugin/vcs/github/github_test.goindex 24e79f19e1..a3e0ab1578 100644--- a/plugin/vcs/github/github_test.go+++ b/plugin/vcs/github/github_test.go@@ -2,7 +2,6 @@ package githubimport ("context"- "fmt""io""net/http""strings"@@ -13,25 +12,19 @@ import ("github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/vcs"+ "github.com/bytebase/bytebase/plugin/vcs/internal/oauth")-type mockRoundTripper struct {- roundTrip func(r *http.Request) (*http.Response, error)-}--func (m *mockRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {- return m.roundTrip(r)-}-func TestProvider_FetchUserInfo(t *testing.T) {p := newProvider(vcs.ProviderConfig{Client: &http.Client{- Transport: &mockRoundTripper{- roundTrip: func(r *http.Request) (*http.Response, error) {+ Transport: &common.MockRoundTripper{+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {assert.Equal(t, "/users/octocat", r.URL.Path)return &http.Response{StatusCode: http.StatusOK,+ // Example response taken from https://docs.github.com/en/rest/reference/users#get-a-userBody: io.NopCloser(strings.NewReader(`{"login": "octocat",@@ -80,7 +73,6 @@ func TestProvider_FetchUserInfo(t *testing.T) {}}`)),- Request: r,}, nil},},@@ -102,11 +94,21 @@ func TestProvider_FetchUserInfo(t *testing.T) {func TestOAuth_RefreshToken(t *testing.T) {ctx := context.Background()client := &http.Client{- Transport: &mockRoundTripper{- roundTrip: func(r *http.Request) (*http.Response, error) {- assert.Equal(t, "/login/oauth/access_token", r.URL.Path)+ Transport: &common.MockRoundTripper{+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {+ token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")+ if token == "expired" {+ return &http.Response{+ StatusCode: http.StatusBadRequest,+ Body: io.NopCloser(strings.NewReader(`+ {"error":"invalid_token","error_description":"Token is expired. You can either do re-authorization or token refresh."}+ `)),+ }, nil+ }+return &http.Response{StatusCode: http.StatusOK,+ // Example response taken from https://docs.github.com/en/developers/apps/building-github-apps/refreshing-user-to-server-access-tokens#renewing-a-user-token-with-a-refresh-tokenBody: io.NopCloser(strings.NewReader(`{"access_token": "ghu_16C7e42F292c6912E7710c838347Ae178B4a",@@ -117,12 +119,11 @@ func TestOAuth_RefreshToken(t *testing.T) {"token_type": "bearer"}`)),- Request: r,}, nil},},}- token := "old"+ token := "expired"calledRefresher := falserefresher := func(_, _ string, _ int64) error {@@ -130,57 +131,17 @@ func TestOAuth_RefreshToken(t *testing.T) {return nil}- called := 0- _, _, err := retry(ctx, client, &token, oauthContext{}, refresher,- func() (*http.Response, error) {- called++- if called == 1 {- return &http.Response{- StatusCode: http.StatusBadRequest,- Body: io.NopCloser(strings.NewReader(`-{"error":"invalid_token","error_description":"Token is expired. You can either do re-authorization or token refresh."}-`)),- }, nil- }- return &http.Response{- StatusCode: http.StatusOK,- Body: io.NopCloser(strings.NewReader(`{}`)),- }, nil- },+ _, _, err := oauth.Get(+ ctx,+ client,+ "https://api.github.com/users/octocat",+ &token,+ tokenRefresher(+ oauthContext{},+ refresher,+ ),)require.NoError(t, err)assert.Equal(t, "ghu_16C7e42F292c6912E7710c838347Ae178B4a", token)assert.True(t, calledRefresher)}--func TestRetry_Exceeded(t *testing.T) {- ctx := context.Background()- client := &http.Client{- Transport: &mockRoundTripper{- roundTrip: func(r *http.Request) (*http.Response, error) {- assert.Equal(t, "/login/oauth/access_token", r.URL.Path)- return &http.Response{- StatusCode: http.StatusOK,- Body: io.NopCloser(strings.NewReader(`{}`)),- Request: r,- }, nil- },- },- }- _ = client- token := "old"- _, _, err := retry(ctx, client, &token, oauthContext{},- func(_, _ string, _ int64) error { return nil },- func() (*http.Response, error) {- return &http.Response{- StatusCode: http.StatusBadRequest,- Body: io.NopCloser(strings.NewReader(`-{"error":"invalid_token","error_description":"Token is expired. You can either do re-authorization or token refresh."}-`)),- }, nil- },- )- wantErr := `retries exceeded for oauth refresher with status code 400 and body ""`- gotErr := fmt.Sprintf("%v", err)- assert.Equal(t, wantErr, gotErr)-}diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.goindex 4a09781837..32bb6aca68 100644--- a/plugin/vcs/gitlab/gitlab.go+++ b/plugin/vcs/gitlab/gitlab.go@@ -11,25 +11,23 @@ import ("strconv""strings"+ "github.com/pkg/errors""go.uber.org/zap""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/vcs"+ "github.com/bytebase/bytebase/plugin/vcs/internal/oauth")const (// SecretTokenLength is the length of secret token.SecretTokenLength = 16- maxRetries = 3-// apiPath is the API path.apiPath = "api/v4")-var (- _ vcs.Provider = (*Provider)(nil)-)+var _ vcs.Provider = (*Provider)(nil)// WebhookType is the gitlab webhook type.type WebhookType string@@ -179,24 +177,29 @@ func init() {vcs.Register(vcs.GitLabSelfHost, newProvider)}-// Provider is the GitLab self host provider.+// Provider is a GitLab self host VCS provider.type Provider struct {- l *zap.Logger+ l *zap.Logger+ client *http.Client}func newProvider(config vcs.ProviderConfig) vcs.Provider {+ if config.Client == nil {+ config.Client = &http.Client{}+ }return &Provider{- l: config.Logger,+ l: config.Logger,+ client: config.Client,}}// APIURL returns the API URL path of a GitLab instance.-func (provider *Provider) APIURL(instanceURL string) string {+func (p *Provider) APIURL(instanceURL string) string {return fmt.Sprintf("%s/%s", instanceURL, apiPath)}-// ExchangeOAuthToken exchange oauth content with the provdied authentication code-func (provider *Provider) ExchangeOAuthToken(ctx context.Context, instanceURL string, oauthExchange *common.OAuthExchange) (*vcs.OAuthToken, error) {+// ExchangeOAuthToken exchange oauth content with the provided authentication code.+func (p *Provider) ExchangeOAuthToken(ctx context.Context, instanceURL string, oauthExchange *common.OAuthExchange) (*vcs.OAuthToken, error) {urlParams := &url.Values{}urlParams.Set("client_id", oauthExchange.ClientID)urlParams.Set("client_secret", oauthExchange.ClientSecret)@@ -205,18 +208,15 @@ func (provider *Provider) ExchangeOAuthToken(ctx context.Context, instanceURL sturlParams.Set("grant_type", "authorization_code")url := fmt.Sprintf("%s/oauth/token?%s", instanceURL, urlParams.Encode())- req, err := http.NewRequest("POST", url, nil)-+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, nil)if err != nil {- urlParams.Set("client_secrete", "**encrypted**")- urlWithoutSecret := fmt.Sprintf("%s/oauth/token?%s", instanceURL, urlParams.Encode())- return nil, fmt.Errorf("failed to construct POST %v (%w)", urlWithoutSecret, err)+ urlParams.Set("client_secret", "**redacted**")+ redactedURL := fmt.Sprintf("%s/oauth/token?%s", instanceURL, urlParams.Encode())+ return nil, errors.Wrapf(err, "construct POST %s", redactedURL)}-req.Header.Set("Content-Type", "application/json")- client := &http.Client{}- resp, err := client.Do(req)+ resp, err := p.client.Do(req)if err != nil {return nil, fmt.Errorf("failed to exchange Oauth Token, code %v, error: %v", resp.StatusCode, err)}@@ -231,36 +231,40 @@ func (provider *Provider) ExchangeOAuthToken(ctx context.Context, instanceURL streturn nil, fmt.Errorf("failed to unmarshal oauth response body, code %v, error: %v", resp.StatusCode, err)}- // derivative expiresAt- // For GitLab, as of 13.12, the default config won't expire the access token, thus this field is 0.- // see https://gitlab.com/gitlab-org/gitlab/-/issues/21745.+ // For GitLab, as of 13.12, the default config won't expire the access token,+ // thus this field is 0. See https://gitlab.com/gitlab-org/gitlab/-/issues/21745.if oauthToken.ExpiresIn != 0 {oauthToken.ExpiresTs = oauthToken.CreatedAt + oauthToken.ExpiresIn}-return oauthToken, nil}-// FetchRepositoryList will fetch all repository in which the authenticated user has a maintainer role-func (provider *Provider) FetchRepositoryList(ctx context.Context, oauthCtx common.OauthContext, instanceURL string) ([]*vcs.Repository, error) {- code, body, err := httpGet(- instanceURL,- // 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)- "projects?membership=true&simple=true&min_access_level=40",+// FetchRepositoryList fetched all repositories in which the authenticated user+// has a maintainer role.+func (p *Provider) FetchRepositoryList(ctx context.Context, oauthCtx common.OauthContext, instanceURL string) ([]*vcs.Repository, 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/%s/projects?membership=true&simple=true&min_access_level=40", instanceURL, apiPath)+ code, body, err := oauth.Get(+ ctx,+ p.client,+ url,&oauthCtx.AccessToken,- oauthContext{- ClientID: oauthCtx.ClientID,- ClientSecret: oauthCtx.ClientSecret,- RefreshToken: oauthCtx.RefreshToken,- },- oauthCtx.Refresher,+ tokenRefresher(+ instanceURL,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),)if err != nil {- return nil, err+ return nil, errors.Wrap(err, "GET")}- if code == 404 {+ if code == http.StatusNotFound {return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to fetch repository list from GitLab instance %s", instanceURL))} else if code >= 300 {return nil, fmt.Errorf("failed to read repository list from GitLab instance %s, status code: %d",@@ -269,50 +273,53 @@ func (provider *Provider) FetchRepositoryList(ctx context.Context, oauthCtx comm)}- var gitLabrepository []gitLabRepository- if err := json.Unmarshal([]byte(body), &gitLabrepository); err != nil {- return nil, err+ var gitlabRepos []gitLabRepository+ if err := json.Unmarshal([]byte(body), &gitlabRepos); err != nil {+ return nil, errors.Wrap(err, "unmarshal")}- var repository []*vcs.Repository- for _, gitLabRepo := range gitLabrepository {+ var repos []*vcs.Repository+ for _, r := range gitlabRepos {repo := &vcs.Repository{- ID: gitLabRepo.ID,- Name: gitLabRepo.Name,- FullPath: gitLabRepo.PathWithNamespace,- WebURL: gitLabRepo.WebURL,+ ID: r.ID,+ Name: r.Name,+ FullPath: r.PathWithNamespace,+ WebURL: r.WebURL,}- repository = append(repository, repo)+ repos = append(repos, repo)}-- return repository, nil+ return repos, nil}-// fetchUserInfo will fetch user info from the given resourceURI, resourceURI should be either 'user' or 'users/:userID'-func fetchUserInfo(ctx context.Context, oauthCtx common.OauthContext, instanceURL, resourceURI string) (*vcs.UserInfo, error) {- code, body, err := httpGet(- instanceURL,- resourceURI,+// fetchUserInfo fetches user information from the given resourceURI, which+// should be either "user" or "users/{userID}".+func (p *Provider) fetchUserInfo(ctx context.Context, oauthCtx common.OauthContext, instanceURL, resourceURI string) (*vcs.UserInfo, error) {+ url := fmt.Sprintf("%s/%s/%s", instanceURL, apiPath, resourceURI)+ code, body, err := oauth.Get(+ ctx,+ p.client,+ url,&oauthCtx.AccessToken,- oauthContext{- ClientID: oauthCtx.ClientID,- ClientSecret: oauthCtx.ClientSecret,- RefreshToken: oauthCtx.RefreshToken,- },- oauthCtx.Refresher,+ tokenRefresher(+ instanceURL,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),)if err != nil {- return nil, err+ return nil, errors.Wrap(err, "GET")}- if code == 404 {+ if code == http.StatusNotFound {errInfo := []string{fmt.Sprintf("failed to fetch user info from GitLab instance %s", instanceURL)}-resourceURISplit := strings.Split(resourceURI, "/")if len(resourceURI) > 1 {- errInfo = append(errInfo, fmt.Sprintf("UserID: %v", resourceURISplit[1]))+ errInfo = append(errInfo, fmt.Sprintf("UserID: %s", resourceURISplit[1]))}-return nil, common.Errorf(common.NotFound, fmt.Errorf(strings.Join(errInfo, ", ")))} else if code >= 300 {return nil, fmt.Errorf("failed to read user info from GitLab instance %s, status code: %d",@@ -321,22 +328,21 @@ func fetchUserInfo(ctx context.Context, oauthCtx common.OauthContext, instanceUR)}- userInfo := &vcs.UserInfo{}- if err := json.Unmarshal([]byte(body), userInfo); err != nil {- return nil, err+ var userInfo vcs.UserInfo+ if err := json.Unmarshal([]byte(body), &userInfo); err != nil {+ return nil, errors.Wrap(err, "unmarshal")}-- return userInfo, err+ return &userInfo, err}-// TryLogin will try to fetch the user info from the current OAuth content of GitLab.-func (provider *Provider) TryLogin(ctx context.Context, oauthCtx common.OauthContext, instanceURL string) (*vcs.UserInfo, error) {- return fetchUserInfo(ctx, oauthCtx, instanceURL, "user")+// TryLogin tries to fetch the user info from the current OAuth context.+func (p *Provider) TryLogin(ctx context.Context, oauthCtx common.OauthContext, instanceURL string) (*vcs.UserInfo, error) {+ return p.fetchUserInfo(ctx, oauthCtx, instanceURL, "user")}-// FetchUserInfo will fetch user info from GitLab. If userID is set to nil, the user info of the current oauth would be returned.-func (provider *Provider) FetchUserInfo(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, userID string) (*vcs.UserInfo, error) {- return fetchUserInfo(ctx, oauthCtx, instanceURL, fmt.Sprintf("users/%s", userID))+// FetchUserInfo fetches user info of given user ID.+func (p *Provider) FetchUserInfo(ctx context.Context, oauthCtx common.OauthContext, instanceURL, userID string) (*vcs.UserInfo, error) {+ return p.fetchUserInfo(ctx, oauthCtx, instanceURL, fmt.Sprintf("users/%s", userID))}func getRoleAndMappedRole(accessLevel int32) (gitLabRole ProjectRole, bytebaseRole common.ProjectRole) {@@ -362,21 +368,26 @@ func getRoleAndMappedRole(accessLevel int32) (gitLabRole ProjectRole, bytebaseRo}// FetchRepositoryActiveMemberList fetch all active members of a repository-func (provider *Provider) FetchRepositoryActiveMemberList(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string) ([]*vcs.RepositoryMember, error) {- code, body, err := httpGet(- instanceURL,- // official API doc: https://docs.gitlab.com/14.6/ee/api/members.html- fmt.Sprintf("projects/%s/members/all", repositoryID),+func (p *Provider) FetchRepositoryActiveMemberList(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string) ([]*vcs.RepositoryMember, error) {+ // Official API doc: https://docs.gitlab.com/14.6/ee/api/members.html+ url := fmt.Sprintf("%s/%s/projects/%s/members/all", instanceURL, apiPath, repositoryID)+ code, body, err := oauth.Get(+ ctx,+ p.client,+ url,&oauthCtx.AccessToken,- oauthContext{- ClientID: oauthCtx.ClientID,- ClientSecret: oauthCtx.ClientSecret,- RefreshToken: oauthCtx.RefreshToken,- },- oauthCtx.Refresher,+ tokenRefresher(+ instanceURL,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),)if err != nil {- return nil, err+ return nil, errors.Wrap(err, "GET")}if code == 404 {@@ -402,7 +413,7 @@ func (provider *Provider) FetchRepositoryActiveMemberList(ctx context.Context, o// And since most callers are not GitLab admins, thus we fetch public email// TODO: need to work around this if the user does not set public email. For now, we just return an error listing users not having public emails.// TODO: if the number of the member is too large, fetching sequentially may cause performance issue- userInfo, err := provider.FetchUserInfo(ctx, oauthCtx, instanceURL, strconv.Itoa(gitLabMember.ID))+ userInfo, err := p.FetchUserInfo(ctx, oauthCtx, instanceURL, strconv.Itoa(gitLabMember.ID))if err != nil {return nil, err}@@ -431,17 +442,22 @@ func (provider *Provider) FetchRepositoryActiveMemberList(ctx context.Context, o}// FetchRepositoryFileList fetch the files from repository tree-func (provider *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, ref string, filePath string) ([]*vcs.RepositoryTreeNode, error) {- code, body, err := httpGet(- instanceURL,- fmt.Sprintf("projects/%s/repository/tree?recursive=true&ref=%s&path=%s", repositoryID, ref, filePath),+func (p *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, ref, filePath string) ([]*vcs.RepositoryTreeNode, error) {+ url := fmt.Sprintf("%s/%s/projects/%s/repository/tree?recursive=true&ref=%s&path=%s", instanceURL, apiPath, repositoryID, ref, filePath)+ code, body, err := oauth.Get(+ ctx,+ p.client,+ url,&oauthCtx.AccessToken,- oauthContext{- ClientID: oauthCtx.ClientID,- ClientSecret: oauthCtx.ClientSecret,- RefreshToken: oauthCtx.RefreshToken,- },- oauthCtx.Refresher,+ tokenRefresher(+ instanceURL,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),)if err != nil {return nil, fmt.Errorf("failed to fetch repository tree on GitLab instance %s, err: %w", instanceURL, err)@@ -470,7 +486,7 @@ func (provider *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx}// CreateFile creates a file.-func (provider *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, fileCommitCreate vcs.FileCommitCreate) error {+func (p *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate) error {body, err := json.Marshal(FileCommit{Branch: fileCommitCreate.Branch,CommitMessage: fileCommitCreate.CommitMessage,@@ -480,17 +496,22 @@ func (provider *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthCreturn fmt.Errorf("failed to marshal file commit: %w", err)}- code, _, err := httpPost(- instanceURL,- fmt.Sprintf("projects/%s/repository/files/%s", repositoryID, url.QueryEscape(filePath)),+ url := fmt.Sprintf("%s/%s/projects/%s/repository/files/%s", instanceURL, apiPath, repositoryID, url.QueryEscape(filePath))+ code, _, err := oauth.Post(+ ctx,+ p.client,+ url,&oauthCtx.AccessToken,- bytes.NewBuffer(body),- oauthContext{- ClientID: oauthCtx.ClientID,- ClientSecret: oauthCtx.ClientSecret,- RefreshToken: oauthCtx.RefreshToken,- },- oauthCtx.Refresher,+ bytes.NewReader(body),+ tokenRefresher(+ instanceURL,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),)if err != nil {return fmt.Errorf("failed to create file %s on GitLab instance %s, err: %w", filePath, instanceURL, err)@@ -507,7 +528,7 @@ func (provider *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthC}// OverwriteFile overwrite the content of a file.-func (provider *Provider) OverwriteFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, fileCommitCreate vcs.FileCommitCreate) error {+func (p *Provider) OverwriteFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate) error {body, err := json.Marshal(FileCommit{Branch: fileCommitCreate.Branch,CommitMessage: fileCommitCreate.CommitMessage,@@ -518,17 +539,22 @@ func (provider *Provider) OverwriteFile(ctx context.Context, oauthCtx common.Oaureturn fmt.Errorf("failed to marshal file commit: %w", err)}- code, _, err := httpPut(- instanceURL,- fmt.Sprintf("projects/%s/repository/files/%s", repositoryID, url.QueryEscape(filePath)),+ url := fmt.Sprintf("%s/%s/projects/%s/repository/files/%s", instanceURL, apiPath, repositoryID, url.QueryEscape(filePath))+ code, _, err := oauth.Put(+ ctx,+ p.client,+ url,&oauthCtx.AccessToken,- bytes.NewBuffer(body),- oauthContext{- ClientID: oauthCtx.ClientID,- ClientSecret: oauthCtx.ClientSecret,- RefreshToken: oauthCtx.RefreshToken,- },- oauthCtx.Refresher,+ bytes.NewReader(body),+ tokenRefresher(+ instanceURL,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),)if err != nil {return fmt.Errorf("failed to create file %s on GitLab instance %s, error: %w", filePath, instanceURL, err)@@ -545,19 +571,23 @@ func (provider *Provider) OverwriteFile(ctx context.Context, oauthCtx common.Oau}// ReadFile reads the content of a file.-func (provider *Provider) ReadFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, commitID string) (string, error) {- code, body, err := httpGet(- instanceURL,- fmt.Sprintf("projects/%s/repository/files/%s/raw?ref=%s", repositoryID, url.QueryEscape(filePath), commitID),+func (p *Provider) ReadFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath, commitID string) (string, error) {+ url := fmt.Sprintf("%s/%s/projects/%s/repository/files/%s/raw?ref=%s", instanceURL, apiPath, repositoryID, url.QueryEscape(filePath), commitID)+ code, body, err := oauth.Get(+ ctx,+ p.client,+ url,&oauthCtx.AccessToken,- oauthContext{- ClientID: oauthCtx.ClientID,- ClientSecret: oauthCtx.ClientSecret,- RefreshToken: oauthCtx.RefreshToken,- },- oauthCtx.Refresher,+ tokenRefresher(+ instanceURL,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),)-if err != nil {return "", fmt.Errorf("failed to read file %s from GitLab instance %s: %w", filePath, instanceURL, err)}@@ -576,19 +606,23 @@ func (provider *Provider) ReadFile(ctx context.Context, oauthCtx common.OauthCon}// ReadFileMeta reads the metadata of a file.-func (provider *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, branch string) (*vcs.FileMeta, error) {- code, body, err := httpGet(- instanceURL,- fmt.Sprintf("projects/%s/repository/files/%s?ref=%s", repositoryID, url.QueryEscape(filePath), url.QueryEscape(branch)),+func (p *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath, branch string) (*vcs.FileMeta, error) {+ url := fmt.Sprintf("%s/%s/projects/%s/repository/files/%s?ref=%s", instanceURL, apiPath, repositoryID, url.QueryEscape(filePath), url.QueryEscape(branch))+ code, body, err := oauth.Get(+ ctx,+ p.client,+ url,&oauthCtx.AccessToken,- oauthContext{- ClientID: oauthCtx.ClientID,- ClientSecret: oauthCtx.ClientSecret,- RefreshToken: oauthCtx.RefreshToken,- },- oauthCtx.Refresher,+ tokenRefresher(+ instanceURL,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),)-if err != nil {return nil, fmt.Errorf("failed to read file meta %s from GitLab instance %s: %w", filePath, instanceURL, err)}@@ -614,19 +648,23 @@ func (provider *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.Oaut}// CreateWebhook creates a webhook in a GitLab project.-func (provider *Provider) CreateWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, payload []byte) (string, error) {- resourcePath := fmt.Sprintf("projects/%s/hooks", repositoryID)- code, body, err := httpPost(- instanceURL,- resourcePath,+func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, payload []byte) (string, error) {+ url := fmt.Sprintf("%s/%s/projects/%s/hooks", instanceURL, apiPath, repositoryID)+ code, body, err := oauth.Post(+ ctx,+ p.client,+ url,&oauthCtx.AccessToken,- bytes.NewBuffer(payload),- oauthContext{- ClientID: oauthCtx.ClientID,- ClientSecret: oauthCtx.ClientSecret,- RefreshToken: oauthCtx.RefreshToken,- },- oauthCtx.Refresher,+ bytes.NewReader(payload),+ tokenRefresher(+ instanceURL,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),)if err != nil {return "", fmt.Errorf("failed to create webhook for repository %s from GitLab instance %s: %w", repositoryID, instanceURL, err)@@ -655,19 +693,23 @@ func (provider *Provider) CreateWebhook(ctx context.Context, oauthCtx common.Oau}// PatchWebhook patches a webhook in a GitLab project.-func (provider *Provider) PatchWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, webhookID string, payload []byte) error {- resourcePath := fmt.Sprintf("projects/%s/hooks/%s", repositoryID, webhookID)- code, _, err := httpPut(- instanceURL,- resourcePath,+func (p *Provider) PatchWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, webhookID string, payload []byte) error {+ url := fmt.Sprintf("%s/%s/projects/%s/hooks/%s", instanceURL, apiPath, repositoryID, webhookID)+ code, _, err := oauth.Put(+ ctx,+ p.client,+ url,&oauthCtx.AccessToken,- bytes.NewBuffer(payload),- oauthContext{- ClientID: oauthCtx.ClientID,- ClientSecret: oauthCtx.ClientSecret,- RefreshToken: oauthCtx.RefreshToken,- },- oauthCtx.Refresher,+ bytes.NewReader(payload),+ tokenRefresher(+ instanceURL,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),)if err != nil {return fmt.Errorf("failed to patch webhook ID %s for repository %s from GitLab instance %s: %w", webhookID, repositoryID, instanceURL, err)@@ -680,18 +722,22 @@ func (provider *Provider) PatchWebhook(ctx context.Context, oauthCtx common.Oaut}// DeleteWebhook deletes a webhook in a GitLab project.-func (provider *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, webhookID string) error {- resourcePath := fmt.Sprintf("projects/%s/hooks/%s", repositoryID, webhookID)- code, _, err := httpDelete(- instanceURL,- resourcePath,+func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, webhookID string) error {+ url := fmt.Sprintf("%s/%s/projects/%s/hooks/%s", instanceURL, apiPath, repositoryID, webhookID)+ code, _, err := oauth.Delete(+ ctx,+ p.client,+ url,&oauthCtx.AccessToken,- oauthContext{- ClientID: oauthCtx.ClientID,- ClientSecret: oauthCtx.ClientSecret,- RefreshToken: oauthCtx.RefreshToken,- },- oauthCtx.Refresher,+ tokenRefresher(+ instanceURL,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),)if err != nil {return fmt.Errorf("failed to delete webhook ID %s for repository %s from GitLab instance %s: %w", webhookID, repositoryID, instanceURL, err)@@ -703,215 +749,68 @@ func (provider *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.Oaureturn nil}-// httpPost sends a POST request.-func httpPost(instanceURL string, resourcePath string, token *string, body io.Reader, oauthContext oauthContext, refresher common.TokenRefresher) (code int, respBody string, err error) {- return retry(instanceURL, token, oauthContext, refresher, func() (*http.Response, error) {- url := fmt.Sprintf("%s/%s/%s", instanceURL, apiPath, resourcePath)- req, err := http.NewRequest("POST",- url, body)- if err != nil {- return nil, fmt.Errorf("failed to construct POST %v (%w)", url, err)- }-- req.Header.Set("Content-Type", "application/json")- req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", *token))- client := &http.Client{}- resp, err := client.Do(req)- if err != nil {- return nil, fmt.Errorf("failed POST %v (%w)", url, err)- }- return resp, nil- })+// oauthContext is the request context for refreshing oauth token.+type oauthContext struct {+ ClientID string `json:"client_id"`+ ClientSecret string `json:"client_secret"`+ RefreshToken string `json:"refresh_token"`+ GrantType string `json:"grant_type"`}-// httpGet sends a GET request.-func httpGet(instanceURL string, resourcePath string, token *string, oauthContext oauthContext, refresher common.TokenRefresher) (code int, respBody string, err error) {- return retry(instanceURL, token, oauthContext, refresher, func() (*http.Response, error) {- url := fmt.Sprintf("%s/%s/%s", instanceURL, apiPath, resourcePath)- req, err := http.NewRequest("GET",- url, nil)- if err != nil {- return nil, fmt.Errorf("failed to construct GET %v (%w)", url, err)- }+type refreshOauthResponse struct {+ AccessToken string `json:"access_token"`+ RefreshToken string `json:"refresh_token"`+ ExpiresIn int64 `json:"expires_in"`+ CreatedAt int64 `json:"created_at"`+ // token_type, scope are not used.+}- req.Header.Set("Content-Type", "application/json")- req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", *token))- client := &http.Client{}- resp, err := client.Do(req)+func tokenRefresher(instanceURL string, oauthCtx oauthContext, refresher common.TokenRefresher) oauth.TokenRefresher {+ return func(ctx context.Context, client *http.Client, oldToken *string) error {+ url := fmt.Sprintf("%s/oauth/token", instanceURL)+ oauthCtx.GrantType = "refresh_token"+ body, err := json.Marshal(oauthCtx)if err != nil {- return nil, fmt.Errorf("failed GET %v (%w)", url, err)+ return err}- return resp, nil- })-}-// httpPut sends a PUT request.-func httpPut(instanceURL string, resourcePath string, token *string, body io.Reader, oauthContext oauthContext, refresher common.TokenRefresher) (code int, respBody string, err error) {- return retry(instanceURL, token, oauthContext, refresher, func() (*http.Response, error) {- url := fmt.Sprintf("%s/%s/%s", instanceURL, apiPath, resourcePath)- req, err := http.NewRequest("PUT",- url, body)+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))if err != nil {- return nil, fmt.Errorf("failed to construct PUT %v (%w)", url, err)+ return errors.Wrapf(err, "construct POST %s", url)}req.Header.Set("Content-Type", "application/json")- req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", *token))- client := &http.Client{}resp, err := client.Do(req)if err != nil {- return nil, fmt.Errorf("failed PUT %v (%w)", url, err)+ return errors.Wrapf(err, "POST %s", url)}- return resp, nil- })-}-// httpDelete sends a DELETE request.-func httpDelete(instanceURL string, resourcePath string, token *string, oauthContext oauthContext, refresher common.TokenRefresher) (code int, respBody string, err error) {- return retry(instanceURL, token, oauthContext, refresher, func() (*http.Response, error) {- url := fmt.Sprintf("%s/%s/%s", instanceURL, apiPath, resourcePath)- req, err := http.NewRequest("DELETE",- url, nil)+ body, err = io.ReadAll(resp.Body)if err != nil {- return nil, fmt.Errorf("failed to construct DELETE %v (%w)", url, err)+ return errors.Wrapf(err, "read body of POST %s", url)}- req.Header.Set("Content-Type", "application/json")- req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", *token))- client := &http.Client{}- resp, err := client.Do(req)- if err != nil {- return nil, fmt.Errorf("failed DELETE %v (%w)", url, err)+ if resp.StatusCode != http.StatusOK {+ return errors.Errorf("non-200 status code %d with body %q", resp.StatusCode, body)}- return resp, nil- })-}--func retry(instanceURL string, token *string, oauthContext oauthContext, refresher common.TokenRefresher, f func() (*http.Response, error)) (code int, respBody string, err error) {- retries := 0-RETRY:- retries++-- resp, err := f()- if err != nil {- return 0, "", err- }- body, err := io.ReadAll(resp.Body)- if err != nil {- return 0, "", fmt.Errorf("failed to read gitlab response body, code %v, error: %v", resp.StatusCode, err)- }-- if err := getOAuthErrorDetails(resp.StatusCode, string(body)); err != nil {- if _, ok := err.(oauthError); ok && retries < maxRetries {- // Refresh and store the token.- if err := refreshToken(instanceURL, token, oauthContext, refresher); err != nil {- return 0, "", err- }- goto RETRY+ var r refreshOauthResponse+ if err := json.Unmarshal(body, &r); err != nil {+ return errors.Wrapf(err, "unmarshal body from POST %s", url)}- // err must be oauthError. So this happens only when the number of retries has exceeded.- return 0, "", fmt.Errorf("retries exceeded for oauth refresher; original code %v body %s; oauth error: %v", resp.StatusCode, string(body), err)- }-- return resp.StatusCode, string(body), nil-}--type oauthError struct {- Err string `json:"error"`- ErrorDescription string `json:"error_description"`-}-func (e oauthError) Error() string {- return fmt.Sprintf("gitlab oauth response error %q description %q", e.Err, e.ErrorDescription)-}+ // Update the old token to new value for retries.+ *oldToken = r.AccessToken-// Only returns error if it's an oauth error. For other errors like 404 we don't return error.-// We do this because this method is only intended to be used by oauth to refresh access token-// on expiration. When it's error like 404, GitLab api doesn't return it as error so we keep the-// similar behavior and let caller check the response status code.-func getOAuthErrorDetails(code int, body string) error {- if 200 <= code && code < 300 {- return nil- }-- var oe oauthError- if err := json.Unmarshal([]byte(body), &oe); err != nil {- // If we failed to unmarshal body with oauth error, it's not oauthError and we should return nil.+ // For GitLab, as of 13.12, the default config won't expire the access token,+ // thus this field is 0. See https://gitlab.com/gitlab-org/gitlab/-/issues/21745.+ var expireAt int64+ if r.ExpiresIn != 0 {+ expireAt = r.CreatedAt + r.ExpiresIn+ }+ if err := refresher(r.AccessToken, r.RefreshToken, expireAt); err != nil {+ return err+ }return nil}- // https://www.oauth.com/oauth2-servers/access-tokens/access-token-response/- // {"error":"invalid_token","error_description":"Token is expired. You can either do re-authorization or token refresh."}- if oe.Err == "invalid_token" && strings.Contains(oe.ErrorDescription, "expired") {- return &oe- }- return nil-}--// oauthContext is the request context for refreshing oauth token.-type oauthContext struct {- ClientID string `json:"client_id"`- ClientSecret string `json:"client_secret"`- RefreshToken string `json:"refresh_token"`- GrantType string `json:"grant_type"`-}--type refreshOauthResponse struct {- AccessToken string `json:"access_token"`- RefreshToken string `json:"refresh_token"`- ExpiresIn int64 `json:"expires_in"`- CreatedAt int64 `json:"created_at"`- // token_type, scope are not used.-}--func refreshToken(instanceURL string, oldToken *string, oauthContext oauthContext, refresher common.TokenRefresher) error {- url := fmt.Sprintf("%s/oauth/token", instanceURL)- oauthContext.GrantType = "refresh_token"- body, err := json.Marshal(oauthContext)- if err != nil {- return err- }-- req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))- if err != nil {- return fmt.Errorf("failed to construct refresh token POST %v (%w)", url, err)- }- req.Header.Set("Content-Type", "application/json")- client := &http.Client{}- resp, err := client.Do(req)- if err != nil {- return fmt.Errorf("failed to send refresh token POST %v (%w)", url, err)- }- body, err = io.ReadAll(resp.Body)- if err != nil {- return fmt.Errorf("failed to read body from refresh token POST %v (%w)", url, err)- }-- // We should not call getOAuthErrorDetails.- // In the sequence of 1) get file content with oauth error, 2) refresh token.- // If step 2) failed still with oauth error, we should stop retries because we should always expect refreshing token request to succeed unless we're holding any invalid refresh token already.-- if resp.StatusCode != http.StatusOK {- return fmt.Errorf("failed to fetch refresh token, response code %v body %s", resp.StatusCode, body)- }-- var r refreshOauthResponse- if err := json.Unmarshal([]byte(body), &r); err != nil {- return fmt.Errorf("failed to unmarshal body from refresh token POST %v (%w)", url, err)- }-- // Update the old token to new value for retries.- *oldToken = r.AccessToken-- // For GitLab, as of 13.12, the default config won't expire the access token, thus this field is 0.- // see https://gitlab.com/gitlab-org/gitlab/-/issues/21745.- var expireAt int64- if r.ExpiresIn != 0 {- expireAt = r.CreatedAt + r.ExpiresIn- }- if err := refresher(r.AccessToken, r.RefreshToken, expireAt); err != nil {- return err- }-- return nil}diff --git a/plugin/vcs/gitlab/gitlab_test.go b/plugin/vcs/gitlab/gitlab_test.gonew file mode 100644index 0000000000..0ab7bb9f98--- /dev/null+++ b/plugin/vcs/gitlab/gitlab_test.go@@ -0,0 +1,123 @@+package gitlab++import (+ "context"+ "io"+ "net/http"+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/plugin/vcs"+ "github.com/bytebase/bytebase/plugin/vcs/internal/oauth"+)++func TestProvider_FetchUserInfo(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/users/1", r.URL.Path)+ return &http.Response{+ StatusCode: http.StatusOK,+ // Example response taken from https://docs.gitlab.com/ee/api/users.html#single-user+ Body: io.NopCloser(strings.NewReader(`+{+ "id": 1,+ "username": "john_smith",+ "name": "John Smith",+ "state": "active",+ "avatar_url": "http://localhost:3000/uploads/user/avatar/1/cd8.jpeg",+ "web_url": "http://localhost:3000/john_smith",+ "created_at": "2012-05-23T08:00:58Z",+ "bio": "",+ "bot": false,+ "location": null,+ "public_email": "[email protected]",+ "skype": "",+ "linkedin": "",+ "twitter": "",+ "website_url": "",+ "organization": "",+ "job_title": "Operations Specialist",+ "followers": 1,+ "following": 1+}+`)),+ }, nil+ },+ },+ },+ },+ )++ ctx := context.Background()+ got, err := p.FetchUserInfo(ctx, common.OauthContext{}, "", "1")+ require.NoError(t, err)++ want := &vcs.UserInfo{+ PublicEmail: "[email protected]",+ Name: "John Smith",+ State: vcs.StateActive,+ }+ assert.Equal(t, want, got)+}++func TestOAuth_RefreshToken(t *testing.T) {+ ctx := context.Background()+ client := &http.Client{+ Transport: &common.MockRoundTripper{+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {+ token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")+ if token == "expired" {+ return &http.Response{+ StatusCode: http.StatusBadRequest,+ Body: io.NopCloser(strings.NewReader(`+ {"error":"invalid_token","error_description":"Token is expired. You can either do re-authorization or token refresh."}+ `)),+ }, nil+ }++ return &http.Response{+ StatusCode: http.StatusOK,+ // Example response taken from https://docs.gitlab.com/ee/api/oauth2.html#authorization-code-with-proof-key-for-code-exchange-pkce+ Body: io.NopCloser(strings.NewReader(`+{+ "access_token": "de6780bc506a0446309bd9362820ba8aed28aa506c71eedbe1c5c4f9dd350e54",+ "token_type": "bearer",+ "expires_in": 7200,+ "refresh_token": "8257e65c97202ed1726cf9571600918f3bffb2544b26e00a61df9897668c33a1",+ "created_at": 1607635748+}+`)),+ }, nil+ },+ },+ }+ token := "expired"++ calledRefresher := false+ refresher := func(_, _ string, _ int64) error {+ calledRefresher = true+ return nil+ }++ _, _, err := oauth.Get(+ ctx,+ client,+ "https://gitlab.example.com/api/v4/users/octocat",+ &token,+ tokenRefresher(+ "https://gitlab.example.com",+ oauthContext{},+ refresher,+ ),+ )+ require.NoError(t, err)+ assert.Equal(t, "de6780bc506a0446309bd9362820ba8aed28aa506c71eedbe1c5c4f9dd350e54", token)+ assert.True(t, calledRefresher)+}diff --git a/plugin/vcs/internal/oauth/oauth.go b/plugin/vcs/internal/oauth/oauth.gonew file mode 100644index 0000000000..7367c890cf--- /dev/null+++ b/plugin/vcs/internal/oauth/oauth.go@@ -0,0 +1,127 @@+package oauth++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "strings"++ "github.com/pkg/errors"+)++// TokenRefresher is a function to refresh the OAuth token and assign back to+// the old token upon a successful refresh.+type TokenRefresher func(ctx context.Context, client *http.Client, oldToken *string) error++func requester(ctx context.Context, client *http.Client, method, url string, token *string, body io.Reader) func() (*http.Response, error) {+ return func() (*http.Response, error) {+ req, err := http.NewRequestWithContext(ctx, method, url, body)+ if err != nil {+ return nil, errors.Wrapf(err, "construct %s %s", method, url)+ }++ req.Header.Set("Content-Type", "application/json")+ req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", *token))+ resp, err := client.Do(req)+ if err != nil {+ return nil, errors.Wrapf(err, "%s %s", method, url)+ }+ return resp, nil+ }+}++// Post makes a HTTP POST request to the given URL using the token. It refreshes+// token and retries the request in the case of the token has expired.+func Post(ctx context.Context, client *http.Client, url string, token *string, body io.Reader, tokenRefresher TokenRefresher) (code int, respBody string, err error) {+ return retry(ctx, client, token, tokenRefresher, requester(ctx, client, http.MethodPost, url, token, body))+}++// Get makes a HTTP GET request to the given URL using the token. It refreshes+// token and retries the request in the case of the token has expired.+func Get(ctx context.Context, client *http.Client, url string, token *string, tokenRefresher TokenRefresher) (code int, respBody string, err error) {+ return retry(ctx, client, token, tokenRefresher, requester(ctx, client, http.MethodGet, url, token, nil))+}++// Put makes a HTTP PUT request to the given URL using the token. It refreshes+// token and retries the request in the case of the token has expired.+func Put(ctx context.Context, client *http.Client, url string, token *string, body io.Reader, tokenRefresher TokenRefresher) (code int, respBody string, err error) {+ return retry(ctx, client, token, tokenRefresher, requester(ctx, client, http.MethodPut, url, token, body))+}++// Delete makes a HTTP DELETE request to the given URL using the token. It refreshes+// token and retries the request in the case of the token has expired.+func Delete(ctx context.Context, client *http.Client, url string, token *string, tokenRefresher TokenRefresher) (code int, respBody string, err error) {+ return retry(ctx, client, token, tokenRefresher, requester(ctx, client, http.MethodDelete, url, token, nil))+}++const maxRetries = 3++func retry(ctx context.Context, client *http.Client, token *string, tokenRefresher TokenRefresher, f func() (*http.Response, error)) (code int, respBody string, err error) {+ var resp *http.Response+ var body []byte+ for retries := 0; retries < maxRetries; retries++ {+ select {+ case <-ctx.Done():+ return 0, "", ctx.Err()+ default:+ }++ resp, err = f()+ if err != nil {+ return 0, "", err+ }++ body, err := io.ReadAll(resp.Body)+ if err != nil {+ return 0, "", errors.Wrapf(err, "read response body with status code %d", resp.StatusCode)+ }++ if err = getOAuthErrorDetails(resp.StatusCode, body); err != nil {+ if _, ok := err.(*oauthError); ok {+ // Refresh the token+ if err := tokenRefresher(ctx, client, token); err != nil {+ return 0, "", err+ }+ continue+ }+ return 0, "", errors.Errorf("got unexpected OAuth error %T", err)+ }+ return resp.StatusCode, string(body), nil+ }+ return 0, "", errors.Errorf("retries exceeded for OAuth refresher with status code %d and body %q", resp.StatusCode, string(body))+}++type oauthError struct {+ Err string `json:"error"`+ ErrorDescription string `json:"error_description"`+}++func (e oauthError) Error() string {+ return fmt.Sprintf("OAuth response error %q description %q", e.Err, e.ErrorDescription)+}++// getOAuthErrorDetails only returns error if it's an OAuth error. For other+// errors like 404 we don't return error. We do this because this method is only+// intended to be used by oauth to refresh access token on expiration.+//+// When it's error like 404, GitLab API doesn't return it as error so we keep+// the similar behavior and let caller check the response status code.+func getOAuthErrorDetails(code int, body []byte) error {+ if 200 <= code && code < 300 {+ return nil+ }++ var oe oauthError+ if err := json.Unmarshal(body, &oe); err != nil {+ // If we failed to unmarshal body with oauth error, it's not oauthError and we should return nil.+ return nil+ }+ // https://www.oauth.com/oauth2-servers/access-tokens/access-token-response/+ // {"error":"invalid_token","error_description":"Token is expired. You can either do re-authorization or token refresh."}+ if oe.Err == "invalid_token" && strings.Contains(oe.ErrorDescription, "expired") {+ return &oe+ }+ return nil+}diff --git a/plugin/vcs/internal/oauth/oauth_test.go b/plugin/vcs/internal/oauth/oauth_test.gonew file mode 100644index 0000000000..9b3151718c--- /dev/null+++ b/plugin/vcs/internal/oauth/oauth_test.go@@ -0,0 +1,111 @@+package oauth++import (+ "context"+ "fmt"+ "io"+ "net/http"+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/common"+)++func TestPost(t *testing.T) {+ ctx := context.Background()+ client := &http.Client{+ Transport: &common.MockRoundTripper{+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {+ assert.Equal(t, http.MethodPost, r.Method)+ assert.Equal(t, "application/json", r.Header.Get("Content-Type"))+ assert.Equal(t, "Bearer token", r.Header.Get("Authorization"))++ body, err := io.ReadAll(r.Body)+ require.NoError(t, err)+ assert.Equal(t, "POST body", string(body))+ return &http.Response{}, nil+ },+ },+ }+ token := "token"+ _, _, err := Post(ctx, client, "", &token, strings.NewReader("POST body"), nil)+ require.NoError(t, err)+}++func TestGet(t *testing.T) {+ ctx := context.Background()+ client := &http.Client{+ Transport: &common.MockRoundTripper{+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {+ assert.Equal(t, http.MethodGet, r.Method)+ assert.Equal(t, "application/json", r.Header.Get("Content-Type"))+ assert.Equal(t, "Bearer token", r.Header.Get("Authorization"))+ return &http.Response{}, nil+ },+ },+ }+ token := "token"+ _, _, err := Get(ctx, client, "", &token, nil)+ require.NoError(t, err)+}++func TestPut(t *testing.T) {+ ctx := context.Background()+ client := &http.Client{+ Transport: &common.MockRoundTripper{+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {+ assert.Equal(t, http.MethodPut, r.Method)+ assert.Equal(t, "application/json", r.Header.Get("Content-Type"))+ assert.Equal(t, "Bearer token", r.Header.Get("Authorization"))++ body, err := io.ReadAll(r.Body)+ require.NoError(t, err)+ assert.Equal(t, "PUT body", string(body))+ return &http.Response{}, nil+ },+ },+ }+ token := "token"+ _, _, err := Put(ctx, client, "", &token, strings.NewReader("PUT body"), nil)+ require.NoError(t, err)+}++func TestDelete(t *testing.T) {+ ctx := context.Background()+ client := &http.Client{+ Transport: &common.MockRoundTripper{+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {+ assert.Equal(t, http.MethodDelete, r.Method)+ assert.Equal(t, "application/json", r.Header.Get("Content-Type"))+ assert.Equal(t, "Bearer token", r.Header.Get("Authorization"))+ return &http.Response{}, nil+ },+ },+ }+ token := "token"+ _, _, err := Delete(ctx, client, "", &token, nil)+ require.NoError(t, err)+}++func TestRetry_Exceeded(t *testing.T) {+ ctx := context.Background()+ token := "expired"++ _, _, err := retry(ctx, nil, &token,+ func(_ context.Context, _ *http.Client, _ *string) error { return nil },+ func() (*http.Response, error) {+ return &http.Response{+ StatusCode: http.StatusBadRequest,+ Body: io.NopCloser(strings.NewReader(`+{"error":"invalid_token","error_description":"Token is expired. You can either do re-authorization or token refresh."}+`)),+ }, nil+ },+ )+ wantErr := `retries exceeded for OAuth refresher with status code 400 and body ""`+ gotErr := fmt.Sprintf("%v", err)+ assert.Equal(t, wantErr, gotErr)+}