Skip to content

Commit

Permalink
feat: support Dingtalk notify for sign secret (megaease#190)
Browse files Browse the repository at this point in the history
  • Loading branch information
samanhappy committed Aug 8, 2022
1 parent 92c5345 commit 504c529
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -916,6 +916,7 @@ notify:
dingtalk:
- name: "dingtalk alert service"
webhook: "https://oapi.dingtalk.com/robot/send?access_token=xxxx"
secret: "" # sign secret if set
# Notify to Lark
lark:
- name: "lark alert service"
Expand Down
21 changes: 20 additions & 1 deletion notify/dingtalk/dingtalk.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,15 @@ package dingtalk

import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"time"

"github.com/megaease/easeprobe/global"
"github.com/megaease/easeprobe/notify/base"
Expand All @@ -34,6 +39,7 @@ import (
type NotifyConfig struct {
base.DefaultNotify `yaml:",inline"`
WebhookURL string `yaml:"webhook"`
SignSecret string `yaml:"secret"`
}

// Config configures the dingtalk notification
Expand Down Expand Up @@ -61,7 +67,7 @@ func (c *NotifyConfig) SendDingtalkNotification(title, msg string) error {
}
}
`, title, msg)
req, err := http.NewRequest(http.MethodPost, c.WebhookURL, bytes.NewBuffer([]byte(msgContent)))
req, err := http.NewRequest(http.MethodPost, addSign(c.WebhookURL, c.SignSecret), bytes.NewBuffer([]byte(msgContent)))
if err != nil {
return err
}
Expand Down Expand Up @@ -92,3 +98,16 @@ func (c *NotifyConfig) SendDingtalkNotification(title, msg string) error {
}
return nil
}

// add sign for url by secret
func addSign(webhookURL string, secret string) string {
if secret != "" {
timestamp := time.Now().UnixMilli()
stringToSign := fmt.Sprint(timestamp, "\n", secret)
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(stringToSign))
sign := url.QueryEscape(base64.StdEncoding.EncodeToString(h.Sum(nil)))
return fmt.Sprint(webhookURL, "&timestamp=", timestamp, "&sign="+sign)
}
return webhookURL
}

0 comments on commit 504c529

Please sign in to comment.