Skip to content

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

chore: update bitbucket pipeline (#10819)

ecmadao620ac1b60f42
diff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.go
index fbdb3eea8b..be25ab1147 100644
--- a/backend/api/v1/project_service.go
+++ b/backend/api/v1/project_service.go
@@ -1253,8 +1253,7 @@ func (s *ProjectService) setupVCSSQLReviewCI(ctx context.Context, repository *st
return nil, err
}
case vcsplugin.Bitbucket:
- // TODO(ed): we need to call the API to enable the pipeline.
- if err := setupVCSSQLReviewCIForBitBucket(ctx, oauthContext, repository, vcs, branch, sqlReviewEndpoint, repository.WebhookSecretToken); err != nil {
+ if err := setupVCSSQLReviewCIForBitBucket(ctx, oauthContext, repository, vcs, branch, sqlReviewEndpoint); err != nil {
return nil, err
}
}
@@ -1380,8 +1379,12 @@ func setupVCSSQLReviewCIForBitBucket(
vcs *store.ExternalVersionControlMessage,
branch *vcsplugin.BranchInfo,
sqlReviewEndpoint string,
- sqlReviewSecret string,
) error {
+ bitbucketPlugin := vcsplugin.Get(vcs.Type, vcsplugin.ProviderConfig{})
+ if err := bitbucket.EnableSQLReviewCI(ctx, oauthContext, bitbucketPlugin.APIURL(vcs.InstanceURL), vcs.InstanceURL, repository.ExternalID); err != nil {
+ return errors.Wrapf(err, "failed to enable the pipeline")
+ }
+
if err := createOrUpdateVCSSQLReviewFile(ctx, oauthContext, repository, vcs, branch, bitbucket.SQLReviewScriptFilePath, func(_ *vcsplugin.FileMeta) (string, error) {
return bitbucket.SQLReviewScript, nil
}); err != nil {
@@ -1392,7 +1395,7 @@ func setupVCSSQLReviewCIForBitBucket(
content := make(map[string]any)
if fileMeta != nil {
- ciFileContent, err := vcsplugin.Get(vcs.Type, vcsplugin.ProviderConfig{}).ReadFileContent(
+ ciFileContent, err := bitbucketPlugin.ReadFileContent(
ctx,
oauthContext,
vcs.InstanceURL,
@@ -1411,7 +1414,7 @@ func setupVCSSQLReviewCIForBitBucket(
}
}
- newContent, err := bitbucket.SetupBitBucketCI(content, sqlReviewEndpoint, sqlReviewSecret)
+ newContent, err := bitbucket.SetupBitBucketCI(content, sqlReviewEndpoint)
if err != nil {
return "", err
}
@@ -3195,7 +3198,7 @@ func createVCSWebhook(ctx context.Context, vcsType vcsplugin.Type, webhookEndpoi
// refreshToken is a no-op token refresher. It should be used when the repository isn't created yet.
func refreshTokenNoop() common.TokenRefresher {
- return func(newToken, newRefreshToken string, expiresTs int64) error {
+ return func(_, _ string, _ int64) error {
return nil
}
}
diff --git a/backend/plugin/vcs/bitbucket/bitbucket.go b/backend/plugin/vcs/bitbucket/bitbucket.go
index 9d0991bec1..d7a4d00c6e 100644
--- a/backend/plugin/vcs/bitbucket/bitbucket.go
+++ b/backend/plugin/vcs/bitbucket/bitbucket.go
@@ -851,11 +851,169 @@ func (p *Provider) CreatePullRequest(ctx context.Context, oauthCtx *common.Oauth
}, nil
}
-// UpsertEnvironmentVariable creates or updates the environment variable in the repository.
+type pipelineVariable struct {
+ // Type should always be "pipeline_variable"
+ Type string `json:"type,omitempty"`
+ UUID string `json:"uuid,omitempty"`
+ Key string `json:"key,omitempty"`
+ Value string `json:"value,omitempty"`
+ Secured bool `json:"secured,omitempty"`
+}
+
+type listPipelineVariable struct {
+ Values []*pipelineVariable `json:"values"`
+}
+
+// UpsertEnvironmentVariable creates or updates the pipeline variable in the repository.
+func (p *Provider) UpsertEnvironmentVariable(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, key, value string) error {
+ existed, err := p.getPipelineVariable(ctx, oauthCtx, instanceURL, repositoryID, key)
+ if err != nil {
+ return err
+ }
+
+ if existed == nil {
+ return p.createPipelineVariable(ctx, oauthCtx, instanceURL, repositoryID, key, value)
+ }
+ return p.updatePipelineVariable(ctx, oauthCtx, instanceURL, repositoryID, existed.UUID, value)
+}
+
+// getPipelineVariable gets the pipeline variable in the repository.
+//
+// https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pipelines/#api-repositories-workspace-repo-slug-pipelines-config-variables-get.
+func (p *Provider) getPipelineVariable(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, key string) (*pipelineVariable, error) {
+ url := fmt.Sprintf("%s/repositories/%s/pipelines_config/variables", p.APIURL(instanceURL), repositoryID)
+ code, _, body, err := oauth.Get(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return nil, errors.Wrapf(err, "GET %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return nil, nil
+ } else if code >= 300 {
+ return nil,
+ errors.Errorf("failed to found variable from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+
+ variables := new(listPipelineVariable)
+ if err := json.Unmarshal([]byte(body), variables); err != nil {
+ return nil, err
+ }
+
+ for _, variable := range variables.Values {
+ if variable.Key == key {
+ return variable, nil
+ }
+ }
+
+ return nil, nil
+}
+
+// createPipelineVariable creates the pipeline variable in the repository.
+//
+// https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pipelines/#api-repositories-workspace-repo-slug-pipelines-config-variables-post.
+func (p *Provider) createPipelineVariable(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, key, value string) error {
+ url := fmt.Sprintf("%s/repositories/%s/pipelines_config/variables", p.APIURL(instanceURL), repositoryID)
+ body, err := json.Marshal(
+ pipelineVariable{
+ Type: "pipeline_variable",
+ Key: key,
+ Value: value,
+ Secured: true,
+ },
+ )
+ if err != nil {
+ return errors.Wrap(err, "marshal variable create")
+ }
+ code, _, resp, err := oauth.Post(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(body),
+ tokenRefresher(
+ instanceURL,
+ 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, "failed to create pipeline variable through URL %s", url)
+ } else if code >= 300 {
+ return errors.Errorf("failed to create pipeline variable through URL %s, status code: %d, body: %s",
+ url,
+ code,
+ resp,
+ )
+ }
+ return nil
+}
+
+// updatePipelineVariable updates the environment variable in the repository.
//
-// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pipelines/#api-repositories-workspace-repo-slug-pipelines-config-variables-post
-// WARNING: This is not supported in Bitbucket Cloud.
-func (*Provider) UpsertEnvironmentVariable(context.Context, *common.OauthContext, string, string, string, string) error {
+// https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pipelines/#api-repositories-workspace-repo-slug-pipelines-config-variables-variable-uuid-put.
+func (p *Provider) updatePipelineVariable(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, variableID, value string) error {
+ url := fmt.Sprintf("%s/repositories/%s/pipelines_config/variables/%s", p.APIURL(instanceURL), repositoryID, variableID)
+ body, err := json.Marshal(
+ pipelineVariable{
+ Value: value,
+ },
+ )
+ if err != nil {
+ return errors.Wrap(err, "marshal variable update")
+ }
+ code, _, resp, err := oauth.Put(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(body),
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "PUT %s", url)
+ }
+ if code == http.StatusNotFound {
+ return common.Errorf(common.NotFound, "failed to update pipeline variable through URL %s", url)
+ } else if code >= 300 {
+ return errors.Errorf("failed to update pipeline variable through URL %s, status code: %d, body: %s",
+ url,
+ code,
+ resp,
+ )
+ }
return nil
}
diff --git a/backend/plugin/vcs/bitbucket/pipeline-step.yml b/backend/plugin/vcs/bitbucket/pipeline-step.yml
index 20035475a7..d7a53d9b0c 100644
--- a/backend/plugin/vcs/bitbucket/pipeline-step.yml
+++ b/backend/plugin/vcs/bitbucket/pipeline-step.yml
@@ -1,4 +1,4 @@
name: %s
image: atlassian/default-image:4
script:
- - bash %s --pull-request-id="$BITBUCKET_PR_ID" --repo-id="$BITBUCKET_REPO_FULL_NAME" --repo-url="$BITBUCKET_GIT_HTTP_ORIGIN" --api="%s" --token="%s"
+ - bash %s --pull-request-id="$BITBUCKET_PR_ID" --repo-id="$BITBUCKET_REPO_FULL_NAME" --repo-url="$BITBUCKET_GIT_HTTP_ORIGIN" --api="%s" --token="$%s"
diff --git a/backend/plugin/vcs/bitbucket/sql_review.go b/backend/plugin/vcs/bitbucket/sql_review.go
index 8625e4adcc..f8d402caa8 100644
--- a/backend/plugin/vcs/bitbucket/sql_review.go
+++ b/backend/plugin/vcs/bitbucket/sql_review.go
@@ -1,11 +1,19 @@
package bitbucket
import (
+ "bytes"
+ "context"
_ "embed"
+ "encoding/json"
"fmt"
+ "net/http"
"github.com/pkg/errors"
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/plugin/vcs"
+ "github.com/bytebase/bytebase/backend/plugin/vcs/internal/oauth"
+
"gopkg.in/yaml.v3"
)
@@ -19,6 +27,10 @@ type pipeline struct {
Step *pipelineStep `yaml:"step"`
}
+type pipelineConfig struct {
+ Enabled bool `json:"enabled"`
+}
+
const (
// CIFilePath is the local path for BitBucket ci file.
CIFilePath = "bitbucket-pipelines.yml"
@@ -37,24 +49,70 @@ var sqlReviewPipelineStep string
//go:embed bytebase-sql-review.sh
var SQLReviewScript string
-func getSQLReviewStep(endpoint, webhookSecret string) string {
+func getSQLReviewStep(endpoint string) string {
return fmt.Sprintf(
sqlReviewPipelineStep,
pipelineStepName,
SQLReviewScriptFilePath,
endpoint,
- // TODO(ed): insert secret in the repo environment variable and use vcs.SQLReviewAPISecretName.
- webhookSecret,
+ vcs.SQLReviewAPISecretName,
+ )
+}
+
+// EnableSQLReviewCI enables the pipeline.
+//
+// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pipelines/#api-repositories-workspace-repo-slug-pipelines-config-put.
+func EnableSQLReviewCI(ctx context.Context, oauthCtx *common.OauthContext, apiURL, instanceURL, repositoryID string) error {
+ body, err := json.Marshal(
+ pipelineConfig{
+ Enabled: true,
+ },
)
+ if err != nil {
+ return errors.Wrap(err, "marshal pipeline config")
+ }
+
+ client := &http.Client{}
+ url := fmt.Sprintf("%s/repositories/%s/pipelines_config", apiURL, repositoryID)
+ code, _, resp, err := oauth.Put(
+ ctx,
+ client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(body),
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "PUT %s", url)
+ }
+ if code >= 300 {
+ return errors.Errorf("failed to update pipeline config from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ resp,
+ )
+ }
+ return nil
}
-func SetupBitBucketCI(bitBucketCI map[string]any, endpoint, webhookSecret string) (string, error) {
+func SetupBitBucketCI(bitBucketCI map[string]any, endpoint string) (string, error) {
if _, ok := bitBucketCI["image"]; !ok {
bitBucketCI["image"] = "atlassian/default-image:4"
}
if _, ok := bitBucketCI["pipelines"]; !ok {
bitBucketCI["pipelines"] = make(map[string]any)
}
+ // enable pipeline for pull request
+ // https://support.atlassian.com/bitbucket-cloud/docs/pipeline-start-conditions/#Pull-Requests
+ // https://stackoverflow.com/questions/55019205/how-to-run-pipeline-only-on-pull-request-to-master-branch
if _, ok := bitBucketCI["pipelines"].(map[string]any)["pull-requests"]; !ok {
bitBucketCI["pipelines"].(map[string]any)["pull-requests"] = make(map[string]any)
}
@@ -70,7 +128,7 @@ func SetupBitBucketCI(bitBucketCI map[string]any, endpoint, webhookSecret string
prSteps = append(prSteps, steps)
}
- stepStr := getSQLReviewStep(endpoint, webhookSecret)
+ stepStr := getSQLReviewStep(endpoint)
pipelineStep := &pipelineStep{}
if err := yaml.Unmarshal([]byte(stepStr), pipelineStep); err != nil {
return "", errors.Wrapf(err, "failed to parse pipeline step")
diff --git a/backend/plugin/vcs/gitlab/gitlab.go b/backend/plugin/vcs/gitlab/gitlab.go
index aa428a552c..1b48e50295 100644
--- a/backend/plugin/vcs/gitlab/gitlab.go
+++ b/backend/plugin/vcs/gitlab/gitlab.go
@@ -904,10 +904,10 @@ func (p *Provider) getEnvironmentVariable(ctx context.Context, oauthCtx *common.
}
if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, "failed to read file from URL %s", url)
+ return nil, common.Errorf(common.NotFound, "failed to found variable from URL %s", url)
} else if code >= 300 {
return nil,
- errors.Errorf("failed to read file from URL %s, status code: %d, body: %s",
+ errors.Errorf("failed to found variable from URL %s, status code: %d, body: %s",
url,
code,
body,
@@ -979,7 +979,7 @@ func (p *Provider) updateEnvironmentVariable(ctx context.Context, oauthCtx *comm
},
)
if err != nil {
- return errors.Wrap(err, "marshal environment create")
+ return errors.Wrap(err, "marshal environment update")
}
code, _, resp, err := oauth.Put(
ctx,
diff --git a/frontend/src/components/VCS/VCSProviderOAuthPanel.vue b/frontend/src/components/VCS/VCSProviderOAuthPanel.vue
index d1634d1192..3176cb58e2 100644
--- a/frontend/src/components/VCS/VCSProviderOAuthPanel.vue
+++ b/frontend/src/components/VCS/VCSProviderOAuthPanel.vue
@@ -411,7 +411,8 @@
</dt>
<dd class="text-sm text-main">
Account > Read, Webhooks > Read and write, Repositories >
- Write, Pipelines > Edit variables, Pull requests > Write
+ Write and Admin, Pipelines > Edit variables, Pull requests >
+ Write
</dd>
</div>
</dl>