Skip to content

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

Add test webhook support from UI and for each webhook provider

天舟85bf55d35364
diff --git a/api/issue.go b/api/issue.go
index 582c14171f..2c1928ecd7 100644
--- a/api/issue.go
+++ b/api/issue.go
@@ -3,9 +3,6 @@ package api
import (
"context"
"encoding/json"
- "fmt"
-
- "github.com/gosimple/slug"
)
// Issue status
@@ -174,7 +171,3 @@ type IssueService interface {
FindIssue(ctx context.Context, find *IssueFind) (*Issue, error)
PatchIssue(ctx context.Context, patch *IssuePatch) (*Issue, error)
}
-
-func IssueSlug(issue *Issue) string {
- return fmt.Sprintf("%s-%d", slug.Make(issue.Name), issue.ID)
-}
diff --git a/api/project_webhook.go b/api/project_webhook.go
index fc15eaa673..3a1c66b523 100644
--- a/api/project_webhook.go
+++ b/api/project_webhook.go
@@ -79,6 +79,10 @@ type ProjectWebhookDelete struct {
DeleterId int
}
+type ProjectWebhookTestResult struct {
+ Error string `jsonapi:"attr,error"`
+}
+
type ProjectWebhookService interface {
CreateProjectWebhook(ctx context.Context, create *ProjectWebhookCreate) (*ProjectWebhook, error)
FindProjectWebhookList(ctx context.Context, find *ProjectWebhookFind) ([]*ProjectWebhook, error)
diff --git a/api/slug.go b/api/slug.go
new file mode 100644
index 0000000000..cb6004a16a
--- /dev/null
+++ b/api/slug.go
@@ -0,0 +1,19 @@
+package api
+
+import (
+ "fmt"
+
+ "github.com/gosimple/slug"
+)
+
+func IssueSlug(issue *Issue) string {
+ return fmt.Sprintf("%s-%d", slug.Make(issue.Name), issue.ID)
+}
+
+func ProjectSlug(project *Project) string {
+ return fmt.Sprintf("%s-%d", slug.Make(project.Name), project.ID)
+}
+
+func ProjectWebhookSlug(projectWebhook *ProjectWebhook) string {
+ return fmt.Sprintf("%s-%d", slug.Make(projectWebhook.Name), projectWebhook.ID)
+}
diff --git a/frontend/src/store/modules/projectWebhook.ts b/frontend/src/store/modules/projectWebhook.ts
index a1c0a99fb4..2cf9630f55 100644
--- a/frontend/src/store/modules/projectWebhook.ts
+++ b/frontend/src/store/modules/projectWebhook.ts
@@ -6,6 +6,7 @@ import {
ProjectWebhookId,
ProjectWebhookPatch,
ProjectWebhookState,
+ ProjectWebhookTestResult,
ResourceObject,
unknown,
} from "../../types";
@@ -21,6 +22,14 @@ function convert(
};
}
+function convertTestResult(
+ testResult: ResourceObject
+): ProjectWebhookTestResult {
+ return {
+ ...(testResult.attributes as ProjectWebhookTestResult),
+ };
+}
+
const state: () => ProjectWebhookState = () => ({
projectWebhookListByProjectId: new Map(),
});
@@ -179,6 +188,25 @@ const actions = {
projectWebhookId,
});
},
+
+ async testProjectWebhookById(
+ { dispatch, commit }: any,
+ {
+ projectId,
+ projectWebhookId,
+ }: {
+ projectId: ProjectId;
+ projectWebhookId: ProjectWebhookId;
+ }
+ ) {
+ const data = (
+ await axios.get(
+ `/api/project/${projectId}/webhook/${projectWebhookId}/test`
+ )
+ ).data;
+
+ return convertTestResult(data.data);
+ },
};
const mutations = {
diff --git a/frontend/src/types/projectWebhook.ts b/frontend/src/types/projectWebhook.ts
index 6f816f49ef..905e09e89a 100644
--- a/frontend/src/types/projectWebhook.ts
+++ b/frontend/src/types/projectWebhook.ts
@@ -112,3 +112,7 @@ export type ProjectWebhookPatch = {
// Comma separated list. Server doesn't support deserialize into pointer to string array (*[]string in Golang)
activityList?: string;
};
+
+export type ProjectWebhookTestResult = {
+ error?: string;
+};
diff --git a/frontend/src/views/ProjectWebhookDetail.vue b/frontend/src/views/ProjectWebhookDetail.vue
index e5aae9a1de..c926566bfd 100644
--- a/frontend/src/views/ProjectWebhookDetail.vue
+++ b/frontend/src/views/ProjectWebhookDetail.vue
@@ -1,10 +1,19 @@
<template>
<div class="space-y-4 divide-y divide-block-border">
- <div class="flex flex-row space-x-2 items-center">
- <img class="h-6 w-6" :src="`/src/assets/${logo}`" />
- <h3 class="text-xl leading-6 font-medium text-main">
- {{ projectWebhook.name }}
- </h3>
+ <div class="flex justify-between">
+ <div class="flex flex-row space-x-2 items-center">
+ <img class="h-6 w-6" :src="`/src/assets/${logo}`" />
+ <h3 class="text-xl leading-6 font-medium text-main">
+ {{ projectWebhook.name }}
+ </h3>
+ </div>
+ <button
+ @click.prevent="testWebhook"
+ type="button"
+ class="btn-normal whitespace-nowrap items-center"
+ >
+ Test Webhook
+ </button>
</div>
<ProjectWebhookForm
class="pt-4"
@@ -21,7 +30,10 @@ import { computed } from "@vue/runtime-core";
import ProjectWebhookForm from "../components/ProjectWebhookForm.vue";
import { idFromSlug } from "../utils";
import { useStore } from "vuex";
-import { PROJECT_HOOK_TYPE_ITEM_LIST } from "../types";
+import {
+ ProjectWebhookTestResult,
+ PROJECT_HOOK_TYPE_ITEM_LIST,
+} from "../types";
export default {
name: "ProjectWebhookDetail",
@@ -66,10 +78,36 @@ export default {
return "";
});
+ const testWebhook = () => {
+ store
+ .dispatch("projectWebhook/testProjectWebhookById", {
+ projectId: idFromSlug(props.projectSlug),
+ projectWebhookId: idFromSlug(props.projectWebhookSlug),
+ })
+ .then((testResult: ProjectWebhookTestResult) => {
+ if (testResult.error) {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "CRITICAL",
+ title: `Test webhook event failed.`,
+ description: testResult.error,
+ manualHide: true,
+ });
+ } else {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "SUCCESS",
+ title: `Test webhook event OK.`,
+ });
+ }
+ });
+ };
+
return {
project,
projectWebhook,
logo,
+ testWebhook,
};
},
};
diff --git a/plugin/webhook/dingtalk.go b/plugin/webhook/dingtalk.go
index 93eff58fa8..eb83ae073a 100644
--- a/plugin/webhook/dingtalk.go
+++ b/plugin/webhook/dingtalk.go
@@ -4,11 +4,17 @@ import (
"bytes"
"encoding/json"
"fmt"
+ "io/ioutil"
"net/http"
"strings"
"time"
)
+type DingTalkWebhookResponse struct {
+ ErrorCode int `json:"errcode"`
+ ErrorMessage string `json:"errmsg"`
+}
+
type DingTalkWebhookMarkdown struct {
Title string `json:"title"`
Text string `json:"text"`
@@ -60,10 +66,25 @@ func (receiver *DingTalkReceiver) post(context WebhookContext) error {
client := &http.Client{
Timeout: timeout,
}
- _, err = client.Do(req)
+ resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to POST webhook %v (%w)", context.URL, err)
}
+ b, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return fmt.Errorf("failed to read POST webhook response %v (%w)", context.URL, err)
+ }
+ defer resp.Body.Close()
+
+ webhookResponse := &DingTalkWebhookResponse{}
+ if err := json.Unmarshal(b, webhookResponse); err != nil {
+ return fmt.Errorf("malformatted webhook response %v (%w)", context.URL, err)
+ }
+
+ if webhookResponse.ErrorCode != 0 {
+ return fmt.Errorf("%s", webhookResponse.ErrorMessage)
+ }
+
return nil
}
diff --git a/plugin/webhook/discord.go b/plugin/webhook/discord.go
index 5e185b2f75..81b1923628 100644
--- a/plugin/webhook/discord.go
+++ b/plugin/webhook/discord.go
@@ -4,10 +4,16 @@ import (
"bytes"
"encoding/json"
"fmt"
+ "io/ioutil"
"net/http"
"time"
)
+type DiscordWebhookResponse struct {
+ Code int `json:"code"`
+ Message string `json:"message"`
+}
+
type DiscordWebhookEmbedField struct {
Name string `json:"name"`
Value string `json:"value"`
@@ -75,10 +81,25 @@ func (receiver *DiscordReceiver) post(context WebhookContext) error {
client := &http.Client{
Timeout: timeout,
}
- _, err = client.Do(req)
+ resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to POST webhook %+v (%w)", context.URL, err)
}
+ b, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return fmt.Errorf("failed to read POST webhook response %v (%w)", context.URL, err)
+ }
+ defer resp.Body.Close()
+
+ webhookResponse := &DiscordWebhookResponse{}
+ if err := json.Unmarshal(b, webhookResponse); err != nil {
+ return fmt.Errorf("malformatted webhook response %v (%w)", context.URL, err)
+ }
+
+ if webhookResponse.Code != 0 {
+ return fmt.Errorf("%s", webhookResponse.Message)
+ }
+
return nil
}
diff --git a/plugin/webhook/feishu.go b/plugin/webhook/feishu.go
index e9d29ab350..bf9e07ec35 100644
--- a/plugin/webhook/feishu.go
+++ b/plugin/webhook/feishu.go
@@ -4,10 +4,16 @@ import (
"bytes"
"encoding/json"
"fmt"
+ "io/ioutil"
"net/http"
"time"
)
+type FeishuWebhookResponse struct {
+ Code int `json:"code"`
+ Message string `json:"msg"`
+}
+
type FeishuWebhookPostSection struct {
Tag string `json:"tag"`
Text string `json:"text"`
@@ -123,10 +129,25 @@ func (receiver *FeishuReceiver) post(context WebhookContext) error {
client := &http.Client{
Timeout: timeout,
}
- _, err = client.Do(req)
+ resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to POST webhook %+v (%w)", context.URL, err)
}
+ b, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return fmt.Errorf("failed to read POST webhook response %v (%w)", context.URL, err)
+ }
+ defer resp.Body.Close()
+
+ webhookResponse := &FeishuWebhookResponse{}
+ if err := json.Unmarshal(b, webhookResponse); err != nil {
+ return fmt.Errorf("malformatted webhook response %v (%w)", context.URL, err)
+ }
+
+ if webhookResponse.Code != 0 {
+ return fmt.Errorf("%s", webhookResponse.Message)
+ }
+
return nil
}
diff --git a/plugin/webhook/slack.go b/plugin/webhook/slack.go
index 41fdd4dabf..a6b365a51b 100644
--- a/plugin/webhook/slack.go
+++ b/plugin/webhook/slack.go
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
+ "io/ioutil"
"net/http"
"time"
)
@@ -120,10 +121,20 @@ func (receiver *SlackReceiver) post(context WebhookContext) error {
client := &http.Client{
Timeout: timeout,
}
- _, err = client.Do(req)
+ resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to POST webhook %+v (%w)", context.URL, err)
}
+ b, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return fmt.Errorf("failed to read POST webhook response %v (%w)", context.URL, err)
+ }
+ defer resp.Body.Close()
+
+ if string(b) != "ok" {
+ return fmt.Errorf("%s", string(b))
+ }
+
return nil
}
diff --git a/plugin/webhook/teams.go b/plugin/webhook/teams.go
index 609e6ebc13..46981876f9 100644
--- a/plugin/webhook/teams.go
+++ b/plugin/webhook/teams.go
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
+ "io/ioutil"
"net/http"
"time"
)
@@ -97,10 +98,20 @@ func (receiver *TeamsReceiver) post(context WebhookContext) error {
client := &http.Client{
Timeout: timeout,
}
- _, err = client.Do(req)
+ resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to POST webhook %+v (%w)", context.URL, err)
}
+ b, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return fmt.Errorf("failed to read POST webhook response %v (%w)", context.URL, err)
+ }
+ defer resp.Body.Close()
+
+ if string(b) != "1" {
+ return fmt.Errorf("%s", string(b))
+ }
+
return nil
}
diff --git a/plugin/webhook/wecom.go b/plugin/webhook/wecom.go
index 617b3a2a16..01c1d26261 100644
--- a/plugin/webhook/wecom.go
+++ b/plugin/webhook/wecom.go
@@ -4,11 +4,17 @@ import (
"bytes"
"encoding/json"
"fmt"
+ "io/ioutil"
"net/http"
"strings"
"time"
)
+type WeComWebhookResponse struct {
+ ErrorCode int `json:"errcode"`
+ ErrorMessage string `json:"errmsg"`
+}
+
type WeComWebhookMarkdown struct {
Content string `json:"content"`
}
@@ -58,10 +64,25 @@ func (receiver *WeComReceiver) post(context WebhookContext) error {
client := &http.Client{
Timeout: timeout,
}
- _, err = client.Do(req)
+ resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to POST webhook %v (%w)", context.URL, err)
}
+ b, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return fmt.Errorf("failed to read POST webhook response %v (%w)", context.URL, err)
+ }
+ defer resp.Body.Close()
+
+ webhookResponse := &WeComWebhookResponse{}
+ if err := json.Unmarshal(b, webhookResponse); err != nil {
+ return fmt.Errorf("malformatted webhook response %v (%w)", context.URL, err)
+ }
+
+ if webhookResponse.ErrorCode != 0 {
+ return fmt.Errorf("%s", webhookResponse.ErrorMessage)
+ }
+
return nil
}
diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csv
index 7f56f169cf..549e840a13 100644
--- a/server/acl_casbin_policy_dba.csv
+++ b/server/acl_casbin_policy_dba.csv
@@ -18,6 +18,7 @@ p, DBA, /project/{projectId}/webhook, POST
p, DBA, /project/{projectId}/webhook/{webhookId}, GET
p, DBA, /project/{projectId}/webhook/{webhookId}, PATCH
p, DBA, /project/{projectId}/webhook/{webhookId}, DELETE
+p, DBA, /project/{projectId}/webhook/{webhookId}/test, GET
p, DBA, /environment, POST
p, DBA, /environment, GET
p, DBA, /environment/{id}, PATCH
diff --git a/server/acl_casbin_policy_developer.csv b/server/acl_casbin_policy_developer.csv
index 1697425e76..aabf974d62 100644
--- a/server/acl_casbin_policy_developer.csv
+++ b/server/acl_casbin_policy_developer.csv
@@ -18,6 +18,7 @@ p, DEVELOPER, /project/{projectId}/webhook, POST
p, DEVELOPER, /project/{projectId}/webhook/{webhookId}, GET
p, DEVELOPER, /project/{projectId}/webhook/{webhookId}, PATCH
p, DEVELOPER, /project/{projectId}/webhook/{webhookId}, DELETE
+p, DEVELOPER, /project/{projectId}/webhook/{webhookId}/test, GET
p, DEVELOPER, /environment, GET
p, DEVELOPER, /instance, GET
p, DEVELOPER, /instance/{id}, GET
diff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csv
index 6eb678999b..a52c0a7b98 100644
--- a/server/acl_casbin_policy_owner.csv
+++ b/server/acl_casbin_policy_owner.csv
@@ -22,6 +22,7 @@ p, OWNER, /project/{projectId}/webhook, POST
p, OWNER, /project/{projectId}/webhook/{webhookId}, GET
p, OWNER, /project/{projectId}/webhook/{webhookId}, PATCH
p, OWNER, /project/{projectId}/webhook/{webhookId}, DELETE
+p, OWNER, /project/{projectId}/webhook/{webhookId}/test, GET
p, OWNER, /environment, POST
p, OWNER, /environment, GET
p, OWNER, /environment/{id}, PATCH
diff --git a/server/issue.go b/server/issue.go
index c56d8b0d6e..bbd997862f 100644
--- a/server/issue.go
+++ b/server/issue.go
@@ -538,7 +538,6 @@ func (s *Server) ChangeIssueStatus(ctx context.Context, issue *api.Issue, newSta
// Call exteranl webhook endpoint in Go routine to avoid blocking web serveing thread.
go func() {
for _, hook := range hookList {
- s.l.Info(fmt.Sprintf("hook name: %s, %s", hook.Name, hook.URL))
title := ""
switch newStatus {
case "OPEN":
diff --git a/server/project_webhook.go b/server/project_webhook.go
index 8c062eb57f..2922600950 100644
--- a/server/project_webhook.go
+++ b/server/project_webhook.go
@@ -5,9 +5,11 @@ import (
"fmt"
"net/http"
"strconv"
+ "time"
"github.com/bytebase/bytebase"
"github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/plugin/webhook"
"github.com/google/jsonapi"
"github.com/labstack/echo/v4"
)
@@ -174,6 +176,70 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
c.Response().WriteHeader(http.StatusOK)
return nil
})
+
+ g.GET("/project/:projectId/webhook/:webhookId/test", func(c echo.Context) error {
+ projectId, err := strconv.Atoi(c.Param("projectId"))
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectId"))).SetInternal(err)
+ }
+
+ projectFind := &api.ProjectFind{
+ ID: &projectId,
+ }
+ project, err := s.ProjectService.FindProject(context.Background(), projectFind)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project ID not found: %d", projectId))
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project ID: %v", projectId)).SetInternal(err)
+ }
+
+ id, err := strconv.Atoi(c.Param("webhookId"))
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project webhook ID is not a number: %s", c.Param("webhookId"))).SetInternal(err)
+ }
+
+ find := &api.ProjectWebhookFind{
+ ID: &id,
+ }
+ hook, err := s.ProjectWebhookService.FindProjectWebhook(context.Background(), find)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project webhook ID not found: %d", id))
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project webhook ID: %v", id)).SetInternal(err)
+ }
+
+ result := &api.ProjectWebhookTestResult{}
+ err = webhook.Post(
+ hook.Type,
+ webhook.WebhookContext{
+ URL: hook.URL,
+ Title: fmt.Sprintf("Test webhook '%s'", hook.Name),
+ Description: "This is a test",
+ Link: fmt.Sprintf("%s:%d/project/%s/webhook/%s", s.frontendHost, s.frontendPort, api.ProjectSlug(project), api.ProjectWebhookSlug(hook)),
+ CreatorName: "Bytebase",
+ CreatorEmail: "[email protected]",
+ CreatedTs: time.Now().Unix(),
+ MetaList: []webhook.WebhookMeta{
+ {
+ Name: "Project",
+ Value: project.Name,
+ },
+ },
+ },
+ )
+
+ if err != nil {
+ result.Error = err.Error()
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, result); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal project webhook response: %v", projectId)).SetInternal(err)
+ }
+ return nil
+ })
}
func (s *Server) ComposeProjectWebhookRelationship(ctx context.Context, hook *api.ProjectWebhook) error {