Skip to content

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

Move the webhook creation from frontend to backend

天舟85982fa32049
diff --git a/api/repository.go b/api/repository.go
index cdd7a830cd..17230e14a7 100644
--- a/api/repository.go
+++ b/api/repository.go
@@ -23,15 +23,16 @@ type Repository struct {
Project *Project `jsonapi:"relation,project"`
// Domain specific fields
- Name string `jsonapi:"attr,name"`
- FullPath string `jsonapi:"attr,fullPath"`
- WebURL string `jsonapi:"attr,webURL"`
- BaseDirectory string `jsonapi:"attr,baseDirectory"`
- BranchFilter string `jsonapi:"attr,branchFilter"`
- ExternalId string `jsonapi:"attr,externalId"`
- ExternalWebhookId string
- WebhookEndpointId string
- SecretToken string
+ Name string `jsonapi:"attr,name"`
+ FullPath string `jsonapi:"attr,fullPath"`
+ WebURL string `jsonapi:"attr,webURL"`
+ BaseDirectory string `jsonapi:"attr,baseDirectory"`
+ BranchFilter string `jsonapi:"attr,branchFilter"`
+ ExternalId string `jsonapi:"attr,externalId"`
+ ExternalWebhookId string
+ WebhookURLHost string
+ WebhookEndpointId string
+ WebhookSecretToken string
}
type RepositoryCreate struct {
@@ -44,15 +45,19 @@ type RepositoryCreate struct {
ProjectId int `jsonapi:"attr,projectId"`
// Domain specific fields
- Name string `jsonapi:"attr,name"`
- FullPath string `jsonapi:"attr,fullPath"`
- WebURL string `jsonapi:"attr,webURL"`
- BaseDirectory string `jsonapi:"attr,baseDirectory"`
- BranchFilter string `jsonapi:"attr,branchFilter"`
- ExternalId string `jsonapi:"attr,externalId"`
- ExternalWebhookId string `jsonapi:"attr,externalWebhookId"`
- WebhookEndpointId string `jsonapi:"attr,webhookEndpointId"`
- SecretToken string `jsonapi:"attr,secretToken"`
+ Name string `jsonapi:"attr,name"`
+ FullPath string `jsonapi:"attr,fullPath"`
+ WebURL string `jsonapi:"attr,webURL"`
+ BaseDirectory string `jsonapi:"attr,baseDirectory"`
+ BranchFilter string `jsonapi:"attr,branchFilter"`
+ ExternalId string `jsonapi:"attr,externalId"`
+ // Token belonged by the end user creating the webhook. We are accessing the end user's repository
+ // so we should use her access token instead of the access token stored in VCS.
+ AccessToken string `jsonapi:"attr,accessToken"`
+ ExternalWebhookId string
+ WebhookURLHost string
+ WebhookEndpointId string
+ WebhookSecretToken string
}
type RepositoryFind struct {
diff --git a/external/gitlab/gitlab.go b/external/gitlab/gitlab.go
index befb0a2297..e8cbc0ec33 100644
--- a/external/gitlab/gitlab.go
+++ b/external/gitlab/gitlab.go
@@ -7,7 +7,8 @@ import (
)
const (
- ApiPath = "api/v4"
+ ApiPath = "api/v4"
+ SECRET_TOKEN_LENGTH = 16
)
type GitLabWebhookType string
@@ -24,6 +25,26 @@ func (e GitLabWebhookType) String() string {
return "UNKNOWN"
}
+type WebhookInfo struct {
+ ID int `json:"id"`
+}
+
+type WebhookPost struct {
+ URL string `json:"url"`
+ SecretToken string `json:"token"`
+ // This is set to true
+ PushEvents bool `json:"push_events"`
+ // For now, there is no native dry run DDL support in mysql/postgres. One may wonder if we could wrap the DDL
+ // in a transaction and just not commit at the end, unfortunately there are side effects which are hard to control.
+ // See https://www.postgresql.org/message-id/CAMsr%2BYGiYQ7PYvYR2Voio37YdCpp79j5S%2BcmgVJMOLM2LnRQcA%40mail.gmail.com
+ // So we can't possibly display useful info when reviewing a MR, thus we don't enable this event.
+ // 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"`
+}
+
type WebhookPut struct {
URL string `json:"url"`
PushEventsBranchFilter string `json:"push_events_branch_filter"`
@@ -57,6 +78,25 @@ type WebhookPushEvent struct {
CommitList []WebhookCommit `json:"commits"`
}
+func POST(instanceURL string, resourcePath string, token string, body io.Reader) (*http.Response, error) {
+ url := fmt.Sprintf("%s/%s/%s", instanceURL, ApiPath, resourcePath)
+ req, err := http.NewRequest("POST",
+ url, body)
+ if err != nil {
+ return nil, fmt.Errorf("failed to construct POST %v (%w)", url, err)
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Add("Authorization", "Bearer "+token)
+ client := &http.Client{}
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("failed POST %v (%w)", url, err)
+ }
+
+ return resp, nil
+}
+
func GET(instanceURL string, resourcePath string, token string) (*http.Response, error) {
url := fmt.Sprintf("%s/%s/%s", instanceURL, ApiPath, resourcePath)
req, err := http.NewRequest("GET",
diff --git a/frontend/.env.dev b/frontend/.env.dev
index d7fba3f837..083c815f94 100644
--- a/frontend/.env.dev
+++ b/frontend/.env.dev
@@ -1,2 +1 @@
-NODE_ENV=development
-VITE_BACKEND=http://localhost:8080
\ No newline at end of file
+NODE_ENV=development
\ No newline at end of file
diff --git a/frontend/src/components/RepositorySetupWizard.vue b/frontend/src/components/RepositorySetupWizard.vue
index ceba80b72d..c615b53a69 100644
--- a/frontend/src/components/RepositorySetupWizard.vue
+++ b/frontend/src/components/RepositorySetupWizard.vue
@@ -118,39 +118,23 @@ export default {
};
const tryFinishSetup = (allowFinishCallback: () => void) => {
- // The secret token to validate the gitlab webhook sender.
- const secretToken = randomString(16);
- const webhookEndpointId = uuidv4();
const createFunc = () => {
+ const repositoryCreate: RepositoryCreate = {
+ vcsId: state.config.vcs.id,
+ projectId: props.project.id,
+ name: state.config.repositoryInfo.name,
+ fullPath: state.config.repositoryInfo.fullPath,
+ webURL: state.config.repositoryInfo.webURL,
+ baseDirectory: state.config.repositoryConfig.baseDirectory,
+ branchFilter: state.config.repositoryConfig.branchFilter,
+ externalId: state.config.repositoryInfo.externalId,
+ accessToken: state.config.token.accessToken,
+ };
store
- .dispatch("gitlab/createWebhook", {
- vcs: state.config.vcs,
- webhookEndpointId,
- projectId: state.config.repositoryInfo.externalId,
- branchFilter: state.config.repositoryConfig.branchFilter.trim(),
- secretToken,
- accessToken: state.config.token.accessToken,
- })
- .then((webhook: WebhookInfo) => {
- const repositoryCreate: RepositoryCreate = {
- vcsId: state.config.vcs.id,
- projectId: props.project.id,
- name: state.config.repositoryInfo.name,
- fullPath: state.config.repositoryInfo.fullPath,
- webURL: state.config.repositoryInfo.webURL,
- baseDirectory: state.config.repositoryConfig.baseDirectory,
- branchFilter: state.config.repositoryConfig.branchFilter,
- externalId: state.config.repositoryInfo.externalId,
- externalWebhookId: webhook.id,
- webhookEndpointId,
- secretToken,
- };
- store
- .dispatch("repository/createRepository", repositoryCreate)
- .then(() => {
- allowFinishCallback();
- emit("finish");
- });
+ .dispatch("repository/createRepository", repositoryCreate)
+ .then(() => {
+ allowFinishCallback();
+ emit("finish");
});
};
if (props.create) {
diff --git a/frontend/src/main.ts b/frontend/src/main.ts
index 05bddcb1e9..5c2c200ba2 100644
--- a/frontend/src/main.ts
+++ b/frontend/src/main.ts
@@ -36,7 +36,6 @@ import highlight from "./directives/highlight";
import {
isDev,
isRelease,
- backendURL,
humanizeTs,
sizeToFit,
urlfy,
@@ -76,7 +75,6 @@ registerStoreWithRoleUtil(store);
console.debug("dev:", isDev());
console.debug("release:", isRelease());
-console.debug("backend:", backendURL());
axios.defaults.timeout = 10000;
axios.interceptors.request.use((request) => {
diff --git a/frontend/src/store/modules/gitlab.ts b/frontend/src/store/modules/gitlab.ts
index 6659d321af..56bca6c827 100644
--- a/frontend/src/store/modules/gitlab.ts
+++ b/frontend/src/store/modules/gitlab.ts
@@ -4,12 +4,9 @@ import {
VCS,
OAuthConfig,
OAuthToken,
- WebhookInfo,
} from "../../types";
-import { backendURL } from "../../utils";
const GITLAB_API_PATH = "api/v4";
-const GITLAB_WEBHOOK_PATH = "hook/gitlab";
const getters = {};
@@ -68,56 +65,6 @@ const actions = {
return data.map((item: any) => convertGitLabProject(item));
},
-
- // Create webhook to receive push event
- async createWebhook(
- {}: any,
- {
- vcs,
- webhookEndpointId,
- projectId,
- branchFilter,
- secretToken,
- accessToken,
- }: {
- vcs: VCS;
- projectId: string;
- branchFilter: string;
- webhookEndpointId: string;
- secretToken: string;
- accessToken: string;
- }
- ): Promise<WebhookInfo> {
- const url = `${backendURL()}/${GITLAB_WEBHOOK_PATH}/${webhookEndpointId}`;
- const data = (
- await axios.post(
- `${vcs.instanceURL}/${GITLAB_API_PATH}/projects/${projectId}/hooks`,
- {
- url,
- token: secretToken,
- push_events: true,
- // For now, there is no native dry run DDL support in mysql/postgres. One may wonder if we could wrap the DDL
- // in a transaction and just not commit at the end, unfortunately there are side effects which are hard to control.
- // See https://www.postgresql.org/message-id/CAMsr%2BYGiYQ7PYvYR2Voio37YdCpp79j5S%2BcmgVJMOLM2LnRQcA%40mail.gmail.com
- // So we can't possibly display useful info when reviewing a MR, thus we don't enable this event.
- // Saying that, delivering a souding dry run solution would be great and hopefully we can achieve that one day.
- // merge_requests_events: true,
- push_events_branch_filter: branchFilter,
- // TODO(tianzhou): Be lax to not enable_ssl_verification
- enable_ssl_verification: false,
- },
- {
- headers: {
- Authorization: "Bearer " + accessToken,
- },
- }
- )
- ).data;
-
- return {
- id: data.id.toString(),
- };
- },
};
const mutations = {};
diff --git a/frontend/src/types/repository.ts b/frontend/src/types/repository.ts
index 6ec323844d..01e9a041e0 100644
--- a/frontend/src/types/repository.ts
+++ b/frontend/src/types/repository.ts
@@ -42,9 +42,7 @@ export type RepositoryCreate = {
baseDirectory: string;
branchFilter: string;
externalId: string;
- externalWebhookId: string;
- webhookEndpointId: string;
- secretToken: string;
+ accessToken: string;
};
export type RepositoryPatch = {
@@ -68,10 +66,6 @@ export type ExternalRepositoryInfo = {
webURL: string;
};
-export type WebhookInfo = {
- id: string;
-};
-
export function baseDirectoryWebURL(repository: Repository): string {
if (repository.vcs.type == "GITLAB_SELF_HOST") {
// If branchFilter is empty (default branch) or branch filter contains wildcard,
diff --git a/frontend/src/utils/util.ts b/frontend/src/utils/util.ts
index 6772b668f3..66c22759ba 100644
--- a/frontend/src/utils/util.ts
+++ b/frontend/src/utils/util.ts
@@ -8,16 +8,6 @@ export function isRelease(): boolean {
return import.meta.env.PROD;
}
-// Use VITE_BACKEND as the backendURL if specified. Otherwise, just use the current host
-// For dev environment, we usually set VITE_BACKEND to point to different backend.
-// For production environment, we won't set VITE_BACKEND because we bundle frontend/backend as a monolithic.
-export function backendURL(): string {
- if (import.meta.env.VITE_BACKEND) {
- return import.meta.env.VITE_BACKEND as string;
- }
- return window.location.origin;
-}
-
export function humanizeTs(ts: number): string {
const time = moment.utc(ts * 1000);
if (moment().year() == time.year()) {
diff --git a/go.mod b/go.mod
index 943cea4a0a..33760a021c 100644
--- a/go.mod
+++ b/go.mod
@@ -13,6 +13,7 @@ require (
github.com/mattn/go-sqlite3 v1.14.7
github.com/pkg/errors v0.9.1 // indirect
github.com/qiangmzsx/string-adapter/v2 v2.1.0
+ github.com/satori/go.uuid v1.2.0
github.com/spf13/cobra v1.2.0
go.uber.org/multierr v1.7.0 // indirect
go.uber.org/zap v1.17.0
diff --git a/go.sum b/go.sum
index 228f1409e1..29e0eb2e63 100644
--- a/go.sum
+++ b/go.sum
@@ -189,8 +189,10 @@ github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfV
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
+github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
+github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/labstack/echo/v4 v4.2.2 h1:bq2fdZCionY1jck8rzUpQEu2YSmI8QbX6LHrCa60IVs=
github.com/labstack/echo/v4 v4.2.2/go.mod h1:AA49e0DZ8kk5jTOOCKNuPR6oTnBS0dYiM4FW1e6jwpg=
@@ -236,6 +238,8 @@ github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6L
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
+github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
+github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
@@ -609,6 +613,7 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
diff --git a/server/project.go b/server/project.go
index fb0b26e620..8f14c0707c 100644
--- a/server/project.go
+++ b/server/project.go
@@ -14,6 +14,7 @@ import (
"github.com/bytebase/bytebase/external/gitlab"
"github.com/google/jsonapi"
"github.com/labstack/echo/v4"
+ uuid "github.com/satori/go.uuid"
"go.uber.org/zap"
)
@@ -146,6 +147,58 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
if err := jsonapi.UnmarshalPayload(c.Request().Body, repositoryCreate); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create linked repository request").SetInternal(err)
}
+
+ vcsFind := &api.VCSFind{
+ ID: &repositoryCreate.VCSId,
+ }
+ vcs, err := s.VCSService.FindVCS(context.Background(), vcsFind)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("VCS ID not found: %d", repositoryCreate.VCSId))
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find VCS for creating repository: %d", repositoryCreate.VCSId)).SetInternal(err)
+ }
+
+ repositoryCreate.WebhookURLHost = fmt.Sprintf("%s:%d", s.host, s.port)
+ repositoryCreate.WebhookEndpointId = uuid.NewV4().String()
+ repositoryCreate.WebhookSecretToken = bytebase.RandomString(gitlab.SECRET_TOKEN_LENGTH)
+ switch vcs.Type {
+ case "GITLAB_SELF_HOST":
+ webhookPost := gitlab.WebhookPost{
+ URL: fmt.Sprintf("%s:%d/%s/%s", s.host, s.port, gitLabWebhookPath, repositoryCreate.WebhookEndpointId),
+ SecretToken: repositoryCreate.WebhookSecretToken,
+ PushEvents: true,
+ PushEventsBranchFilter: repositoryCreate.BranchFilter,
+ EnableSSLVerification: false,
+ }
+ body, 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)
+ resp, err := gitlab.POST(vcs.InstanceURL, resourcePath, repositoryCreate.AccessToken, bytes.NewBuffer(body))
+ 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()
+
+ // 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 {
+ return echo.NewHTTPError(http.StatusInternalServerError,
+ fmt.Sprintf("Failed to create webhook for project ID: %v, status code: %d, status: %s",
+ repositoryCreate.ProjectId,
+ resp.StatusCode,
+ resp.Status,
+ ))
+ }
+
+ 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)
+ }
+
repositoryCreate.CreatorId = c.Get(GetPrincipalIdContextKey()).(int)
// Remove enclosing /
repositoryCreate.BaseDirectory = strings.Trim(repositoryCreate.BaseDirectory, "/")
@@ -270,6 +323,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
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 {
@@ -344,6 +398,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
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 {
diff --git a/server/webhook.go b/server/webhook.go
index 88556b1572..3e0c480d30 100644
--- a/server/webhook.go
+++ b/server/webhook.go
@@ -58,7 +58,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository relationship: %v", repository.Name)).SetInternal(err)
}
- if c.Request().Header.Get("X-Gitlab-Token") != repository.SecretToken {
+ if c.Request().Header.Get("X-Gitlab-Token") != repository.WebhookSecretToken {
return echo.NewHTTPError(http.StatusBadRequest, "Secret token mismatch")
}
@@ -92,6 +92,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
s.l.Warn("Failed to read added repository file response. Skip", zap.String("file", added), zap.Error(err))
continue
}
+ defer resp.Body.Close()
// Find matching database list
databaseFind := &api.DatabaseFind{
diff --git a/store/migration/10001__init_schema.sql b/store/migration/10001__init_schema.sql
index 693577a17a..de5074f489 100644
--- a/store/migration/10001__init_schema.sql
+++ b/store/migration/10001__init_schema.sql
@@ -773,10 +773,12 @@ CREATE TABLE repo (
-- Push webhook id from the corresponding VCS provider.
-- For GitLab, this is the project webhook id. e.g. 123
external_webhook_id TEXT NOT NULL,
- -- Identify the target repository receiving the webhook event. This is a random string, and we don't store the full URL because the backend may change host.
+ -- Identify the host of the webhook url where the webhook event sends. We store this to identify stale webhook url whose url doesn't match the current bytebase --host.
+ webhook_url_host TEXT NOT NULL,
+ -- Identify the target repository receiving the webhook event. This is a random string.
webhook_endpoint_id TEXT NOT NULL UNIQUE,
- -- For GitLab, webhook request contains this in the 'X-Gitlab-Token" header and we can compare it with the one stored in db to validate it sends to the expected endpoint.
- secret_token TEXT NOT NULL
+ -- For GitLab, webhook request contains this in the 'X-Gitlab-Token" header and we compare it with the one stored in db to validate it sends to the expected endpoint.
+ webhook_secret_token TEXT NOT NULL
);
INSERT INTO
diff --git a/store/repository.go b/store/repository.go
index 5a73895ace..f03ff57abc 100644
--- a/store/repository.go
+++ b/store/repository.go
@@ -153,11 +153,12 @@ func (s *RepositoryService) createRepository(ctx context.Context, tx *Tx, create
branch_filter,
external_id,
external_webhook_id,
+ webhook_url_host,
webhook_endpoint_id,
- secret_token
+ webhook_secret_token
)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- RETURNING id, creator_id, created_ts, updater_id, updated_ts, vcs_id, project_id, name, full_path, web_url, base_directory, branch_filter, external_id, external_webhook_id, webhook_endpoint_id, secret_token
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, vcs_id, project_id, name, full_path, web_url, base_directory, branch_filter, external_id, external_webhook_id, webhook_url_host, webhook_endpoint_id, webhook_secret_token
`,
create.CreatorId,
create.CreatorId,
@@ -170,8 +171,9 @@ func (s *RepositoryService) createRepository(ctx context.Context, tx *Tx, create
create.BranchFilter,
create.ExternalId,
create.ExternalWebhookId,
+ create.WebhookURLHost,
create.WebhookEndpointId,
- create.SecretToken,
+ create.WebhookSecretToken,
)
if err != nil {
@@ -196,8 +198,9 @@ func (s *RepositoryService) createRepository(ctx context.Context, tx *Tx, create
&repository.BranchFilter,
&repository.ExternalId,
&repository.ExternalWebhookId,
+ &repository.WebhookURLHost,
&repository.WebhookEndpointId,
- &repository.SecretToken,
+ &repository.WebhookSecretToken,
); err != nil {
return nil, FormatError(err)
}
@@ -237,8 +240,9 @@ func findRepositoryList(ctx context.Context, tx *Tx, find *api.RepositoryFind) (
branch_filter,
external_id,
external_webhook_id,
+ webhook_url_host,
webhook_endpoint_id,
- secret_token
+ webhook_secret_token
FROM repo
WHERE `+strings.Join(where, " AND "),
args...,
@@ -267,8 +271,9 @@ func findRepositoryList(ctx context.Context, tx *Tx, find *api.RepositoryFind) (
&repository.BranchFilter,
&repository.ExternalId,
&repository.ExternalWebhookId,
+ &repository.WebhookURLHost,
&repository.WebhookEndpointId,
- &repository.SecretToken,
+ &repository.WebhookSecretToken,
); err != nil {
return nil, FormatError(err)
}
@@ -300,7 +305,7 @@ func patchRepository(ctx context.Context, tx *Tx, patch *api.RepositoryPatch) (*
UPDATE repo
SET `+strings.Join(set, ", ")+`
WHERE id = ?
- RETURNING id, creator_id, created_ts, updater_id, updated_ts, vcs_id, project_id, name, full_path, web_url, base_directory, branch_filter, external_id, external_webhook_id, webhook_endpoint_id, secret_token
+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, vcs_id, project_id, name, full_path, web_url, base_directory, branch_filter, external_id, external_webhook_id, webhook_url_host, webhook_endpoint_id, webhook_secret_token
`,
args...,
)
@@ -326,8 +331,9 @@ func patchRepository(ctx context.Context, tx *Tx, patch *api.RepositoryPatch) (*
&repository.BranchFilter,
&repository.ExternalId,
&repository.ExternalWebhookId,
+ &repository.WebhookURLHost,
&repository.WebhookEndpointId,
- &repository.SecretToken,
+ &repository.WebhookSecretToken,
); err != nil {
return nil, FormatError(err)
}
diff --git a/store/seed/test/10170__repo.sql b/store/seed/test/10170__repo.sql
index beba8adf37..7143f39795 100644
--- a/store/seed/test/10170__repo.sql
+++ b/store/seed/test/10170__repo.sql
@@ -13,8 +13,9 @@ INSERT INTO
branch_filter,
external_id,
external_webhook_id,
+ webhook_url_host,
webhook_endpoint_id,
- secret_token
+ webhook_secret_token
)
VALUES
(
@@ -32,6 +33,7 @@ VALUES
"13",
-- Refers to the webhook in bytebase-demo/blog
"60",
+ "https://demo.bytebase.com",
"e99bf622-7f58-4d6b-a5be-b97af313d7ea",
"xxxxxxxxxxxxxxxx"
);
@@ -50,8 +52,9 @@ INSERT INTO
branch_filter,
external_id,
external_webhook_id,
+ webhook_url_host,
webhook_endpoint_id,
- secret_token
+ webhook_secret_token
)
VALUES
(
@@ -69,6 +72,7 @@ VALUES
"14",
-- Refers to the webhook in bytebase-demo/shop
"61",
+ "https://demo.bytebase.com",
"c5e30130-7322-4f84-953a-d08168c047d1",
"xxxxxxxxxxxxxxxx"
);
\ No newline at end of file