Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(github): update call sites of `vcs.Provider` methods to reach parity with GitLab (#1899)
Joe Chena5b965fedae6
diff --git a/api/project_member.go b/api/project_member.goindex 2d257f3269..4f166ba70e 100644--- a/api/project_member.go+++ b/api/project_member.go@@ -10,10 +10,13 @@ import (type ProjectRoleProvider stringconst (- // ProjectRoleProviderBytebase is the role provider of a project.+ // ProjectRoleProviderBytebase indicates the role provider is the Bytebase.ProjectRoleProviderBytebase ProjectRoleProvider = "BYTEBASE"- // ProjectRoleProviderGitLabSelfHost is the role provider of a project.+ // ProjectRoleProviderGitLabSelfHost indicates the role provider is the GitLab+ // self-hosted.ProjectRoleProviderGitLabSelfHost ProjectRoleProvider = "GITLAB_SELF_HOST"+ // ProjectRoleProviderGitHubCom indicates the role provider is the GitHub.com.+ ProjectRoleProviderGitHubCom ProjectRoleProvider = "GITHUB_COM")// ProjectRoleProviderPayload is the payload for role providerdiff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.goindex 0f087afc4c..d40158da2a 100644--- a/plugin/vcs/github/github.go+++ b/plugin/vcs/github/github.go@@ -112,6 +112,34 @@ type WebhookInfo struct {ID int `json:"id"`}+// WebhookConfig represents the GitHub API message for webhook configuration.+type WebhookConfig struct {+ // URL is the URL to which the payloads will be delivered.+ URL string `json:"url"`+ // ContentType is the media type used to serialize the payloads. Supported+ // values include "json" and "form". The default is "form".+ ContentType string `json:"content_type"`+ // Secret is the secret will be used as the key to generate the HMAC hex digest+ // value for delivery signature headers.+ Secret string `json:"secret"`+ // InsecureSSL determines whether the SSL certificate of the host for url will+ // be verified when delivering payloads. Supported values include 0+ // (verification is performed) and 1 (verification is not performed). The+ // default is 0.+ InsecureSSL int `json:"insecure_ssl"`+}++// WebhookCreateOrUpdate represents a GitHub API request for creating or+// updating a webhook.+type WebhookCreateOrUpdate struct {+ // Config contains settings for the webhook.+ Config WebhookConfig `json:"config"`+ // Events determines what events the hook is triggered for. The default is+ // ["push"]. The full list of events can be viewed at+ // https://docs.github.com/webhooks/event-payloads.+ Events []string `json:"events"`+}+// 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) {diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.goindex db28907718..a6d108ea9e 100644--- a/plugin/vcs/gitlab/gitlab.go+++ b/plugin/vcs/gitlab/gitlab.go@@ -45,8 +45,8 @@ type WebhookInfo struct {ID int `json:"id"`}-// WebhookPost is the API message for webhook POST.-type WebhookPost struct {+// WebhookCreate represents a GitLab API request for creating a new webhook.+type WebhookCreate struct {URL string `json:"url"`SecretToken string `json:"token"`// This is set to true@@ -58,12 +58,11 @@ type WebhookPost struct {// Saying that, delivering a souding dry run solution would be great and hopefully we can achieve that one day.// MergeRequestsEvents bool `json:"merge_requests_events"`PushEventsBranchFilter string `json:"push_events_branch_filter"`- // TODO(tianzhou): This is set to false, be lax to not enable_ssl_verification- EnableSSLVerification bool `json:"enable_ssl_verification"`+ EnableSSLVerification bool `json:"enable_ssl_verification"`}-// WebhookPut is the API message for webhook PUT.-type WebhookPut struct {+// WebhookUpdate represents a GitLab API request for updating a new webhook.+type WebhookUpdate struct {URL string `json:"url"`PushEventsBranchFilter string `json:"push_events_branch_filter"`}diff --git a/server/project.go b/server/project.goindex e1510ef108..1fc857e66d 100644--- a/server/project.go+++ b/server/project.go@@ -8,16 +8,16 @@ import ("strconv""strings"- "github.com/bytebase/bytebase/api"- "github.com/bytebase/bytebase/common"- "github.com/bytebase/bytebase/common/log"- "go.uber.org/zap"-"github.com/google/jsonapi""github.com/google/uuid""github.com/labstack/echo/v4"+ "go.uber.org/zap"+ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/common/log"vcsPlugin "github.com/bytebase/bytebase/plugin/vcs"+ "github.com/bytebase/bytebase/plugin/vcs/github""github.com/bytebase/bytebase/plugin/vcs/gitlab")@@ -226,19 +226,34 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {repositoryCreate.WebhookEndpointID = uuid.New().String()repositoryCreate.WebhookSecretToken = common.RandomString(gitlab.SecretTokenLength)- // Create webhook and retrieve the created webhook id+ // Create a new webhook and retrieve the created webhook IDvar webhookCreatePayload []byte- if vcs.Type == "GITLAB_SELF_HOST" {- webhookPost := gitlab.WebhookPost{- URL: fmt.Sprintf("%s:%d/%s/%s", s.profile.BackendHost, s.profile.BackendPort, gitLabWebhookPath, repositoryCreate.WebhookEndpointID),+ switch vcs.Type {+ case vcsPlugin.GitLabSelfHost:+ webhookCreate := gitlab.WebhookCreate{+ URL: fmt.Sprintf("%s:%d/%s/%s", s.profile.BackendHost, s.profile.BackendPort, gitlabWebhookPath, repositoryCreate.WebhookEndpointID),SecretToken: repositoryCreate.WebhookSecretToken,PushEvents: true,PushEventsBranchFilter: repositoryCreate.BranchFilter,- EnableSSLVerification: false,+ EnableSSLVerification: false, // TODO(tianzhou): This is set to false, be lax to not enable_ssl_verification+ }+ webhookCreatePayload, err = json.Marshal(webhookCreate)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal request body for creating webhook for project ID: %d", repositoryCreate.ProjectID)).SetInternal(err)+ }+ case vcsPlugin.GitHubCom:+ webhookPost := github.WebhookCreateOrUpdate{+ Config: github.WebhookConfig{+ URL: fmt.Sprintf("%s:%d/%s/%s", s.profile.BackendHost, s.profile.BackendPort, githubWebhookPath, repositoryCreate.WebhookEndpointID),+ ContentType: "json",+ Secret: repositoryCreate.WebhookSecretToken,+ InsecureSSL: 1, // TODO: Allow user to specify this value through api.RepositoryCreate+ },+ Events: []string{"push"},}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)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal request body for creating webhook for project ID: %d", repositoryCreate.ProjectID)).SetInternal(err)}}@@ -378,15 +393,30 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {// 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 []byte- if vcs.Type == "GITLAB_SELF_HOST" {- webhookPut := gitlab.WebhookPut{- URL: fmt.Sprintf("%s:%d/%s/%s", s.profile.BackendHost, s.profile.BackendPort, gitLabWebhookPath, updatedRepo.WebhookEndpointID),+ var webhookUpdatePayload []byte+ switch vcs.Type {+ case vcsPlugin.GitLabSelfHost:+ webhookUpdate := gitlab.WebhookUpdate{+ URL: fmt.Sprintf("%s:%d/%s/%s", s.profile.BackendHost, s.profile.BackendPort, gitlabWebhookPath, updatedRepo.WebhookEndpointID),PushEventsBranchFilter: *repoPatch.BranchFilter,}- webhookPatchPayload, err = json.Marshal(webhookPut)+ webhookUpdatePayload, err = json.Marshal(webhookUpdate)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal request body for updating webhook %s for project ID: %v", repo.ExternalWebhookID, projectID)).SetInternal(err)+ }+ case vcsPlugin.GitHubCom:+ webhookUpdate := github.WebhookCreateOrUpdate{+ Config: github.WebhookConfig{+ URL: fmt.Sprintf("%s:%d/%s/%s", s.profile.BackendHost, s.profile.BackendPort, githubWebhookPath, updatedRepo.WebhookEndpointID),+ ContentType: "json",+ Secret: updatedRepo.WebhookSecretToken,+ InsecureSSL: 1, // TODO: Allow user to specify this value through api.RepositoryPatch+ },+ Events: []string{"push"},+ }+ webhookUpdatePayload, err = json.Marshal(webhookUpdate)if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal put request for updating webhook %s for project ID: %v", repo.ExternalWebhookID, projectID)).SetInternal(err)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal request body for updating webhook %s for project ID: %v", repo.ExternalWebhookID, projectID)).SetInternal(err)}}@@ -403,7 +433,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {vcs.InstanceURL,repo.ExternalID,repo.ExternalWebhookID,- webhookPatchPayload,+ webhookUpdatePayload,)if err != nil {diff --git a/server/project_member.go b/server/project_member.goindex 2a09a1f381..73cc1ef6f7 100644--- a/server/project_member.go+++ b/server/project_member.go@@ -114,10 +114,18 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {createList = append(createList, createProjectMember)}+ var roleProvider api.ProjectRoleProvider+ switch vcs.Type {+ case vcsPlugin.GitLabSelfHost:+ roleProvider = api.ProjectRoleProviderGitLabSelfHost+ case vcsPlugin.GitHubCom:+ roleProvider = api.ProjectRoleProviderGitHubCom+ }+batchUpdateProjectMember := &api.ProjectMemberBatchUpdate{ID: projectID,UpdaterID: c.Get(getPrincipalIDContextKey()).(int),- RoleProvider: api.ProjectRoleProviderGitLabSelfHost, /* we only support gitlab for now */+ RoleProvider: roleProvider,List: createList,}createdMemberList, deletedMemberList, err := s.store.BatchUpdateProjectMember(ctx, batchUpdateProjectMember)diff --git a/server/task_executor.go b/server/task_executor.goindex cb553b144e..6044e333bc 100644--- a/server/task_executor.go+++ b/server/task_executor.go@@ -8,12 +8,13 @@ import ("strconv""strings"+ "go.uber.org/zap"+"github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/common/log""github.com/bytebase/bytebase/plugin/db"vcsPlugin "github.com/bytebase/bytebase/plugin/vcs"- "go.uber.org/zap")// TaskExecutor is the task executor.@@ -336,7 +337,7 @@ func findRepositoryByTask(ctx context.Context, server *Server, task *api.Task) (// 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 *vcsPlugin.PushEvent, mi *db.MigrationInfo, branch string, latestSchemaFile string, schema string, bytebaseURL string) (string, error) {- schemaFileMeta, err := vcsPlugin.Get(vcsPlugin.GitLabSelfHost, vcsPlugin.ProviderConfig{}).ReadFileMeta(+ schemaFileMeta, err := vcsPlugin.Get(repository.VCS.Type, vcsPlugin.ProviderConfig{}).ReadFileMeta(ctx,common.OauthContext{ClientID: repository.VCS.ApplicationID,@@ -383,7 +384,7 @@ func writeBackLatestSchema(ctx context.Context, server *Server, repository *api.zap.String("schema_file", latestSchemaFile),)- err := vcsPlugin.Get(vcsPlugin.GitLabSelfHost, vcsPlugin.ProviderConfig{}).CreateFile(+ err := vcsPlugin.Get(repository.VCS.Type, vcsPlugin.ProviderConfig{}).CreateFile(ctx,common.OauthContext{ClientID: repository.VCS.ApplicationID,@@ -407,7 +408,7 @@ func writeBackLatestSchema(ctx context.Context, server *Server, repository *api.)schemaFileCommit.LastCommitID = schemaFileMeta.LastCommitID- err := vcsPlugin.Get(vcsPlugin.GitLabSelfHost, vcsPlugin.ProviderConfig{}).OverwriteFile(+ err := vcsPlugin.Get(repository.VCS.Type, vcsPlugin.ProviderConfig{}).OverwriteFile(ctx,common.OauthContext{ClientID: repository.VCS.ApplicationID,@@ -427,7 +428,7 @@ func writeBackLatestSchema(ctx context.Context, server *Server, repository *api.}// VCS such as GitLab API doesn't return the commit on write, so we have to call ReadFileMeta again- schemaFileMeta, err = vcsPlugin.Get(vcsPlugin.GitLabSelfHost, vcsPlugin.ProviderConfig{}).ReadFileMeta(+ schemaFileMeta, err = vcsPlugin.Get(repository.VCS.Type, vcsPlugin.ProviderConfig{}).ReadFileMeta(ctx,common.OauthContext{ClientID: repository.VCS.ApplicationID,diff --git a/server/webhook.go b/server/webhook.goindex dfd8afb9cc..d1fc8d0567 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -24,7 +24,8 @@ import ()var (- gitLabWebhookPath = "hook/gitlab"+ gitlabWebhookPath = "hook/gitlab"+ githubWebhookPath = "hook/github")func (s *Server) registerWebhookRoutes(g *echo.Group) {@@ -157,7 +158,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Webhook endpoint not found: %v", webhookEndpointID))}- content, err := vcs.Get(vcs.GitLabSelfHost, vcs.ProviderConfig{}).ReadFileContent(+ content, err := vcs.Get(repo2.VCS.Type, vcs.ProviderConfig{}).ReadFileContent(ctx,common.OauthContext{ClientID: repo2.VCS.ApplicationID,diff --git a/tests/fake/gitlab.go b/tests/fake/gitlab.goindex 8c3f1dabdf..1f8000cc08 100644--- a/tests/fake/gitlab.go+++ b/tests/fake/gitlab.go@@ -29,7 +29,7 @@ type GitLab struct {}type projectData struct {- webhooks []*gitlab.WebhookPost+ webhooks []*gitlab.WebhookCreate// files is a map that the full file path is the key and the file content is the value.files map[string]string}@@ -87,15 +87,15 @@ func (gl *GitLab) createProjectHook(c echo.Context) error {if err != nil {return fmt.Errorf("failed to read create project hook request body, error %w", err)}- webhookPost := &gitlab.WebhookPost{}- if err := json.Unmarshal(b, webhookPost); err != nil {+ webhookCreate := &gitlab.WebhookCreate{}+ if err := json.Unmarshal(b, webhookCreate); err != nil {return fmt.Errorf("failed to unmarshal create project hook request body, error %w", err)}pd, ok := gl.projects[gitlabProjectID]if !ok {return fmt.Errorf("gitlab project %q doesn't exist", gitlabProjectID)}- pd.webhooks = append(pd.webhooks, webhookPost)+ pd.webhooks = append(pd.webhooks, webhookCreate)if err := json.NewEncoder(c.Response().Writer).Encode(&gitlab.WebhookInfo{ID: gl.nextWebhookID,