Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(oauth): correctly handle access token refresh (#5149)
Joe Chenab57a9437c78
diff --git a/backend/plugin/vcs/bitbucket/bitbucket.go b/backend/plugin/vcs/bitbucket/bitbucket.goindex c6b5a7ed41..c2c920cfb7 100644--- a/backend/plugin/vcs/bitbucket/bitbucket.go+++ b/backend/plugin/vcs/bitbucket/bitbucket.go@@ -987,10 +987,10 @@ func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthConte// 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"`+ ClientID string+ ClientSecret string+ RefreshToken string+ GrantType string}type refreshOAuthResponse struct {@@ -1002,11 +1002,12 @@ type refreshOAuthResponse struct {func tokenRefresher(instanceURL string, oauthCtx oauthContext, refresher common.TokenRefresher) oauth.TokenRefresher {return func(ctx context.Context, client *http.Client, oldToken *string) error {- form := &url.Values{}- form.Set("grant_type", "refresh_token")- form.Set("refresh_token", oauthCtx.RefreshToken)+ params := &url.Values{}+ params.Set("grant_type", "refresh_token")+ params.Set("refresh_token", oauthCtx.RefreshToken)+url := fmt.Sprintf("%s/site/oauth2/access_token", instanceURL)- req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(form.Encode()))+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(params.Encode()))if err != nil {return errors.Wrapf(err, "construct POST %s", url)}diff --git a/backend/plugin/vcs/bitbucket/bitbucket_test.go b/backend/plugin/vcs/bitbucket/bitbucket_test.goindex 2e97e3f4fb..a4d3561bfc 100644--- a/backend/plugin/vcs/bitbucket/bitbucket_test.go+++ b/backend/plugin/vcs/bitbucket/bitbucket_test.go@@ -877,7 +877,7 @@ func TestOAuth_RefreshToken(t *testing.T) {return &http.Response{StatusCode: http.StatusUnauthorized,Body: io.NopCloser(strings.NewReader(`- {"error":"invalid_token","error_description":"Token is expired. You can either do re-authorization or token refresh."}+ {"error":"invalid_grant","error_description":"The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."}`)),}, nil}diff --git a/backend/plugin/vcs/github/github.go b/backend/plugin/vcs/github/github.goindex c396e42f43..a6e5c6fbc8 100644--- a/backend/plugin/vcs/github/github.go+++ b/backend/plugin/vcs/github/github.go@@ -1333,10 +1333,10 @@ func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthConte// 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"`+ ClientID string+ ClientSecret string+ RefreshToken string+ GrantType string}type refreshOAuthResponse struct {@@ -1349,25 +1349,25 @@ type refreshOAuthResponse struct {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/login/oauth/access_token", instanceURL)- oauthCtx.GrantType = "refresh_token"- body, err := json.Marshal(oauthCtx)- if err != nil {- return err- }+ params := &url.Values{}+ params.Set("client_id", oauthCtx.ClientID)+ params.Set("client_secret", oauthCtx.ClientSecret)+ params.Set("refresh_token", oauthCtx.RefreshToken)+ params.Set("grant_type", "refresh_token")- req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))+ url := fmt.Sprintf("%s/login/oauth/access_token", instanceURL)+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(params.Encode()))if err != nil {return errors.Wrapf(err, "construct POST %s", url)}- req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")resp, err := client.Do(req)if err != nil {return errors.Wrapf(err, "POST %s", url)}- body, err = io.ReadAll(resp.Body)+ body, err := io.ReadAll(resp.Body)if err != nil {return errors.Wrapf(err, "read body of POST %s", url)}diff --git a/backend/plugin/vcs/github/github_test.go b/backend/plugin/vcs/github/github_test.goindex e5ded85a33..a43324c138 100644--- a/backend/plugin/vcs/github/github_test.go+++ b/backend/plugin/vcs/github/github_test.go@@ -732,7 +732,7 @@ func TestOAuth_RefreshToken(t *testing.T) {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."}+ {"error":"invalid_grant","error_description":"The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."}`)),}, nil}diff --git a/backend/plugin/vcs/gitlab/gitlab.go b/backend/plugin/vcs/gitlab/gitlab.goindex f0437909cd..78ff879625 100644--- a/backend/plugin/vcs/gitlab/gitlab.go+++ b/backend/plugin/vcs/gitlab/gitlab.go@@ -10,6 +10,7 @@ import ("net/http""net/url""strconv"+ "strings""time""github.com/pkg/errors"@@ -1227,10 +1228,10 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, i// 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"`+ ClientID string+ ClientSecret string+ RefreshToken string+ GrantType string}type refreshOauthResponse struct {@@ -1243,25 +1244,25 @@ type refreshOauthResponse struct {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 err- }+ params := &url.Values{}+ params.Set("client_id", oauthCtx.ClientID)+ params.Set("client_secret", oauthCtx.ClientSecret)+ params.Set("refresh_token", oauthCtx.RefreshToken)+ params.Set("grant_type", "refresh_token")- req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))+ url := fmt.Sprintf("%s/oauth/token", instanceURL)+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(params.Encode()))if err != nil {return errors.Wrapf(err, "construct POST %s", url)}- req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")resp, err := client.Do(req)if err != nil {return errors.Wrapf(err, "POST %s", url)}- body, err = io.ReadAll(resp.Body)+ body, err := io.ReadAll(resp.Body)if err != nil {return errors.Wrapf(err, "read body of POST %s", url)}diff --git a/backend/plugin/vcs/gitlab/gitlab_test.go b/backend/plugin/vcs/gitlab/gitlab_test.goindex 0c5df5664c..c41af0cd82 100644--- a/backend/plugin/vcs/gitlab/gitlab_test.go+++ b/backend/plugin/vcs/gitlab/gitlab_test.go@@ -428,7 +428,7 @@ func TestOAuth_RefreshToken(t *testing.T) {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."}+ {"error":"invalid_grant","error_description":"The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."}`)),}, nil}diff --git a/backend/server/oauth.go b/backend/server/oauth.goindex 515da9f26d..93b36d4471 100644--- a/backend/server/oauth.go+++ b/backend/server/oauth.go@@ -73,7 +73,7 @@ func (s *Server) registerOAuthRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find workspace setting").SetInternal(err)}- oauthExchange.RedirectURL = fmt.Sprintf("%s/oauth/callback", oauthRedirectURL(setting.ExternalUrl))+ oauthExchange.RedirectURL = fmt.Sprintf("%s/oauth/callback", setting.ExternalUrl)oauthToken, err := vcsPlugin.Get(vcsType, vcsPlugin.ProviderConfig{}).ExchangeOAuthToken(c.Request().Context(),@@ -81,7 +81,10 @@ func (s *Server) registerOAuthRoutes(g *echo.Group) {oauthExchange,)if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, oauthErrorMessage(setting.ExternalUrl)).SetInternal(err)+ return echo.NewHTTPError(+ http.StatusInternalServerError,+ fmt.Sprintf("Failed to exchange OAuth token. Make sure %q matches your browser host. Note that if you are not using port 80 or 443, you should also specify the port such as --external-url=http://host:port", setting.ExternalUrl),+ ).SetInternal(err)}resp := &api.OAuthToken{diff --git a/backend/server/project.go b/backend/server/project.goindex 4065972f13..ba0c7cc065 100644--- a/backend/server/project.go+++ b/backend/server/project.go@@ -287,7 +287,16 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {// When the branch names doesn't contain wildcards, we should make sure the branch exists in the repo.if !strings.Contains(repositoryCreate.BranchFilter, "*") {- notFound, err := isBranchNotFound(ctx, vcs, repositoryCreate.AccessToken, repositoryCreate.RefreshToken, repositoryCreate.ExternalID, repositoryCreate.BranchFilter)+ notFound, err := isBranchNotFound(+ ctx,+ vcs,+ s.store,+ repositoryCreate.WebURL,+ repositoryCreate.AccessToken,+ repositoryCreate.RefreshToken,+ repositoryCreate.ExternalID,+ repositoryCreate.BranchFilter,+ )if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get branch %q", repositoryCreate.BranchFilter)).SetInternal(err)}@@ -516,7 +525,16 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {// When the branch names doesn't contain wildcards, we should make sure the branch exists in the repo.if !strings.Contains(newBranchFilter, "*") {- notFound, err := isBranchNotFound(ctx, vcs, repo.AccessToken, repo.RefreshToken, repo.ExternalID, newBranchFilter)+ notFound, err := isBranchNotFound(+ ctx,+ vcs,+ s.store,+ repo.WebURL,+ repo.AccessToken,+ repo.RefreshToken,+ repo.ExternalID,+ newBranchFilter,+ )if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get branch %q", newBranchFilter)).SetInternal(err)}@@ -1306,14 +1324,14 @@ func refreshTokenNoop() common.TokenRefresher {}}-func isBranchNotFound(ctx context.Context, vcs *api.VCS, accessToken, refreshToken, externalID, branch string) (bool, error) {+func isBranchNotFound(ctx context.Context, vcs *api.VCS, store *store.Store, webURL, accessToken, refreshToken, externalID, branch string) (bool, error) {_, err := vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{}).GetBranch(ctx,common.OauthContext{ClientID: vcs.ApplicationID,ClientSecret: vcs.Secret,AccessToken: accessToken,RefreshToken: refreshToken,- Refresher: nil,+ Refresher: utils.RefreshToken(ctx, store, webURL),},vcs.InstanceURL, externalID, branch)diff --git a/backend/server/server_frontend_embed.go b/backend/server/server_frontend_embed.goindex 4e444d4013..b6aef9878f 100644--- a/backend/server/server_frontend_embed.go+++ b/backend/server/server_frontend_embed.go@@ -5,14 +5,11 @@ package serverimport ("embed"- "fmt""io/fs""net/http""github.com/labstack/echo/v4""github.com/labstack/echo/v4/middleware"-- "github.com/bytebase/bytebase/backend/common")//go:embed dist/assets/*@@ -50,14 +47,3 @@ func embedFrontend(e *echo.Echo) {Filesystem: getFileSystem("dist/assets"),}))}--func oauthRedirectURL(externalURL string) string {- return externalURL-}--func oauthErrorMessage(externalURL string) string {- if externalURL == "" {- return fmt.Sprintf("Failed to exchange OAuth token. You have not configured --external-url, please follow %s", common.ExternalURLPlaceholder)- }- return fmt.Sprintf("Failed to exchange OAuth token. Make sure --external-url %s matches your browser host. Note that if you are not using port 80 or 443, you should also specify the port such as --external-url=http://host:port", externalURL)-}diff --git a/backend/server/server_frontend_not_embed.go b/backend/server/server_frontend_not_embed.goindex 88108b3b1e..49607e5e58 100644--- a/backend/server/server_frontend_not_embed.go+++ b/backend/server/server_frontend_not_embed.go@@ -4,9 +4,7 @@package serverimport (- "fmt""net/http"- "os""github.com/labstack/echo/v4"@@ -20,17 +18,3 @@ func embedFrontend(e *echo.Echo) {return c.HTML(http.StatusOK, "This Bytebase build does not bundle frontend and backend together.")})}--// In non embedded mode, the redirect URL is the frontend URL which is different-// from the external URL. By default, this frontend URL is http://localhost:3000-func oauthRedirectURL(_ string) string {- url := os.Getenv("BB_REDIRECT_URL")- if url != "" {- return url- }- return "http://localhost:3000"-}--func oauthErrorMessage(externalURL string) string {- return fmt.Sprintf("Failed to exchange OAuth token. Make sure BB_REDIRECT_URL: %s matches your browser host. Note that if you are not using port 80 or 443, you should also specify the port such as --external-url=http://host:port", externalURL)-}