Skip to content

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

refactor: oauth (#11420)

Danny Xu03e2805733f7
diff --git a/backend/common/oauth.go b/backend/common/oauth.go
index fd1c8b497c..f5d7d98d51 100644
--- a/backend/common/oauth.go
+++ b/backend/common/oauth.go
@@ -1,17 +1,6 @@
package common
-// TokenRefresher is a function refreshes the oauth token and updates the repository.
-type TokenRefresher func(token, refreshToken string, expiresTs int64) error
-
// OauthContext encapsulated the oauth info.
type OauthContext struct {
AccessToken string
}
-
-// OAuthExchange encapsulated the exchange OAuth context.
-type OAuthExchange struct {
- ClientID string
- ClientSecret string
- Code string
- RedirectURL string
-}
diff --git a/backend/plugin/vcs/azure/azure.go b/backend/plugin/vcs/azure/azure.go
index 005c4032eb..c7647b6a4e 100644
--- a/backend/plugin/vcs/azure/azure.go
+++ b/backend/plugin/vcs/azure/azure.go
@@ -2,7 +2,6 @@
package azure
import (
- "bytes"
"context"
"encoding/json"
"fmt"
@@ -17,7 +16,7 @@ import (
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/plugin/vcs"
- "github.com/bytebase/bytebase/backend/plugin/vcs/internal/oauth"
+ "github.com/bytebase/bytebase/backend/plugin/vcs/internal"
)
func init() {
@@ -176,7 +175,7 @@ func getChangesByCommit(ctx context.Context, oauthCtx *common.OauthContext, exte
values := &url.Values{}
values.Set("api-version", "7.0")
url := fmt.Sprintf("%s/commits/%s/changes?%s", apiURL, url.PathEscape(commitID), values.Encode())
- code, _, body, err := oauth.Get(ctx, client, url, oauthCtx.AccessToken)
+ code, _, body, err := internal.Get(ctx, client, url, oauthCtx.AccessToken)
if err != nil {
return nil, errors.Wrapf(err, "GET %s", url)
}
@@ -234,7 +233,7 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx *common.
for _, organization := range organizations {
if err := func() error {
url := fmt.Sprintf("https://dev.azure.com/%s/_apis/git/repositories?%s", url.PathEscape(organization), urlParams.Encode())
- code, _, body, err := oauth.Get(ctx, p.client, url, oauthCtx.AccessToken)
+ code, _, body, err := internal.Get(ctx, p.client, url, oauthCtx.AccessToken)
if err != nil {
return errors.Wrapf(err, "GET %s", url)
}
@@ -289,7 +288,7 @@ func (p *Provider) getAuthenticatedProfilePublicAlias(ctx context.Context, oauth
values.Set("api-version", "7.0")
url := fmt.Sprintf("https://app.vssps.visualstudio.com/_apis/profile/profiles/me?%s", values.Encode())
- code, _, body, err := oauth.Get(ctx, p.client, url, oauthCtx.AccessToken)
+ code, _, body, err := internal.Get(ctx, p.client, url, oauthCtx.AccessToken)
if err != nil {
return "", errors.Wrapf(err, "GET %s", url)
}
@@ -318,7 +317,7 @@ func (p *Provider) listOrganizationsForMember(ctx context.Context, oauthCtx *com
urlParams.Set("api-version", "7.0")
url := fmt.Sprintf("https://app.vssps.visualstudio.com/_apis/accounts?%s", urlParams.Encode())
- code, _, body, err := oauth.Get(ctx, p.client, url, oauthCtx.AccessToken)
+ code, _, body, err := internal.Get(ctx, p.client, url, oauthCtx.AccessToken)
if err != nil {
return nil, errors.Wrapf(err, "GET %s", url)
}
@@ -377,7 +376,7 @@ func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx *common.OauthCo
values.Set("versionDescriptor.version", refInfo.RefName)
url := fmt.Sprintf("%s/items?%s", apiURL, values.Encode())
- code, _, body, err := oauth.Get(ctx, p.client, url, oauthCtx.AccessToken)
+ code, _, body, err := internal.Get(ctx, p.client, url, oauthCtx.AccessToken)
if err != nil {
return "", errors.Wrapf(err, "GET %s", url)
}
@@ -409,7 +408,7 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx *common.OauthContext,
urlParams.Set("api-version", "7.0")
url := fmt.Sprintf("%s/stats/branches?%s", apiURL, urlParams.Encode())
- code, _, body, err := oauth.Get(ctx, p.client, url, oauthCtx.AccessToken)
+ code, _, body, err := internal.Get(ctx, p.client, url, oauthCtx.AccessToken)
if err != nil {
return nil, errors.Wrapf(err, "GET %s", url)
}
@@ -455,7 +454,7 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx *common.Oau
urlParams.Set("api-version", "7.0")
url := fmt.Sprintf("%s/pullrequests/%s?%s", apiURL, pullRequestID, urlParams.Encode())
- code, _, resp, err := oauth.Get(
+ code, _, resp, err := internal.Get(
ctx,
p.client,
url,
@@ -505,12 +504,12 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthCont
urlParams := &url.Values{}
urlParams.Set("api-version", "7.0")
url := fmt.Sprintf("https://dev.azure.com/%s/_apis/hooks/subscriptions?%s", url.PathEscape(organizationName), urlParams.Encode())
- code, _, body, err := oauth.Post(
+ code, _, body, err := internal.Post(
ctx,
p.client,
url,
oauthCtx.AccessToken,
- bytes.NewReader(payload),
+ payload,
)
if err != nil {
return "", errors.Wrapf(err, "failed to create webhook")
@@ -544,7 +543,7 @@ func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx *common.OauthCont
values.Set("api-version", "7.0")
url := fmt.Sprintf("https://dev.azure.com/%s/_apis/hooks/subscriptions/%s?%s", url.PathEscape(organizationName), url.PathEscape(webhookID), values.Encode())
- code, _, body, err := oauth.Delete(
+ code, _, body, err := internal.Delete(
ctx,
p.client,
url,
diff --git a/backend/plugin/vcs/bitbucket/bitbucket.go b/backend/plugin/vcs/bitbucket/bitbucket.go
index 8ad3f5fcdb..5faa8caac7 100644
--- a/backend/plugin/vcs/bitbucket/bitbucket.go
+++ b/backend/plugin/vcs/bitbucket/bitbucket.go
@@ -2,7 +2,6 @@
package bitbucket
import (
- "bytes"
"context"
"encoding/json"
"fmt"
@@ -16,7 +15,7 @@ import (
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/plugin/vcs"
- "github.com/bytebase/bytebase/backend/plugin/vcs/internal/oauth"
+ "github.com/bytebase/bytebase/backend/plugin/vcs/internal"
)
const (
@@ -90,7 +89,7 @@ type CommitDiffStat struct {
}
func (p *Provider) fetchPaginatedDiffFileList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, url string) (diffs []*CommitDiffStat, next string, err error) {
- code, _, body, err := oauth.Get(
+ code, _, body, err := internal.Get(
ctx,
p.client,
url,
@@ -172,7 +171,7 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx *common.
// the paginated results along with a string indicating the URL of the next page
// (if exists).
func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx *common.OauthContext, url string) (repos []*Repository, next string, err error) {
- code, _, body, err := oauth.Get(
+ code, _, body, err := internal.Get(
ctx,
p.client,
url,
@@ -218,7 +217,7 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx *c
// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-source/#raw-file-contents
func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, refInfo vcs.RefInfo) (string, error) {
url := fmt.Sprintf("%s/repositories/%s/src/%s/%s", p.APIURL(instanceURL), repositoryID, url.PathEscape(refInfo.RefName), url.PathEscape(filePath))
- code, _, body, err := oauth.Get(
+ code, _, body, err := internal.Get(
ctx,
p.client,
url,
@@ -257,7 +256,7 @@ type Branch struct {
// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-refs/#api-repositories-workspace-repo-slug-refs-branches-name-get
func (p *Provider) GetBranch(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, branchName string) (*vcs.BranchInfo, error) {
url := fmt.Sprintf("%s/repositories/%s/refs/branches/%s", p.APIURL(instanceURL), repositoryID, branchName)
- code, _, body, err := oauth.Get(
+ code, _, body, err := internal.Get(
ctx,
p.client,
url,
@@ -394,12 +393,12 @@ type Webhook struct {
// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-repositories-workspace-repo-slug-hooks-post
func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string, payload []byte) (string, error) {
url := fmt.Sprintf("%s/repositories/%s/hooks", p.APIURL(instanceURL), repositoryID)
- code, _, body, err := oauth.Post(
+ code, _, body, err := internal.Post(
ctx,
p.client,
url,
oauthCtx.AccessToken,
- bytes.NewReader(payload),
+ payload,
)
if err != nil {
return "", errors.Wrapf(err, "POST %s", url)
@@ -431,7 +430,7 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthCont
// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-repositories-workspace-repo-slug-hooks-uid-delete
func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, webhookID string) error {
url := fmt.Sprintf("%s/repositories/%s/hooks/%s", p.APIURL(instanceURL), repositoryID, webhookID)
- code, _, body, err := oauth.Delete(
+ code, _, body, err := internal.Delete(
ctx,
p.client,
url,
diff --git a/backend/plugin/vcs/github/github.go b/backend/plugin/vcs/github/github.go
index ad32939cdc..26cb78c01c 100644
--- a/backend/plugin/vcs/github/github.go
+++ b/backend/plugin/vcs/github/github.go
@@ -2,7 +2,6 @@
package github
import (
- "bytes"
"context"
"encoding/json"
"fmt"
@@ -17,7 +16,7 @@ import (
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/plugin/vcs"
- "github.com/bytebase/bytebase/backend/plugin/vcs/internal/oauth"
+ "github.com/bytebase/bytebase/backend/plugin/vcs/internal"
)
const (
@@ -188,7 +187,7 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx *common.
// with a boolean indicating whether the next page exists.
func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL string, page int) (repos []Repository, hasNextPage bool, err error) {
url := fmt.Sprintf("%s/user/repos?page=%d&per_page=%d", p.APIURL(instanceURL), page, apiPageSize)
- code, _, body, err := oauth.Get(
+ code, _, body, err := internal.Get(
ctx,
p.client,
url,
@@ -225,7 +224,7 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx *c
// Docs: https://docs.github.com/en/rest/repos/contents#get-repository-content
func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, refInfo vcs.RefInfo) (string, error) {
url := fmt.Sprintf("%s/repos/%s/contents/%s?ref=%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath), refInfo.RefName)
- code, _, body, err := oauth.GetWithHeader(
+ code, _, body, err := internal.GetWithHeader(
ctx,
p.client,
url,
@@ -321,7 +320,7 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx *common.Oau
// listPaginatedPullRequestFile lists the changed files in the pull request with pagination.
func (p *Provider) listPaginatedPullRequestFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, pullRequestID string, page int) ([]PullRequestFile, error) {
requestURL := fmt.Sprintf("%s/repos/%s/pulls/%s/files?per_page=%d&page=%d", p.APIURL(instanceURL), repositoryID, pullRequestID, apiPageSize, page)
- code, _, body, err := oauth.Get(
+ code, _, body, err := internal.Get(
ctx,
p.client,
requestURL,
@@ -369,7 +368,7 @@ type ReferenceObject struct {
// Docs: https://docs.github.com/en/rest/git/refs#get-a-reference
func (p *Provider) GetBranch(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, branchName string) (*vcs.BranchInfo, error) {
url := fmt.Sprintf("%s/repos/%s/git/ref/heads/%s", p.APIURL(instanceURL), repositoryID, branchName)
- code, _, body, err := oauth.Get(
+ code, _, body, err := internal.Get(
ctx,
p.client,
url,
@@ -415,12 +414,12 @@ type PullRequest struct {
// Docs: https://docs.github.com/en/rest/webhooks/repos#create-a-repository-webhook
func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string, payload []byte) (string, error) {
url := fmt.Sprintf("%s/repos/%s/hooks", p.APIURL(instanceURL), repositoryID)
- code, _, body, err := oauth.Post(
+ code, _, body, err := internal.Post(
ctx,
p.client,
url,
oauthCtx.AccessToken,
- bytes.NewReader(payload),
+ payload,
)
if err != nil {
return "", errors.Wrapf(err, "POST %s", url)
@@ -452,7 +451,7 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthCont
// Docs: https://docs.github.com/en/rest/webhooks/repos#delete-a-repository-webhook
func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, webhookID string) error {
url := fmt.Sprintf("%s/repos/%s/hooks/%s", p.APIURL(instanceURL), repositoryID, webhookID)
- code, _, body, err := oauth.Delete(
+ code, _, body, err := internal.Delete(
ctx,
p.client,
url,
diff --git a/backend/plugin/vcs/gitlab/gitlab.go b/backend/plugin/vcs/gitlab/gitlab.go
index 8d57feecb7..4e11f356ee 100644
--- a/backend/plugin/vcs/gitlab/gitlab.go
+++ b/backend/plugin/vcs/gitlab/gitlab.go
@@ -2,7 +2,6 @@
package gitlab
import (
- "bytes"
"context"
"encoding/json"
"fmt"
@@ -15,7 +14,7 @@ import (
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/plugin/vcs"
- "github.com/bytebase/bytebase/backend/plugin/vcs/internal/oauth"
+ "github.com/bytebase/bytebase/backend/plugin/vcs/internal"
)
const (
@@ -124,8 +123,7 @@ type RepositoryTreeNode struct {
// File represents a GitLab API response for a repository file.
type File struct {
- Content string
- LastCommitID string
+ Content string
}
// CommitsDiff represents a GitLab API response for comparing two commits.
@@ -205,7 +203,7 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx *c
// 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, apiPageSize)
- code, _, body, err := oauth.Get(
+ code, _, body, err := internal.Get(
ctx,
p.client,
url,
@@ -268,7 +266,7 @@ type MergeRequestFile struct {
// Docs: https://docs.gitlab.com/ee/api/merge_requests.html#get-single-mr-changes
func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, pullRequestID string) ([]*vcs.PullRequestFile, error) {
url := fmt.Sprintf("%s/projects/%s/merge_requests/%s/changes", p.APIURL(instanceURL), repositoryID, pullRequestID)
- code, _, body, err := oauth.Get(
+ code, _, body, err := internal.Get(
ctx,
p.client,
url,
@@ -330,7 +328,7 @@ type MergeRequestCreate struct {
// Docs: https://docs.gitlab.com/ee/api/branches.html#get-single-repository-branch
func (p *Provider) GetBranch(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, branchName string) (*vcs.BranchInfo, error) {
url := fmt.Sprintf("%s/projects/%s/repository/branches/%s", p.APIURL(instanceURL), repositoryID, branchName)
- code, _, body, err := oauth.Get(
+ code, _, body, err := internal.Get(
ctx,
p.client,
url,
@@ -371,12 +369,12 @@ type MergeRequest struct {
// Docs: https://docs.gitlab.com/ee/api/projects.html#add-project-hook
func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string, payload []byte) (string, error) {
url := fmt.Sprintf("%s/projects/%s/hooks", p.APIURL(instanceURL), repositoryID)
- code, _, body, err := oauth.Post(
+ code, _, body, err := internal.Post(
ctx,
p.client,
url,
oauthCtx.AccessToken,
- bytes.NewReader(payload),
+ payload,
)
if err != nil {
return "", errors.Wrapf(err, "POST %s", url)
@@ -413,7 +411,7 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthCont
// Docs: https://docs.gitlab.com/ee/api/projects.html#delete-project-hook
func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, webhookID string) error {
url := fmt.Sprintf("%s/projects/%s/hooks/%s", p.APIURL(instanceURL), repositoryID, webhookID)
- code, _, body, err := oauth.Delete(
+ code, _, body, err := internal.Delete(
ctx,
p.client,
url,
@@ -444,7 +442,7 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx *common.OauthContext,
// In such cases, the HTTP header "Content-Encoding" will, for example, be changed to "gzip" and makes the value of "Content-Length" untrustworthy.
// We can avoid dealing with this type of problem by using the raw API instead of the typical JSON API.
url := fmt.Sprintf("%s/projects/%s/repository/files/%s/raw?ref=%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath), url.QueryEscape(refInfo.RefName))
- code, header, body, err := oauth.Get(
+ code, _, body, err := internal.Get(
ctx,
p.client,
url,
@@ -466,7 +464,6 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx *common.OauthContext,
}
return &File{
- Content: body,
- LastCommitID: header.Get("x-gitlab-last-commit-id"),
+ Content: body,
}, nil
}
diff --git a/backend/plugin/vcs/internal/oauth/oauth.go b/backend/plugin/vcs/internal/oauth/oauth.go
deleted file mode 100644
index 98842ad337..0000000000
--- a/backend/plugin/vcs/internal/oauth/oauth.go
+++ /dev/null
@@ -1,177 +0,0 @@
-// Package oauth provides library for VCS plugins.
-package oauth
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "fmt"
- "io"
- "log/slog"
- "net/http"
- "strings"
-
- "github.com/pkg/errors"
-
- "github.com/bytebase/bytebase/backend/common/log"
-)
-
-func requester(ctx context.Context, client *http.Client, method, url string, token string, body io.Reader) func() (*http.Response, error) {
- //nolint:bodyclose
- return requesterWithHeader(ctx, client, method, url, token, body, nil)
-}
-
-func requesterWithHeader(ctx context.Context, client *http.Client, method, url string, token string, body io.Reader, header map[string]string) func() (*http.Response, error) {
- // The body may be read multiple times but io.Reader is meant to be read once,
- // so we read the body first and build the reader every time.
- var bodyBytes []byte
- if body != nil {
- b, err := io.ReadAll(body)
- if err != nil {
- return func() (*http.Response, error) {
- return nil, errors.Wrap(err, "failed to read from body")
- }
- }
- bodyBytes = b
- }
- return func() (*http.Response, error) {
- req, err := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(bodyBytes))
- 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))
- for k, v := range header {
- req.Header.Set(k, v)
- }
-
- 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) (code int, header http.Header, respBody string, err error) {
- return PostWithHeader(ctx, client, url, token, body, nil)
-}
-
-// PostWithHeader makes a HTTP POST request to the given URL using the token and
-// additional header. It refreshes token and retries the request in the case of
-// the token has expired.
-func PostWithHeader(ctx context.Context, client *http.Client, url string, token string, body io.Reader, header map[string]string) (code int, _ http.Header, respBody string, err error) {
- //nolint:bodyclose
- return retry(ctx, requesterWithHeader(ctx, client, http.MethodPost, url, token, body, header))
-}
-
-// 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) (code int, header http.Header, respBody string, err error) {
- //nolint:bodyclose
- return retry(ctx, requester(ctx, client, http.MethodGet, url, token, nil))
-}
-
-// GetWithHeader makes a HTTP GET request to the given URL using the token and
-// additional header. It refreshes token and retries the request in the case of
-// the token has expired.
-func GetWithHeader(ctx context.Context, client *http.Client, url string, token string, header map[string]string) (code int, _ http.Header, respBody string, err error) {
- //nolint:bodyclose
- return retry(ctx, requesterWithHeader(ctx, client, http.MethodGet, url, token, nil, header))
-}
-
-// 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) (code int, header http.Header, respBody string, err error) {
- //nolint:bodyclose
- return retry(ctx, requester(ctx, client, http.MethodPut, url, token, body))
-}
-
-// Patch makes a HTTP PATCH request to the given URL using the token. It
-// refreshes token and retries the request in the case of the token has expired.
-func Patch(ctx context.Context, client *http.Client, url string, token string, body io.Reader) (code int, header http.Header, respBody string, err error) {
- //nolint:bodyclose
- return retry(ctx, requester(ctx, client, http.MethodPatch, 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) (code int, header http.Header, respBody string, err error) {
- //nolint:bodyclose
- return retry(ctx, requester(ctx, client, http.MethodDelete, url, token, nil))
-}
-
-func retry(ctx context.Context, f func() (*http.Response, error)) (code int, header http.Header, respBody string, err error) {
- // TODO(d): handle timeout retries.
- select {
- case <-ctx.Done():
- return 0, nil, "", ctx.Err()
- default:
- }
-
- resp, err := f()
- if err != nil {
- return 0, nil, "", err
- }
-
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return 0, nil, "", errors.Wrapf(err, "read response body with status code %d", resp.StatusCode)
- }
- if err := resp.Body.Close(); err != nil {
- slog.Warn("failed to close resp body", log.BBError(err))
- }
-
- if err = getOAuthErrorDetails(resp.StatusCode, body); err != nil {
- return 0, nil, "", errors.Errorf("got unexpected OAuth error %T", err)
- }
- return resp.StatusCode, resp.Header, string(body), nil
-}
-
-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 {
- // Special case for Azure DevOps OAuth error.
- if code == http.StatusNonAuthoritativeInfo && bytes.Contains(body, []byte("Azure DevOps Services | Sign In")) {
- return &oauthError{}
- }
-
- if 200 <= code && code < 300 {
- return nil
- }
-
- // Special case for Bitbucket OAuth error.
- if bytes.Contains(body, []byte("OAuth2 access token expired.")) {
- return &oauthError{}
- }
-
- 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.
- // nolint:nilerr
- 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."}
- // {"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."}
- if (oe.Err == "invalid_token" || oe.Err == "invalid_grant") && strings.Contains(oe.ErrorDescription, "expired") {
- return &oe
- }
- return nil
-}
diff --git a/backend/plugin/vcs/internal/oauth/oauth_test.go b/backend/plugin/vcs/internal/oauth/oauth_test.go
deleted file mode 100644
index cc1243cadc..0000000000
--- a/backend/plugin/vcs/internal/oauth/oauth_test.go
+++ /dev/null
@@ -1,111 +0,0 @@
-package oauth
-
-import (
- "context"
- "io"
- "net/http"
- "strings"
- "testing"
-
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
-
- "github.com/bytebase/bytebase/backend/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"))
- 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)
- 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"))
- require.NoError(t, err)
-}
-
-func TestPatch(t *testing.T) {
- ctx := context.Background()
- client := &http.Client{
- Transport: &common.MockRoundTripper{
- MockRoundTrip: func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, http.MethodPatch, 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, "PATCH body", string(body))
- return &http.Response{}, nil
- },
- },
- }
- token := "token"
- _, _, _, err := Patch(ctx, client, "", token, strings.NewReader("PATCH body"))
- 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)
- require.NoError(t, err)
-}
diff --git a/backend/plugin/vcs/internal/request.go b/backend/plugin/vcs/internal/request.go
new file mode 100644
index 0000000000..5212ce4924
--- /dev/null
+++ b/backend/plugin/vcs/internal/request.go
@@ -0,0 +1,100 @@
+// Package internal provides library for VCS plugins.
+package internal
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/common/log"
+)
+
+// 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 []byte) (code int, header http.Header, respBody string, err error) {
+ //nolint:bodyclose
+ return retry(ctx, requesterWithHeader(ctx, client, http.MethodPost, url, token, bytes.NewReader(body), nil))
+}
+
+// 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) (code int, header http.Header, respBody string, err error) {
+ //nolint:bodyclose
+ return retry(ctx, requesterWithHeader(ctx, client, http.MethodGet, url, token, nil, nil))
+}
+
+// GetWithHeader makes a HTTP GET request to the given URL using the token and
+// additional header. It refreshes token and retries the request in the case of
+// the token has expired.
+func GetWithHeader(ctx context.Context, client *http.Client, url string, token string, header map[string]string) (code int, _ http.Header, respBody string, err error) {
+ //nolint:bodyclose
+ return retry(ctx, requesterWithHeader(ctx, client, http.MethodGet, url, token, nil, header))
+}
+
+// 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) (code int, header http.Header, respBody string, err error) {
+ //nolint:bodyclose
+ return retry(ctx, requesterWithHeader(ctx, client, http.MethodDelete, url, token, nil, nil))
+}
+
+func requesterWithHeader(ctx context.Context, client *http.Client, method, url string, token string, body io.Reader, header map[string]string) func() (*http.Response, error) {
+ // The body may be read multiple times but io.Reader is meant to be read once,
+ // so we read the body first and build the reader every time.
+ var bodyBytes []byte
+ if body != nil {
+ b, err := io.ReadAll(body)
+ if err != nil {
+ return func() (*http.Response, error) {
+ return nil, errors.Wrap(err, "failed to read from body")
+ }
+ }
+ bodyBytes = b
+ }
+ return func() (*http.Response, error) {
+ req, err := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(bodyBytes))
+ 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))
+ for k, v := range header {
+ req.Header.Set(k, v)
+ }
+
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, errors.Wrapf(err, "%s %s", method, url)
+ }
+ return resp, nil
+ }
+}
+
+func retry(ctx context.Context, f func() (*http.Response, error)) (code int, header http.Header, respBody string, err error) {
+ // TODO(d): handle timeout retries.
+ select {
+ case <-ctx.Done():
+ return 0, nil, "", ctx.Err()
+ default:
+ }
+
+ resp, err := f()
+ if err != nil {
+ return 0, nil, "", err
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return 0, nil, "", errors.Wrapf(err, "read response body with status code %d", resp.StatusCode)
+ }
+ if err := resp.Body.Close(); err != nil {
+ slog.Warn("failed to close resp body", log.BBError(err))
+ }
+ return resp.StatusCode, resp.Header, string(body), nil
+}