Skip to content

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

feat(github): implement `CreateWebhook`, `PatchWebhook` and `DeleteWebhook` (#1892)

Joe Chenc2412b024077
diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.go
index 034efdeb9e..0f087afc4c 100644
--- a/plugin/vcs/github/github.go
+++ b/plugin/vcs/github/github.go
@@ -107,6 +107,11 @@ type File struct {
SHA string `json:"sha"`
}
+// WebhookInfo represents a GitHub API response for the webhook information.
+type WebhookInfo struct {
+ ID int `json:"id"`
+}
+
// 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) {
@@ -130,14 +135,9 @@ func (p *Provider) fetchUserInfo(ctx context.Context, oauthCtx common.OauthConte
}
if code == http.StatusNotFound {
- errInfo := []string{"failed to fetch user info from GitHub.com"}
- resourceURISplit := strings.Split(resourceURI, "/")
- if len(resourceURI) > 1 {
- errInfo = append(errInfo, fmt.Sprintf("Username: %s", resourceURISplit[1]))
- }
- return nil, common.Errorf(common.NotFound, fmt.Errorf(strings.Join(errInfo, ", ")))
+ return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to read user info from URL %s", url))
} else if code >= 300 {
- return nil, fmt.Errorf("failed to read user info from GitHub.com, status code: %d", code)
+ return nil, fmt.Errorf("failed to read user info from URL %s, status code: %d, body: %s", url, code, body)
}
var user User
@@ -196,9 +196,9 @@ func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx common.OauthCon
}
if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, errors.New("failed to fetch commit data from GitHub.com, not found"))
+ return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to fetch commit data from URL %s", url))
} else if code >= 300 {
- return nil, fmt.Errorf("failed to fetch commit data from GitHub.com, status code: %d, body: %s", code, body)
+ return nil, fmt.Errorf("failed to fetch commit data from URL %s, status code: %d, body: %s", url, code, body)
}
commit := &Commit{}
@@ -573,8 +573,7 @@ func (p *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext,
if code == http.StatusNotFound {
return common.Errorf(common.NotFound, fmt.Errorf("failed to create/update file through URL %s", url))
- }
- if code >= 300 {
+ } else if code >= 300 {
return fmt.Errorf("failed to create/update file through URL %s, status code: %d, body: %s",
url,
code,
@@ -672,19 +671,117 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, r
return &file, nil
}
-// CreateWebhook creates a webhook in a GitLab project.
-func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, payload []byte) (string, error) {
- return "", errors.New("not implemented yet") // TODO: https://github.com/bytebase/bytebase/issues/928
+// CreateWebhook creates a webhook in the repository with given payload.
+//
+// Docs: https://docs.github.com/en/rest/webhooks/repos#create-a-repository-webhook
+func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx common.OauthContext, _, repositoryID string, payload []byte) (string, error) {
+ url := fmt.Sprintf("%s/repos/%s/hooks", apiURL, repositoryID)
+ code, body, err := oauth.Post(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(payload),
+ tokenRefresher(
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return "", errors.Wrapf(err, "POST %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return "", common.Errorf(common.NotFound, fmt.Errorf("failed to create webhook through URL %s", url))
+ } else if code >= 300 {
+ return "",
+ fmt.Errorf("failed to create webhook through URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+
+ var webhookInfo WebhookInfo
+ if err = json.Unmarshal([]byte(body), &webhookInfo); err != nil {
+ return "", errors.Wrap(err, "unmarshal body")
+ }
+ return strconv.Itoa(webhookInfo.ID), nil
}
-// PatchWebhook patches a webhook in a GitLab project.
-func (p *Provider) PatchWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, webhookID string, payload []byte) error {
- return errors.New("not implemented yet") // TODO: https://github.com/bytebase/bytebase/issues/928
+// PatchWebhook patches the webhook in the repository with given payload.
+//
+// Docs: https://docs.github.com/en/rest/webhooks/repos#update-a-repository-webhook
+func (p *Provider) PatchWebhook(ctx context.Context, oauthCtx common.OauthContext, _, repositoryID, webhookID string, payload []byte) error {
+ url := fmt.Sprintf("%s/repos/%s/hooks/%s", apiURL, repositoryID, webhookID)
+ code, body, err := oauth.Patch(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(payload),
+ tokenRefresher(
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "PATCH %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return common.Errorf(common.NotFound, fmt.Errorf("failed to patch webhook through URL %s", url))
+ } else if code >= 300 {
+ return fmt.Errorf("failed to patch webhook through URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+ return nil
}
-// DeleteWebhook deletes a webhook in a GitLab project.
-func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, webhookID string) error {
- return errors.New("not implemented yet") // TODO: https://github.com/bytebase/bytebase/issues/928
+// DeleteWebhook deletes the webhook from the repository.
+//
+// Docs: https://docs.github.com/en/rest/webhooks/repos#delete-a-repository-webhook
+func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthContext, _, repositoryID, webhookID string) error {
+ url := fmt.Sprintf("%s/repos/%s/hooks/%s", apiURL, repositoryID, webhookID)
+ code, body, err := oauth.Delete(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "DELETE %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return nil // It is OK if the webhook has already gone
+ } else if code >= 300 {
+ return fmt.Errorf("failed to delete webhook through URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+ return nil
}
// oauthContext is the request context for refreshing oauth token.
diff --git a/plugin/vcs/github/github_test.go b/plugin/vcs/github/github_test.go
index 1c54170064..642c3f9794 100644
--- a/plugin/vcs/github/github_test.go
+++ b/plugin/vcs/github/github_test.go
@@ -976,6 +976,101 @@ You can look around to get an idea how to structure your project and, when done,
assert.Equal(t, want, got)
}
+func TestProvider_CreateWebhook(t *testing.T) {
+ p := newProvider(
+ vcs.ProviderConfig{
+ Client: &http.Client{
+ Transport: &common.MockRoundTripper{
+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/repos/1/hooks", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ // Example response taken from https://docs.github.com/en/rest/webhooks/repos#create-a-repository-webhook
+ Body: io.NopCloser(strings.NewReader(`
+{
+ "type": "Repository",
+ "id": 12345678,
+ "name": "web",
+ "active": true,
+ "events": [
+ "push",
+ "pull_request"
+ ],
+ "config": {
+ "content_type": "json",
+ "insecure_ssl": "0",
+ "url": "https://example.com/webhook"
+ },
+ "updated_at": "2019-06-03T00:57:16Z",
+ "created_at": "2019-06-03T00:57:16Z",
+ "url": "https://api.github.com/repos/octocat/Hello-World/hooks/12345678",
+ "test_url": "https://api.github.com/repos/octocat/Hello-World/hooks/12345678/test",
+ "ping_url": "https://api.github.com/repos/octocat/Hello-World/hooks/12345678/pings",
+ "deliveries_url": "https://api.github.com/repos/octocat/Hello-World/hooks/12345678/deliveries",
+ "last_response": {
+ "code": null,
+ "status": "unused",
+ "message": null
+ }
+}
+`)),
+ }, nil
+ },
+ },
+ },
+ },
+ )
+
+ ctx := context.Background()
+ got, err := p.CreateWebhook(ctx, common.OauthContext{}, "", "1", []byte(""))
+ require.NoError(t, err)
+ assert.Equal(t, "12345678", got)
+}
+
+func TestProvider_PatchWebhook(t *testing.T) {
+ p := newProvider(
+ vcs.ProviderConfig{
+ Client: &http.Client{
+ Transport: &common.MockRoundTripper{
+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/repos/1/hooks/1", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader("")),
+ }, nil
+ },
+ },
+ },
+ },
+ )
+
+ ctx := context.Background()
+ err := p.PatchWebhook(ctx, common.OauthContext{}, "", "1", "1", []byte(""))
+ require.NoError(t, err)
+}
+
+func TestProvider_DeleteWebhook(t *testing.T) {
+ p := newProvider(
+ vcs.ProviderConfig{
+ Client: &http.Client{
+ Transport: &common.MockRoundTripper{
+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/repos/1/hooks/1", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader("")),
+ }, nil
+ },
+ },
+ },
+ },
+ )
+
+ ctx := context.Background()
+ err := p.DeleteWebhook(ctx, common.OauthContext{}, "", "1", "1")
+ require.NoError(t, err)
+}
+
func TestOAuth_RefreshToken(t *testing.T) {
ctx := context.Background()
client := &http.Client{
diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.go
index 7235b6085b..db28907718 100644
--- a/plugin/vcs/gitlab/gitlab.go
+++ b/plugin/vcs/gitlab/gitlab.go
@@ -40,7 +40,7 @@ const (
WebhookPush WebhookType = "push"
)
-// WebhookInfo is the API message for webhook info.
+// WebhookInfo represents a GitLab API response for the webhook information.
type WebhookInfo struct {
ID int `json:"id"`
}
@@ -360,16 +360,12 @@ func (p *Provider) fetchUserInfo(ctx context.Context, oauthCtx common.OauthConte
}
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: %s", resourceURISplit[1]))
- }
- return nil, common.Errorf(common.NotFound, fmt.Errorf(strings.Join(errInfo, ", ")))
+ return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to read user info from URL %s", url))
} else if code >= 300 {
- return nil, fmt.Errorf("failed to read user info from GitLab instance %s, status code: %d",
- instanceURL,
+ return nil, fmt.Errorf("failed to read user info from URL %s, status code: %d, body: %s",
+ url,
code,
+ body,
)
}
@@ -407,10 +403,10 @@ func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx common.OauthCon
return nil, errors.Wrap(err, "GET")
}
if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to fetch commit data from GitLab instance %s, not found", instanceURL))
+ return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to fetch commit data from URL %s", url))
} else if code >= 300 {
- return nil, fmt.Errorf("failed to fetch commit data from GitLab instance %s, status code: %d, body: %s",
- instanceURL,
+ return nil, fmt.Errorf("failed to fetch commit data from URL %s, status code: %d, body: %s",
+ url,
code,
body,
)
@@ -687,12 +683,11 @@ func (p *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext,
if code == http.StatusNotFound {
return common.Errorf(common.NotFound, fmt.Errorf("failed to create file through URL %s", url))
- }
- if code >= 300 {
- return fmt.Errorf("failed to create file %s on GitLab instance %s, status code: %d",
- filePath,
- instanceURL,
+ } else if code >= 300 {
+ return fmt.Errorf("failed to create file through URL %s, status code: %d, body: %s",
+ url,
code,
+ body,
)
}
return nil
@@ -737,12 +732,11 @@ func (p *Provider) OverwriteFile(ctx context.Context, oauthCtx common.OauthConte
if code == http.StatusNotFound {
return common.Errorf(common.NotFound, fmt.Errorf("failed to overwrite file through URL %s", url))
- }
- if code >= 300 {
- return fmt.Errorf("failed to overwrite file %s on GitLab instance %s, status code: %d",
- filePath,
- instanceURL,
+ } else if code >= 300 {
+ return fmt.Errorf("failed to overwrite file through URL %s, status code: %d, body: %s",
+ url,
code,
+ body,
)
}
return nil
@@ -776,7 +770,9 @@ func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx common.OauthCon
return file.Content, nil
}
-// CreateWebhook creates a webhook in a GitLab project.
+// CreateWebhook creates a webhook in the repository with given payload.
+//
+// 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(
@@ -796,35 +792,39 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx common.OauthConte
),
)
if err != nil {
- return "", fmt.Errorf("failed to create webhook for repository %s from GitLab instance %s: %w", repositoryID, instanceURL, err)
+ return "", errors.Wrapf(err, "POST %s", url)
}
- if code >= 300 {
- reason := fmt.Sprintf(
- "failed to create webhook for repository %s from GitLab instance %s, status code: %d",
- repositoryID,
- instanceURL,
+ if code == http.StatusNotFound {
+ return "", common.Errorf(common.NotFound, fmt.Errorf("failed to create webhook through URL %s", url))
+ } else if code >= 300 {
+ reason := fmt.Sprintf("failed to create webhook through URL %s, status code: %d, body: %s",
+ url,
code,
+ body,
)
- // Add helper tips if the status code is 422, refer to bytebase#101 for more context.
+
+ // Add helper tips if the status code is 422, refer to https://github.com/bytebase/bytebase/issues/101 for more context.
if code == http.StatusUnprocessableEntity {
reason += ".\n\nIf GitLab and Bytebase are in the same private network, " +
"please follow the instructions in https://docs.gitlab.com/ee/security/webhooks.html"
}
- return "", fmt.Errorf(reason)
+ return "", errors.New(reason)
}
- webhookInfo := &WebhookInfo{}
- if err := json.Unmarshal([]byte(body), webhookInfo); err != nil {
- return "", fmt.Errorf("failed to unmarshal create webhook response for repository %s from GitLab instance %s: %w", repositoryID, instanceURL, err)
+ var webhookInfo WebhookInfo
+ if err = json.Unmarshal([]byte(body), &webhookInfo); err != nil {
+ return "", errors.Wrap(err, "unmarshal body")
}
return strconv.Itoa(webhookInfo.ID), nil
}
-// PatchWebhook patches a webhook in a GitLab project.
+// PatchWebhook patches the webhook in the repository with given payload.
+//
+// Docs: https://docs.gitlab.com/ee/api/projects.html#edit-project-hook
func (p *Provider) PatchWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, webhookID string, payload []byte) error {
url := fmt.Sprintf("%s/projects/%s/hooks/%s", p.APIURL(instanceURL), repositoryID, webhookID)
- code, _, err := oauth.Put(
+ code, body, err := oauth.Put(
ctx,
p.client,
url,
@@ -841,19 +841,27 @@ func (p *Provider) PatchWebhook(ctx context.Context, oauthCtx common.OauthContex
),
)
if err != nil {
- return fmt.Errorf("failed to patch webhook ID %s for repository %s from GitLab instance %s: %w", webhookID, repositoryID, instanceURL, err)
+ return errors.Wrapf(err, "PUT %s", url)
}
- if code >= 300 {
- return fmt.Errorf("failed to patch webhook ID %s for repository %s from GitLab instance %s, status code: %d", webhookID, repositoryID, instanceURL, code)
+ if code == http.StatusNotFound {
+ return common.Errorf(common.NotFound, fmt.Errorf("failed to patch webhook through URL %s", url))
+ } else if code >= 300 {
+ return fmt.Errorf("failed to patch webhook through URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
}
return nil
}
-// DeleteWebhook deletes a webhook in a GitLab project.
+// DeleteWebhook deletes the webhook from the repository.
+//
+// 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, _, err := oauth.Delete(
+ code, body, err := oauth.Delete(
ctx,
p.client,
url,
@@ -869,11 +877,17 @@ func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthConte
),
)
if err != nil {
- return fmt.Errorf("failed to delete webhook ID %s for repository %s from GitLab instance %s: %w", webhookID, repositoryID, instanceURL, err)
+ return errors.Wrapf(err, "DELETE %s", url)
}
- if code >= 300 {
- return fmt.Errorf("failed to delete webhook ID %s for repository %s from GitLab instance %s, status code: %d", webhookID, repositoryID, instanceURL, code)
+ if code == http.StatusNotFound {
+ return nil // It is OK if the webhook has already gone
+ } else if code >= 300 {
+ return fmt.Errorf("failed to delete webhook through URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
}
return nil
}
@@ -907,10 +921,10 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, i
return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to read file from URL %s", url))
} else if code >= 300 {
return nil,
- fmt.Errorf("failed to read file %s on GitLab instance %s, status code: %d",
- filePath,
- instanceURL,
+ fmt.Errorf("failed to read file from URL %s, status code: %d, body: %s",
+ url,
code,
+ body,
)
}
diff --git a/plugin/vcs/gitlab/gitlab_test.go b/plugin/vcs/gitlab/gitlab_test.go
index 2b3b758138..b607365d33 100644
--- a/plugin/vcs/gitlab/gitlab_test.go
+++ b/plugin/vcs/gitlab/gitlab_test.go
@@ -665,6 +665,95 @@ You can look around to get an idea how to structure your project and, when done,
assert.Equal(t, want, got)
}
+func TestProvider_CreateWebhook(t *testing.T) {
+ p := newProvider(
+ vcs.ProviderConfig{
+ Client: &http.Client{
+ Transport: &common.MockRoundTripper{
+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/api/v4/projects/1/hooks", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ // Example response taken from https://docs.gitlab.com/ee/api/projects.html#get-project-hook
+ Body: io.NopCloser(strings.NewReader(`
+{
+ "id": 1,
+ "url": "http://example.com/hook",
+ "project_id": 3,
+ "push_events": true,
+ "push_events_branch_filter": "",
+ "issues_events": true,
+ "confidential_issues_events": true,
+ "merge_requests_events": true,
+ "tag_push_events": true,
+ "note_events": true,
+ "confidential_note_events": true,
+ "job_events": true,
+ "pipeline_events": true,
+ "wiki_page_events": true,
+ "deployment_events": true,
+ "releases_events": true,
+ "enable_ssl_verification": true,
+ "created_at": "2012-10-12T17:04:47Z"
+}
+`)),
+ }, nil
+ },
+ },
+ },
+ },
+ )
+
+ ctx := context.Background()
+ got, err := p.CreateWebhook(ctx, common.OauthContext{}, "", "1", []byte(""))
+ require.NoError(t, err)
+ assert.Equal(t, "1", got)
+}
+
+func TestProvider_PatchWebhook(t *testing.T) {
+ p := newProvider(
+ vcs.ProviderConfig{
+ Client: &http.Client{
+ Transport: &common.MockRoundTripper{
+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/api/v4/projects/1/hooks/1", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader("")),
+ }, nil
+ },
+ },
+ },
+ },
+ )
+
+ ctx := context.Background()
+ err := p.PatchWebhook(ctx, common.OauthContext{}, "", "1", "1", []byte(""))
+ require.NoError(t, err)
+}
+
+func TestProvider_DeleteWebhook(t *testing.T) {
+ p := newProvider(
+ vcs.ProviderConfig{
+ Client: &http.Client{
+ Transport: &common.MockRoundTripper{
+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/api/v4/projects/1/hooks/1", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader("")),
+ }, nil
+ },
+ },
+ },
+ },
+ )
+
+ ctx := context.Background()
+ err := p.DeleteWebhook(ctx, common.OauthContext{}, "", "1", "1")
+ require.NoError(t, err)
+}
+
func TestOAuth_RefreshToken(t *testing.T) {
ctx := context.Background()
client := &http.Client{
diff --git a/plugin/vcs/internal/oauth/oauth.go b/plugin/vcs/internal/oauth/oauth.go
index e14bf0e6f0..921acae51f 100644
--- a/plugin/vcs/internal/oauth/oauth.go
+++ b/plugin/vcs/internal/oauth/oauth.go
@@ -50,6 +50,12 @@ func Put(ctx context.Context, client *http.Client, url string, token *string, bo
return retry(ctx, client, token, tokenRefresher, 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, tokenRefresher TokenRefresher) (code int, respBody string, err error) {
+ return retry(ctx, client, token, tokenRefresher, 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, tokenRefresher TokenRefresher) (code int, respBody string, err error) {
diff --git a/plugin/vcs/internal/oauth/oauth_test.go b/plugin/vcs/internal/oauth/oauth_test.go
index 9b3151718c..df361442cc 100644
--- a/plugin/vcs/internal/oauth/oauth_test.go
+++ b/plugin/vcs/internal/oauth/oauth_test.go
@@ -73,6 +73,27 @@ func TestPut(t *testing.T) {
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"), nil)
+ require.NoError(t, err)
+}
+
func TestDelete(t *testing.T) {
ctx := context.Background()
client := &http.Client{