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(vcs): create the vcs plugin provider interface and add the GitLab implementation (#312)
tianzhouc3af045e91e9
diff --git a/api/vcs.go b/api/vcs.goindex 8cf7190a01..65869115ca 100644--- a/api/vcs.go+++ b/api/vcs.go@@ -20,12 +20,12 @@ type VCS struct {UpdatedTs int64 `jsonapi:"attr,updatedTs"`// Domain specific fields- Name string `jsonapi:"attr,name"`- Type vcs.VCSType `jsonapi:"attr,type"`- InstanceURL string `jsonapi:"attr,instanceUrl"`- APIURL string `jsonapi:"attr,apiUrl"`- ApplicationID string `jsonapi:"attr,applicationId"`- Secret string `jsonapi:"attr,secret"`+ Name string `jsonapi:"attr,name"`+ Type vcs.Type `jsonapi:"attr,type"`+ InstanceURL string `jsonapi:"attr,instanceUrl"`+ APIURL string `jsonapi:"attr,apiUrl"`+ ApplicationID string `jsonapi:"attr,applicationId"`+ Secret string `jsonapi:"attr,secret"`}// VCSCreate is the API message for creating a VCS.@@ -35,9 +35,9 @@ type VCSCreate struct {CreatorID int// Domain specific fields- Name string `jsonapi:"attr,name"`- Type vcs.VCSType `jsonapi:"attr,type"`- InstanceURL string `jsonapi:"attr,instanceUrl"`+ Name string `jsonapi:"attr,name"`+ Type vcs.Type `jsonapi:"attr,type"`+ InstanceURL string `jsonapi:"attr,instanceUrl"`// APIURL derives from InstanceURLAPIURL stringApplicationID string `jsonapi:"attr,applicationId"`diff --git a/common/oauth.go b/common/oauth.gonew file mode 100644index 0000000000..14c2c7208f--- /dev/null+++ b/common/oauth.go@@ -0,0 +1,13 @@+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 {+ ClientID string+ ClientSecret string+ AccessToken string+ RefreshToken string+ Refresher TokenRefresher+}diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.goindex 5a9444cd63..d5642d2a8b 100644--- a/plugin/vcs/gitlab/gitlab.go+++ b/plugin/vcs/gitlab/gitlab.go@@ -2,20 +2,32 @@ package gitlabimport ("bytes"+ "context""encoding/json""fmt""io""net/http"+ "net/url"+ "strconv""strings"++ "github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/plugin/vcs"+ "go.uber.org/zap")const (- // APIPath is the API path.- APIPath = "api/v4"// SecretTokenLength is the length of secret token.SecretTokenLength = 16maxRetries = 3++ // apiPath is the API path.+ apiPath = "api/v4"+)++var (+ _ vcs.Provider = (*Provider)(nil))// WebhookType is the gitlab webhook type.@@ -34,8 +46,8 @@ func (e WebhookType) String() string {return "UNKNOWN"}-// WebhookInfo is the API message for webhook info.-type WebhookInfo struct {+// webhookInfo is the API message for webhook info.+type webhookInfo struct {ID int `json:"id"`}@@ -94,23 +106,270 @@ type WebhookPushEvent struct {CommitList []WebhookCommit `json:"commits"`}-// FileCommit is the API message for file commit.-type FileCommit struct {+// fileCommit is the API message for file commit.+type fileCommit struct {Branch string `json:"branch"`Content string `json:"content"`CommitMessage string `json:"commit_message"`LastCommitID string `json:"last_commit_id,omitempty"`}-// File is the API message for file.-type File struct {+// fileMeta is the API message for file metadata.+type fileMeta struct {LastCommitID string `json:"last_commit_id"`}-// POST sends a POST request.-func POST(instanceURL string, resourcePath string, token *string, body io.Reader, oauthContext OauthContext, refresher TokenRefresher) (*http.Response, error) {+func init() {+ vcs.Register(vcs.GitLabSelfHost, newProvider)+}++// Provider is the GitLab self host provider.+type Provider struct {+ l *zap.Logger+}++func newProvider(config vcs.ProviderConfig) vcs.Provider {+ return &Provider{+ l: config.Logger,+ }+}++func (provider *Provider) APIURL(instanceURL string) string {+ return fmt.Sprintf("%s/%s", instanceURL, apiPath)+}++func (provider *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, fileCommitCreate vcs.FileCommitCreate) error {+ body, err := json.Marshal(fileCommit{+ Branch: fileCommitCreate.Branch,+ CommitMessage: fileCommitCreate.CommitMessage,+ Content: fileCommitCreate.Content,+ })+ if err != nil {+ return fmt.Errorf("failed to marshal file commit: %w", err)+ }+ resp, err := httpPost(+ instanceURL,+ filePath,+ &oauthCtx.AccessToken,+ bytes.NewBuffer(body),+ 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)+ }++ if resp.StatusCode >= 300 {+ return fmt.Errorf("failed to create file %s on GitLab instance %s, status code: %d",+ filePath,+ instanceURL,+ resp.StatusCode,+ )+ }+ return nil+}++func (provider *Provider) OverwriteFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, fileCommitCreate vcs.FileCommitCreate) error {+ body, err := json.Marshal(fileCommit{+ Branch: fileCommitCreate.Branch,+ CommitMessage: fileCommitCreate.CommitMessage,+ Content: fileCommitCreate.Content,+ LastCommitID: fileCommitCreate.LastCommitID,+ })+ if err != nil {+ return fmt.Errorf("failed to marshal file commit: %w", err)+ }++ resp, err := httpPut(+ instanceURL,+ filePath,+ &oauthCtx.AccessToken,+ bytes.NewBuffer(body),+ 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)+ }++ if resp.StatusCode >= 300 {+ return fmt.Errorf("failed to create file %s on GitLab instance %s, status code: %d",+ filePath,+ instanceURL,+ resp.StatusCode,+ )+ }+ return nil+}++func (provider *Provider) ReadFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, commitID string) (io.ReadCloser, error) {+ resp, err := httpGet(+ instanceURL,+ fmt.Sprintf("projects/%s/repository/files/%s/raw?ref=%s", repositoryID, url.QueryEscape(filePath), commitID),+ &oauthCtx.AccessToken,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ )++ if err != nil {+ return nil, fmt.Errorf("failed to read file %s from GitLab instance %s: %w", filePath, instanceURL, err)+ }++ if resp.StatusCode == 404 {+ return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to read file %s from GitLab instance %s, file not found", filePath, instanceURL))+ } else if resp.StatusCode >= 300 {+ return nil, fmt.Errorf("failed to read file %s from GitLab instance %s, status code: %d",+ filePath,+ instanceURL,+ resp.StatusCode,+ )+ }++ return resp.Body, nil+}++func (provider *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, branch string) (*vcs.FileMeta, error) {+ resp, err := httpGet(+ instanceURL,+ fmt.Sprintf("projects/%s/repository/files/%s?ref=%s", repositoryID, url.QueryEscape(filePath), url.QueryEscape(branch)),+ &oauthCtx.AccessToken,+ 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)+ }++ if resp.StatusCode == 404 {+ return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to read file meta %s from GitLab instance %s, file not found", filePath, instanceURL))+ } else if resp.StatusCode >= 300 {+ return nil, fmt.Errorf("failed to read file meta %s from GitLab instance %s, status code: %d",+ filePath,+ instanceURL,+ resp.StatusCode,+ )+ }+ defer resp.Body.Close()++ file := &fileMeta{}+ if err := json.NewDecoder(resp.Body).Decode(file); err != nil {+ return nil, fmt.Errorf("failed to unmarshal file meta from GitLab instance %s: %w", instanceURL, err)+ }++ return &vcs.FileMeta{+ LastCommitID: file.LastCommitID,+ }, nil+}++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)+ resp, err := httpPost(+ instanceURL,+ resourcePath,+ &oauthCtx.AccessToken,+ bytes.NewBuffer(payload),+ 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)+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 300 {+ reason := fmt.Sprintf(+ "failed to create webhook for repository %s from GitLab instance %s, status code: %d",+ repositoryID,+ instanceURL,+ resp.StatusCode,+ )+ // Add helper tips if the status code is 422, refer to bytebase#101 for more context.+ if resp.StatusCode == 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)+ }++ webhookInfo := &webhookInfo{}+ if err := json.NewDecoder(resp.Body).Decode(webhookInfo); err != nil {+ return "", fmt.Errorf("failed to unmarshal create webhook response for repository %s from GitLab instance %s: %w", repositoryID, instanceURL, err)+ }+ return strconv.Itoa(webhookInfo.ID), nil+}++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)+ resp, err := httpPut(+ instanceURL,+ resourcePath,+ &oauthCtx.AccessToken,+ bytes.NewBuffer(payload),+ 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)+ }++ if resp.StatusCode >= 300 {+ return fmt.Errorf("failed to patch webhook ID %s for repository %s from GitLab instance %s, status code: %d", webhookId, repositoryID, instanceURL, resp.StatusCode)+ }+ return nil+}++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)+ resp, err := httpDelete(+ instanceURL,+ resourcePath,+ &oauthCtx.AccessToken,+ 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)+ }++ if resp.StatusCode >= 300 {+ return fmt.Errorf("failed to delete webhook ID %s for repository %s from GitLab instance %s, status code: %d", webhookId, repositoryID, instanceURL, resp.StatusCode)+ }+ return nil+}++// httpPost sends a POST request.+func httpPost(instanceURL string, resourcePath string, token *string, body io.Reader, oauthContext oauthContext, refresher common.TokenRefresher) (*http.Response, error) {return retry(instanceURL, token, oauthContext, refresher, func() (*http.Response, error) {- url := fmt.Sprintf("%s/%s/%s", instanceURL, APIPath, resourcePath)+ url := fmt.Sprintf("%s/%s/%s", instanceURL, apiPath, resourcePath)req, err := http.NewRequest("POST",url, body)if err != nil {@@ -128,10 +387,10 @@ func POST(instanceURL string, resourcePath string, token *string, body io.Reader})}-// GET sends a GET request.-func GET(instanceURL string, resourcePath string, token *string, oauthContext OauthContext, refresher TokenRefresher) (*http.Response, error) {+// httpGet sends a GET request.+func httpGet(instanceURL string, resourcePath string, token *string, oauthContext oauthContext, refresher common.TokenRefresher) (*http.Response, error) {return retry(instanceURL, token, oauthContext, refresher, func() (*http.Response, error) {- url := fmt.Sprintf("%s/%s/%s", instanceURL, APIPath, resourcePath)+ url := fmt.Sprintf("%s/%s/%s", instanceURL, apiPath, resourcePath)req, err := http.NewRequest("GET",url, nil)if err != nil {@@ -149,10 +408,10 @@ func GET(instanceURL string, resourcePath string, token *string, oauthContext Oa})}-// PUT sends a PUT request.-func PUT(instanceURL string, resourcePath string, token *string, body io.Reader, oauthContext OauthContext, refresher TokenRefresher) (*http.Response, error) {+// httpPut sends a PUT request.+func httpPut(instanceURL string, resourcePath string, token *string, body io.Reader, oauthContext oauthContext, refresher common.TokenRefresher) (*http.Response, error) {return retry(instanceURL, token, oauthContext, refresher, func() (*http.Response, error) {- url := fmt.Sprintf("%s/%s/%s", instanceURL, APIPath, resourcePath)+ url := fmt.Sprintf("%s/%s/%s", instanceURL, apiPath, resourcePath)req, err := http.NewRequest("PUT",url, body)if err != nil {@@ -170,10 +429,10 @@ func PUT(instanceURL string, resourcePath string, token *string, body io.Reader,})}-// DELETE sends a DELETE request.-func DELETE(instanceURL string, resourcePath string, token *string, oauthContext OauthContext, refresher TokenRefresher) (*http.Response, error) {+// httpDelete sends a DELETE request.+func httpDelete(instanceURL string, resourcePath string, token *string, oauthContext oauthContext, refresher common.TokenRefresher) (*http.Response, error) {return retry(instanceURL, token, oauthContext, refresher, func() (*http.Response, error) {- url := fmt.Sprintf("%s/%s/%s", instanceURL, APIPath, resourcePath)+ url := fmt.Sprintf("%s/%s/%s", instanceURL, apiPath, resourcePath)req, err := http.NewRequest("DELETE",url, nil)if err != nil {@@ -191,7 +450,7 @@ func DELETE(instanceURL string, resourcePath string, token *string, oauthContext})}-func retry(instanceURL string, token *string, oauthContext OauthContext, refresher TokenRefresher, f func() (*http.Response, error)) (*http.Response, error) {+func retry(instanceURL string, token *string, oauthContext oauthContext, refresher common.TokenRefresher, f func() (*http.Response, error)) (*http.Response, error) {retries := 0RETRY:retries++@@ -255,11 +514,8 @@ func expiredTokenError(e error) bool {return oe.Err == "invalid_token" && strings.Contains(oe.ErrorDescription, "expired")}-// TokenRefresher is a function refreshes the oauth token and updates the repository.-type TokenRefresher func(token, refreshToken string, expiresTs int64) error--// OauthContext is the request context for refreshing oauth token.-type OauthContext struct {+// 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"`@@ -274,7 +530,7 @@ type refreshOauthResponse struct {// token_type, scope are not used.}-func refreshToken(instanceURL string, oldToken *string, oauthContext OauthContext, refresher TokenRefresher) error {+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)diff --git a/plugin/vcs/vcs.go b/plugin/vcs/vcs.goindex 4ee81cc63a..ed4cdab829 100644--- a/plugin/vcs/vcs.go+++ b/plugin/vcs/vcs.go@@ -1,16 +1,25 @@package vcs-// VCSType is the type of VCS.-type VCSType string+import (+ "context"+ "io"+ "sync"++ "github.com/bytebase/bytebase/common"+ "go.uber.org/zap"+)++// Type is the type of a VCS.+type Type stringconst (- // GitSelfHost is the VCS type for gitlab self host.- GitSelfHost VCSType = "GITLAB_SELF_HOST"+ // GitLabSelfHost is the VCS type for gitlab self host.+ GitLabSelfHost Type = "GITLAB_SELF_HOST")-func (e VCSType) String() string {+func (e Type) String() string {switch e {- case GitSelfHost:+ case GitLabSelfHost:return "GITLAB_SELF_HOST"}return "UNKNOWN"@@ -31,9 +40,22 @@ type VCSFileCommit struct {Added string `json:"added"`}+// FileCommitCreate is the payload for committing a new file.+type FileCommitCreate struct {+ Branch string+ Content string+ CommitMessage string+ LastCommitID string+}++// FileMata records the file metadata.+type FileMeta struct {+ LastCommitID string+}+// VCSPushEvent is the API message for a VCS push event.type VCSPushEvent struct {- VCSType VCSType `json:"vcsType"`+ VCSType Type `json:"vcsType"`BaseDirectory string `json:"baseDir"`Ref string `json:"ref"`RepositoryID string `json:"repositoryId"`@@ -42,3 +64,84 @@ type VCSPushEvent struct {AuthorName string `json:"authorName"`FileCommit VCSFileCommit `json:"fileCommit"`}++type Provider interface {+ // Returns the API URL for a given VCS instance URL+ APIURL(instanceURL string) string+ // Commits a new file+ //+ // oauthCtx: OAuth context to write the file content+ // instanceURL: VCS instance URL+ // repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)+ // filePath: file path to be written+ // fileCommit: the new file commit info+ CreateFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, fileCommit FileCommitCreate) error+ // Overwrites an existing file+ //+ // Similar to CreateFile except it overwrites an existing file. The fileCommit shoud includes the "LastCommitID" field which is used to detect conflicting writes.+ OverwriteFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, fileCommit FileCommitCreate) error+ // Reads the file content. Returns an io.ReadCloser on success. If file does not exist, returns NotFound error.+ //+ // oauthCtx: OAuth context to read the file content+ // instanceURL: VCS instance URL+ // repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)+ // filePath: file path to be read+ // commitID: the specific version to be read+ ReadFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, commitID string) (io.ReadCloser, error)+ // Reads the file metadata. Returns the file meta on success.+ //+ // Similar to ReadFile except it specifies a branch instead of a commitID.+ ReadFileMeta(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, branch string) (*FileMeta, error)+ // Creates a webhook. Returns the created webhook ID on succeess.+ //+ // oauthCtx: OAuth context to create the webhook+ // instanceURL: VCS instance URL+ // repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)+ // payload: the webhook payload+ CreateWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, payload []byte) (string, error)+ // Patches a webhook.+ //+ // The payload stores the patched field(s).+ PatchWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, webhookId string, payload []byte) error+ // Deletes a webhook.+ DeleteWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, webhookId string) error+}++var (+ providerMu sync.RWMutex+ providers = make(map[Type]providerFunc)+)++// ProviderConfig is the provider configuration.+type ProviderConfig struct {+ Logger *zap.Logger+}++type providerFunc func(ProviderConfig) Provider++// Register makes a vcs provider available by the provided type.+// If Register is called twice with the same name or if provider is nil,+// it panics.+func Register(vcsType Type, f providerFunc) {+ providerMu.Lock()+ defer providerMu.Unlock()+ if f == nil {+ panic("vcs: Register provider is nil")+ }+ if _, dup := providers[vcsType]; dup {+ panic("vcs: Register called twice for provider " + vcsType)+ }+ providers[vcsType] = f+}++// Get returns a vcs provider specified by its vcs type+func Get(vcsType Type, providerConfig ProviderConfig) Provider {+ providerMu.RLock()+ f, ok := providers[vcsType]+ providerMu.RUnlock()+ if !ok {+ panic("vcs: unknown provider " + vcsType)+ }++ return f(providerConfig)+}diff --git a/server/project.go b/server/project.goindex 654c2c97f2..f33290379f 100644--- a/server/project.go+++ b/server/project.go@@ -1,7 +1,6 @@package serverimport (- "bytes""context""encoding/json""fmt"@@ -11,11 +10,12 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"++ vcsPlugin "github.com/bytebase/bytebase/plugin/vcs""github.com/bytebase/bytebase/plugin/vcs/gitlab""github.com/google/jsonapi""github.com/google/uuid""github.com/labstack/echo/v4"- "go.uber.org/zap")func (s *Server) registerProjectRoutes(g *echo.Group) {@@ -178,6 +178,9 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {repositoryCreate.WebhookURLHost = fmt.Sprintf("%s:%d", s.host, s.port)repositoryCreate.WebhookEndpointID = uuid.New().String()repositoryCreate.WebhookSecretToken = common.RandomString(gitlab.SecretTokenLength)++ // Create webhook and retrieve the created webhook id+ var webhookCreatePayload []byteswitch vcs.Type {case "GITLAB_SELF_HOST":webhookPost := gitlab.WebhookPost{@@ -187,38 +190,28 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {PushEventsBranchFilter: repositoryCreate.BranchFilter,EnableSSLVerification: false,}- body, err := json.Marshal(webhookPost)+ webhookCreatePayload, err = json.Marshal(webhookPost)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal post request for creating webhook for project ID: %v", repositoryCreate.ProjectID)).SetInternal(err)}- resourcePath := fmt.Sprintf("projects/%s/hooks", repositoryCreate.ExternalID)- // We use s.refreshTokenNoop() because the repository isn't created yet.- resp, err := gitlab.POST(vcs.InstanceURL, resourcePath, &repositoryCreate.AccessToken, bytes.NewBuffer(body), gitlab.OauthContext{}, s.refreshTokenNoop())- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create webhook for project ID: %v", repositoryCreate.ProjectID)).SetInternal(err)- }- defer resp.Body.Close()-- if resp.StatusCode >= 300 {- reason := fmt.Sprintf(- "Failed to create webhook for project ID: %d, status code: %d",- repositoryCreate.ProjectID,- resp.StatusCode,- )- // Add helper tips if the status code is 422, refer to bytebase#101 for more context.- if resp.StatusCode == 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 echo.NewHTTPError(http.StatusInternalServerError, reason)- }+ }- webhookInfo := &gitlab.WebhookInfo{}- if err := json.NewDecoder(resp.Body).Decode(webhookInfo); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to unmarshal create webhook response for project ID: %v", repositoryCreate.ProjectID)).SetInternal(err)- }- repositoryCreate.ExternalWebhookID = strconv.Itoa(webhookInfo.ID)+ webhookId, err := vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{Logger: s.l}).CreateWebhook(+ ctx,+ common.OauthContext{+ AccessToken: repositoryCreate.AccessToken,+ // We use s.refreshTokenNoop() because the repository isn't created yet.+ Refresher: s.refreshTokenNoop(),+ },+ vcs.InstanceURL,+ repositoryCreate.ExternalID,+ webhookCreatePayload,+ )++ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create webhook for project ID: %v", repositoryCreate.ProjectID)).SetInternal(err)}+ repositoryCreate.ExternalWebhookID = webhookIdrepositoryCreate.CreatorID = c.Get(getPrincipalIDContextKey()).(int)// Remove enclosing /@@ -342,51 +335,42 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update repository for project ID: %d", projectID)).SetInternal(err)}if vcs == nil {- err := fmt.Errorf("Failed to find VCS configuration for ID: %d", repository.VCSID)+ err := fmt.Errorf("failed to find VCS configuration for ID: %d", repository.VCSID)return echo.NewHTTPError(http.StatusInternalServerError, err.Error()).SetInternal(err)}- // Updates the webhook after we successfully update the repository.+ // Update the webhook after we successfully update the repository.// This is because in case the webhook update fails, we can still have a reconcile process to reconcile the webhook state.// If we update it before we update the repository, then if the repository update fails, then the reconcile process will reconcile the webhook to the pre-update state which is likely not intended.+ var webhookPatchPayload []byteswitch vcs.Type {case "GITLAB_SELF_HOST":webhookPut := gitlab.WebhookPut{URL: fmt.Sprintf("%s:%d/%s/%s", s.host, s.port, gitLabWebhookPath, updatedRepository.WebhookEndpointID),PushEventsBranchFilter: *repositoryPatch.BranchFilter,}- json, err := json.Marshal(webhookPut)+ webhookPatchPayload, err = json.Marshal(webhookPut)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal put request for updating webhook %s for project ID: %v", repository.ExternalWebhookID, projectID)).SetInternal(err)}- resourcePath := fmt.Sprintf("projects/%s/hooks/%s", repository.ExternalID, repository.ExternalWebhookID)- resp, err := gitlab.PUT(- vcs.InstanceURL,- resourcePath,- &repository.AccessToken,- bytes.NewBuffer(json),- gitlab.OauthContext{- ClientID: repository.VCS.ApplicationID,- ClientSecret: repository.VCS.Secret,- RefreshToken: repository.RefreshToken,- },- s.refreshToken(ctx, repository.ID),- )- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update webhook ID %s for project ID: %v", repository.ExternalWebhookID, projectID)).SetInternal(err)- }- defer resp.Body.Close()-- // Just emits a warning since we have already updated the repository entry. We will have a separate process to reconcile the state.- if resp.StatusCode >= 300 {- s.l.Error(("Failed to update gitlab webhook when updating repository for project"),- zap.Int("status_code", resp.StatusCode),- zap.String("status", resp.Status),- zap.Int("project_id", projectID),- zap.Int("repository_id", repository.ID),- zap.String("resource_path", resourcePath),- zap.String("body", string(json)),- )- }+ }++ err = vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{Logger: s.l}).PatchWebhook(+ ctx,+ common.OauthContext{+ ClientID: repository.VCS.ApplicationID,+ ClientSecret: repository.VCS.Secret,+ AccessToken: repository.AccessToken,+ RefreshToken: repository.RefreshToken,+ Refresher: s.refreshToken(ctx, repository.ID),+ },+ vcs.InstanceURL,+ repository.ExternalID,+ repository.ExternalWebhookID,+ webhookPatchPayload,+ )++ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update webhook ID %s for project ID: %v", repository.ExternalWebhookID, projectID)).SetInternal(err)}}@@ -445,38 +429,25 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete repository for project ID: %d", projectID)).SetInternal(err)}- // Deletes the webhook after we successfully delete the repository.+ // Delete the webhook after we successfully delete the repository.// This is because in case the webhook deletion fails, we can still have a cleanup process to cleanup the orphaned webhook.// If we delete it before we delete the repository, then if the repository deletion fails, we will have a broken repository with no webhook.- switch vcs.Type {- case "GITLAB_SELF_HOST":- resp, err := gitlab.DELETE(- vcs.InstanceURL,- fmt.Sprintf("projects/%s/hooks/%s",- repository.ExternalID,- repository.ExternalWebhookID),- &repository.AccessToken,- gitlab.OauthContext{- ClientID: repository.VCS.ApplicationID,- ClientSecret: repository.VCS.Secret,- RefreshToken: repository.RefreshToken,- },- s.refreshToken(ctx, repository.ID),- )- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete webhook ID %s for project ID: %v", repository.ExternalWebhookID, projectID)).SetInternal(err)- }- defer resp.Body.Close()-- // Just emits a warning since we have already removed the repository entry. We will have a separate process to cleanup the orphaned webhook.- if resp.StatusCode >= 300 {- s.l.Error(("Failed to delete gitlab webhook when unlinking repository from project"),- zap.Int("status_code", resp.StatusCode),- zap.Int("project_id", projectID),- zap.Int("repository_id", repository.ID),- zap.String("gitlab_project_id", repository.ExternalID),- zap.String("gitlab_webhook_id", repository.ExternalWebhookID))- }+ err = vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{Logger: s.l}).DeleteWebhook(+ ctx,+ common.OauthContext{+ ClientID: repository.VCS.ApplicationID,+ ClientSecret: repository.VCS.Secret,+ AccessToken: repository.AccessToken,+ RefreshToken: repository.RefreshToken,+ Refresher: s.refreshToken(ctx, repository.ID),+ },+ vcs.InstanceURL,+ repository.ExternalID,+ repository.ExternalWebhookID,+ )++ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete webhook ID %s for project ID: %v", repository.ExternalWebhookID, projectID)).SetInternal(err)}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)@@ -613,7 +584,7 @@ func validateRepositorySchemaPathTemplate(schemaPathTemplate string) error {}// refreshToken is a token refresher that stores the latest access token configuration to repository.-func (s *Server) refreshToken(ctx context.Context, repositoryID int) gitlab.TokenRefresher {+func (s *Server) refreshToken(ctx context.Context, repositoryID int) common.TokenRefresher {return func(token, refreshToken string, expiresTs int64) error {if _, err := s.RepositoryService.PatchRepository(ctx, &api.RepositoryPatch{ID: repositoryID,@@ -629,7 +600,7 @@ func (s *Server) refreshToken(ctx context.Context, repositoryID int) gitlab.Toke}// refreshToken is a no-op token refresher. It should be used when the repository isn't created yet.-func (s *Server) refreshTokenNoop() gitlab.TokenRefresher {+func (s *Server) refreshTokenNoop() common.TokenRefresher {return func(newToken, newRefreshToken string, expiresTs int64) error {return nil}diff --git a/server/task_executor_schema_update.go b/server/task_executor_schema_update.goindex 43d3c76d2c..e924f78de9 100644--- a/server/task_executor_schema_update.go+++ b/server/task_executor_schema_update.go@@ -1,11 +1,9 @@package serverimport (- "bytes""context""encoding/json""fmt"- "net/url""path/filepath""strconv""strings"@@ -14,7 +12,6 @@ import ("github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/vcs"- "github.com/bytebase/bytebase/plugin/vcs/gitlab""go.uber.org/zap")@@ -256,35 +253,29 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Serve// Writes back the latest schema to the repository after migration// Returns the commit id on success.func writeBackLatestSchema(ctx context.Context, server *Server, repository *api.Repository, pushEvent *vcs.VCSPushEvent, mi *db.MigrationInfo, branch string, latestSchemaFile string, schema string, bytebaseURL string) (string, error) {- filePath := fmt.Sprintf("projects/%s/repository/files/%s", repository.ExternalID, url.QueryEscape(latestSchemaFile))- getFilePath := filePath + "?ref=" + url.QueryEscape(branch)-- getResp, err := gitlab.GET(- repository.VCS.InstanceURL,- getFilePath,- &repository.AccessToken,- gitlab.OauthContext{+ schemaFileMeta, err := vcs.Get(vcs.GitLabSelfHost, vcs.ProviderConfig{Logger: server.l}).ReadFileMeta(+ ctx,+ common.OauthContext{ClientID: repository.VCS.ApplicationID,ClientSecret: repository.VCS.Secret,RefreshToken: repository.RefreshToken,+ Refresher: server.refreshToken(ctx, repository.ID),},- server.refreshToken(ctx, repository.ID),+ repository.VCS.InstanceURL,+ repository.ExternalID,+ latestSchemaFile,+ branch,)- if err != nil {- return "", fmt.Errorf("failed to fetch latest schema file from %s, err: %w", repository.VCS.InstanceURL, err)- }- defer getResp.Body.Close()createSchemaFile := falseverb := "Update"- if getResp.StatusCode >= 300 && getResp.StatusCode != 404 {- return "", fmt.Errorf("failed to fetch latest schema file from %s, status code: %d",- repository.VCS.InstanceURL,- getResp.StatusCode,- )- } else if getResp.StatusCode == 404 {- createSchemaFile = true- verb = "Create"+ if err != nil {+ if common.ErrorCode(err) == common.NotFound {+ createSchemaFile = true+ verb = "Create"+ } else {+ return "", fmt.Errorf("failed to fetch latest schema: %w", err)+ }}commitTitle := fmt.Sprintf("[Bytebase] %s latest schema for %q after migration %s", verb, mi.Database, mi.Version)@@ -298,108 +289,66 @@ func writeBackLatestSchema(ctx context.Context, server *Server, repository *api.pushEvent.FileCommit.Message,)- schemaFileCommit := gitlab.FileCommit{+ schemaFileCommit := vcs.FileCommitCreate{Branch: branch,CommitMessage: fmt.Sprintf("%s\n\n%s", commitTitle, commitBody),Content: schema,}if createSchemaFile {- body, err := json.Marshal(schemaFileCommit)- if err != nil {- return "", fmt.Errorf("failed to marshal file request %s after applying migration %s to %q", filePath, mi.Version, mi.Database)- }-- resp, err := gitlab.POST(- repository.VCS.InstanceURL,- filePath,- &repository.AccessToken,- bytes.NewBuffer(body),- gitlab.OauthContext{+ err := vcs.Get(vcs.GitLabSelfHost, vcs.ProviderConfig{Logger: server.l}).CreateFile(+ ctx,+ common.OauthContext{ClientID: repository.VCS.ApplicationID,ClientSecret: repository.VCS.Secret,RefreshToken: repository.RefreshToken,+ Refresher: server.refreshToken(ctx, repository.ID),},- server.refreshToken(ctx, repository.ID),+ repository.VCS.InstanceURL,+ repository.ExternalID,+ latestSchemaFile,+ schemaFileCommit,)- if err != nil {- return "", fmt.Errorf("failed to create file %s after applying migration %s to %q, err: %w", filePath, mi.Version, mi.Database, err)- }- defer resp.Body.Close()-- if resp.StatusCode >= 300 {- return "", fmt.Errorf("failed to create file %s after applying migration %s to %q, status code: %d",- filePath,- mi.Version,- mi.Database,- resp.StatusCode,- )- }- } else {- file := &gitlab.File{}- if err := json.NewDecoder(getResp.Body).Decode(file); err != nil {- return "", fmt.Errorf("failed to unmarshal file response %s after applying migration %s to %q", filePath, mi.Version, mi.Database)- }- schemaFileCommit.LastCommitID = file.LastCommitID- body, err := json.Marshal(schemaFileCommit)if err != nil {- return "", fmt.Errorf("failed to marshal file request %s after applying migration %s to %q", filePath, mi.Version, mi.Database)+ return "", fmt.Errorf("failed to create file after applying migration %s to %q: %w", mi.Version, mi.Database, err)}-- resp, err := gitlab.PUT(- repository.VCS.InstanceURL,- filePath,- &repository.AccessToken,- bytes.NewBuffer(body),- gitlab.OauthContext{+ } else {+ schemaFileCommit.LastCommitID = schemaFileMeta.LastCommitID+ err := vcs.Get(vcs.GitLabSelfHost, vcs.ProviderConfig{Logger: server.l}).OverwriteFile(+ ctx,+ common.OauthContext{ClientID: repository.VCS.ApplicationID,ClientSecret: repository.VCS.Secret,RefreshToken: repository.RefreshToken,+ Refresher: server.refreshToken(ctx, repository.ID),},- server.refreshToken(ctx, repository.ID),+ repository.VCS.InstanceURL,+ repository.ExternalID,+ latestSchemaFile,+ schemaFileCommit,)if err != nil {- return "", fmt.Errorf("failed to create file %s after applying migration %s to %q, error: %w", filePath, mi.Version, mi.Database, err)- }- defer resp.Body.Close()-- if resp.StatusCode >= 300 {- return "", fmt.Errorf("failed to create file %s after applying migration %s to %q, status code: %d",- filePath,- mi.Version,- mi.Database,- resp.StatusCode,- )+ return "", fmt.Errorf("failed to create file after applying migration %s to %q: %w", mi.Version, mi.Database, err)}}- // GitLab API doesn't return the commit on write, so we have to call GET again- getResp, err = gitlab.GET(- repository.VCS.InstanceURL,- getFilePath,- &repository.AccessToken,- gitlab.OauthContext{+ // VCS such as GitLab API doesn't return the commit on write, so we have to call ReadFileMeta again+ schemaFileMeta, err = vcs.Get(vcs.GitLabSelfHost, vcs.ProviderConfig{Logger: server.l}).ReadFileMeta(+ ctx,+ common.OauthContext{ClientID: repository.VCS.ApplicationID,ClientSecret: repository.VCS.Secret,RefreshToken: repository.RefreshToken,+ Refresher: server.refreshToken(ctx, repository.ID),},- server.refreshToken(ctx, repository.ID),+ repository.VCS.InstanceURL,+ repository.ExternalID,+ latestSchemaFile,+ branch,)- if err != nil {- return "", fmt.Errorf("failed to fetch latest schema file after update, VCS instance: %s, err: %w", repository.VCS.InstanceURL, err)- }- defer getResp.Body.Close()- if getResp.StatusCode >= 300 && getResp.StatusCode != 404 {- return "", fmt.Errorf("failed to fetch latest schema file after update, VCS instance: %s, status code: %d",- repository.VCS.InstanceURL,- getResp.StatusCode,- )- }-- file := &gitlab.File{}- if err := json.NewDecoder(getResp.Body).Decode(file); err != nil {- return "", fmt.Errorf("failed to unmarshal file response %s after update, VCS instance: %s", filePath, repository.VCS.InstanceURL)+ if err != nil {+ return "", fmt.Errorf("failed to fetch latest schema file %s after update: %w", latestSchemaFile, err)}- return file.LastCommitID, nil+ return schemaFileMeta.LastCommitID, nil}diff --git a/server/vcs.go b/server/vcs.goindex dc2ea49804..2a57559424 100644--- a/server/vcs.go+++ b/server/vcs.go@@ -9,7 +9,7 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"- "github.com/bytebase/bytebase/plugin/vcs/gitlab"+ "github.com/bytebase/bytebase/plugin/vcs""github.com/google/jsonapi""github.com/labstack/echo/v4")@@ -25,7 +25,7 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {}// Trim ending "/"vcsCreate.InstanceURL = strings.TrimRight(vcsCreate.InstanceURL, "/")- vcsCreate.APIURL = fmt.Sprintf("%s/%s", vcsCreate.InstanceURL, gitlab.APIPath)+ vcsCreate.APIURL = vcs.Get(vcs.GitLabSelfHost, vcs.ProviderConfig{Logger: s.l}).APIURL(vcsCreate.InstanceURL)vcs, err := s.VCSService.CreateVCS(ctx, vcsCreate)if err != nil {diff --git a/server/webhook.go b/server/webhook.goindex 4ebdb27887..83c0b53243 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -6,7 +6,6 @@ import ("fmt""io""net/http"- "net/url""path/filepath""regexp""strconv"@@ -159,28 +158,30 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {}// Retrieve sql by reading the file content- resp, err := gitlab.GET(- repository.VCS.InstanceURL,- fmt.Sprintf("projects/%s/repository/files/%s/raw?ref=%s", repository.ExternalID, url.QueryEscape(added), commit.ID),- &repository.AccessToken,- gitlab.OauthContext{+ reader, err := vcs.Get(vcs.GitLabSelfHost, vcs.ProviderConfig{Logger: s.l}).ReadFile(+ ctx,+ common.OauthContext{ClientID: repository.VCS.ApplicationID,ClientSecret: repository.VCS.Secret,RefreshToken: repository.RefreshToken,+ Refresher: s.refreshToken(ctx, repository.ID),},- s.refreshToken(ctx, repository.ID),+ repository.VCS.InstanceURL,+ repository.ExternalID,+ added,+ commit.ID,)if err != nil {- createIgnoredFileActivity(fmt.Errorf("failed to read file: %w", err))+ createIgnoredFileActivity(err)continue}+ defer reader.Close()- b, err := io.ReadAll(resp.Body)+ b, err := io.ReadAll(reader)if err != nil {createIgnoredFileActivity(fmt.Errorf("failed to read file response: %w", err))continue}- defer resp.Body.Close()// Find matching database listdatabaseFind := &api.DatabaseFind{